From b1bef5eacf76dea9b4e84b25b0c887f819a24e7f Mon Sep 17 00:00:00 2001 From: sdiemert Date: Tue, 13 Oct 2015 21:26:04 +0000 Subject: [PATCH 01/10] Added scripts executing nagios-nrpe checks. --- util/nrpe/install-nrpe.sh | 4 ++ .../monitoring_scripts/check_delay_job.sh | 54 ++++++++++++++++ .../monitoring_scripts/check_diskspace.sh | 55 +++++++++++++++++ util/nrpe/monitoring_scripts/check_import.sh | 61 +++++++++++++++++++ util/nrpe/monitoring_scripts/check_load.sh | 56 +++++++++++++++++ .../monitoring_scripts/check_processes.sh | 54 ++++++++++++++++ util/nrpe/monitoring_scripts/check_swap.sh | 55 +++++++++++++++++ util/nrpe/monitoring_scripts/check_tomcat.sh | 56 +++++++++++++++++ util/nrpe/monitoring_scripts/check_users.sh | 55 +++++++++++++++++ 9 files changed, 450 insertions(+) create mode 100755 util/nrpe/install-nrpe.sh create mode 100755 util/nrpe/monitoring_scripts/check_delay_job.sh create mode 100755 util/nrpe/monitoring_scripts/check_diskspace.sh create mode 100755 util/nrpe/monitoring_scripts/check_import.sh create mode 100755 util/nrpe/monitoring_scripts/check_load.sh create mode 100755 util/nrpe/monitoring_scripts/check_processes.sh create mode 100755 util/nrpe/monitoring_scripts/check_swap.sh create mode 100755 util/nrpe/monitoring_scripts/check_tomcat.sh create mode 100755 util/nrpe/monitoring_scripts/check_users.sh diff --git a/util/nrpe/install-nrpe.sh b/util/nrpe/install-nrpe.sh new file mode 100755 index 0000000..e36ad92 --- /dev/null +++ b/util/nrpe/install-nrpe.sh @@ -0,0 +1,4 @@ +#!/bin/bash + +sudo apt-get update +sudo apt-get install nagios-nrpe-plugin -y diff --git a/util/nrpe/monitoring_scripts/check_delay_job.sh b/util/nrpe/monitoring_scripts/check_delay_job.sh new file mode 100755 index 0000000..13c89d5 --- /dev/null +++ b/util/nrpe/monitoring_scripts/check_delay_job.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +# This script takes 1 argument, the endpoint number to check. + +# Check the number of arguments and make sure it is as expected. +if [ $# -ne 1 ]; then + echo "" + echo "ERROR: Script takes exactly 1 argument, the endpoint to connect to." + echo "Sample usage: $ ./check_delayed_job 5" + echo "" + exit 1; +fi + +# Get the port by adding the endpoint number base port. +PORT=$((40000+$1)) + +URL="http://localhost:"$PORT"/sysinfo/delayed_job" +TMPFILE=`/bin/tempfile -p_PDC_` +CMD=`/usr/bin/curl -sSf $URL > $TMPFILE 2>&1` +STATUS=$? +if [ $STATUS -ne 0 ]; then + /bin/echo "UNKNOWN - For $URL got $(cat $TMPFILE)" + /bin/rm $TMPFILE + exit 3 +fi + +# Expect two lines of output from call to web server + +# first line should be Nagios message +NAGIOSMSG=`/usr/bin/head -1 $TMPFILE` +# second line should be Nagios status code +STATUSSTR=`/bin/cat $TMPFILE | /usr/bin/head -2 | /usr/bin/tail -1` +/bin/rm $TMPFILE +NAGIOSSTATUS=-1 +if [ "$STATUSSTR" == "Status Code: 0" ]; then + NAGIOSSTATUS=0 +fi +if [ "$STATUSSTR" == "Status Code: 1" ]; then + NAGIOSSTATUS=1 +fi +if [ "$STATUSSTR" == "Status Code: 2" ]; then + NAGIOSSTATUS=2 +fi +if [ "$STATUSSTR" == "Status Code: 3" ]; then + NAGIOSSTATUS=3 +fi +if [ "$NAGIOSSTATUS" -ge 0 -a "$NAGIOSSTATUS" -le 3 ]; then + echo $NAGIOSMSG + exit $NAGIOSSTATUS +else + # shouldn't get here unless there was a completely unexpected response + /bin/echo "UNKNOWN - Unexpected response from \"$URL\". Return status $STATUS" + exit 3 +fi diff --git a/util/nrpe/monitoring_scripts/check_diskspace.sh b/util/nrpe/monitoring_scripts/check_diskspace.sh new file mode 100755 index 0000000..20aa5b9 --- /dev/null +++ b/util/nrpe/monitoring_scripts/check_diskspace.sh @@ -0,0 +1,55 @@ +#!/bin/bash + +# This script takes 1 argument, the endpoint number to check. + +# Check the number of arguments and make sure it is as expected. + +if [ $# -ne 1 ]; then + echo "" + echo "ERROR: Script takes exactly 1 argument, the endpoint to connect to." + echo "Sample usage: $ ./check_diskspace.sh 5" + echo "" + exit 1; +fi + +# Get the port by adding the endpoint number base port. +PORT=$((40000+$1)) + +URL="http://localhost:"$PORT"/sysinfo/diskspace" +TMPFILE=`/bin/tempfile -p_PDC_` +CMD=`/usr/bin/curl -sSf $URL > $TMPFILE 2>&1` +STATUS=$? +if [ $STATUS -ne 0 ]; then + /bin/echo "UNKNOWN - For $URL got $(cat $TMPFILE)" + /bin/rm $TMPFILE + exit 3 +fi + +# Expect two lines of output from call to web server + +# first line should be Nagios message +NAGIOSMSG=`/usr/bin/head -1 $TMPFILE` +# second line should be Nagios status code +STATUSSTR=`/bin/cat $TMPFILE | /usr/bin/head -2 | /usr/bin/tail -1` +/bin/rm $TMPFILE +NAGIOSSTATUS=-1 +if [ "$STATUSSTR" == "Status Code: 0" ]; then + NAGIOSSTATUS=0 +fi +if [ "$STATUSSTR" == "Status Code: 1" ]; then + NAGIOSSTATUS=1 +fi +if [ "$STATUSSTR" == "Status Code: 2" ]; then + NAGIOSSTATUS=2 +fi +if [ "$STATUSSTR" == "Status Code: 3" ]; then + NAGIOSSTATUS=3 +fi +if [ "$NAGIOSSTATUS" -ge 0 -a "$NAGIOSSTATUS" -le 3 ]; then + echo $NAGIOSMSG + exit $NAGIOSSTATUS +else + # shouldn't get here unless there was a completely unexpected response + /bin/echo "UNKNOWN - Unexpected response from \"$URL\". Return status $STATUS" + exit 3 +fi diff --git a/util/nrpe/monitoring_scripts/check_import.sh b/util/nrpe/monitoring_scripts/check_import.sh new file mode 100755 index 0000000..dc9cb41 --- /dev/null +++ b/util/nrpe/monitoring_scripts/check_import.sh @@ -0,0 +1,61 @@ +#!/bin/bash + +# This script takes 1 argument, the endpoint number to check. + +# Check the number of arguments and make sure it is as expected. + +if [ $# -ne 1 ]; then + echo "" + echo "ERROR: Script takes exactly 1 argument, the endpoint to connect to." + echo "Sample usage: $ ./check_import.sh 5" + echo "" + exit 1 +fi + +# Get the port by adding the endpoint number base port. +PORT=$((40000+$1)) + +URL="http://localhost:"$PORT"/sysinfo/import" + +TMPFILE=`/bin/tempfile -p_PDC_` + +CMD=`/usr/bin/curl -sSf $URL > $TMPFILE 2>&1` + +STATUS=$? + +if [ $STATUS -ne 0 ]; then + + /bin/echo "UNKNOWN - For $URL got $(cat $TMPFILE)" + /bin/rm $TMPFILE + exit 3 + +fi + +# Expect two lines of output from call to web server + +# first line should be Nagios message +NAGIOSMSG=`/usr/bin/head -1 $TMPFILE` +# second line should be Nagios status code +STATUSSTR=`/bin/cat $TMPFILE | /usr/bin/head -2 | /usr/bin/tail -1` +/bin/rm $TMPFILE +NAGIOSSTATUS=-1 +if [ "$STATUSSTR" == "Status Code: 0" ]; then + NAGIOSSTATUS=0 +fi +if [ "$STATUSSTR" == "Status Code: 1" ]; then + NAGIOSSTATUS=1 +fi +if [ "$STATUSSTR" == "Status Code: 2" ]; then + NAGIOSSTATUS=2 +fi +if [ "$STATUSSTR" == "Status Code: 3" ]; then + NAGIOSSTATUS=3 +fi +if [ "$NAGIOSSTATUS" -ge 0 -a "$NAGIOSSTATUS" -le 3 ]; then + echo $NAGIOSMSG + exit $NAGIOSSTATUS +else + # shouldn't get here unless there was a completely unexpected response + /bin/echo "UNKNOWN - Unexpected response from \"$URL\". Return status $STATUS" + exit 3 +fi diff --git a/util/nrpe/monitoring_scripts/check_load.sh b/util/nrpe/monitoring_scripts/check_load.sh new file mode 100755 index 0000000..108fbc2 --- /dev/null +++ b/util/nrpe/monitoring_scripts/check_load.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +# This script takes 1 argument, the endpoint number to check. + +# Check the number of arguments and make sure it is as expected. + +if [ $# -ne 1 ]; then + echo "" + echo "ERROR: Script takes exactly 1 argument, the endpoint to connect to." + echo "Sample usage: $ ./check_load.sh 5" + echo "" + exit 1; +fi + +# Get the port by adding the endpoint number base port. +PORT=$((40000+$1)) + +URL="http://localhost:"$PORT"/sysinfo/load" +TMPFILE=`/bin/tempfile -p_PDC_` +CMD=`/usr/bin/curl -sSf $URL > $TMPFILE 2>&1` +STATUS=$? + +if [ $STATUS -ne 0 ]; then + /bin/echo "UNKNOWN - For $URL got $(cat $TMPFILE)" + /bin/rm $TMPFILE + exit 3 +fi + +# Expect two lines of output from call to web server + +# first line should be Nagios message +NAGIOSMSG=`/usr/bin/head -1 $TMPFILE` +# second line should be Nagios status code +STATUSSTR=`/bin/cat $TMPFILE | /usr/bin/head -2 | /usr/bin/tail -1` +/bin/rm $TMPFILE +NAGIOSSTATUS=-1 +if [ "$STATUSSTR" == "Status Code: 0" ]; then + NAGIOSSTATUS=0 +fi +if [ "$STATUSSTR" == "Status Code: 1" ]; then + NAGIOSSTATUS=1 +fi +if [ "$STATUSSTR" == "Status Code: 2" ]; then + NAGIOSSTATUS=2 +fi +if [ "$STATUSSTR" == "Status Code: 3" ]; then + NAGIOSSTATUS=3 +fi +if [ "$NAGIOSSTATUS" -ge 0 -a "$NAGIOSSTATUS" -le 3 ]; then + echo $NAGIOSMSG + exit $NAGIOSSTATUS +else + # shouldn't get here unless there was a completely unexpected response + /bin/echo "UNKNOWN - Unexpected response from \"$URL\". Return status $STATUS" + exit 3 +fi diff --git a/util/nrpe/monitoring_scripts/check_processes.sh b/util/nrpe/monitoring_scripts/check_processes.sh new file mode 100755 index 0000000..9e5e4e3 --- /dev/null +++ b/util/nrpe/monitoring_scripts/check_processes.sh @@ -0,0 +1,54 @@ +#!/bin/bash + +# This script takes 1 argument, the endpoint number to check. + +# Check the number of arguments and make sure it is as expected. +if [ $# -ne 1 ]; then + echo "" + echo "ERROR: Script takes exactly 1 argument, the endpoint to connect to." + echo "Sample usage: $ ./check_processes.sh 5" + echo "" + exit 1; +fi + + +# Get the port by adding the endpoint number base port. +PORT=$((40000+$1)) + +URL="http://localhost:"$PORT"/sysinfo/processes" +TMPFILE=`/bin/tempfile` + +# Expect two lines of output from call to web server +CMD=`/usr/bin/curl -sSf $URL > $TMPFILE 2>&1` +STATUS=$? +if [ $STATUS -ne 0 ]; then + /bin/echo "UNKNOWN - For $URL got $(cat $TMPFILE)" + /bin/rm $TMPFILE + exit 3 +fi +# first line should be Nagios message +NAGIOSMSG=`/usr/bin/head -1 $TMPFILE` +# second line should be Nagios status code +STATUSSTR=`/bin/cat $TMPFILE | /usr/bin/head -2 | /usr/bin/tail -1` +/bin/rm $TMPFILE +NAGIOSSTATUS=-1 +if [ "$STATUSSTR" == "Status Code: 0" ]; then + NAGIOSSTATUS=0 +fi +if [ "$STATUSSTR" == "Status Code: 1" ]; then + NAGIOSSTATUS=1 +fi +if [ "$STATUSSTR" == "Status Code: 2" ]; then + NAGIOSSTATUS=2 +fi +if [ "$STATUSSTR" == "Status Code: 3" ]; then + NAGIOSSTATUS=3 +fi +if [ "$NAGIOSSTATUS" -ge 0 -a "$NAGIOSSTATUS" -le 3 ]; then + echo $NAGIOSMSG + exit $NAGIOSSTATUS +else + # shouldn't get here unless there was a completely unexpected response + /bin/echo "UNKNOWN - Unexpected response from \"$URL\". Return status $STATUS" + exit 3 +fi diff --git a/util/nrpe/monitoring_scripts/check_swap.sh b/util/nrpe/monitoring_scripts/check_swap.sh new file mode 100755 index 0000000..c04671e --- /dev/null +++ b/util/nrpe/monitoring_scripts/check_swap.sh @@ -0,0 +1,55 @@ +#!/bin/bash + +# This script takes 1 argument, the endpoint number to check. + +# Check the number of arguments and make sure it is as expected. + +if [ $# -ne 1 ]; then + echo "" + echo "ERROR: Script takes exactly 1 argument, the endpoint to connect to." + echo "Sample usage: $ ./check_swap.sh 5" + echo "" + exit 1 +fi + +# Get the port by adding the endpoint number base port. +PORT=$((40000+$1)) + +URL="http://localhost:"$PORT"/sysinfo/swap" +TMPFILE=`/bin/tempfile -p_PDC_` +CMD=`/usr/bin/curl -sSf $URL > $TMPFILE 2>&1` +STATUS=$? + +if [ $STATUS -ne 0 ]; then + /bin/echo "UNKNOWN - For $URL got $(cat $TMPFILE)" + /bin/rm $TMPFILE + exit 3 +fi + +# Expect two lines of output from call to web server +# first line should be Nagios message +NAGIOSMSG=`/usr/bin/head -1 $TMPFILE` +# second line should be Nagios status code +STATUSSTR=`/bin/cat $TMPFILE | /usr/bin/head -2 | /usr/bin/tail -1` +/bin/rm $TMPFILE +NAGIOSSTATUS=-1 +if [ "$STATUSSTR" == "Status Code: 0" ]; then + NAGIOSSTATUS=0 +fi +if [ "$STATUSSTR" == "Status Code: 1" ]; then + NAGIOSSTATUS=1 +fi +if [ "$STATUSSTR" == "Status Code: 2" ]; then + NAGIOSSTATUS=2 +fi +if [ "$STATUSSTR" == "Status Code: 3" ]; then + NAGIOSSTATUS=3 +fi +if [ "$NAGIOSSTATUS" -ge 0 -a "$NAGIOSSTATUS" -le 3 ]; then + echo $NAGIOSMSG + exit $NAGIOSSTATUS +else + # shouldn't get here unless there was a completely unexpected response + /bin/echo "UNKNOWN - Unexpected response from \"$URL\". Return status $STATUS" + exit 3 +fi diff --git a/util/nrpe/monitoring_scripts/check_tomcat.sh b/util/nrpe/monitoring_scripts/check_tomcat.sh new file mode 100755 index 0000000..bfaf375 --- /dev/null +++ b/util/nrpe/monitoring_scripts/check_tomcat.sh @@ -0,0 +1,56 @@ +#!/bin/bash + +# This script takes 1 argument, the endpoint number to check. + +# Check the number of arguments and make sure it is as expected. + +if [ $# -ne 1 ]; then + echo "" + echo "ERROR: Script takes exactly 1 argument, the endpoint to connect to." + echo "Sample usage: $ ./check_tomcat.sh 5" + echo "" + exit 1 +fi + +# Get the port by adding the endpoint number base port. +PORT=$((40000+$1)) + +URL="http://localhost:"$PORT"/sysinfo/tomcat" + +TMPFILE=`/bin/tempfile -p_PDC_` +CMD=`/usr/bin/curl -sSf $URL > $TMPFILE 2>&1` +STATUS=$? + +if [ $STATUS -ne 0 ]; then + /bin/echo "UNKNOWN - For $URL got $(cat $TMPFILE)" + /bin/rm $TMPFILE + exit 3 +fi + +# Expect two lines of output from call to web server +# first line should be Nagios message +NAGIOSMSG=`/usr/bin/head -1 $TMPFILE` +# second line should be Nagios status code +STATUSSTR=`/bin/cat $TMPFILE | /usr/bin/head -2 | /usr/bin/tail -1` +/bin/rm $TMPFILE +NAGIOSSTATUS=-1 +if [ "$STATUSSTR" == "Status Code: 0" ]; then + NAGIOSSTATUS=0 +fi +if [ "$STATUSSTR" == "Status Code: 1" ]; then + NAGIOSSTATUS=1 +fi +if [ "$STATUSSTR" == "Status Code: 2" ]; then + NAGIOSSTATUS=2 +fi +if [ "$STATUSSTR" == "Status Code: 3" ]; then + NAGIOSSTATUS=3 +fi +if [ "$NAGIOSSTATUS" -ge 0 -a "$NAGIOSSTATUS" -le 3 ]; then + echo $NAGIOSMSG + exit $NAGIOSSTATUS +else + # shouldn't get here unless there was a completely unexpected response + /bin/echo "UNKNOWN - Unexpected response from \"$URL\". Return status $STATUS" + exit 3 +fi diff --git a/util/nrpe/monitoring_scripts/check_users.sh b/util/nrpe/monitoring_scripts/check_users.sh new file mode 100755 index 0000000..326fa3f --- /dev/null +++ b/util/nrpe/monitoring_scripts/check_users.sh @@ -0,0 +1,55 @@ +#!/bin/bash + +# This script takes 1 argument, the endpoint number to check. + +# Check the number of arguments and make sure it is as expected. + +if [ $# -ne 1 ]; then + echo "" + echo "ERROR: Script takes exactly 1 argument, the endpoint to connect to." + echo "Sample usage: $ ./check_users.sh 5" + echo "" + exit 1 +fi + +# Get the port by adding the endpoint number base port. +PORT=$((40000+$1)) + +URL="http://localhost:"$PORT"/sysinfo/users" + +TMPFILE=`/bin/tempfile -p_PDC_` +CMD=`/usr/bin/curl -sSf $URL > $TMPFILE 2>&1` +STATUS=$? + +if [ $STATUS -ne 0 ]; then + /bin/echo "UNKNOWN - For $URL got $(cat $TMPFILE)" + /bin/rm $TMPFILE + exit 3 +fi +# Expect two lines of output from call to web server +# first line should be Nagios message +NAGIOSMSG=`/usr/bin/head -1 $TMPFILE` +# second line should be Nagios status code +STATUSSTR=`/bin/cat $TMPFILE | /usr/bin/head -2 | /usr/bin/tail -1` +/bin/rm $TMPFILE +NAGIOSSTATUS=-1 +if [ "$STATUSSTR" == "Status Code: 0" ]; then + NAGIOSSTATUS=0 +fi +if [ "$STATUSSTR" == "Status Code: 1" ]; then + NAGIOSSTATUS=1 +fi +if [ "$STATUSSTR" == "Status Code: 2" ]; then + NAGIOSSTATUS=2 +fi +if [ "$STATUSSTR" == "Status Code: 3" ]; then + NAGIOSSTATUS=3 +fi +if [ "$NAGIOSSTATUS" -ge 0 -a "$NAGIOSSTATUS" -le 3 ]; then + echo $NAGIOSMSG + exit $NAGIOSSTATUS +else + # shouldn't get here unless there was a completely unexpected response + /bin/echo "UNKNOWN - Unexpected response from \"$URL\". Return status $STATUS" + exit 3 +fi From cb9d1d75671c20309b30e62ce1e72829b3b323f5 Mon Sep 17 00:00:00 2001 From: sdiemert Date: Tue, 13 Oct 2015 23:06:09 +0000 Subject: [PATCH 02/10] Added script to add a new command to nrpe. --- util/nrpe/add_nrpe_command.sh | 71 ++++++++++++++++++++++++++ util/nrpe/deploy_monitoring_scripts.sh | 52 +++++++++++++++++++ util/nrpe/monitoring_scripts/README.md | 11 ++++ 3 files changed, 134 insertions(+) create mode 100755 util/nrpe/add_nrpe_command.sh create mode 100755 util/nrpe/deploy_monitoring_scripts.sh create mode 100644 util/nrpe/monitoring_scripts/README.md diff --git a/util/nrpe/add_nrpe_command.sh b/util/nrpe/add_nrpe_command.sh new file mode 100755 index 0000000..ff8eeac --- /dev/null +++ b/util/nrpe/add_nrpe_command.sh @@ -0,0 +1,71 @@ +#!/bin/bash + +# This script adds a command to the NRPE service, command names must be compatible with +# the command names used by the Nagios server to access the NRPE commands. +# +# This script takes 3 arguments: $ ./add_nrpe_command.sh , for example: +# +# $ ./add_nrpe_command.sh /usr/local/lib/nagios/check_processes.sh 5 /etc/nagios/nrpe_local.cfg +# +# If the PATH_TO_NRPE_CONFIG argument is not given a default /etc/nagios/nrpe_local.cfg is used. +# +# Exit Codes for the script are: +# +# 0 - Completed noramally, command succcessfully added. +# 1 - Error due to invalid parameters +# 2 - Did not complete due to command already being installed. + +if [ $# -ne 2 ] && [ $# -ne 3 ]; then + echo "" + echo "ERROR: Invalid number of parameters to script, received "$#" parameters, expected 2 or 3". + echo "Usage: $ ./add_nrpe_command.sh " + echo "" + exit 1 +fi + +CMD_SCRIPT=$1 +EP=$2 + +if [ $# == 3 ]; then + NRPE_CONFIG=$3 +else + NRPE_CONFIG=/etc/nagios/nrpe_local.cfg +fi + +# Check that all files exist as expected. + +# Check that config file is in place. +if ! [ -w $NRPE_CONFIG ]; then + echo "ERROR: no such file: $NRPE_CONFIG" + exit 1 +fi + +# Check that nrpe script file is in place. +if ! [ -x $CMD_SCRIPT ]; then + echo "ERROR: no such file: $CMD_SCRIPT" + exit 1 +fi + +# Do some manipulation of the names. +# TODO: Update this to use PDC-XXXX naming scheme; changes need to occur on Nagios server side aswell. + +SCRIPT_NAME=$(basename $CMD_SCRIPT) +EP_NUM=$(printf "%03d" $EP) +EP_NAME="pdc"$EP_NUM +CMD_NAME=${SCRIPT_NAME%.*}"_"$EP_NAME +CMD="command["$CMD_NAME"]="$CMD_SCRIPT" "$EP + +# Check if the script is already installed. + +if grep -q $CMD_NAME $NRPE_CONFIG; then + # The command is already installed, we will not overwrite this. + # + echo "WARNING: $CMD_NAME is already in the $NRPE_CONFIG file, will not overwrite." + exit 2 +else + # The command is not already installed, will append this to the config file. + # + echo $CMD >> $NRPE_CONFIG + echo "INFO: Adding $CMD to $NRPE_CONFIG file. " + exit 0 +fi diff --git a/util/nrpe/deploy_monitoring_scripts.sh b/util/nrpe/deploy_monitoring_scripts.sh new file mode 100755 index 0000000..c66142b --- /dev/null +++ b/util/nrpe/deploy_monitoring_scripts.sh @@ -0,0 +1,52 @@ +#!/bin/bash + +# This script deploys the scripts required for NRPE to monitor endpoints. +# +# Assumptions: +# +# * This script assumes that the PDC composer code is deployed within the /app directory of this host. +# +# In summary this script: +# +# 1) Creates (or clears) the directory /usr/local/lib/nagios/ +# 2) Copies the monitoring scripts from ./monitoring_scripts/ into /usr/local/lib/nagios/ +# 3) Sets up commands in /etc/nagios/nrpe_local.cfg to use the scripts. +# 4) Restarts the NRPE server. +# +# This scripts takes a list of endpoint id's to deploy monitoring for example: +# +# $ deploy_monitoring_scripts.sh 1 2 3 4 5 +# +# Will set up the scripts for endpoints 1 through 5 + +# Set up some variables + +BASE_DIR=/app/util/nrpe/ +SCRIPT_DEPLOY_DIR=/usr/local/lib/nagios +NRPE_CFG_FILE=/etc/nagios/nrpe_local.cfg + +# 1) Remove any existing scripts within the /usr/local/lib/nagios/ directory. + +rm -rf $SCRIPT_DEPLOY_DIR + +mkdir -p $SCRIPT_DEPLOY_DIR + +# 2) Copy in the default scripts from within the ./monitoring_scripts/ directory. + +cp -r $BASE_DIR""monitoring_scripts/* $SCRIPT_DEPLOY_DIR + +# 3) Set up the commands in /etc/nagios/nrpe_local.cfg, we use another script to support this. + +for ep in $@ #gets all arguments to the script. +do + echo "Configuring scripts for endpoint: "$ep + + for f in $SCRIPT_DEPLOY_DIR/* #get all executable filese + do + if [[ -x $f ]]; then + ./add_nrpe_command.sh $NRPE_CFG_FILE $f $ep + fi + done +done + +exit 0 diff --git a/util/nrpe/monitoring_scripts/README.md b/util/nrpe/monitoring_scripts/README.md new file mode 100644 index 0000000..583dfc8 --- /dev/null +++ b/util/nrpe/monitoring_scripts/README.md @@ -0,0 +1,11 @@ +## NRPE Monitoring Scripts + +Each of these scripts makes a call to the endpoint to request information about that system's health. + +Each script should take exactly 1 argument and must be executable, the endpont number make the request to, for example: + +`./check_processes.sh 4` + +Will check the number of processes running on the PDC-0004 endpoint. + +Any modications to this paradigm (1 argument) will require adjustments to the scripts that manage this scripts, in the parent directory. From 0ec0add71b10a8f2e0116dea63f051ae161d1859 Mon Sep 17 00:00:00 2001 From: sdiemert Date: Tue, 13 Oct 2015 23:33:02 +0000 Subject: [PATCH 03/10] Updated install script --- util/nrpe/deploy_monitoring_scripts.sh | 40 +++++++++++++++++++++++++- util/nrpe/install-nrpe.sh | 17 +++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/util/nrpe/deploy_monitoring_scripts.sh b/util/nrpe/deploy_monitoring_scripts.sh index c66142b..233252b 100755 --- a/util/nrpe/deploy_monitoring_scripts.sh +++ b/util/nrpe/deploy_monitoring_scripts.sh @@ -1,6 +1,8 @@ #!/bin/bash # This script deploys the scripts required for NRPE to monitor endpoints. +# +# !!!!!!!!!!!!!!!!! THIS SCRIPT WILL REMOVE ANY EXISTING NRPE CONFIGURATIONS !!!!!!!!!!!!!!!!!!!!!!! # # Assumptions: # @@ -19,6 +21,22 @@ # # Will set up the scripts for endpoints 1 through 5 +echo "" +echo "" +echo "---------------------------------------------------" +echo "THIS SCRIPT WILL REMOVE ANY EXISTING NRPE CONFIGURATIONS" +read -p "Press ENTER to continue, CTRL-C to halt." +echo "---------------------------------------------------" +echo "" +echo "" + +if [ $# == 0 ]; then + echo "ERROR: This script takes endpoint number arguments, $# were provided, exiting..." + echo "" + exit 1 + +fi + # Set up some variables BASE_DIR=/app/util/nrpe/ @@ -37,16 +55,36 @@ cp -r $BASE_DIR""monitoring_scripts/* $SCRIPT_DEPLOY_DIR # 3) Set up the commands in /etc/nagios/nrpe_local.cfg, we use another script to support this. +# 3.1) Remove existing config file + +rm -rf $NRPE_CFG_FILE +touch $NRPE_CFG_FILE + for ep in $@ #gets all arguments to the script. do + echo "" echo "Configuring scripts for endpoint: "$ep + echo "---------------------------------" for f in $SCRIPT_DEPLOY_DIR/* #get all executable filese do if [[ -x $f ]]; then - ./add_nrpe_command.sh $NRPE_CFG_FILE $f $ep + ./add_nrpe_command.sh $f $ep $NRPE_CFG_FILE fi done + echo "================================" done +# 4) Restart nagios-nrpe server + +echo "" +echo "Restarting NRPE Server: " +echo "------------------------" + +sudo service nagios-nrpe-server restart + +echo "" +echo "-----------------------" +echo "All Done, Exiting..." + exit 0 diff --git a/util/nrpe/install-nrpe.sh b/util/nrpe/install-nrpe.sh index e36ad92..1f14893 100755 --- a/util/nrpe/install-nrpe.sh +++ b/util/nrpe/install-nrpe.sh @@ -1,4 +1,21 @@ #!/bin/bash +NRPE_PORT=3010 +NRPE_CONFIG=/etc/nagios/nrpe.cfg + +# install the NRPE service + sudo apt-get update sudo apt-get install nagios-nrpe-plugin -y + +# Set the port for NRPE to listen on: + +sed -i 's/server_port=[0-9]\+/server_port='$NRPE_PORT'/g' $NRPE_CONFIG + +# Make the /usr/local/lib/nagios directory for storing plugin scripts + +mkdir -p /usr/local/lib/nagios + +# Make a nrpe_local.cfg file if it does not already exist + +touch /etc/nagios/nrpe_local.cfg From 2bcce3288d2544a600202c59180070bee1315f2e Mon Sep 17 00:00:00 2001 From: sdiemert Date: Tue, 13 Oct 2015 23:43:33 +0000 Subject: [PATCH 04/10] updated Dockerfile to use NRPE. --- Dockerfile | 1 + util/nrpe/endpoints.txt | 1 + util/nrpe/install-nrpe.sh | 14 ++++++++++++++ 3 files changed, 16 insertions(+) create mode 100644 util/nrpe/endpoints.txt diff --git a/Dockerfile b/Dockerfile index 7ebf9e5..92d9a89 100644 --- a/Dockerfile +++ b/Dockerfile @@ -42,6 +42,7 @@ RUN ( \ echo "fi"; \ echo "chown -R autossh:autossh /home/autossh/.ssh/"; \ echo ""; \ + echo "/app/util/install-nrpe.sh"; \ echo ""; \ echo "# Start service"; \ echo "#"; \ diff --git a/util/nrpe/endpoints.txt b/util/nrpe/endpoints.txt new file mode 100644 index 0000000..93a4845 --- /dev/null +++ b/util/nrpe/endpoints.txt @@ -0,0 +1 @@ +1 2 3 4 diff --git a/util/nrpe/install-nrpe.sh b/util/nrpe/install-nrpe.sh index 1f14893..028d8c4 100755 --- a/util/nrpe/install-nrpe.sh +++ b/util/nrpe/install-nrpe.sh @@ -1,5 +1,7 @@ #!/bin/bash +PWD=$(pwd) + NRPE_PORT=3010 NRPE_CONFIG=/etc/nagios/nrpe.cfg @@ -19,3 +21,15 @@ mkdir -p /usr/local/lib/nagios # Make a nrpe_local.cfg file if it does not already exist touch /etc/nagios/nrpe_local.cfg + +# Move into the working directory + +cd /app/util/nrpe/ + +# Use the file endpoints.txt as a list of endpoint numbers to use. + +./deploy_monitoring_scripts.sh $(cat endpoints.txt) + +# Move back to original directory + +cd $PWD From 256e72261803f62f51ca5b7b9c0d842e4db25440 Mon Sep 17 00:00:00 2001 From: Fieran Mason Date: Fri, 16 Oct 2015 19:46:39 +0000 Subject: [PATCH 05/10] retroImporter added --- installed --- .../node_modules/mongodb/HISTORY.md | 1218 ++ .../node_modules/mongodb/LICENSE | 201 + .../node_modules/mongodb/Makefile | 11 + .../node_modules/mongodb/README.md | 322 + util/retroImporter/node_modules/mongodb/c.js | 24 + .../node_modules/mongodb/conf.json | 69 + .../node_modules/mongodb/index.js | 47 + .../node_modules/mongodb/lib/admin.js | 581 + .../mongodb/lib/aggregation_cursor.js | 432 + .../node_modules/mongodb/lib/apm.js | 571 + .../node_modules/mongodb/lib/bulk/common.js | 393 + .../node_modules/mongodb/lib/bulk/ordered.js | 532 + .../mongodb/lib/bulk/unordered.js | 541 + .../node_modules/mongodb/lib/collection.js | 3128 +++++ .../mongodb/lib/command_cursor.js | 296 + .../node_modules/mongodb/lib/cursor.js | 1149 ++ .../node_modules/mongodb/lib/db.js | 1731 +++ .../node_modules/mongodb/lib/gridfs/chunk.js | 237 + .../mongodb/lib/gridfs/grid_store.js | 1919 +++ .../node_modules/mongodb/lib/metadata.js | 64 + .../node_modules/mongodb/lib/mongo_client.js | 463 + .../node_modules/mongodb/lib/mongos.js | 491 + .../mongodb/lib/read_preference.js | 104 + .../node_modules/mongodb/lib/replset.js | 555 + .../node_modules/mongodb/lib/server.js | 437 + .../node_modules/mongodb/lib/topology_base.js | 152 + .../node_modules/mongodb/lib/url_parser.js | 295 + .../node_modules/mongodb/lib/utils.js | 234 + .../node_modules/mongodb/load.js | 32 + .../node_modules/es6-promise/CHANGELOG.md | 9 + .../mongodb/node_modules/es6-promise/LICENSE | 19 + .../node_modules/es6-promise/README.md | 61 + .../es6-promise/dist/es6-promise.js | 957 ++ .../es6-promise/dist/es6-promise.min.js | 9 + .../es6-promise/dist/test/browserify.js | 11631 ++++++++++++++++ .../es6-promise/dist/test/es6-promise.js | 950 ++ .../es6-promise/dist/test/es6-promise.min.js | 1 + .../es6-promise/dist/test/index.html | 25 + .../es6-promise/dist/test/json3.js | 902 ++ .../es6-promise/dist/test/mocha.css | 270 + .../es6-promise/dist/test/mocha.js | 6095 ++++++++ .../es6-promise/dist/test/worker.js | 16 + .../es6-promise/lib/es6-promise.umd.js | 18 + .../es6-promise/lib/es6-promise/-internal.js | 250 + .../es6-promise/lib/es6-promise/asap.js | 111 + .../es6-promise/lib/es6-promise/enumerator.js | 113 + .../es6-promise/lib/es6-promise/polyfill.js | 26 + .../es6-promise/lib/es6-promise/promise.js | 408 + .../lib/es6-promise/promise/all.js | 52 + .../lib/es6-promise/promise/race.js | 104 + .../lib/es6-promise/promise/reject.js | 46 + .../lib/es6-promise/promise/resolve.js | 48 + .../es6-promise/lib/es6-promise/utils.js | 22 + .../node_modules/es6-promise/package.json | 88 + .../node_modules/mongodb-core/HISTORY.md | 246 + .../mongodb/node_modules/mongodb-core/LICENSE | 201 + .../node_modules/mongodb-core/Makefile | 11 + .../node_modules/mongodb-core/README.md | 225 + .../node_modules/mongodb-core/TESTING.md | 18 + .../node_modules/mongodb-core/conf.json | 60 + .../node_modules/mongodb-core/index.js | 18 + .../mongodb-core/lib/auth/gssapi.js | 244 + .../mongodb-core/lib/auth/mongocr.js | 160 + .../mongodb-core/lib/auth/plain.js | 150 + .../mongodb-core/lib/auth/scram.js | 317 + .../mongodb-core/lib/auth/sspi.js | 234 + .../mongodb-core/lib/auth/x509.js | 145 + .../mongodb-core/lib/connection/commands.js | 519 + .../mongodb-core/lib/connection/connection.js | 462 + .../mongodb-core/lib/connection/logger.js | 196 + .../mongodb-core/lib/connection/pool.js | 275 + .../mongodb-core/lib/connection/utils.js | 77 + .../node_modules/mongodb-core/lib/cursor.js | 756 + .../node_modules/mongodb-core/lib/error.js | 44 + .../mongodb-core/lib/tools/smoke_plugin.js | 59 + .../lib/topologies/command_result.js | 37 + .../mongodb-core/lib/topologies/mongos.js | 1000 ++ .../lib/topologies/read_preference.js | 106 + .../mongodb-core/lib/topologies/replset.js | 1333 ++ .../lib/topologies/replset_state.js | 483 + .../mongodb-core/lib/topologies/server.js | 1230 ++ .../mongodb-core/lib/topologies/session.js | 93 + .../lib/topologies/strategies/ping.js | 276 + .../lib/wireprotocol/2_4_support.js | 559 + .../lib/wireprotocol/2_6_support.js | 291 + .../lib/wireprotocol/3_2_support.js | 494 + .../mongodb-core/lib/wireprotocol/commands.js | 357 + .../mongodb-core/node_modules/bson/HISTORY | 113 + .../mongodb-core/node_modules/bson/LICENSE | 201 + .../mongodb-core/node_modules/bson/README.md | 69 + .../bson/alternate_parsers/bson.js | 1574 +++ .../bson/alternate_parsers/faster_bson.js | 429 + .../node_modules/bson/browser_build/bson.js | 4843 +++++++ .../bson/browser_build/package.json | 8 + .../node_modules/bson/lib/bson/binary.js | 344 + .../bson/lib/bson/binary_parser.js | 385 + .../node_modules/bson/lib/bson/bson.js | 323 + .../node_modules/bson/lib/bson/code.js | 24 + .../node_modules/bson/lib/bson/db_ref.js | 32 + .../node_modules/bson/lib/bson/double.js | 33 + .../bson/lib/bson/float_parser.js | 121 + .../node_modules/bson/lib/bson/index.js | 86 + .../node_modules/bson/lib/bson/long.js | 856 ++ .../node_modules/bson/lib/bson/map.js | 126 + .../node_modules/bson/lib/bson/max_key.js | 14 + .../node_modules/bson/lib/bson/min_key.js | 14 + .../node_modules/bson/lib/bson/objectid.js | 273 + .../bson/lib/bson/parser/calculate_size.js | 310 + .../bson/lib/bson/parser/deserializer.js | 544 + .../bson/lib/bson/parser/serializer.js | 909 ++ .../node_modules/bson/lib/bson/regexp.js | 30 + .../node_modules/bson/lib/bson/symbol.js | 47 + .../node_modules/bson/lib/bson/timestamp.js | 856 ++ .../node_modules/bson/package.json | 70 + .../node_modules/bson/tools/gleak.js | 21 + .../node_modules/kerberos/.travis.yml | 20 + .../node_modules/kerberos/LICENSE | 201 + .../node_modules/kerberos/README.md | 4 + .../node_modules/kerberos/binding.gyp | 46 + .../node_modules/kerberos/build/Makefile | 324 + .../Release/.deps/Release/kerberos.node.d | 1 + .../.deps/Release/obj.target/kerberos.node.d | 1 + .../obj.target/kerberos/lib/base64.o.d | 4 + .../obj.target/kerberos/lib/kerberos.o.d | 71 + .../kerberos/lib/kerberos_context.o.d | 70 + .../obj.target/kerberos/lib/kerberosgss.o.d | 16 + .../obj.target/kerberos/lib/worker.o.d | 57 + .../kerberos/build/Release/kerberos.node | Bin 0 -> 85259 bytes .../build/Release/obj.target/kerberos.node | Bin 0 -> 85259 bytes .../Release/obj.target/kerberos/lib/base64.o | Bin 0 -> 4176 bytes .../obj.target/kerberos/lib/kerberos.o | Bin 0 -> 86232 bytes .../kerberos/lib/kerberos_context.o | Bin 0 -> 31808 bytes .../obj.target/kerberos/lib/kerberosgss.o | Bin 0 -> 19608 bytes .../Release/obj.target/kerberos/lib/worker.o | Bin 0 -> 2720 bytes .../kerberos/build/binding.Makefile | 6 + .../node_modules/kerberos/build/config.gypi | 138 + .../kerberos/build/kerberos.target.mk | 151 + .../node_modules/kerberos/builderror.log | 25 + .../node_modules/kerberos/index.js | 6 + .../kerberos/lib/auth_processes/mongodb.js | 281 + .../node_modules/kerberos/lib/base64.c | 134 + .../node_modules/kerberos/lib/base64.h | 22 + .../node_modules/kerberos/lib/kerberos.cc | 893 ++ .../node_modules/kerberos/lib/kerberos.h | 50 + .../node_modules/kerberos/lib/kerberos.js | 164 + .../kerberos/lib/kerberos_context.cc | 134 + .../kerberos/lib/kerberos_context.h | 64 + .../node_modules/kerberos/lib/kerberosgss.c | 931 ++ .../node_modules/kerberos/lib/kerberosgss.h | 73 + .../node_modules/kerberos/lib/sspi.js | 15 + .../node_modules/kerberos/lib/win32/base64.c | 121 + .../node_modules/kerberos/lib/win32/base64.h | 18 + .../kerberos/lib/win32/kerberos.cc | 51 + .../kerberos/lib/win32/kerberos.h | 60 + .../kerberos/lib/win32/kerberos_sspi.c | 244 + .../kerberos/lib/win32/kerberos_sspi.h | 106 + .../node_modules/kerberos/lib/win32/worker.cc | 7 + .../node_modules/kerberos/lib/win32/worker.h | 38 + .../lib/win32/wrappers/security_buffer.cc | 101 + .../lib/win32/wrappers/security_buffer.h | 48 + .../lib/win32/wrappers/security_buffer.js | 12 + .../wrappers/security_buffer_descriptor.cc | 182 + .../wrappers/security_buffer_descriptor.h | 46 + .../wrappers/security_buffer_descriptor.js | 3 + .../lib/win32/wrappers/security_context.cc | 856 ++ .../lib/win32/wrappers/security_context.h | 74 + .../lib/win32/wrappers/security_context.js | 3 + .../win32/wrappers/security_credentials.cc | 348 + .../lib/win32/wrappers/security_credentials.h | 68 + .../win32/wrappers/security_credentials.js | 22 + .../node_modules/kerberos/lib/worker.cc | 7 + .../node_modules/kerberos/lib/worker.h | 38 + .../kerberos/node_modules/nan/.dntrc | 30 + .../kerberos/node_modules/nan/CHANGELOG.md | 374 + .../kerberos/node_modules/nan/LICENSE.md | 13 + .../kerberos/node_modules/nan/README.md | 367 + .../kerberos/node_modules/nan/appveyor.yml | 38 + .../kerberos/node_modules/nan/doc/.build.sh | 38 + .../node_modules/nan/doc/asyncworker.md | 97 + .../kerberos/node_modules/nan/doc/buffers.md | 54 + .../kerberos/node_modules/nan/doc/callback.md | 52 + .../node_modules/nan/doc/converters.md | 41 + .../kerberos/node_modules/nan/doc/errors.md | 226 + .../node_modules/nan/doc/maybe_types.md | 480 + .../kerberos/node_modules/nan/doc/methods.md | 624 + .../kerberos/node_modules/nan/doc/new.md | 141 + .../node_modules/nan/doc/node_misc.md | 114 + .../node_modules/nan/doc/persistent.md | 292 + .../kerberos/node_modules/nan/doc/scopes.md | 73 + .../kerberos/node_modules/nan/doc/script.md | 38 + .../node_modules/nan/doc/string_bytes.md | 62 + .../node_modules/nan/doc/v8_internals.md | 199 + .../kerberos/node_modules/nan/doc/v8_misc.md | 63 + .../kerberos/node_modules/nan/include_dirs.js | 1 + .../kerberos/node_modules/nan/nan.h | 2136 +++ .../kerberos/node_modules/nan/nan_callbacks.h | 88 + .../node_modules/nan/nan_callbacks_12_inl.h | 512 + .../nan/nan_callbacks_pre_12_inl.h | 506 + .../node_modules/nan/nan_converters.h | 64 + .../node_modules/nan/nan_converters_43_inl.h | 42 + .../nan/nan_converters_pre_43_inl.h | 42 + .../nan/nan_implementation_12_inl.h | 399 + .../nan/nan_implementation_pre_12_inl.h | 259 + .../node_modules/nan/nan_maybe_43_inl.h | 224 + .../node_modules/nan/nan_maybe_pre_43_inl.h | 295 + .../kerberos/node_modules/nan/nan_new.h | 332 + .../node_modules/nan/nan_object_wrap.h | 155 + .../node_modules/nan/nan_persistent_12_inl.h | 129 + .../nan/nan_persistent_pre_12_inl.h | 238 + .../node_modules/nan/nan_string_bytes.h | 305 + .../kerberos/node_modules/nan/nan_weak.h | 422 + .../kerberos/node_modules/nan/package.json | 92 + .../kerberos/node_modules/nan/tools/1to2.js | 412 + .../kerberos/node_modules/nan/tools/README.md | 14 + .../node_modules/nan/tools/package.json | 19 + .../node_modules/kerberos/package.json | 55 + .../kerberos/test/kerberos_tests.js | 34 + .../kerberos/test/kerberos_win32_test.js | 15 + .../win32/security_buffer_descriptor_tests.js | 41 + .../test/win32/security_buffer_tests.js | 22 + .../test/win32/security_credentials_tests.js | 55 + .../node_modules/mongodb-core/package.json | 66 + .../simple_2_document_limit_toArray.dat | 11000 +++++++++++++++ .../node_modules/readable-stream/.npmignore | 5 + .../node_modules/readable-stream/LICENSE | 27 + .../node_modules/readable-stream/README.md | 15 + .../node_modules/readable-stream/duplex.js | 1 + .../readable-stream/lib/_stream_duplex.js | 89 + .../lib/_stream_passthrough.js | 46 + .../readable-stream/lib/_stream_readable.js | 982 ++ .../readable-stream/lib/_stream_transform.js | 210 + .../readable-stream/lib/_stream_writable.js | 386 + .../node_modules/core-util-is/README.md | 3 + .../node_modules/core-util-is/float.patch | 604 + .../node_modules/core-util-is/lib/util.js | 107 + .../node_modules/core-util-is/package.json | 53 + .../node_modules/core-util-is/util.js | 106 + .../node_modules/inherits/LICENSE | 16 + .../node_modules/inherits/README.md | 42 + .../node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../node_modules/inherits/package.json | 50 + .../node_modules/inherits/test.js | 25 + .../node_modules/isarray/README.md | 54 + .../node_modules/isarray/build/build.js | 209 + .../node_modules/isarray/component.json | 19 + .../node_modules/isarray/index.js | 3 + .../node_modules/isarray/package.json | 53 + .../node_modules/string_decoder/.npmignore | 2 + .../node_modules/string_decoder/LICENSE | 20 + .../node_modules/string_decoder/README.md | 7 + .../node_modules/string_decoder/index.js | 221 + .../node_modules/string_decoder/package.json | 54 + .../node_modules/readable-stream/package.json | 69 + .../readable-stream/passthrough.js | 1 + .../node_modules/readable-stream/readable.js | 6 + .../node_modules/readable-stream/transform.js | 1 + .../node_modules/readable-stream/writable.js | 1 + .../node_modules/mongodb/package.json | 66 + util/retroImporter/node_modules/mongodb/t.js | 73 + util/retroImporter/node_modules/mongodb/t1.js | 77 + .../node_modules/mongodb/wercker.yml | 19 + util/retroImporter/package.json | 15 + util/retroImporter/retroImporter.js | 203 + 264 files changed, 93500 insertions(+) create mode 100644 util/retroImporter/node_modules/mongodb/HISTORY.md create mode 100644 util/retroImporter/node_modules/mongodb/LICENSE create mode 100644 util/retroImporter/node_modules/mongodb/Makefile create mode 100644 util/retroImporter/node_modules/mongodb/README.md create mode 100644 util/retroImporter/node_modules/mongodb/c.js create mode 100644 util/retroImporter/node_modules/mongodb/conf.json create mode 100644 util/retroImporter/node_modules/mongodb/index.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/admin.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/aggregation_cursor.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/apm.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/bulk/common.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/bulk/ordered.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/bulk/unordered.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/collection.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/command_cursor.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/cursor.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/db.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/gridfs/chunk.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/gridfs/grid_store.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/metadata.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/mongo_client.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/mongos.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/read_preference.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/replset.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/server.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/topology_base.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/url_parser.js create mode 100644 util/retroImporter/node_modules/mongodb/lib/utils.js create mode 100644 util/retroImporter/node_modules/mongodb/load.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/browserify.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/index.html create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/index.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Makefile create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d create mode 100755 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node create mode 100755 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos.node create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml create mode 100755 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/asyncworker.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/buffers.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/callback.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/converters.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/errors.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/maybe_types.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/methods.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/new.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/node_misc.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/persistent.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/scopes.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/script.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/string_bytes.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/v8_internals.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/v8_misc.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/include_dirs.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks_12_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks_pre_12_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters_43_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters_pre_43_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_maybe_43_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_maybe_pre_43_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_new.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_object_wrap.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_persistent_12_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_persistent_pre_12_inl.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_string_bytes.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_weak.h create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/package.json create mode 100755 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/1to2.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/package.json create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/readable.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/transform.js create mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/writable.js create mode 100644 util/retroImporter/node_modules/mongodb/package.json create mode 100644 util/retroImporter/node_modules/mongodb/t.js create mode 100644 util/retroImporter/node_modules/mongodb/t1.js create mode 100644 util/retroImporter/node_modules/mongodb/wercker.yml create mode 100644 util/retroImporter/package.json create mode 100644 util/retroImporter/retroImporter.js diff --git a/util/retroImporter/node_modules/mongodb/HISTORY.md b/util/retroImporter/node_modules/mongodb/HISTORY.md new file mode 100644 index 0000000..4d8fd75 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/HISTORY.md @@ -0,0 +1,1218 @@ +2.0.45 09-30-2015 +----------------- +* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. + +2.0.44 09-28-2015 +----------------- +* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. +* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. +* Updated mongodb-core to 1.2.14. +* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. +* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) +* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. +* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. +* NODE-572 Remove examples that use the second parameter to `find()`. + +2.0.43 09-14-2015 +----------------- +* Propagate timeout event correctly to db instances. +* Application Monitoring API (APM) implemented. +* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. +* Updated mongodb-core to 1.2.12. +* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. +* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) +* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) +* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) + +2.0.42 08-18-2015 +----------------- +* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. + +2.0.41 08-14-2015 +----------------- +* Added missing Mongos.prototype.parserType function. +* Updated mongodb-core to 1.2.10. + +2.0.40 07-14-2015 +----------------- +* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. +* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +* NODE-518 connectTimeoutMS is doubled in 2.0.39. +* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). +* NODE-526 Unique index not throwing duplicate key error. +* NODE-528 Ignore undefined fields in Collection.find(). +* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. + +2.0.39 07-14-2015 +----------------- +* Updated mongodb-core to 1.2.6 for NODE-505. + +2.0.38 07-14-2015 +----------------- +* NODE-505 Query fails to find records that have a 'result' property with an array value. + +2.0.37 07-14-2015 +----------------- +* NODE-504 Collection * Default options when using promiseLibrary. +* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. +* Updated mongodb-core to 1.2.5 to fix NODE-492. + +2.0.36 07-07-2015 +----------------- +* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). +* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. + +2.0.35 06-17-2015 +----------------- +* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. + +2.0.34 06-17-2015 +----------------- +* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. +* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. +* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +2.0.33 05-20-2015 +----------------- +* Bumped mongodb-core to 1.1.32. + +2.0.32 05-19-2015 +----------------- +* NODE-463 db.close immediately executes its callback. +* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 05-08-2015 +----------------- +* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 05-07-2015 +----------------- +* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 05-07-2015 +----------------- +* NODE-444 Possible memory leak, too many listeners added. +* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +* Bumped mongodb-core to 1.1.26. + +2.0.28 04-24-2015 +----------------- +* Bumped mongodb-core to 1.1.25 +* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +* NODE-430 Cursor.count() opts argument masked by var opts = {} +* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +* NODE-438 replaceOne is not returning the result.ops property as described in the docs. +* NODE-433 _read, pipe and write all open gridstore automatically if not open. +* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +* Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 04-07-2015 +----------------- +* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 04-07-2015 +----------------- +* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +* NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 03-26-2015 +----------------- +* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 03-24-2015 +----------------- +* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +* Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +* NODE-380 Correctly return MongoError from toError method. +* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +* Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +* Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +* Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +* Added ~1.0 mongodb-tools module for test running. +* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +* Fixed some MongoClient.connect options pass through issues and added test coverage. +* Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +* Bumped mongodb-core to 1.1.8. +* Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +* Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +* listCollections filters out index namespaces on < 2.8 correctly +* Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +* NODE-328 fixed db.open return when no callback available issue and added test. +* NODE-327 Refactored listCollections to return cursor to support 2.8. +* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +* Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +* All classes are now strict (Issue #1233) +* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +* Fixed recursion issues in debug logging due to JSON.stringify() +* Documentation fixes (Issue #1232, https://github.com/wsmoak) +* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +* NODE-322 Finished up prototype refactoring of Db class. +* NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +* NODE-318 collection.update error while setting a function with serializeFunctions option. +* Documentation fixes. + +2.0.6 2014-11-14 +---------------- +* Refactored code to be prototype based instead of privileged methods. +* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +* Implemented missing aspects of the CRUD specification. +* Fixed documentation issues. +* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +* Minor fixes to documentation and generation of documentation. +* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +* Made each rewind on each call allowing for re-using the cursor. +* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +* NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +* Bumped mongodb-core to 1.0.2. +* Fixed bson module dependency issue by relying on the mongodb-core one. +* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +* Dependency fix + +2.0.0 2014-10-07 +---------------- +* First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +* Cluster Management Spec compatible. + +2.0.0-alpha1 2014-09-08 +----------------------- +* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + * Might break some application +* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +* Removed Grid class +* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +* Cursor toArray and each resets and re-runs the cursor +* FindAndModify returns whole result document instead of just value +* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +* Removed db.dereference method +* Removed db.cursorInfo method +* Removed db.stats method +* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +* Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +* Fixed BSON and Kerberos compilation issues +* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +* Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +* NODE-240 Operations on SSL connection hang on node 0.11.x +* NODE-235 writeResult is not being passed on when error occurs in insert +* NODE-229 Allow count to work with query hints +* NODE-233 collection.save() does not support fullResult +* NODE-244 Should parseError also emit a `disconnected` event? +* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +* NODE-248 Crash with X509 auth +* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +* Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +* NODE-205 correctly emit authenticate event +* NODE-210 ensure no undefined connection error when checking server state +* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +* NODE-220 don't throw error if ensureIndex errors out in Gridstore +* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +* Fixed test running filters +* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +* Fixed parsing issue for w:0 in url parser when in connection string +* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +* Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +* Removed leaking global variable (Issue #1174, https://github.com/dainis) +* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +* Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +* Correctly emit joined event when primary change +* Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +* All node exceptions will no longer be caught if on('error') is defined +* Added X509 auth support +* Fix for MongoClient connection timeout issue (NODE-97) +* Pass through error messages from parseError instead of just text (Issue #1125) +* Close db connection on error (Issue #1128, https://github.com/benighted) +* Fixed documentation generation +* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +* Insert/Update/Remove using new write commands when available +* Added support for new roles based API's in 2.6 for addUser/removeUser +* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +* Support for OP_LOG_REPLAY flag (NODE-94) +* Fixes for SSL HA ping and discovery. +* Uses createIndexes if available for ensureIndex/createIndex +* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +* Made CommandCursor behave as Readable stream. +* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +* Refactored commands to all go through command function ensuring consistent command execution. +* Fixed issues where readPreferences where not correctly passed to mongos. +* Catch error == null and make err detection more prominent (NODE-130) +* Allow reads from arbiter for single server connection (NODE-117) +* Handle error coming back with no documents (NODE-130) +* Correctly use close parameter in Gridstore.write() (NODE-125) +* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +* Ignore return commands that have no registered callback +* Made collection.count not use the db.command function +* Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +* Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +* Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +* BSON size checking now done pre serialization (Issue #1037) +* Added isConnected returns false when no connection Pool exists (Issue #1043) +* Unified command handling to ensure same handling (Issue #1041, #1042) +* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +* Fixed issue with Kerberos authentication on Windows for re-authentication. +* Fixed Mongos failover behavior to correctly throw out old servers. +* Ensure stored queries/write ops are executed correctly after connection timeout +* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +* Fixed bug with callback third parameter on some commands (Issue #1033) +* Fixed possible issue where killcursor command might leave hanging functions +* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +* Throw error if dbName or collection name contains null character (at command level and at collection level) +* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +* Add driver version to export (Issue #1021, https://github.com/aheckmann) +* Add text to readpreference obedient commands (Issue #1019) +* Drivers should check the query failure bit even on getmore response (Issue #1018) +* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +* Support SASL PLAIN authentication (Issue #1009) +* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +* Introduced write and read concerns for GridFS (Issue #996) +* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +* Fixed issue with pool size on replicaset connections (Issue #1000) +* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +* Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +* Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +* Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +* Applied auth before server instance is set as connected when single server connection +* Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +* Refactored test suite to speed up running of replicaset tests +* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +* Corrected a slaveOk setting issue (Issue #906, #905) +* Fixed HA issue where ping's would not go to correct server on HA server connection failure. +* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +* Fixed race condition in Cursor stream (NODE-31) +* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +* Added support for maxMessageSizeBytes if available (DRIVERS-1) +* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +* Fixed missing MongoErrors on some cursor methods (Issue #882) +* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +* Added limit/skip options to Collection.count (Issue #870) +* Added applySkipLimit option to Cursor.count (Issue #870) +* Enabled ping strategy as default for Replicaset if none specified (Issue #876) +* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +* Added fixes for handling type 2 binary due to PHP driver (Issue #864) +* Moved callBackStore to Base class to have single unified store (Issue #866) +* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +* Only open a new HA socket when previous one dead (Issue #859, #857) +* Minor fixes + +1.2.9 2013-01-15 +---------------- +* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +* Connection string with no db specified should default to admin db (Issue #848) +* Support port passed as string to Server class (Issue #844) +* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +* Included toError wrapper code moved to utils.js file (Issue #839, #840) +* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +* Rolled back batches as they hang in certain situations +* Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +* Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +* Fixed ssl regression, added more test coverage (Issue #800) +* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +* Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +* Fix for journal write concern not correctly being passed under some circumstances. +* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +* Fix for double callback on insert with w:0 specified (Issue #783) +* Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +* Force correct setting of read_secondary based on the read preference (Issue #741) +* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +* Mongos connection with auth not working (Issue #737) +* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + * open/close/db/connect methods implemented +* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +* Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +* Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +* fix Admin.serverStatus (Issue #723, https://github.com/Contra) +* logging on connection open/close(Issue #721, https://github.com/asiletto) +* more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +* Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +* Cleanup of non-closing connections (Issue #706) +* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +* Set keepalive on as default, override if not needed +* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +* Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +* Proper stopping of strategy on replicaset stop +* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +* Fix for eval on replicaset Issue #684 +* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +* Added exhaust option for find for feature completion (not recommended for normal use) +* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +* Fix gridfs readstream (Issue #607, https://github.com/tedeh). +* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +* Cleanup map reduce (Issue #614, https://github.com/aheckmann). +* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +* Date identification handled correctly in bson js parser when running in vm context. +* Documentation updates +* GridStore filename not set on read (Issue #621) +* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +* Added support for awaitdata for tailable cursors (Issue #624) +* Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +* Fixed auth to work better when multiple connections are involved. +* Default connection pool size increased to 5 connections. +* Fixes for the ReadStream class to work properly with 0.8 of Node.js +* Added explain function support to aggregation helper +* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +* Fixed Always emit db events (Issue #657) +* Close event not correctly resets DB openCalled variable to allow reconnect +* Added open event on connection established for replicaset, mongos and server +* Much faster BSON C++ parser thanks to Lucasfilm Singapore. +* Refactoring of replicaset connection logic to simplify the code. +* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +* Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +* Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +* Passing back getLastError object as 3rd parameter on findAndModify command. +* Fixed a bunch of performance regressions in objectId and cursor. +* Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +* Fixes to handling of failover on server error +* Only emits error messages if there are error listeners to avoid uncaught events +* Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +* _id=0 is being turned into an ObjectID (Issue #551) +* fix for error in GridStore write method (Issue #559) +* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +* Connection pools handles closing themselves down and clearing the state +* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +* Returning update status document at the end of the callback for updates, (Issue #569) +* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +* Stats not returned from map reduce with inline results (Issue #542) +* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +* Streaming large files from GridFS causes truncation (Issue #540) +* Make callback type checks agnostic to V8 context boundaries (Issue #545) +* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +* Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +* BSON parser is externalized in it's own repository, currently using git master +* Fixes for Replicaset connectivity issue (Issue #537) +* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +* Removed SimpleEmitter and replaced with standard EventEmitter +* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +* Fixed memory leak in C++ bson parser (Issue #526) +* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +* Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/util/retroImporter/node_modules/mongodb/LICENSE b/util/retroImporter/node_modules/mongodb/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/Makefile b/util/retroImporter/node_modules/mongodb/Makefile new file mode 100644 index 0000000..36e1202 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/util/retroImporter/node_modules/mongodb/README.md b/util/retroImporter/node_modules/mongodb/README.md new file mode 100644 index 0000000..2828713 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/README.md @@ -0,0 +1,322 @@ +[![NPM](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![NPM](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.png)](http://travis-ci.org/mongodb/node-mongodb-native) + +[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The MongoDB driver is the high level part of the 2.0 or higher MongoDB driver and is meant for end users. + +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| api-doc | http://mongodb.github.io/node-mongodb-native/2.0/api/ | +| source | https://github.com/mongodb/node-mongodb-native | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login . +- Navigate to the NODE project . +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +QuickStart +========== +The quick start guide will show you how to setup a simple application using node.js and MongoDB. Its scope is only how to set up the driver and perform the simple crud operations. For more in depth coverage we encourage reading the tutorials. + +Create the package.json file +---------------------------- +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Enter the following command and answer the questions to create the initial structure for your new project + +``` +npm init +``` + +Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init` + +``` +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb": "~2.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +Connecting to MongoDB +--------------------- +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server and the database **myproject**. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + db.close(); +}); +``` + +Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console. + +Let's Add some code to show the different CRUD operations available. + +Inserting a Document +-------------------- +Let's create a function that will insert some documents for us. + +```js +var insertDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.insert([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the document collection"); + callback(result); + }); +} +``` + +The insert command will return a results object that contains several fields that might be useful. + +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert + +Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + db.close(); + }); +}); +``` + +We can now run the update **app.js** file. + +``` +node app.js +``` + +You should see the following output after running the **app.js** file. + +``` +Connected correctly to server +Inserted 3 documents into the document collection +``` + +Updating a document +------------------- +Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**. + +```js +var updateDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.update({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} +``` + +The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + db.close(); + }); + }); +}); +``` + +Remove a document +----------------- +Next lets remove the document where the field **a** equals to **3**. + +```js +var removeDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.remove({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} +``` + +This will remove the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient.connect** callback function. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + db.close(); + }); + }); + }); +}); +``` + +Finally let's retrieve all the documents using a simple find. + +Find All Documents +------------------ +We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query. + +```js +var findDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + assert.equal(2, docs.length); + console.log("Found the following records"); + console.dir(docs); + callback(docs); + }); +} +``` + +This query will return all the documents in the **documents** collection. Since we removed a document the total documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + findDocuments(db, function() { + db.close(); + }); + }); + }); + }); +}); +``` + +This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest. + +## Next Steps + + * [MongoDB Documentation](http://mongodb.org/) + * [Read about Schemas](http://learnmongodbthehardway.com/) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) diff --git a/util/retroImporter/node_modules/mongodb/c.js b/util/retroImporter/node_modules/mongodb/c.js new file mode 100644 index 0000000..5b6bc1e --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/c.js @@ -0,0 +1,24 @@ +var MongoClient = require('./').MongoClient; + +var index = 0; + +MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { + setInterval(function() { + db = db.db("index" + index, {noListener:true}); + var collection = db.collection("index" + index); + collection.insert({a:index}) + }, 1); +}); + +// var Server = require('./').Server, +// Db = require('./').Db, +// ReadPreference = require('./').ReadPreference; +// +// new Db('test', new Server('localhost', 31001), {readPreference: ReadPreference.SECONDARY}).open(function(err, db) { +// +// db.collection('test').find().toArray(function(err, docs) { +// console.dir(err) +// console.dir(docs) +// db.close(); +// }); +// }); diff --git a/util/retroImporter/node_modules/mongodb/conf.json b/util/retroImporter/node_modules/mongodb/conf.json new file mode 100644 index 0000000..15f3021 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/conf.json @@ -0,0 +1,69 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/functional/operation_example_tests.js", + "test/functional/operation_promises_example_tests.js", + "test/functional/operation_generators_example_tests.js", + "test/functional/authentication_tests.js", + "lib/admin.js", + "lib/collection.js", + "lib/cursor.js", + "lib/aggregation_cursor.js", + "lib/command_cursor.js", + "lib/db.js", + "lib/mongo_client.js", + "lib/mongos.js", + "lib/read_preference.js", + "lib/replset.js", + "lib/server.js", + "lib/bulk/common.js", + "lib/bulk/ordered.js", + "lib/bulk/unordered.js", + "lib/gridfs/grid_store.js", + "node_modules/mongodb-core/lib/error.js", + "node_modules/mongodb-core/lib/connection/logger.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} diff --git a/util/retroImporter/node_modules/mongodb/index.js b/util/retroImporter/node_modules/mongodb/index.js new file mode 100644 index 0000000..df24555 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/index.js @@ -0,0 +1,47 @@ +// Core module +var core = require('mongodb-core'), + Instrumentation = require('./lib/apm'); + +// Set up the connect function +var connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; + +// Actual driver classes exported +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/server'); +connect.ReplSet = require('./lib/replset'); +connect.Mongos = require('./lib/mongos'); +connect.ReadPreference = require('./lib/read_preference'); +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.Cursor = require('./lib/cursor'); + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + return new Instrumentation(core, options, callback); +} + +// Set our exports to be the connect function +module.exports = connect; diff --git a/util/retroImporter/node_modules/mongodb/lib/admin.js b/util/retroImporter/node_modules/mongodb/lib/admin.js new file mode 100644 index 0000000..1f89512 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/admin.js @@ -0,0 +1,581 @@ +"use strict"; + +var toError = require('./utils').toError, + Define = require('./metadata'), + shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Use the admin database for the operation + * var adminDb = db.admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +var Admin = function(db, topology, promiseLibrary) { + if(!(this instanceof Admin)) return new Admin(db, topology); + var self = this; + + // Internal state + this.s = { + db: db + , topology: topology + , promiseLibrary: promiseLibrary + } +} + +var define = Admin.define = new Define('Admin', Admin, false); + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand(command, options, function(err, doc) { + return callback != null ? callback(err, doc) : null; + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand(command, options, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.serverInfo(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.serverInfo(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('buildInfo', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err != null) return callback(err, null); + callback(null, doc); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('serverInfo', {callback: true, promise:true}); + +/** + * Retrieve this db's server status. + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return serverStatus(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + serverStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var serverStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { + if(err == null && doc.ok === 1) { + callback(null, doc); + } else { + if(err) return callback(err, false); + return callback(toError(doc), false); + } + }); +} + +define.classMethod('serverStatus', {callback: true, promise:true}); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingLevel = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingLevel(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingLevel(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingLevel = function(self, callback) { + self.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) { + doc = doc; + + if(err == null && doc.ok === 1) { + var was = doc.was; + if(was == 0) return callback(null, "off"); + if(was == 1) return callback(null, "slow_only"); + if(was == 2) return callback(null, "all"); + return callback(new Error("Error: illegal profiling level value " + was), null); + } else { + err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + } + }); +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({ping: 1}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({ping: 1}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('ping', {callback: true, promise:true}); + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.authenticate = function(username, password, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options); + options.authdb = 'admin'; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.authenticate(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.authenticate(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.logout = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.logout({authdb: 'admin'}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.logout({authdb: 'admin'}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +// Get write concern +var writeConcern = function(options, db) { + options = shallowClone(options); + + // If options already contain write concerns return it + if(options.w || options.wtimeout || options.j || options.fsync) { + return options; + } + + // Set db write concern if available + if(db.writeConcern) { + if(options.w) options.w = db.writeConcern.w; + if(options.wtimeout) options.wtimeout = db.writeConcern.wtimeout; + if(options.j) options.j = db.writeConcern.j; + if(options.fsync) options.fsync = db.writeConcern.fsync; + } + + // Return modified options + return options; +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name to admin + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.addUser(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.addUser(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('addUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.removeUser(username, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.removeUser(username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.setProfilingLevel = function(level, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return setProfilingLevel(self, level, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + setProfilingLevel(self, level, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var setProfilingLevel = function(self, level, callback) { + var command = {}; + var profile = 0; + + if(level == "off") { + profile = 0; + } else if(level == "slow_only") { + profile = 1; + } else if(level == "all") { + profile = 2; + } else { + return callback(new Error("Error: illegal profiling level value " + level)); + } + + // Set up the profile number + command['profile'] = profile; + + self.s.db.executeDbAdminCommand(command, function(err, doc) { + doc = doc; + + if(err == null && doc.ok === 1) + return callback(null, level); + return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + }); +} + +define.classMethod('setProfilingLevel', {callback: true, promise:true}); + +/** + * Retrive the current profiling information for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingInfo = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingInfo(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingInfo(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingInfo = function(self, callback) { + try { + self.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options=null] Optional settings. + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') + return validateCollection(self, collectionName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + validateCollection(self, collectionName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var validateCollection = function(self, collectionName, options, callback) { + var command = {validate: collectionName}; + var keys = Object.keys(options); + + // Decorate command with extra options + for(var i = 0; i < keys.length; i++) { + if(options.hasOwnProperty(keys[i])) { + command[keys[i]] = options[keys[i]]; + } + } + + self.s.db.command(command, function(err, doc) { + if(err != null) return callback(err, null); + + if(doc.ok === 0) + return callback(new Error("Error with validate command"), null); + if(doc.result != null && doc.result.constructor != String) + return callback(new Error("Error with validation data"), null); + if(doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error("Error: invalid collection " + collectionName), null); + if(doc.valid != null && !doc.valid) + return callback(new Error("Error: invalid collection " + collectionName), null); + + return callback(null, doc); + }); +} + +define.classMethod('validateCollection', {callback: true, promise:true}); + +/** + * List the available databases + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return self.s.db.executeDbAdminCommand({listDatabases:1}, {}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('listDatabases', {callback: true, promise:true}); + +/** + * Get ReplicaSet status + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return replSetGetStatus(self, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replSetGetStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var replSetGetStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { + if(err == null && doc.ok === 1) + return callback(null, doc); + if(err) return callback(err, false); + callback(toError(doc), false); + }); +} + +define.classMethod('replSetGetStatus', {callback: true, promise:true}); + +module.exports = Admin; diff --git a/util/retroImporter/node_modules/mongodb/lib/aggregation_cursor.js b/util/retroImporter/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 0000000..3663229 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,432 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = AggregationCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(AggregationCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' + , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified']; + +// Extend the Cursor +for(var name in CoreCursor.prototype) { + AggregationCursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {AggregationCursor} + */ +AggregationCursor.prototype.batchSize = function(value) { + if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true }); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", drvier:true }); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.geoNear = function(document) { + this.s.cmd.pipeline.push({$geoNear: document}); + return this; +} + +define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.group = function(document) { + this.s.cmd.pipeline.push({$group: document}); + return this; +} + +define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.limit = function(value) { + this.s.cmd.pipeline.push({$limit: value}); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.match = function(document) { + this.s.cmd.pipeline.push({$match: document}); + return this; +} + +define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.out = function(destination) { + this.s.cmd.pipeline.push({$out: destination}); + return this; +} + +define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.project = function(document) { + this.s.cmd.pipeline.push({$project: document}); + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.redact = function(document) { + this.s.cmd.pipeline.push({$redact: document}); + return this; +} + +define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.skip = function(value) { + this.s.cmd.pipeline.push({$skip: value}); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.sort = function(document) { + this.s.cmd.pipeline.push({$sort: document}); + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.unwind = function(field) { + this.s.cmd.pipeline.push({$unwind: field}); + return this; +} + +define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]}); + +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method AggregationCursor.prototype.each + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +AggregationCursor.INIT = 0; +AggregationCursor.OPEN = 1; +AggregationCursor.CLOSED = 2; + +module.exports = AggregationCursor; diff --git a/util/retroImporter/node_modules/mongodb/lib/apm.js b/util/retroImporter/node_modules/mongodb/lib/apm.js new file mode 100644 index 0000000..aba5b86 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/apm.js @@ -0,0 +1,571 @@ +var EventEmitter = require('events').EventEmitter, + inherits = require('util').inherits; + +// Get prototypes +var AggregationCursor = require('./aggregation_cursor'), + CommandCursor = require('./command_cursor'), + OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation, + UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation, + GridStore = require('./gridfs/grid_store'), + Server = require('./server'), + ReplSet = require('./replset'), + Mongos = require('./mongos'), + Cursor = require('./cursor'), + Collection = require('./collection'), + Db = require('./db'), + Admin = require('./admin'); + +var basicOperationIdGenerator = { + operationId: 1, + + next: function() { + return this.operationId++; + } +} + +var basicTimestampGenerator = { + current: function() { + return new Date().getTime(); + }, + + duration: function(start, end) { + return end - start; + } +} + +var senstiveCommands = ['authenticate', 'saslStart', 'saslContinue', 'getnonce', + 'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb']; + +var Instrumentation = function(core, options, callback) { + options = options || {}; + + // Optional id generators + var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator; + // Optional timestamp generator + var timestampGenerator = options.timestampGenerator || basicTimestampGenerator; + // Extend with event emitter functionality + EventEmitter.call(this); + + // Contains all the instrumentation overloads + this.overloads = []; + + // --------------------------------------------------------- + // + // Instrument prototype + // + // --------------------------------------------------------- + + var instrumentPrototype = function(callback) { + var instrumentations = [] + + // Classes to support + var classes = [GridStore, OrderedBulkOperation, UnorderedBulkOperation, + CommandCursor, AggregationCursor, Cursor, Collection, Db]; + + // Add instrumentations to the available list + for(var i = 0; i < classes.length; i++) { + if(classes[i].define) { + instrumentations.push(classes[i].define.generate()); + } + } + + // Return the list of instrumentation points + callback(null, instrumentations); + } + + // Did the user want to instrument the prototype + if(typeof callback == 'function') { + instrumentPrototype(callback); + } + + // --------------------------------------------------------- + // + // Server + // + // --------------------------------------------------------- + + // Reference + var self = this; + // Names of methods we need to wrap + var methods = ['command', 'insert', 'update', 'remove']; + // Prototype + var proto = core.Server.prototype; + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var requestId = core.Query.nextRequestId(); + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + var ns = args[0]; + var commandObj = args[1]; + var options = args[2] || {}; + var keys = Object.keys(commandObj); + var commandName = keys[0]; + var db = ns.split('.')[0]; + + // Do we have a legacy insert/update/remove command + if(x == 'insert' && !this.lastIsMaster().maxWireVersion) { + commandName = 'insert'; + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + insert: col, documents: commandObj + } + + if(options.writeConcern) commandObj.writeConcern = options.writeConcern; + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'update' && !this.lastIsMaster().maxWireVersion) { + commandName = 'update'; + + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + update: col, updates: commandObj + } + + if(options.writeConcern) commandObj.writeConcern = options.writeConcern; + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'remove' && !this.lastIsMaster().maxWireVersion) { + commandName = 'delete'; + + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + delete: col, deletes: commandObj + } + + if(options.writeConcern) commandObj.writeConcern = options.writeConcern; + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'insert' || x == 'update' || x == 'remove' && this.lastIsMaster().maxWireVersion >= 2) { + // Skip the insert/update/remove commands as they are executed as actual write commands in 2.6 or higher + return func.apply(this, args); + } + + // Get the callback + var callback = args.pop(); + // Set current callback operation id from the current context or create + // a new one + var ourOpId = callback.operationId || operationIdGenerator.next(); + + // Get a connection reference for this server instance + var connection = this.s.pool.get() + + // Emit the start event for the command + var command = { + // Returns the command. + command: commandObj, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: ourOpId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connection + }; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.commandObj = {}; + command.commandObj[commandName] = true; + } + + // Emit the started event + self.emit('started', command) + + // Start time + var startTime = timestampGenerator.current(); + + // Push our handler callback + args.push(function(err, r) { + var endTime = timestampGenerator.current(); + var command = { + duration: timestampGenerator.duration(startTime, endTime), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: connection + }; + + // If we have an error + if(err || (r.result.ok == 0)) { + command.failure = err || r.result.writeErrors || r.result; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.failure = {}; + } + + self.emit('failed', command); + } else { + command.reply = r; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.reply = {}; + } + + self.emit('succeeded', command); + } + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } + }); + + // --------------------------------------------------------- + // + // Bulk Operations + // + // --------------------------------------------------------- + + // Inject ourselves into the Bulk methods + var methods = ['execute']; + var prototypes = [ + require('./bulk/ordered').Bulk.prototype, + require('./bulk/unordered').Bulk.prototype + ] + + prototypes.forEach(function(proto) { + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var bulk = this; + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + // Set an operation Id on the bulk object + this.operationId = operationIdGenerator.next(); + + // Get the callback + var callback = args.pop(); + // If we have a callback use this + if(typeof callback == 'function') { + args.push(function(err, r) { + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + return func.apply(this, args); + } + } + }); + }); + + // --------------------------------------------------------- + // + // Cursor + // + // --------------------------------------------------------- + + // Inject ourselves into the Cursor methods + var methods = ['_find', '_getmore', '_killcursor']; + var prototypes = [ + require('./cursor').prototype, + require('./command_cursor').prototype, + require('./aggregation_cursor').prototype + ] + + // Command name translation + var commandTranslation = { + '_find': 'find', '_getmore': 'getMore', '_killcursor': 'killCursors', '_explain': 'explain' + } + + prototypes.forEach(function(proto) { + + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var cursor = this; + var requestId = core.Query.nextRequestId(); + var ourOpId = operationIdGenerator.next(); + var parts = this.ns.split('.'); + var db = parts[0]; + + // Get the collection + parts.shift(); + var collection = parts.join('.'); + + // Set the command + var command = this.query; + var cmd = this.s.cmd; + + // If we have a find method, set the operationId on the cursor + if(x == '_find') { + cursor.operationId = ourOpId; + } + + // Do we have a find command rewrite it + if(cmd.find) { + command = { + find: collection, filter: cmd.query + } + + if(cmd.sort) command.sort = cmd.sort; + if(cmd.fields) command.projection = cmd.fields; + if(cmd.limit && cmd.limit < 0) { + command.limit = Math.abs(cmd.limit); + command.singleBatch = true; + } else if(cmd.limit) { + command.limit = Math.abs(cmd.limit); + } + + // Options + if(cmd.skip) command.skip = cmd.skip; + if(cmd.hint) command.hint = cmd.hint; + if(cmd.batchSize) command.batchSize = cmd.batchSize; + if(cmd.returnKey) command.returnKey = cmd.returnKey; + if(cmd.comment) command.comment = cmd.comment; + if(cmd.min) command.min = cmd.min; + if(cmd.max) command.max = cmd.max; + if(cmd.maxScan) command.maxScan = cmd.maxScan; + if(cmd.readPreference) command['$readPreference'] = cmd.readPreference; + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + + // Flags + if(cmd.awaitData) command.awaitData = cmd.awaitData; + if(cmd.snapshot) command.snapshot = cmd.snapshot; + if(cmd.tailable) command.tailable = cmd.tailable; + if(cmd.oplogReplay) command.oplogReplay = cmd.oplogReplay; + if(cmd.noCursorTimeout) command.noCursorTimeout = cmd.noCursorTimeout; + if(cmd.partial) command.partial = cmd.partial; + if(cmd.showDiskLoc) command.showRecordId = cmd.showDiskLoc; + + // Read Concern + if(cmd.readConcern) command.readConcern = cmd.readConcern; + + // Override method + if(cmd.explain) command.explain = cmd.explain; + if(cmd.exhaust) command.exhaust = cmd.exhaust; + + // If we have a explain flag + if(cmd.explain) { + // Create fake explain command + command = { + explain: command, + verbosity: 'allPlansExecution' + } + + // Set readConcern on the command if available + if(cmd.readConcern) command.readConcern = cmd.readConcern + + // Set up the _explain name for the command + x = '_explain'; + } + } else if(x == '_getmore') { + command = { + getMore: this.cursorState.cursorId, + collection: collection, + batchSize: cmd.batchSize + } + + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + } else if(x == '_killcursors') { + command = { + killCursors: collection, + cursors: [this.cursorState.cursorId] + } + } else { + command = cmd; + } + + // Set up the connection + var connectionId = null; + + // Set local connection + if(this.connection) connectionId = this.connection; + if(!connectionId && this.server && this.server.getConnection) connectionId = this.server.getConnection(); + + // Get the command Name + var commandName = x == '_find' ? Object.keys(command)[0] : commandTranslation[x]; + + // Emit the start event for the command + var command = { + // Returns the command. + command: command, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: this.operationId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connectionId + }; + + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + + // Get the callback + var callback = args.pop(); + + // We do not have a callback but a Promise + if(typeof callback == 'function' || command.commandName == 'killCursors') { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + + // Emit succeeded event with killcursor if we have a legacy protocol + if(command.commandName == 'killCursors' + && this.server.lastIsMaster() + && this.server.lastIsMaster().maxWireVersion < 4) { + // Emit the succeeded command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: [{ok:1}] + }; + + // Emit the command + return self.emit('succeeded', command) + } + + // Add our callback handler + args.push(function(err, r) { + + if(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + } else { + // cursor id is zero, we can issue success command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: cursor.cursorState.documents + }; + + // Emit the command + self.emit('succeeded', command) + } + + // Return + if(!callback) return; + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + // Assume promise, push back the missing value + args.push(callback); + // Get the promise + var promise = func.apply(this, args); + // Return a new promise + return new cursor.s.promiseLibrary(function(resolve, reject) { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + // Execute the function + promise.then(function(r) { + // cursor id is zero, we can issue success command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: cursor.cursorState.documents + }; + + // Emit the command + self.emit('succeeded', command) + }).catch(function(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + // reject the promise + reject(err); + }); + }); + } + } + }); + }); +} + +inherits(Instrumentation, EventEmitter); + +Instrumentation.prototype.uninstrument = function() { + for(var i = 0; i < this.overloads.length; i++) { + var obj = this.overloads[i]; + obj.proto[obj.name] = obj.func; + } + + // Remove all listeners + this.removeAllListeners('started'); + this.removeAllListeners('succeeded'); + this.removeAllListeners('failed'); +} + +module.exports = Instrumentation; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/lib/bulk/common.js b/util/retroImporter/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 0000000..7ec023e --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,393 @@ +"use strict"; + +var utils = require('../utils'); + +// Error codes +var UNKNOWN_ERROR = 8; +var INVALID_BSON_ERROR = 22; +var WRITE_CONCERN_ERROR = 64; +var MULTIPLE_ERROR = 65; + +// Insert types +var INSERT = 1; +var UPDATE = 2; +var REMOVE = 3 + + +// Get write concern +var writeConcern = function(target, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + target.writeConcern = options; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } + + return target +} + +/** + * Helper function to define properties + * @ignore + */ +var defineReadOnlyProperty = function(self, name, value) { + Object.defineProperty(self, name, { + enumerable: true + , get: function() { + return value; + } + }); +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * @ignore + */ +var Batch = function(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; +} + +/** + * Wraps a legacy operation so we can correctly rewrite it's error + * @ignore + */ +var LegacyOp = function(batchType, operation, index) { + this.batchType = batchType; + this.index = index; + this.operation = operation; +} + +/** + * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {boolean} ok Did bulk operation correctly execute + * @property {number} nInserted number of inserted documents + * @property {number} nUpdated number of documents updated logically + * @property {number} nUpserted Number of upserted documents + * @property {number} nModified Number of documents updated physically on disk + * @property {number} nRemoved Number of removed documents + * @return {BulkWriteResult} a BulkWriteResult instance + */ +var BulkWriteResult = function(bulkResult) { + defineReadOnlyProperty(this, "ok", bulkResult.ok); + defineReadOnlyProperty(this, "nInserted", bulkResult.nInserted); + defineReadOnlyProperty(this, "nUpserted", bulkResult.nUpserted); + defineReadOnlyProperty(this, "nMatched", bulkResult.nMatched); + defineReadOnlyProperty(this, "nModified", bulkResult.nModified); + defineReadOnlyProperty(this, "nRemoved", bulkResult.nRemoved); + + /** + * Return an array of inserted ids + * + * @return {object[]} + */ + this.getInsertedIds = function() { + return bulkResult.insertedIds; + } + + /** + * Return an array of upserted ids + * + * @return {object[]} + */ + this.getUpsertedIds = function() { + return bulkResult.upserted; + } + + /** + * Return the upserted id at position x + * + * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index + * @return {object} + */ + this.getUpsertedIdAt = function(index) { + return bulkResult.upserted[index]; + } + + /** + * Return raw internal result + * + * @return {object} + */ + this.getRawResponse = function() { + return bulkResult; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + this.hasWriteErrors = function() { + return bulkResult.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + this.getWriteErrorCount = function() { + return bulkResult.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @return {WriteError} + */ + this.getWriteErrorAt = function(index) { + if(index < bulkResult.writeErrors.length) { + return bulkResult.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {object[]} + */ + this.getWriteErrors = function() { + return bulkResult.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + this.getLastOp = function() { + return bulkResult.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + this.getWriteConcernError = function() { + if(bulkResult.writeConcernErrors.length == 0) { + return null; + } else if(bulkResult.writeConcernErrors.length == 1) { + // Return the error + return bulkResult.writeConcernErrors[0]; + } else { + + // Combine the errors + var errmsg = ""; + for(var i = 0; i < bulkResult.writeConcernErrors.length; i++) { + var err = bulkResult.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if(i == 0) errmsg = errmsg + " and "; + } + + return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_ERROR }); + } + } + + this.toJSON = function() { + return bulkResult; + } + + this.toString = function() { + return "BulkWriteResult(" + this.toJSON(bulkResult) + ")"; + } + + this.isOk = function() { + return bulkResult.ok == 1; + } +} + +/** + * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +var WriteConcernError = function(err) { + if(!(this instanceof WriteConcernError)) return new WriteConcernError(err); + + // Define properties + defineReadOnlyProperty(this, "code", err.code); + defineReadOnlyProperty(this, "errmsg", err.errmsg); + + this.toJSON = function() { + return {code: err.code, errmsg: err.errmsg}; + } + + this.toString = function() { + return "WriteConcernError(" + err.errmsg + ")"; + } +} + +/** + * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {number} index Write concern error original bulk operation index. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +var WriteError = function(err) { + if(!(this instanceof WriteError)) return new WriteError(err); + + // Define properties + defineReadOnlyProperty(this, "code", err.code); + defineReadOnlyProperty(this, "index", err.index); + defineReadOnlyProperty(this, "errmsg", err.errmsg); + + // + // Define access methods + this.getOperation = function() { + return err.op; + } + + this.toJSON = function() { + return {code: err.code, index: err.index, errmsg: err.errmsg, op: err.op}; + } + + this.toString = function() { + return "WriteError(" + JSON.stringify(this.toJSON()) + ")"; + } +} + +/** + * Merges results into shared data structure + * @ignore + */ +var mergeBatchResults = function(ordered, batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if(err) { + result = err; + } else if(result && result.result) { + result = result.result; + } else if(result == null) { + return; + } + + // Do we have a top level error stop processing and return + if(result.ok == 0 && bulkResult.ok == 1) { + bulkResult.ok = 0; + // bulkResult.error = utils.toError(result); + var writeError = { + index: 0 + , code: result.code || 0 + , errmsg: result.message + , op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if(result.ok == 0 && bulkResult.ok == 0) { + return; + } + + // Add lastop if available + if(result.lastOp) { + bulkResult.lastOp = result.lastOp; + } + + // If we have an insert Batch type + if(batch.batchType == INSERT && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if(batch.batchType == REMOVE && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + var nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if(Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for(var i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex + , _id: result.upserted[i]._id + }); + } + } else if(result.upserted) { + + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex + , _id: result.upserted + }); + } + + // If we have an update Batch type + if(batch.batchType == UPDATE && result.n) { + var nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if(typeof nModified == 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = null; + } + } + + if(Array.isArray(result.writeErrors)) { + for(var i = 0; i < result.writeErrors.length; i++) { + + var writeError = { + index: batch.originalZeroIndex + result.writeErrors[i].index + , code: result.writeErrors[i].code + , errmsg: result.writeErrors[i].errmsg + , op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if(result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +// +// Clone the options +var cloneOptions = function(options) { + var clone = {}; + var keys = Object.keys(options); + for(var i = 0; i < keys.length; i++) { + clone[keys[i]] = options[keys[i]]; + } + + return clone; +} + +// Exports symbols +exports.BulkWriteResult = BulkWriteResult; +exports.WriteError = WriteError; +exports.Batch = Batch; +exports.LegacyOp = LegacyOp; +exports.mergeBatchResults = mergeBatchResults; +exports.cloneOptions = cloneOptions; +exports.writeConcern = writeConcern; +exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR; +exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR; +exports.MULTIPLE_ERROR = MULTIPLE_ERROR; +exports.UNKNOWN_ERROR = UNKNOWN_ERROR; +exports.INSERT = INSERT; +exports.UPDATE = UPDATE; +exports.REMOVE = REMOVE; diff --git a/util/retroImporter/node_modules/mongodb/lib/bulk/ordered.js b/util/retroImporter/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 0000000..319a030 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,532 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Define = require('../metadata') + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. + */ +var FindOperatorsOrdered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +FindOperatorsOrdered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.deleteOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.delete = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; + +// Add to internal list of documents +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Reset the current size trackers + _self.s.currentBatchSize = 0; + _self.s.currentBatchSizeBytes = 0; + } else { + // Update current batch size + _self.s.currentBatchSize = _self.s.currentBatchSize + 1; + _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; + } + + if(docType == common.INSERT) { + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentBatch.operations.push(document) + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Return self + return _self; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ +function OrderedBulkOperation(topology, collection, options) { + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + var self = this; + var executed = false; + + // Current item + var currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + var bson = topology.bson; + + // Namespace for the operation + var namespace = collection.collectionName; + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; + var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; + + // Get the capabilities + var capabilities = topology.capabilities(); + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Current batch + var currentBatch = null; + var currentIndex = 0; + var currentBatchSize = 0; + var currentBatchSizeBytes = 0; + var batches = []; + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentBatch: null + , currentIndex: 0 + , currentBatchSize: 0 + , currentBatchSizeBytes: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Capabilities + , capabilities: capabilities + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Fundamental error + , err: null + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = OrderedBulkOperation.define = new Define('OrderedBulkOperation', OrderedBulkOperation, false); + +OrderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + if(op[key].upsert) operation.upsert = true; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +OrderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +OrderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsOrdered(this); +} + +Object.defineProperty(OrderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// +// Execute next write command in a chain +var executeCommands = function(self, callback) { + if(self.s.batches.length == 0) { + return callback(null, new BulkWriteResult(self.s.bulkResult)); + } + + // Ordered execution of the command + var batch = self.s.batches.shift(); + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return callback(err); + } + + // If we have and error + if(err) err.ok = 0; + // Merge the results together + var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); + if(mergeResult != null) { + return callback(null, new BulkWriteResult(self.s.bulkResult)); + } + + // If we are ordered and have errors and they are + // not all replication errors terminate the operation + if(self.s.bulkResult.writeErrors.length > 0) { + return callback(toError(self.s.bulkResult.writeErrors[0]), new BulkWriteResult(self.s.bulkResult)); + } + + // Execute the next command in line + executeCommands(self, callback); + } + + var finalOptions = {ordered: true} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Serialize functions + if(self.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +/** + * The callback format for results + * @callback OrderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {OrderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw new toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') { + return executeCommands(this, callback); + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommands(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeOrderedBulkOp = function(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; diff --git a/util/retroImporter/node_modules/mongodb/lib/bulk/unordered.js b/util/retroImporter/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 0000000..ca45b96 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,541 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Define = require('../metadata') + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. + */ +var FindOperatorsUnordered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.removeOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.remove = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// +// Add to the operations list +// +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Holds the current batch + _self.s.currentBatch = null; + // Get the right type of batch + if(docType == common.INSERT) { + _self.s.currentBatch = _self.s.currentInsertBatch; + } else if(docType == common.UPDATE) { + _self.s.currentBatch = _self.s.currentUpdateBatch; + } else if(docType == common.REMOVE) { + _self.s.currentBatch = _self.s.currentRemoveBatch; + } + + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.operations.push(document); + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Save back the current Batch to the right type + if(docType == common.INSERT) { + _self.s.currentInsertBatch = _self.s.currentBatch; + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } else if(docType == common.UPDATE) { + _self.s.currentUpdateBatch = _self.s.currentBatch; + } else if(docType == common.REMOVE) { + _self.s.currentRemoveBatch = _self.s.currentBatch; + } + + // Update current batch size + _self.s.currentBatch.size = _self.s.currentBatch.size + 1; + _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; + + // Return self + return _self; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +var UnorderedBulkOperation = function(topology, collection, options) { + options = options == null ? {} : options; + + // Contains reference to self + var self = this; + // Get the namesspace for the write operations + var namespace = collection.collectionName; + // Used to mark operation as executed + var executed = false; + + // Current item + // var currentBatch = null; + var currentOp = null; + var currentIndex = 0; + var batches = []; + + // The current Batches for the different operations + var currentInsertBatch = null; + var currentUpdateBatch = null; + var currentRemoveBatch = null; + + // Handle to the bson serializer, used to calculate running sizes + var bson = topology.bson; + + // Get the capabilities + var capabilities = topology.capabilities(); + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; + var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentInsertBatch: null + , currentUpdateBatch: null + , currentRemoveBatch: null + , currentBatch: null + , currentIndex: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Capabilities + , capabilities: capabilities + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = UnorderedBulkOperation.define = new Define('UnorderedBulkOperation', UnorderedBulkOperation, false); + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +UnorderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsUnordered} + */ +UnorderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsUnordered(this); +} + +Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +UnorderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + if(op[key].upsert) operation.upsert = true; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +// +// Execute the command +var executeBatch = function(self, batch, callback) { + var finalOptions = {ordered: false} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return callback(err); + } + + // If we have and error + if(err) err.ok = 0; + callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +// +// Execute all the commands +var executeBatches = function(self, callback) { + var numberOfCommandsToExecute = self.s.batches.length; + var error = null; + // Execute over all the batches + for(var i = 0; i < self.s.batches.length; i++) { + executeBatch(self, self.s.batches[i], function(err, result) { + // Driver layer error capture it + if(err) error = err; + // Count down the number of commands left to execute + numberOfCommandsToExecute = numberOfCommandsToExecute - 1; + + // Execute + if(numberOfCommandsToExecute == 0) { + // Driver level error + if(error) return callback(error); + // Treat write errors + var error = self.s.bulkResult.writeErrors.length > 0 ? toError(self.s.bulkResult.writeErrors[0]) : null; + callback(error, new BulkWriteResult(self.s.bulkResult)); + } + }); + } +} + +/** + * The callback format for results + * @callback UnorderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if(this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if(this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') return executeBatches(this, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeBatches(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeUnorderedBulkOp = function(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; diff --git a/util/retroImporter/node_modules/mongodb/lib/collection.js b/util/retroImporter/node_modules/mongodb/lib/collection.js new file mode 100644 index 0000000..5ae1ebc --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/collection.js @@ -0,0 +1,3128 @@ +"use strict"; + +var checkCollectionName = require('./utils').checkCollectionName + , ObjectID = require('mongodb-core').BSON.ObjectID + , Long = require('mongodb-core').BSON.Long + , Code = require('mongodb-core').BSON.Code + , f = require('util').format + , AggregationCursor = require('./aggregation_cursor') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone + , isObject = require('./utils').isObject + , toError = require('./utils').toError + , normalizeHintField = require('./utils').normalizeHintField + , handleCallback = require('./utils').handleCallback + , decorateCommand = require('./utils').decorateCommand + , formattedOrderClause = require('./utils').formattedOrderClause + , ReadPreference = require('./read_preference') + , CoreReadPreference = require('mongodb-core').ReadPreference + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Cursor = require('./cursor') + , unordered = require('./bulk/unordered') + , ordered = require('./bulk/ordered'); + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} readConcern The current read concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +var Collection = function(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + var self = this; + // Unpack variables + var internalHint = null; + var opts = options != null && ('object' === typeof options) ? options : {}; + var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + var serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; + var raw = options == null || options.raw == null ? db.raw : options.raw; + var readPreference = null; + var collectionHint = null; + var namespace = f("%s.%s", dbName, name); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Assign the right collection level readPreference + if(options && options.readPreference) { + readPreference = options.readPreference; + } else if(db.options.readPreference) { + readPreference = db.options.readPreference; + } + + // Set custom primary key factory if provided + pkFactory = pkFactory == null + ? ObjectID + : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory + // Db + , db: db + // Topology + , topology: topology + // dbName + , dbName: dbName + // Options + , options: options + // Namespace + , namespace: namespace + // Read preference + , readPreference: readPreference + // Raw + , raw: raw + // SlaveOK + , slaveOk: slaveOk + // Serialize functions + , serializeFunctions: serializeFunctions + // internalHint + , internalHint: internalHint + // collectionHint + , collectionHint: collectionHint + // Name + , name: name + // Promise library + , promiseLibrary: promiseLibrary + // Read Concern + , readConcern: options.readConcern + } +} + +var define = Collection.define = new Define('Collection', Collection, false); + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, get: function() { return this.s.name; } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, get: function() { return this.s.namespace; } +}); + +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(this.s.options.w != null) ops.w = this.s.options.w; + if(this.s.options.j != null) ops.j = this.s.options.j; + if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, "hint", { + enumerable: true + , get: function () { return this.s.collectionHint; } + , set: function (v) { this.s.collectionHint = normalizeHintField(v); } +}); + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} query The cursor query object. + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = function() { + var options + , args = Array.prototype.slice.call(arguments, 0) + , has_callback = typeof args[args.length - 1] === 'function' + , has_weird_callback = typeof args[0] === 'function' + , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) + , len = args.length + , selector = len >= 1 ? args[0] : {} + , fields = len >= 2 ? args[1] : undefined; + + if(len === 1 && has_weird_callback) { + // backwards compat for callback?, options case + selector = {}; + options = args[0]; + } + + if(len === 2 && fields !== undefined && !Array.isArray(fields)) { + var fieldKeys = Object.keys(fields); + var is_option = false; + + for(var i = 0; i < fieldKeys.length; i++) { + if(testForFields[fieldKeys[i]] != null) { + is_option = true; + break; + } + } + + if(is_option) { + options = fields; + fields = undefined; + } else { + options = {}; + } + } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { + var newFields = {}; + // Rewrite the array + for(var i = 0; i < fields.length; i++) { + newFields[fields[i]] = 1; + } + // Set the fields + fields = newFields; + } + + if(3 === len) { + options = args[2]; + } + + // Ensure selector is not null + selector = selector == null ? {} : selector; + // Validate correctness off the selector + var object = selector; + if(Buffer.isBuffer(object)) { + var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; + if(object_size != object.length) { + var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); + error.name = 'MongoError'; + throw error; + } + } + + // Validate correctness of the field selector + var object = fields; + if(Buffer.isBuffer(object)) { + var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; + if(object_size != object.length) { + var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); + error.name = 'MongoError'; + throw error; + } + } + + // Check special case where we are using an objectId + if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) { + selector = {_id:selector}; + } + + // If it's a serialized fields field we need to just let it through + // user be warned it better be good + if(options && options.fields && !(Buffer.isBuffer(options.fields))) { + fields = {}; + + if(Array.isArray(options.fields)) { + if(!options.fields.length) { + fields['_id'] = 1; + } else { + for (var i = 0, l = options.fields.length; i < l; i++) { + fields[options.fields[i]] = 1; + } + } + } else { + fields = options.fields; + } + } + + if (!options) options = {}; + + var newOptions = {}; + // Make a shallow copy of options + for (var key in options) { + newOptions[key] = options[key]; + } + + // Unpack options + newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; + newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; + newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.s.raw; + newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; + // // If we have overridden slaveOk otherwise use the default db setting + newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; + + // Add read preference if needed + newOptions = getReadPreference(this, newOptions, this.s.db, this); + // Set slave ok to true if read preference different from primary + if(newOptions.readPreference != null + && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if(selector != null && typeof selector != 'object') { + throw MongoError.create({message: "query selector must be an object", driver:true }); + } + + // Build the find command + var findCommand = { + find: this.s.namespace + , limit: newOptions.limit + , skip: newOptions.skip + , query: selector + } + + // Ensure we use the right await data option + if(typeof newOptions.awaitdata == 'boolean') { + newOptions.awaitData = newOptions.awaitdata + }; + + // Translate to new command option noCursorTimeout + if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + // Merge in options to command + for(var name in newOptions) { + if(newOptions[name] != null) findCommand[name] = newOptions[name]; + } + + // Format the fields + var formatFields = function(fields) { + var object = {}; + if(Array.isArray(fields)) { + for(var i = 0; i < fields.length; i++) { + if(Array.isArray(fields[i])) { + object[fields[i][0]] = fields[i][1]; + } else { + object[fields[i][0]] = 1; + } + } + } else { + object = fields; + } + + return object; + } + + // Special treatment for the fields selector + if(fields) findCommand.fields = formatFields(fields); + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if(newOptions.raw == null && this.s.raw) newOptions.raw = this.s.raw; + + // Sort options + if(findCommand.sort) + findCommand.sort = formattedOrderClause(findCommand.sort); + + // Set the readConcern + if(this.s.readConcern) { + findCommand.readConcern = this.s.readConcern; + } + + // Create the cursor + if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions)); + return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); +} + +define.classMethod('find', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Inserts a single document into MongoDB. + * @method + * @param {object} doc Document to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + if(Array.isArray(doc)) return callback(MongoError.create({message: 'doc parameter must be an object', driver:true })); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return insertOne(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + insertOne(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var insertOne = function(self, doc, options, callback) { + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + // Workaround for pre 2.6 servers + if(r == null) return callback(null, {result: {ok:1}}); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if(callback) callback(null, r); + }); +} + +var mapInserManyResults = function(docs, r) { + var ids = r.getInsertedIds(); + var keys = Object.keys(ids); + var finalIds = new Array(keys); + + for(var i = 0; i < keys.length; i++) { + if(ids[keys[i]]._id) { + finalIds[ids[keys[i]].index] = ids[keys[i]]._id; + } + } + + return { + result: {ok: 1, n: r.insertedCount}, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: finalIds + } +} + +define.classMethod('insertOne', {callback: true, promise:true}); + +/** + * Inserts an array of documents into MongoDB. + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + if(!Array.isArray(docs)) return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); + + // Get the write concern options + if(typeof options.checkKeys != 'boolean') { + options.checkKeys = true; + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Do we want to force the server to assign the _id key + if(forceServerObjectId !== true) { + // Add _id if not specified + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // Generate the bulk write operations + var operations = [{ + insertMany: docs + }]; + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) { + if(err) return callback(err, r); + callback(null, mapInserManyResults(docs, r)); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err) return reject(err); + resolve(mapInserManyResults(docs, r)); + }); + }); +} + +define.classMethod('insertMany', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + + if(!Array.isArray(operations)) { + throw MongoError.create({message: "operations must be an array of documents", driver:true }); + } + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var bulkWrite = function(self, operations, options, callback) { + // Add ignoreUndfined + if(self.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = self.s.options.ignoreUndefined; + } + + // Create the bulk operation + var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options); + + // for each op go through and add to the bulk + for(var i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + + // Final options for write concern + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + + // Execute the bulk + bulk.execute(writeCon, function(err, r) { + // We have connection level error + if(!r && err) return callback(err, null); + // We have single error + if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) { + return callback(toError(r.getWriteErrorAt(0)), r); + } + + // if(err) return callback(err); + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + var inserted = r.getInsertedIds(); + // Map inserted ids + for(var i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + var upserted = r.getUpsertedIds(); + // Map upserted ids + for(var i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Check if we have write errors + if(r.hasWriteErrors()) { + // Get all the errors + var errors = r.getWriteErrors(); + // Return the MongoError object + return callback(toError({ + message: 'write operation failed', code: errors[0].code, writeErrors: errors + }), r); + } + + // Check if we have a writeConcern error + if(r.getWriteConcernError()) { + // Return the MongoError object + return callback(toError(r.getWriteConcernError()), r); + } + + // Return the results + callback(null, r); + }); +} + +var insertDocuments = function(self, docs, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true; + + // If keep going set unordered + if(finalOptions.keepGoing == true) finalOptions.ordered = false; + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Add _id if not specified + if(forceServerObjectId !== true){ + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // File inserts + self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('bulkWrite', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = function(docs, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:false}; + docs = !Array.isArray(docs) ? [docs] : docs; + + if(options.keepGoing == true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +} + +define.classMethod('insert', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateOne(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateOne(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateOne = function(self, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateOne', {callback: true, promise:true}); + +/** + * Replace a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} doc The Document that replaces the matching document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return replaceOne(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replaceOne(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var replaceOne = function(self, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.ops = [update]; + if(callback) callback(null, r); + }); +} + +define.classMethod('replaceOne', {callback: true, promise:true}); + +/** + * Update multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateMany(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateMany(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateMany = function(self, filter, update, options, callback) { + // Set single document update + options.multi = true; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateMany', {callback: true, promise:true}); + +var updateDocuments = function(self, selector, document, options, callback) { + if('function' === typeof options) callback = options, options = null; + if(options == null) options = {}; + if(!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object")); + if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object")); + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Execute the operation + var op = {q: selector, u: document}; + if(options.upsert) op.upsert = true; + if(options.multi) op.multi = true; + + // Update options + self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} document The update document. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = function(selector, document, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateDocuments(self, selector, document, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('update', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for inserts + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteOne(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteOne(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteOne = function(self, filter, options, callback) { + options.single = true; + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +define.classMethod('deleteOne', {callback: true, promise:true}); + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +define.classMethod('removeOne', {callback: true, promise:true}); + +/** + * Delete multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteMany(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteMany(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteMany = function(self, filter, options, callback) { + options.single = false; + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +var removeDocuments = function(self, selector, options, callback) { + if(typeof options == 'function') { + callback = options, options = {}; + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // If selector is null set empty + if(selector == null) selector = {}; + + // Build the op + var op = {q: selector, limit: 0}; + if(options.single) op.limit = 1; + + // Execute the remove + self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('deleteMany', {callback: true, promise:true}); + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +define.classMethod('removeMany', {callback: true, promise:true}); + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = function(selector, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return removeDocuments(self, selector, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeDocuments(self, selector, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('remove', {callback: true, promise:true}); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return save(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + save(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var save = function(self, doc, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + // Establish if we need to perform an insert or update + if(doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(doc == null) return handleCallback(callback, null, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, r); + }); +} + +define.classMethod('save', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options=null] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan=null] Limit the number of items to scan. + * @param {number} [options.min=null] Set index bounds. + * @param {number} [options.max=null] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use find().limit(1).next(function(err, doc){}) + */ +Collection.prototype.findOne = function() { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + var callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return findOne(self, args, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findOne(self, args, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOne = function(self, args, callback) { + var cursor = self.find.apply(self, args).limit(-1).batchSize(1); + // Return the item + cursor.next(function(err, item) { + if(err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); +} + +define.classMethod('findOne', {callback: true, promise:true}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, opt, callback) { + var self = this; + if(typeof opt == 'function') callback = opt, opt = {}; + opt = opt || {}; + + // Execute using callback + if(typeof callback == 'function') return rename(self, newName, opt, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + rename(self, newName, opt, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var rename = function(self, newName, opt, callback) { + // Check the collection name + checkCollectionName(newName); + // Build the command + var renameCollection = f("%s.%s", self.s.dbName, self.s.name); + var toCollection = f("%s.%s", self.s.dbName, newName); + var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false; + var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; + + // Execute against admin + self.s.db.admin().command(cmd, opt, function(err, doc) { + if(err) return handleCallback(callback, err, null); + // We have an error + if(doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options)); + } catch(err) { + return handleCallback(callback, toError(err), null); + } + }); +} + +define.classMethod('rename', {callback: true, promise:true}); + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.dropCollection(self.s.name, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('drop', {callback: true, promise:true}); + +/** + * Returns the options of the collection. + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return options(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var options = function(self, callback) { + self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) { + if(err) return handleCallback(callback, err); + if(collections.length == 0) { + return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true })); + } + + handleCallback(callback, err, collections[0].options || null); + }); +} + +define.classMethod('options', {callback: true, promise:true}); + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return isCapped(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + isCapped(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var isCapped = function(self, callback) { + self.options(function(err, document) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, document && document.capped); + }); +} + +define.classMethod('isCapped', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + + // Execute using callback + if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * @method + * @param {array} indexSpecs An array of index specifications to be created + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndexes = function(indexSpecs, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndexes(self, indexSpecs, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndexes = function(self, indexSpecs, callback) { + // Ensure we generate the correct name if the parameter is not set + for(var i = 0; i < indexSpecs.length; i++) { + if(indexSpecs[i].name == null) { + var keys = []; + + for(var name in indexSpecs[i].key) { + keys.push(f('%s_%s', name, indexSpecs[i].key[name])); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + // Execute the index + self.s.db.command({ + createIndexes: self.s.name, indexes: indexSpecs + }, callback); +} + +define.classMethod('createIndexes', {callback: true, promise:true}); + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return dropIndex(self, indexName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndex(self, indexName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndex = function(self, indexName, options, callback) { + // Delete index command + var cmd = {'deleteIndexes':self.s.name, 'index':indexName}; + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(typeof callback != 'function') return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +define.classMethod('dropIndex', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return dropIndexes(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndexes = function(self, callback) { + self.dropIndex('*', function (err, result) { + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); +} + +define.classMethod('dropIndexes', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; + +define.classMethod('dropAllIndexes', {callback: true, promise:true}); + +/** + * Reindex all indexes on the collection + * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return reIndex(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + reIndex(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var reIndex = function(self, options, callback) { + // Reindex + var cmd = {'reIndex':self.s.name}; + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +define.classMethod('reIndex', {callback: true, promise:true}); + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + options = options || {}; + // Clone the options + options = shallowClone(options); + // Set the CommandCursor constructor + options.cursorFactory = CommandCursor; + // Set the promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // We have a list collections command + if(this.s.db.serverConfig.capabilities().hasListIndexesCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listIndexes: this.s.name, cursor: cursor }; + // Execute the cursor + return this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); + } + + // Get the namespace + var ns = f('%s.system.indexes', this.s.dbName); + // Get the query + return this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options); +}; + +define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var ensureIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return indexExists(self, indexes, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexExists(self, indexes, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexExists = function(self, indexes, callback) { + self.indexInformation(function(err, indexInformation) { + // If we have an error return + if(err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for(var i = 0; i < indexes.length; i++) { + if(indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +define.classMethod('indexExists', {callback: true, promise:true}); + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + var self = this; + // Unpack calls + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return indexInformation(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexInformation = function(self, options, callback) { + self.s.db.indexInformation(self.s.name, options, callback); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * Count number of matching documents in the db to a query. + * @method + * @param {object} query The query for the count. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.limit=null] The limit of documents to count. + * @param {boolean} [options.skip=null] The number of documents to skip for the count. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.count = function(query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback); + + // Check if query is empty + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, query, options, callback) { + var skip = options.skip; + var limit = options.limit; + var hint = options.hint; + var maxTimeMS = options.maxTimeMS; + + // Final query + var cmd = { + 'count': self.s.name, 'query': query + , 'fields': null + }; + + // Add limit and skip if defined + if(typeof skip == 'number') cmd.skip = skip; + if(typeof limit == 'number') cmd.limit = limit; + if(hint) options.hint = hint; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.n); + }); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * The distinct command returns returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback); + + // Ensure the query and options are set + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + distinct(self, key, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var distinct = function(self, key, query, options, callback) { + // maxTimeMS option + var maxTimeMS = options.maxTimeMS; + + // Distinct command + var cmd = { + 'distinct': self.s.name, 'key': key, 'query': query + }; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.values); + }); +} + +define.classMethod('distinct', {callback: true, promise:true}); + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return indexes(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexes = function(self, callback) { + self.s.db.indexInformation(self.s.name, {full:true}, callback); +} + +define.classMethod('indexes', {callback: true, promise:true}); + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return stats(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + stats(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var stats = function(self, options, callback) { + // Build command object + var commandObject = { + collStats:self.s.name + } + + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Execute the command + self.s.db.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from findAndModify command. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndDelete(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndDelete = function(self, filter, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['remove'] = true; + // Execute find and Modify + self.findAndModify( + filter + , options.sort + , null + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndDelete', {callback: true, promise:true}); + +/** + * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} replacement Document replacing the matching document. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndReplace(self, filter, replacement, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndReplace = function(self, filter, replacement, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , replacement + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndReplace', {callback: true, promise:true}); + +/** + * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} update Update operations to be performed on the document + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndUpdate(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndUpdate = function(self, filter, update, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , update + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndUpdate', {callback: true, promise:true}); + +/** + * Find and update a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + var options = shallowClone(options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findAndModify(self, query, sort, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndModify = function(self, query, sort, doc, options, callback) { + // Create findAndModify command object + var queryObject = { + 'findandmodify': self.s.name + , 'query': query + }; + + sort = formattedOrderClause(sort); + if(sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + if(options.fields) { + queryObject.fields = options.fields; + } + + if(doc && !options.remove) { + queryObject.update = doc; + } + + // Either use override on the function, or go back to default on either the collection + // level or db + if(options['serializeFunctions'] != null) { + options['serializeFunctions'] = options['serializeFunctions']; + } else { + options['serializeFunctions'] = self.s.serializeFunctions; + } + + // No check on the documents + options.checkKeys = false; + + // Get the write concern settings + var finalOptions = writeConcern(options, self.s.db, self, options); + + // Decorate the findAndModify command with the write Concern + if(finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if(typeof finalOptions.bypassDocumentValidation == 'boolean') { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + // Execute the command + self.s.db.command(queryObject + , options, function(err, result) { + if(err) return handleCallback(callback, err, null); + return handleCallback(callback, null, result); + }); +} + +define.classMethod('findAndModify', {callback: true, promise:true}); + +/** + * Find and remove a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = function(query, sort, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findAndRemove(self, query, sort, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndRemove = function(self, query, sort, options, callback) { + // Add the remove option + options['remove'] = true; + // Execute the callback + self.findAndModify(query, sort, null, options, callback); +} + +define.classMethod('findAndRemove', {callback: true, promise:true}); + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} pipeline Array containing all the aggregation framework commands for the execution. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~resultCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + var self = this; + if(Array.isArray(pipeline)) { + // Set up callback if one is provided + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if(options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + var args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + var opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = opts && (opts.readPreference + || opts.explain || opts.cursor || opts.out + || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + // If out was specified + if(typeof options.out == 'string') { + pipeline.push({$out: options.out}); + } + + // Build the command + var command = { aggregate : this.s.name, pipeline : pipeline}; + + // If we have bypassDocumentValidation set + if(typeof options.bypassDocumentValidation == 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Do we have a readConcern specified + if(this.s.readConcern) { + command.readConcern = this.s.readConcern; + } + + // If we have allowDiskUse defined + if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // If explain has been specified add it + if(options.explain) command.explain = options.explain; + + // Validate that cursor options is valid + if(options.cursor != null && typeof options.cursor != 'object') { + throw toError('cursor options must be an object'); + } + + // promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Set the AggregationCursor constructor + options.cursorFactory = AggregationCursor; + if(typeof callback != 'function') { + if(this.s.topology.capabilities().hasAggregationCursor) { + options.cursor = options.cursor || { batchSize : 1000 }; + command.cursor = options.cursor; + } + + // Allow disk usage command + if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Execute the cursor + return this.s.topology.cursor(this.s.namespace, command, options); + } + + var cursor = null; + // We do not allow cursor + if(options.cursor) { + return this.s.topology.cursor(this.s.namespace, command, options); + } + + // Execute the command + this.s.db.command(command, options, function(err, result) { + if(err) { + handleCallback(callback, err); + } else if(result['err'] || result['errmsg']) { + handleCallback(callback, toError(result)); + } else if(typeof result == 'object' && result['serverPipeline']) { + handleCallback(callback, null, result['serverPipeline']); + } else if(typeof result == 'object' && result['stages']) { + handleCallback(callback, null, result['stages']); + } else { + handleCallback(callback, null, result.result); + } + }); +} + +define.classMethod('aggregate', {callback: true, promise:false}); + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {numCursors: 1}; + // Set number of cursors to 1 + options.numCursors = options.numCursors || 1; + options.batchSize = options.batchSize || 1000; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Execute using callback + if(typeof callback == 'function') return parallelCollectionScan(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + parallelCollectionScan(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var parallelCollectionScan = function(self, options, callback) { + // Create command object + var commandObject = { + parallelCollectionScan: self.s.name + , numCursors: options.numCursors + } + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null); + + var cursors = []; + // Create command cursors for each item + for(var i = 0; i < result.cursors.length; i++) { + var rawId = result.cursors[i].cursor.id + // Convert cursorId to Long if needed + var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId; + + // Command cursor options + var cmd = { + batchSize: options.batchSize + , cursorId: cursorId + , items: result.cursors[i].cursor.firstBatch + } + + // Add a command cursor + cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +define.classMethod('parallelCollectionScan', {callback: true, promise:true}); + +/** + * Execute the geoNear command to search for items in the collection + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.num=null] Max number of results to return. + * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher) + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions. + * @param {object} [options.query=null] Filter the results by a query. + * @param {boolean} [options.spherical=false] Perform query using a spherical model. + * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X. + * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoNear = function(x, y, options, callback) { + var self = this; + var point = typeof(x) == 'object' && x + , args = Array.prototype.slice.call(arguments, point?1:2); + + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoNear(self, x, y, point, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoNear = function(self, x, y, point, options, callback) { + // Build command object + var commandObject = { + geoNear:self.s.name, + near: point || [x, y] + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Exclude readPreference and existing options to prevent user from + // shooting themselves in the foot + var exclude = { + readPreference: true, + geoNear: true, + near: true + }; + + // Filter out any excluded objects + commandObject = decorateCommand(commandObject, options, exclude); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) return handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoNear', {callback: true, promise:true}); + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {object} [options.search=null] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoHaystackSearch(self, x, y, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoHaystackSearch = function(self, x, y, options, callback) { + // Build command object + var commandObject = { + geoSearch: self.s.name, + near: [x, y] + } + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, {readPreference: true}); + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) handleCallback(callback, utils.toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoHaystackSearch', {callback: true, promise:true}); + +/** + * Group function helper + * @ignore + */ +var groupFunction = function () { + var c = db[ns].find(condition); + var map = new Map(); + var reduce_function = reduce; + + while (c.hasNext()) { + var obj = c.next(); + var key = {}; + + for (var i = 0, len = keys.length; i < len; ++i) { + var k = keys[i]; + key[k] = obj[k]; + } + + var aggObj = map.get(key); + + if (aggObj == null) { + var newObj = Object.extend({}, key); + aggObj = Object.extend(newObj, initial); + map.put(key, aggObj); + } + + reduce_function(obj, aggObj); + } + + return { "result": map.values() }; +}.toString(); + +/** + * Run a group command across a collection + * + * @method + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 3); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + reduce = args.length ? args.shift() : null; + finalize = args.length ? args.shift() : null; + command = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Make sure we are backward compatible + if(!(typeof finalize == 'function')) { + command = finalize; + finalize = null; + } + + if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) { + keys = Object.keys(keys); + } + + if(typeof reduce === 'function') { + reduce = reduce.toString(); + } + + if(typeof finalize === 'function') { + finalize = finalize.toString(); + } + + // Set up the command as default + command = command == null ? true : command; + + // Execute using callback + if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if(command) { + var reduceFunction = reduce instanceof Code + ? reduce + : new Code(reduce); + + var selector = { + group: { + 'ns': self.s.name + , '$reduce': reduceFunction + , 'cond': condition + , 'initial': initial + , 'out': "inline" + } + }; + + // if finalize is defined + if(finalize != null) selector.group['finalize'] = finalize; + // Set up group selector + if ('function' === typeof keys || keys instanceof Code) { + selector.group.$keyf = keys instanceof Code + ? keys + : new Code(keys); + } else { + var hash = {}; + keys.forEach(function (key) { + hash[key] = 1; + }); + selector.group.key = hash; + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + selector.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(selector, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + var scope = reduce != null && reduce instanceof Code + ? reduce.scope + : {}; + + scope.ns = self.s.name; + scope.keys = keys; + scope.condition = condition; + scope.initial = initial; + + // Pass in the function text to execute within mongodb. + var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); + + self.s.db.eval(new Code(groupfn, scope), function (err, results) { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +define.classMethod('group', {callback: true, promise:true}); + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope (scope) { + if(!isObject(scope)) { + return scope; + } + + var keys = Object.keys(scope); + var i = keys.length; + var key; + var new_scope = {}; + + while (i--) { + key = keys[i]; + if ('function' == typeof scope[key]) { + new_scope[key] = new Code(String(scope[key])); + } else { + new_scope[key] = processScope(scope[key]); + } + } + + return new_scope; +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query=null] Query filter object. + * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit=null] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize=null] Finalize function. + * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + var self = this; + if('function' === typeof options) callback = options, options = {}; + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if(null == options.out) { + throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); + } + + if('function' === typeof map) { + map = map.toString(); + } + + if('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + + // Execute using callback + if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + mapReduce(self, map, reduce, options, function(err, r, r1) { + if(err) return reject(err); + if(r instanceof Collection) return resolve(r); + resolve({results: r, stats: r1}); + }); + }); +} + +var mapReduce = function(self, map, reduce, options, callback) { + var mapCommandHash = { + mapreduce: self.s.name + , map: map + , reduce: reduce + }; + + // Add any other options passed in + for(var n in options) { + if('scope' == n) { + mapCommandHash[n] = processScope(options[n]); + } else { + mapCommandHash[n] = options[n]; + } + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // If we have a read preference and inline is not set as output fail hard + if((options.readPreference != false && options.readPreference != 'primary') + && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { + options.readPreference = 'primary'; + } + + // Is bypassDocumentValidation specified + if(typeof options.bypassDocumentValidation == 'boolean') { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Do we have a readConcern specified + if(self.s.readConcern) { + mapCommandHash.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) { + if(err) return handleCallback(callback, err); + // Check if we have an error + if(1 != result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + var stats = {}; + if(result.timeMillis) stats['processtime'] = result.timeMillis; + if(result.counts) stats['counts'] = result.counts; + if(result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if(result.results) { + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, result.results, stats); + } + + // The returned collection + var collection = null; + + // If we have an object it's a different db + if(result.result != null && typeof result.result == 'object') { + var doc = result.result; + collection = self.s.db.db(doc.db).collection(doc.collection); + } else { + // Create a collection object that wraps the result collection + collection = self.s.db.collection(result.result) + } + + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, collection, stats); + }); +} + +define.classMethod('mapReduce', {callback: true, promise:true}); + +/** + * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +} + +define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]}); + +/** + * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +} + +define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]}); + +// Get write concern +var writeConcern = function(target, db, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w != null) opts.w = options.w; + if(options.wtimeout != null) opts.wtimeout = options.wtimeout; + if(options.j != null) opts.j = options.j; + if(options.fsync != null) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Figure out the read preference +var getReadPreference = function(self, options, db, coll) { + var r = null + if(options.readPreference) { + r = options.readPreference + } else if(self.s.readPreference) { + r = self.s.readPreference + } else if(db.readPreference) { + r = db.readPreference; + } + + if(r instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else if(typeof r == 'string') { + options.readPreference = new CoreReadPreference(r); + } + + return options; +} + +var testForFields = { + limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 + , numberOfRetries: 1, awaitdata: 1, awaitData: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 + , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms: 1 +} + +module.exports = Collection; diff --git a/util/retroImporter/node_modules/mongodb/lib/command_cursor.js b/util/retroImporter/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 0000000..37df593 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,296 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = CommandCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(CommandCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' + , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled']; + +// Only inherit the types we need +for(var i = 0; i < methodsToInherit.length; i++) { + CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; +} + +var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {CommandCursor} + */ +CommandCursor.prototype.batchSize = function(value) { + if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ +CommandCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]}); + +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +define.classMethod('get', {callback: true, promise:false}); + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +CommandCursor.INIT = 0; +CommandCursor.OPEN = 1; +CommandCursor.CLOSED = 2; + +module.exports = CommandCursor; diff --git a/util/retroImporter/node_modules/mongodb/lib/cursor.js b/util/retroImporter/node_modules/mongodb/lib/cursor.js new file mode 100644 index 0000000..1a446a8 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,1149 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('mongodb-core').Cursor + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the mongodb-core and node.js + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +var fields = ['numberOfRetries', 'tailableRetryInterval']; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('exhaust', true) // Set cursor as exhaust + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor maxScan + * collection.find({}).maxScan(10) // Set the cursor maxScan + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(10) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).snapshot(true) // Set the cursor snapshot + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = Cursor.INIT; + var streamOptions = {}; + + // Tailable cursor options + var numberOfRetries = options.numberOfRetries || 5; + var tailableRetryInterval = options.tailableRetryInterval || 500; + var currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries + , tailableRetryInterval: tailableRetryInterval + , currentNumberOfRetries: currentNumberOfRetries + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespace + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + // Current doc + , currentDoc: null + } + + // Legacy fields + this.timeout = self.s.options.noCursorTimeout == true; + this.sortValue = self.s.cmd.sort; + this.readPreference = self.s.options.readPreference; +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(Cursor, Readable); + +// Map core cursor _next method so we can apply mapping +CoreCursor.prototype._next = CoreCursor.prototype.next; + +for(var name in CoreCursor.prototype) { + Cursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = Cursor.define = new Define('Cursor', Cursor, true); + +/** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.hasNext = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + if(self.s.currentDoc){ + return callback(null, true); + } else { + return nextObject(self, function(err, doc) { + if(!doc) return callback(null, false); + self.s.currentDoc = doc; + callback(null, true); + }); + } + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + if(self.s.currentDoc){ + resolve(true); + } else { + nextObject(self, function(err, doc) { + if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false); + if(err) return reject(err); + if(!doc) return resolve(false); + self.s.currentDoc = doc; + resolve(true); + }); + } + }); +} + +define.classMethod('hasNext', {callback: true, promise:true}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.next = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + return nextObject(self, callback) + }; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return resolve(doc); + } + + nextObject(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('next', {callback: true, promise:true}); + +/** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ +Cursor.prototype.filter = function(filter) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.query = filter; + return this; +} + +define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @return {Cursor} + */ +Cursor.prototype.maxScan = function(maxScan) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxScan = maxScan; + return this; +} + +define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ +Cursor.prototype.hint = function(hint) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.hint = hint; + return this; +} + +define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.min = function(min) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.min = min; + return this; +} + +define.classMethod('min', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.max = function(max) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.max = max; + return this; +} + +define.classMethod('max', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor returnKey + * @method + * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms: + * @return {Cursor} + */ +Cursor.prototype.returnKey = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.returnKey = value; + return this; +} + +define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ +Cursor.prototype.showRecordId = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.showDiskLoc = value; + return this; +} + +define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @return {Cursor} + */ +Cursor.prototype.snapshot = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.snapshot = value; + return this; +} + +define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setCursorOption = function(field, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true }); + this.s[field] = value; + if(field == 'numberOfRetries') + this.s.currentNumberOfRetries = value; + return this; +} + +define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addCursorFlag = function(flag, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true }); + if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true}); + this.s.cmd[flag] = value; + return this; +} + +define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addQueryModifier = function(name, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true}); + // Strip of the $ + var field = name.substr(1); + // Set on the command + this.s.cmd[field] = value; + // Deal with the special case for sort + if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field]; + return this; +} + +define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.comment = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.comment = value; + return this; +} + +define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxTimeMS = function(value) { + if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxTimeMS = value; + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]}); + +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.project = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.fields = value; + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.sort = function(keyOrList, direction) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + var order = keyOrList; + + if(direction != null) { + order = [[keyOrList, direction]]; + } + + this.s.cmd.sort = order; + this.sortValue = order; + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.batchSize = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true}); + if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + this.s.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.limit = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true}); + this.s.cmd.limit = value; + // this.cursorLimit = value; + this.setCursorLimit(value); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.skip = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true}); + this.s.cmd.skip = value; + this.setCursorSkip(value); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + +/** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + +/** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @deprecated + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.nextObject = Cursor.prototype.next; + +var nextObject = function(self, callback) { + if(self.s.state == Cursor.CLOSED || self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + if(self.s.state == Cursor.INIT && self.s.cmd.sort) { + try { + self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort); + } catch(err) { + return handleCallback(callback, err); + } + } + + // Get the next object + self._next(function(err, doc) { + if(err && err.tailable && self.s.currentNumberOfRetries == 0) return callback(err); + if(err && err.tailable && self.s.currentNumberOfRetries > 0) { + self.s.currentNumberOfRetries = self.s.currentNumberOfRetries - 1; + + return setTimeout(function() { + // Rewind the cursor only when it has not actually read any documents yet + if(self.cursorState.currentLimit == 0) self.rewind(); + // Read the next document, forcing a re-issue of query if no cursorId exists + self.nextObject(callback); + }, self.s.tailableRetryInterval); + } + + self.s.state = Cursor.OPEN; + if(err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +define.classMethod('nextObject', {callback: true, promise:true}); + +// Trampoline emptying the number of retrieved items +// without incurring a nextTick operation +var loop = function(self, callback) { + // No more items we are done + if(self.bufferedCount() == 0) return; + // Get the next document + self._next(callback); + // Loop + return loop; +} + +Cursor.prototype.next = Cursor.prototype.nextObject; + +define.classMethod('next', {callback: true, promise:true}); + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.each = function(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = Cursor.INIT; + // Run the query + _each(this, callback); +}; + +define.classMethod('each', {callback: true, promise:false}); + +// Run the each loop +var _each = function(self, callback) { + if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true}); + if(self.isNotified()) return; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + } + + if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN; + + // Define function to avoid global scope escape + var fn = null; + // Trampoline all the entries + if(self.bufferedCount() > 0) { + while(fn = loop(self, callback)) fn(self, callback); + _each(self, callback); + } else { + self.next(function(err, item) { + if(err) return handleCallback(callback, err); + if(item == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, null); + } + + if(handleCallback(callback, null, item) == false) return; + _each(self, callback); + }) + } +} + +/** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.forEach = function(iterator, callback) { + this.each(function(err, doc){ + if(err) { callback(err); return false; } + if(doc != null) { iterator(doc); return true; } + if(doc == null && callback) { + var internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); +} + +define.classMethod('forEach', {callback: true, promise:false}); + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setReadPreference = function(r) { + if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); + if(r instanceof ReadPreference) { + this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else { + this.s.options.readPreference = new CoreReadPreference(r); + } + + return this; +} + +define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.toArray = function(callback) { + var self = this; + if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true}); + + // Execute using callback + if(typeof callback == 'function') return toArray(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + toArray(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var toArray = function(self, callback) { + var items = []; + + // Reset cursor + self.rewind(); + self.s.state = Cursor.INIT; + + // Fetch all the documents + var fetchDocs = function() { + self._next(function(err, doc) { + if(err) return handleCallback(callback, err); + if(doc == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, items); + } + + // Add doc to items + items.push(doc) + + // Get all buffered objects + if(self.bufferedCount() > 0) { + var docs = self.readBufferedDocuments(self.bufferedCount()) + + // Transform the doc if transform method added + if(self.s.transforms && typeof self.s.transforms.doc == 'function') { + docs = docs.map(self.s.transforms.doc); + } + + items = items.concat(docs); + } + + // Attempt a fetch + fetchDocs(); + }) + } + + fetchDocs(); +} + +define.classMethod('toArray', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + +/** + * Get the count of documents for this cursor + * @method + * @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options=null] Optional settings. + * @param {number} [options.skip=null] The number of documents to skip. + * @param {number} [options.limit=null] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.count = function(applySkipLimit, opts, callback) { + var self = this; + if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true}); + if(typeof opts == 'function') callback = opts, opts = {}; + opts = opts || {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, applySkipLimit, opts, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, applySkipLimit, opts, callback) { + if(typeof applySkipLimit == 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if(applySkipLimit) { + if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip(); + if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit(); + } + + // Command + var delimiter = self.s.ns.indexOf('.'); + + var command = { + 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query + } + + if(typeof opts.maxTimeMS == 'number') { + command.maxTimeMS = opts.maxTimeMS; + } else if(typeof self.s.maxTimeMS == 'number') { + command.maxTimeMS = self.s.maxTimeMS; + } + + // Get a server + var server = self.s.topology.getServer(opts); + // Get a connection + var connection = self.s.topology.getConnection(opts); + // Get the callbacks + var callbacks = server.getCallbacks(); + + // Merge in any options + if(opts.skip) command.skip = opts.skip; + if(opts.limit) command.limit = opts.limit; + if(self.s.options.hint) command.hint = self.s.options.hint; + + // Build Query object + var query = new Query(self.s.bson, f("%s.$cmd", self.s.ns.substr(0, delimiter)), command, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false + }); + + // Set up callback + callbacks.register(query.requestId, function(err, result) { + if(err) return handleCallback(callback, err); + if(result.documents.length == 1 + && (result.documents[0].errmsg + || result.documents[0].err + || result.documents[0]['$err'])) { + return handleCallback(callback, MongoError.create(result.documents[0])); + } + handleCallback(callback, null, result.documents[0].n); + }); + + // Write the initial command out + connection.write(query.toBin()); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.close = function(callback) { + this.s.state = Cursor.CLOSED; + // Kill the cursor + this.kill(); + // Emit the close event for the cursor + this.emit('close'); + // Callback if provided + if(typeof callback == 'function') return handleCallback(callback, null, this); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {null} + */ +Cursor.prototype.map = function(transform) { + this.cursorState.transforms = { doc: transform }; + return this; +} + +define.classMethod('map', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Is the cursor closed + * @method + * @return {boolean} + */ +Cursor.prototype.isClosed = function() { + return this.isDead(); +} + +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); + +Cursor.prototype.destroy = function(err) { + this.pause(); + this.close(); + if(err) this.emit('error', err); +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options=null] Optional settings. + * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ +Cursor.prototype.stream = function(options) { + this.s.streamOptions = options || {}; + return this; +} + +define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.explain = function(callback) { + var self = this; + this.s.cmd.explain = true; + + // Execute using callback + if(typeof callback == 'function') return this._next(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self._next(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('explain', {callback: true, promise:true}); + +Cursor.prototype._read = function(n) { + var self = this; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return self.push(null); + } + + // Get the next item + self.nextObject(function(err, result) { + if(err) { + if(!self.isDead()) self.close(); + if(self.listeners('error') && self.listeners('error').length > 0) { + self.emit('error', err); + } + + // Emit end event + self.emit('end'); + return self.emit('finish'); + } + + // If we provided a transformation method + if(typeof self.s.streamOptions.transform == 'function' && result != null) { + return self.push(self.s.streamOptions.transform(result)); + } + + // If we provided a map function + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) { + return self.push(self.cursorState.transforms.doc(result)); + } + + // Return the result + self.push(result); + }); +} + +Object.defineProperty(Cursor.prototype, 'namespace', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + // TODO: refactor this logic into core + var ns = this.s.ns || ''; + var firstDot = ns.indexOf('.'); + if (firstDot < 0) { + return { + database: this.s.ns, + collection: '' + }; + } + return { + database: ns.substr(0, firstDot), + collection: ns.substr(firstDot + 1) + }; + } +}); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +Cursor.INIT = 0; +Cursor.OPEN = 1; +Cursor.CLOSED = 2; +Cursor.GET_MORE = 3; + +module.exports = Cursor; diff --git a/util/retroImporter/node_modules/mongodb/lib/db.js b/util/retroImporter/node_modules/mongodb/lib/db.js new file mode 100644 index 0000000..6667297 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/db.js @@ -0,0 +1,1731 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , getSingleProperty = require('./utils').getSingleProperty + , shallowClone = require('./utils').shallowClone + , parseIndexOptions = require('./utils').parseIndexOptions + , debugOptions = require('./utils').debugOptions + , CommandCursor = require('./command_cursor') + , handleCallback = require('./utils').handleCallback + , toError = require('./utils').toError + , ReadPreference = require('./read_preference') + , f = require('util').format + , Admin = require('./admin') + , Code = require('mongodb-core').BSON.Code + , CoreReadPreference = require('mongodb-core').ReadPreference + , MongoError = require('mongodb-core').MongoError + , ObjectID = require('mongodb-core').ObjectID + , Define = require('./metadata') + , Logger = require('mongodb-core').Logger + , Collection = require('./collection') + , crypto = require('crypto'); + +var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId' + , 'serializeFunctions', 'raw', 'promoteLongs', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds' + , 'readPreference', 'pkFactory']; + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * var testDb = db.db('test'); + * db.close(); + * }); + */ + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.native_parser=true] Select C++ bson parser instead of JavaScript parser. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. + * @param {number} [options.numberOfRetries=5] Number of times a tailable cursor will re-poll when it gets nothing back. + * @param {number} [options.retryMiliSeconds=500] Number of milliseconds between retries. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @fires Db#close + * @fires Db#authenticated + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +var Db = function(databaseName, topology, options) { + options = options || {}; + if(!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + var self = this; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // var self = this; // Internal state of the db object + this.s = { + // Database name + databaseName: databaseName + // DbCache + , dbCache: {} + // Children db's + , children: [] + // Topology + , topology: topology + // Options + , options: options + // Logger instance + , logger: Logger('Db', options) + // Get the bson parser + , bson: topology ? topology.bson : null + // Authsource if any + , authSource: options.authSource + // Unpack read preference + , readPreference: options.readPreference + // Set buffermaxEntries + , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1 + // Parent db (if chained) + , parentDb: options.parentDb || null + // Set up the primary key factory or fallback to ObjectID + , pkFactory: options.pkFactory || ObjectID + // Get native parser + , nativeParser: options.nativeParser || options.native_parser + // Promise library + , promiseLibrary: promiseLibrary + // No listener + , noListener: typeof options.noListener == 'boolean' ? options.noListener : false + // ReadConcern + , readConcern: options.readConcern + } + + // Ensure we have a valid db name + validateDatabaseName(self.s.databaseName); + + // If we have specified the type of parser + if(typeof self.s.nativeParser == 'boolean') { + if(self.s.nativeParser) { + topology.setBSONParserType("c++"); + } else { + topology.setBSONParserType("js"); + } + } + + // Add a read Only property + getSingleProperty(this, 'serverConfig', self.s.topology); + getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', self.s.databaseName); + + // Last ismaster + Object.defineProperty(this, 'options', { + enumerable:true, + get: function() { return self.s.options; } + }); + + // Last ismaster + Object.defineProperty(this, 'native_parser', { + enumerable:true, + get: function() { return self.s.topology.parserType() == 'c++'; } + }); + + // Last ismaster + Object.defineProperty(this, 'slaveOk', { + enumerable:true, + get: function() { + if(self.s.options.readPreference != null + && (self.s.options.readPreference != 'primary' || self.s.options.readPreference.mode != 'primary')) { + return true; + } + return false; + } + }); + + Object.defineProperty(this, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(self.s.options.w != null) ops.w = self.s.options.w; + if(self.s.options.j != null) ops.j = self.s.options.j; + if(self.s.options.fsync != null) ops.fsync = self.s.options.fsync; + if(self.s.options.wtimeout != null) ops.wtimeout = self.s.options.wtimeout; + return ops; + } + }); + + // This is a child db, do not register any listeners + if(options.parentDb) return; + if(this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(self, 'error', self)); + topology.on('timeout', createListener(self, 'timeout', self)); + topology.on('close', createListener(self, 'close', self)); + topology.on('parseError', createListener(self, 'parseError', self)); + topology.once('open', createListener(self, 'open', self)); + topology.once('fullsetup', createListener(self, 'fullsetup', self)); + topology.once('all', createListener(self, 'all', self)); + topology.on('reconnect', createListener(self, 'reconnect', self)); +} + +inherits(Db, EventEmitter); + +var define = Db.define = new Define('Db', Db, false); + +/** + * The callback format for the Db.open method + * @callback Db~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The Db instance if the open method was successful. + */ + +// Internal method +var open = function(self, callback) { + self.s.topology.connect(self, self.s.options, function(err, topology) { + if(callback == null) return; + var internalCallback = callback; + callback == null; + + if(err) { + self.close(); + return internalCallback(err); + } + + internalCallback(null, self); + }); +} + +/** + * Open the database + * @method + * @param {Db~openCallback} [callback] Callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.open = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + open(self, function(err, db) { + if(err) return reject(err); + resolve(db); + }) + }); +} + +define.classMethod('open', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Db~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +var executeCommand = function(self, command, options, callback) { + var dbName = options.dbName || options.authdb || self.s.databaseName; + // If we have a readPreference set + if(options.readPreference == null && self.s.readPreference) { + options.readPreference = self.s.readPreference; + } + + // Convert the readPreference + if(options.readPreference && typeof options.readPreference == 'string') { + options.readPreference = new CoreReadPreference(options.readPreference); + } else if(options.readPreference instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(options.readPreference.mode + , options.readPreference.tags); + } + + // Debug information + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]' + , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)))); + + // Execute command + self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); +} + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + var self = this; + // Change the callback + if(typeof options == 'function') callback = options, options = {}; + // Clone the options + options = shallowClone(options); + + // Do we have a callback + if(typeof callback == 'function') return executeCommand(self, command, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommand(self, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Db~noResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {null} result Is not set to a value + */ + +/** + * Close the db and it's underlying connections + * @method + * @param {boolean} force Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.close = function(force, callback) { + if(typeof force == 'function') callback = force, force = false; + this.s.topology.close(force); + var self = this; + + // Fire close event if any listeners + if(this.listeners('close').length > 0) { + this.emit('close'); + + // If it's the top level db emit close on all children + if(this.parentDb == null) { + // Fire close on all children + for(var i = 0; i < this.s.children.length; i++) { + this.s.children[i].emit('close'); + } + } + + // Remove listeners after emit + self.removeAllListeners('close'); + } + + // Close parent db if set + if(this.s.parentDb) this.s.parentDb.close(); + // Callback after next event loop tick + if(typeof callback == 'function') return process.nextTick(function() { + handleCallback(callback, null); + }) + + // Return dummy promise + return new this.s.promiseLibrary(function(resolve, reject) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +define.classMethod('admin', {callback: false, promise:false, returns: [Admin]}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can + * can use it without a callback in the following way. var collection = db.collection('mycollection'); + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} callback The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern || this.s.readConcern; + + // Do we have ignoreUndefined set + if(this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute + if(options == null || !options.strict) { + try { + var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options); + if(callback) callback(null, collection); + return collection; + } catch(err) { + if(callback) return callback(err); + throw err; + } + } + + // Strict mode + if(typeof callback != 'function') { + throw toError(f("A callback is required in strict mode. While getting collection %s.", name)); + } + + // Strict mode + this.listCollections({name:name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null); + + try { + return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + } catch(err) { + return handleCallback(callback, err, null); + } + }); +} + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +var createCollection = function(self, name, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self, options); + + // Check if we have the name + self.listCollections({name: name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length > 0 && finalOptions.strict) { + return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null); + } else if (collections.length > 0) { + try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); } + catch(err) { return handleCallback(callback, err); } + } + + // Create collection command + var cmd = {'create':name}; + + // Add all optional parameters + for(var n in options) { + if(options[n] != null && typeof options[n] != 'function') + cmd[n] = options[n]; + } + + // Execute command + self.command(cmd, finalOptions, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + }); + }); +} + +/** + * Creates a collection on a server pre-allocating space, need to create f.ex capped collections. + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {number} [options.size=null] The size of the capped collection in bytes. + * @param {number} [options.max=null] The maximum number of documents in the capped collection. + * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = function(name, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + name = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Do we have a promisesLibrary + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + + // Check if the callback is in fact a string + if(typeof callback == 'string') name = callback; + + // Execute the fallback callback + if(typeof callback == 'function') return createCollection(self, name, options, callback); + return new this.s.promiseLibrary(function(resolve, reject) { + createCollection(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('createCollection', {callback: true, promise:true}); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Build command object + var commandObject = { dbStats:true }; + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + // Execute the command + return this.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +// Transformation methods for cursor results +var listCollectionsTranforms = function(databaseName) { + var matching = f('%s.', databaseName); + + return { + doc: function(doc) { + var index = doc.name.indexOf(matching); + // Remove database name if available + if(doc.name && index == 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + } +} + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} filter Query to filter collections by + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + // Shallow clone the object + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // We have a list collections command + if(this.serverConfig.capabilities().hasListCollectionsCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listCollections : true, filter: filter, cursor: cursor }; + // Set the AggregationCursor constructor + options.cursorFactory = CommandCursor; + // Filter out the correct field values + options.transforms = listCollectionsTranforms(this.s.databaseName); + // Execute the cursor + return this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); + } + + // We cannot use the listCollectionsCommand + if(!this.serverConfig.capabilities().hasListCollectionsCommand) { + // If we have legacy mode and have not provided a full db name filter it + if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { + filter = shallowClone(filter); + filter.name = f('%s.%s', this.s.databaseName, filter.name); + } + } + + // No filter, filter by current database + if(filter == null) { + filter.name = f('/%s/', this.s.databaseName); + } + + // Rewrite the filter to use $and to filter out indexes + if(filter.name) { + filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]}; + } else { + filter = {name:/^((?!\$).)*$/}; + } + + // Return options + var options = {transforms: listCollectionsTranforms(this.s.databaseName)} + // Get the cursor + var cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, options); + // Set the passed in batch size if one was provided + if(options.batchSize) cursor = cursor.batchSize(options.batchSize); + // We have a fallback mode using legacy systems collections + return cursor; +}; + +define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]}); + +var evaluate = function(self, code, parameters, options, callback) { + var finalCode = code; + var finalParameters = []; + + // If not a code object translate to one + if(!(finalCode instanceof Code)) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if(parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = parameters; + } + + // Create execution selector + var cmd = {'$eval':finalCode, 'args':finalParameters}; + // Check if the nolock parameter is passed in + if(options['nolock']) { + cmd['nolock'] = options['nolock']; + } + + // Set primary read preference + options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY); + + // Execute the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result && result.ok == 1) return handleCallback(callback, null, result.retval); + if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null); + handleCallback(callback, err, result); + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = function(code, parameters, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + // Check if the callback is in fact a string + if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback); + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + evaluate(self, code, parameters, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('eval', {callback: true, promise:true}); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Add return new collection + options.new_collection = true; + + // Check if the callback is in fact a string + if(typeof callback == 'function') { + return this.collection(fromCollection).rename(toCollection, options, callback); + } + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.collection(fromCollection).rename(toCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('renameCollection', {callback: true, promise:true}); + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, callback) { + var self = this; + + // Command to execute + var cmd = {'drop':name} + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { + if(err) return handleCallback(callback, err); + if(result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, self.s.options, function(err, result) { + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +}; + +define.classMethod('dropCollection', {callback: true, promise:true}); + +/** + * Drop a database. + * + * @method + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(callback) { + var self = this; + // Drop database command + var cmd = {'dropDatabase':1}; + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, self.s.options, function(err, result) { + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +} + +define.classMethod('dropDatabase', {callback: true, promise:true}); + +/** + * The callback format for the collections method. + * @callback Db~collectionsResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection[]} collections An array of all the collections objects for the db instance. + */ +var collections = function(self, callback) { + // Let's get the collection names + self.listCollections().toArray(function(err, documents) { + if(err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(function(doc) { + return doc.name.indexOf('$') == -1; + }); + + // Return the collection objects + handleCallback(callback, null, documents.map(function(d) { + return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options); + })); + }); +} + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(callback) { + var self = this; + + // Return the callback + if(typeof callback == 'function') return collections(self, callback); + // Return the promise + return new self.s.promiseLibrary(function(resolve, reject) { + collections(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('collections', {callback: true, promise:true}); + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + if(options.readPreference) { + options.readPreference = options.readPreference; + } + + // Return the callback + if(typeof callback == 'function') return self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); + + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + if(err) return reject(err); + resolve(result.result); + }); + }); +}; + +define.classMethod('executeDbAdminCommand', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + // Shallow clone the options + options = shallowClone(options); + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // If we have a callback fallback + if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var createIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Ensure we have a callback + if(finalOptions.writeConcern && typeof callback != 'function') { + throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true}); + } + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { + if(err == null) return handleCallback(callback, err, result); + // Create command + var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + }); + }); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var ensureIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Create command + var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); + var index_name = selector.name; + + // Default command options + var commandOptions = {}; + // Check if the index allready exists + self.indexInformation(name, finalOptions, function(err, indexInformation) { + if(err != null && err.code != 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if(indexInformation == null || !indexInformation[index_name]) { + self.createIndex(name, fieldOrSpec, options, callback); + } else { + if(typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +Db.prototype.addChild = function(db) { + if(this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +} + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} name The name of the database we want to use. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +Db.prototype.db = function(dbName, options) { + options = options || {}; + // Copy the options and add out internal override of the not shared flag + for(var key in this.options) { + options[key] = this.options[key]; + } + + // Do we have the db in the cache already + if(this.s.dbCache[dbName] && options.returnNonCachedInstance !== true) { + return this.s.dbCache[dbName]; + } + + // Add current db as parentDb + if(options.noListener == null || options.noListener == false) { + options.parentDb = this; + } + + // Add promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Return the db object + var db = new Db(dbName, this.s.topology, options) + + // Add as child + if(options.noListener == null || options.noListener == false) { + this.addChild(db); + } + + // Add the db to the cache + this.s.dbCache[dbName] = db; + // Return the database + return db; +}; + +define.classMethod('db', {callback: false, promise:false, returns: [Db]}); + +var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { + // Special case where there is no password ($external users) + if(typeof username == 'string' + && password != null && typeof password == 'object') { + options = password; + password = null; + } + + // Unpack all options + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Error out if we digestPassword set + if(options.digestPassword != null) { + throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."); + } + + // Get additional values + var customData = options.customData != null ? options.customData : {}; + var roles = Array.isArray(options.roles) ? options.roles : []; + var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; + + // If not roles defined print deprecated message + if(roles.length == 0) { + console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"); + } + + // Get the error options + var commandOptions = {writeCommand:true}; + if(options['dbName']) commandOptions.dbName = options['dbName']; + + // Add maxTimeMS to options if set + if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Check the db name and add roles if needed + if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) { + roles = ['root'] + } else if(!Array.isArray(options.roles)) { + roles = ['dbOwner'] + } + + // Build the command to execute + var command = { + createUser: username + , customData: customData + , roles: roles + , digestPassword:false + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // No password + if(typeof password == 'string') { + command.pwd = userPassword; + } + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, !result.ok ? toError(result) : null + , result.ok ? [{user: username, pwd: ''}] : null); + }) +} + +var addUser = function(self, username, password, options, callback) { + // Attempt to execute auth command + _executeAuthCreateUserCommand(self, username, password, options, function(err, r) { + // We need to perform the backward compatible insert operation + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Check if we are inserting the first user + collection.count({}, function(err, count) { + // We got an error (f.ex not authorized) + if(err != null) return handleCallback(callback, err, null); + // Check if the user exists and update i + collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) { + // We got an error (f.ex not authorized) + if(err != null) return handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err, results, full) { + if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]); + if(err) return handleCallback(callback, err, null) + handleCallback(callback, null, [{user:username, pwd:userPassword}]); + }); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return addUser(self, username, password, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + addUser(self, username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('addUser', {callback: true, promise:true}); + +var _executeAuthRemoveUserCommand = function(self, username, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + // Get the error options + var commandOptions = {writeCommand:true}; + if(options['dbName']) commandOptions.dbName = options['dbName']; + + // Get additional values + var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; + + // Add maxTimeMS to options if set + if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Build the command to execute + var command = { + dropUser: username + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000}); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }) +} + +var removeUser = function(self, username, options, callback) { + // Attempt to execute command + _executeAuthRemoveUserCommand(self, username, options, function(err, result) { + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Locate the user + collection.findOne({user: username}, {}, function(err, user) { + if(user == null) return handleCallback(callback, err, false); + collection.remove({user: username}, finalOptions, function(err, result) { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return removeUser(self, username, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeUser(self, username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var authenticate = function(self, username, password, options, callback) { + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + var authdb = options.authdb ? options.authdb : options.dbName; + authdb = options.authSource ? options.authSource : authdb; + authdb = authdb ? authdb : self.databaseName; + + // Callback + var _callback = function(err, result) { + if(self.listeners('authenticated').length > 0) { + self.emit('authenticated', err, result); + } + + // Return to caller + handleCallback(callback, err, result); + } + + // authMechanism + var authMechanism = options.authMechanism || ''; + authMechanism = authMechanism.toUpperCase(); + + // If classic auth delegate to auth command + if(authMechanism == 'MONGODB-CR') { + self.s.topology.auth('mongocr', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'PLAIN') { + self.s.topology.auth('plain', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'MONGODB-X509') { + self.s.topology.auth('x509', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'SCRAM-SHA-1') { + self.s.topology.auth('scram-sha-1', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'GSSAPI') { + if(process.platform == 'win32') { + self.s.topology.auth('sspi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + self.s.topology.auth('gssapi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } + } else if(authMechanism == 'DEFAULT') { + self.s.topology.auth('default', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + handleCallback(callback, MongoError.create({message: f("authentication mechanism %s not supported", options.authMechanism), driver:true})); + } +} + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.authenticate = function(username, password, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + // Shallow copy the options + options = shallowClone(options); + + // Set default mechanism + if(!options.authMechanism) { + options.authMechanism = 'DEFAULT'; + } else if(options.authMechanism != 'GSSAPI' + && options.authMechanism != 'MONGODB-CR' + && options.authMechanism != 'MONGODB-X509' + && options.authMechanism != 'SCRAM-SHA-1' + && options.authMechanism != 'PLAIN') { + return handleCallback(callback, MongoError.create({message: "only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism", driver:true})); + } + + // If we have a callback fallback + if(typeof callback == 'function') return authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return callback(err, r); + callback(null, r); + }); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {object} [options=null] Optional settings. + * @param {string} [options.dbName=null] Logout against different database than current. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.logout = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // logout command + var cmd = {'logout':1}; + + // Add onAll to login to ensure all connection are logged out + options.onAll = true; + + // We authenticated against a different db use that + if(this.s.authSource) options.dbName = this.s.authSource; + + // Execute the command + if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true) + }); + + // Return promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.command(cmd, options, function(err, result) { + if(err) return reject(err); + resolve(true); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +// Figure out the read preference +var getReadPreference = function(options, db) { + if(options.readPreference) return options; + if(db.readPreference) options.readPreference = db.readPreference; + return options; +} + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return indexInformation(self, name, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var indexInformation = function(self, name, options, callback) { + // If we specified full information + var full = options['full'] == null ? false : options['full']; + + // Process all the results from the index command and collection + var processResults = function(indexes) { + // Contains all the information + var info = {}; + // Process all the indexes + for(var i = 0; i < indexes.length; i++) { + var index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for(var name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + self.collection(name).listIndexes().toArray(function(err, indexes) { + if(err) return callback(toError(err)); + if(!Array.isArray(indexes)) return handleCallback(callback, null, []); + if(full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { + var indexParameters = parseIndexOptions(fieldOrSpec); + var fieldHash = indexParameters.fieldHash; + var keys = indexParameters.keys; + + // Generate the index name + var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; + var selector = { + 'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName + } + + // Ensure we have a correct finalUnique + var finalUnique = options == null || 'object' === typeof options ? false : options; + // Set up options + options = options == null || typeof options == 'boolean' ? {} : options; + + // Add all the options + var keysToOmit = Object.keys(selector); + for(var optionName in options) { + if(keysToOmit.indexOf(optionName) == -1) { + selector[optionName] = options[optionName]; + } + } + + if(selector['unique'] == null) selector['unique'] = finalUnique; + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { + // Build the index + var indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; + // Set up the index + var indexes = [{ name: indexName, key: indexParameters.fieldHash }]; + // merge all the options + var keysToOmit = Object.keys(indexes[0]); + for(var optionName in options) { + if(keysToOmit.indexOf(optionName) == -1) { + indexes[0][optionName] = options[optionName]; + } + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete indexes[0][removeKeys[i]]; + } + } + + // Create command + var cmd = {createIndexes: name, indexes: indexes}; + + // Apply write concern to command + cmd = writeConcern(cmd, self, options); + + // Build the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result.ok == 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +// Validate the database name +var validateDatabaseName = function(databaseName) { + if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true}); + if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true}); + if(databaseName == '$external') return; + + var invalidChars = [" ", ".", "$", "/", "\\"]; + for(var i = 0; i < invalidChars.length; i++) { + if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true}); + } +} + +// Get write concern +var writeConcern = function(target, db, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w) opts.w = options.w; + if(options.wtimeout) opts.wtimeout = options.wtimeout; + if(options.j) opts.j = options.j; + if(options.fsync) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Add listeners to topology +var createListener = function(self, e, object) { + var listener = function(err) { + if(e != 'error') { + object.emit(e, err, self); + + // Emit on all associated db's if available + for(var i = 0; i < self.s.children.length; i++) { + self.s.children[i].emit(e, err, self.s.children[i]); + } + } + } + return listener; +} + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db authenticated event + * + * Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated. + * + * @event Db#authenticated + * @type {object} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; +Db.SYSTEM_INDEX_COLLECTION = "system.indexes"; +Db.SYSTEM_PROFILE_COLLECTION = "system.profile"; +Db.SYSTEM_USER_COLLECTION = "system.users"; +Db.SYSTEM_COMMAND_COLLECTION = "$cmd"; +Db.SYSTEM_JS_COLLECTION = "system.js"; + +module.exports = Db; diff --git a/util/retroImporter/node_modules/mongodb/lib/gridfs/chunk.js b/util/retroImporter/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 0000000..d96095f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,237 @@ +"use strict"; + +var Binary = require('mongodb-core').BSON.Binary, + ObjectID = require('mongodb-core').BSON.ObjectID; + +/** + * Class for representing a single chunk in GridFS. + * + * @class + * + * @param file {GridStore} The {@link GridStore} object holding this chunk. + * @param mongoObject {object} The mongo object representation of this chunk. + * + * @throws Error when the type of data field for {@link mongoObject} is not + * supported. Currently supported types for data field are instances of + * {@link String}, {@link Array}, {@link Binary} and {@link Binary} + * from the bson module + * + * @see Chunk#buildMongoObject + */ +var Chunk = function(file, mongoObject, writeConcern) { + if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); + + this.file = file; + var self = this; + var mongoObjectFinal = mongoObject == null ? {} : mongoObject; + this.writeConcern = writeConcern || {w:1}; + this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; + this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; + this.data = new Binary(); + + if(mongoObjectFinal.data == null) { + } else if(typeof mongoObjectFinal.data == "string") { + var buffer = new Buffer(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if(Array.isArray(mongoObjectFinal.data)) { + var buffer = new Buffer(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if(mongoObjectFinal.data._bsontype === 'Binary') { + this.data = mongoObjectFinal.data; + } else if(Buffer.isBuffer(mongoObjectFinal.data)) { + } else { + throw Error("Illegal chunk format"); + } + + // Update position + this.internalPosition = 0; +}; + +/** + * Writes a data to this object and advance the read/write head. + * + * @param data {string} the data to write + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.write = function(data, callback) { + this.data.write(data, this.internalPosition, data.length, 'binary'); + this.internalPosition = this.data.length(); + if(callback != null) return callback(null, this); + return this; +}; + +/** + * Reads data and advances the read/write head. + * + * @param length {number} The length of data to read. + * + * @return {string} The data read if the given length will not exceed the end of + * the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.read = function(length) { + // Default to full read if no index defined + length = length == null || length == 0 ? this.length() : length; + + if(this.length() - this.internalPosition + 1 >= length) { + var data = this.data.read(this.internalPosition, length); + this.internalPosition = this.internalPosition + length; + return data; + } else { + return ''; + } +}; + +Chunk.prototype.readSlice = function(length) { + if ((this.length() - this.internalPosition) >= length) { + var data = null; + if (this.data.buffer != null) { //Pure BSON + data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); + } else { //Native BSON + data = new Buffer(length); + length = this.data.readInto(data, this.internalPosition); + } + this.internalPosition = this.internalPosition + length; + return data; + } else { + return null; + } +}; + +/** + * Checks if the read/write head is at the end. + * + * @return {boolean} Whether the read/write head has reached the end of this + * chunk. + */ +Chunk.prototype.eof = function() { + return this.internalPosition == this.length() ? true : false; +}; + +/** + * Reads one character from the data of this chunk and advances the read/write + * head. + * + * @return {string} a single character data read if the the read/write head is + * not at the end of the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.getc = function() { + return this.read(1); +}; + +/** + * Clears the contents of the data in this chunk and resets the read/write head + * to the initial position. + */ +Chunk.prototype.rewind = function() { + this.internalPosition = 0; + this.data = new Binary(); +}; + +/** + * Saves this chunk to the database. Also overwrites existing entries having the + * same id as this chunk. + * + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.save = function(options, callback) { + var self = this; + if(typeof options == 'function') { + callback = options; + options = {}; + } + + self.file.chunkCollection(function(err, collection) { + if(err) return callback(err); + + // Merge the options + var writeOptions = {}; + for(var name in options) writeOptions[name] = options[name]; + for(var name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + // collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) { + collection.remove({'_id':self.objectId}, writeOptions, function(err, result) { + if(err) return callback(err); + + if(self.data.length() > 0) { + self.buildMongoObject(function(mongoObject) { + var options = {forceServerObjectId:true}; + for(var name in self.writeConcern) { + options[name] = self.writeConcern[name]; + } + + collection.insert(mongoObject, writeOptions, function(err, collection) { + callback(err, self); + }); + }); + } else { + callback(null, self); + } + }); + }); +}; + +/** + * Creates a mongoDB object representation of this chunk. + * + * @param callback {function(Object)} This will be called after executing this + * method. The object will be passed to the first parameter and will have + * the structure: + * + *

+ *        {
+ *          '_id' : , // {number} id for this chunk
+ *          'files_id' : , // {number} foreign key to the file collection
+ *          'n' : , // {number} chunk number
+ *          'data' : , // {bson#Binary} the chunk data itself
+ *        }
+ *        
+ * + * @see MongoDB GridFS Chunk Object Structure + */ +Chunk.prototype.buildMongoObject = function(callback) { + var mongoObject = { + 'files_id': this.file.fileId, + 'n': this.chunkNumber, + 'data': this.data}; + // If we are saving using a specific ObjectId + if(this.objectId != null) mongoObject._id = this.objectId; + + callback(mongoObject); +}; + +/** + * @return {number} the length of the data + */ +Chunk.prototype.length = function() { + return this.data.length(); +}; + +/** + * The position of the read/write head + * @name position + * @lends Chunk# + * @field + */ +Object.defineProperty(Chunk.prototype, "position", { enumerable: true + , get: function () { + return this.internalPosition; + } + , set: function(value) { + this.internalPosition = value; + } +}); + +/** + * The default chunk size + * @constant + */ +Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; + +module.exports = Chunk; diff --git a/util/retroImporter/node_modules/mongodb/lib/gridfs/grid_store.js b/util/retroImporter/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 0000000..62943bd --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1919 @@ +"use strict"; + +/** + * @fileOverview GridFS is a tool for MongoDB to store files to the database. + * Because of the restrictions of the object size the database can hold, a + * facility to split a file into several chunks is needed. The {@link GridStore} + * class offers a simplified api to interact with files while managing the + * chunks of split files behind the scenes. More information about GridFS can be + * found here. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * GridStore = require('mongodb').GridStore, + * ObjectID = require('mongodb').ObjectID, + * test = require('assert'); + * + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * var gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * db.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +var Chunk = require('./chunk'), + ObjectID = require('mongodb-core').BSON.ObjectID, + ReadPreference = require('../read_preference'), + Buffer = require('buffer').Buffer, + Collection = require('../collection'), + fs = require('fs'), + timers = require('timers'), + f = require('util').format, + util = require('util'), + Define = require('../metadata'), + MongoError = require('mongodb-core').MongoError, + inherits = util.inherits, + Duplex = require('stream').Duplex || require('readable-stream').Duplex; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +/** + * Namespace provided by the mongodb-core and node.js + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwriten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [id] optional unique id for this file + * @param {string} [filename] optional filename for this file, no unique constrain on the field + * @param {string} mode set the mode for this file. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata=null] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + */ +var GridStore = function GridStore(db, id, filename, mode, options) { + if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); + var self = this; + this.db = db; + + // Handle options + if(typeof options === 'undefined') options = {}; + // Handle mode + if(typeof mode === 'undefined') { + mode = filename; + filename = undefined; + } else if(typeof mode == 'object') { + options = mode; + mode = filename; + filename = undefined; + } + + if(id instanceof ObjectID) { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } else if(typeof filename == 'undefined') { + this.referenceBy = REFERENCE_BY_FILENAME; + this.filename = id; + if (mode.indexOf('w') != null) { + this.fileId = new ObjectID(); + } + } else { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } + + // Set up the rest + this.mode = mode == null ? "r" : mode; + this.options = options || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = this.options.readPreference || db.options.readPreference || ReadPreference.PRIMARY; + this.writeConcern = _getWriteConcern(db, this.options); + // Set default chunk size + this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, "chunkSize", { enumerable: true + , get: function () { + return this.internalChunkSize; + } + , set: function(value) { + if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { + this.internalChunkSize = this.internalChunkSize; + } else { + this.internalChunkSize = value; + } + } + }); + + Object.defineProperty(this, "md5", { enumerable: true + , get: function () { + return this.internalMd5; + } + }); + + Object.defineProperty(this, "chunkNumber", { enumerable: true + , get: function () { + return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; + } + }); +} + +var define = GridStore.define = new Define('Gridstore', GridStore, true); + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.open = function(callback) { + var self = this; + if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ + throw MongoError.create({message: "Illegal mode " + this.mode, driver:true}); + } + + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + open(self, function(err, store) { + if(err) return reject(err); + resolve(store); + }) + }); +}; + +var open = function(self, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.options); + + // If we are writing we need to ensure we have the right indexes for md5's + if((self.mode == "w" || self.mode == "w+")) { + // Get files collection + var collection = self.collection(); + // Put index on filename + collection.ensureIndex([['filename', 1]], writeConcern, function(err, index) { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], writeConcern, function(err, index) { + // Open the connection + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +} + +// Push the definition for open +define.classMethod('open', {callback: true, promise:true}); + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + */ +GridStore.prototype.eof = function() { + return this.position == this.length ? true : false; +} + +define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]}); + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.getc = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return eof(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + eof(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var eof = function(self, callback) { + if(self.eof()) { + callback(null, null); + } else if(self.currentChunk.eof()) { + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + self.currentChunk = chunk; + self.position = self.position + 1; + callback(err, self.currentChunk.getc()); + }); + } else { + self.position = self.position + 1; + callback(null, self.currentChunk.getc()); + } +} + +define.classMethod('getc', {callback: true, promise:true}); + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.puts = function(string, callback) { + var self = this; + var finalString = string.match(/\n$/) == null ? string + "\n" : string; + // We provided a callback leg + if(typeof callback == 'function') return this.write(finalString, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + self.write(finalString, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('puts', {callback: true, promise:true}); + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +} + +define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]}); + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.write = function write(data, close, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return _writeNormal(this, data, close, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + _writeNormal(self, data, close, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('write', {callback: true, promise:true}); + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + */ +GridStore.prototype.destroy = function destroy() { + // close and do not emit any more events. queued data is not sent. + if(!this.writable) return; + this.readable = false; + if(this.writable) { + this.writable = false; + this._q.length = 0; + this.emit('close'); + } +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.writeFile = function (file, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return writeFile(self, file, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + writeFile(self, file, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var writeFile = function(self, file, callback) { + if (typeof file === 'string') { + fs.open(file, 'r', function (err, fd) { + if(err) return callback(err); + self.writeFile(fd, callback); + }); + return; + } + + self.open(function (err, self) { + if(err) return callback(err, self); + + fs.fstat(file, function (err, stats) { + if(err) return callback(err, self); + + var offset = 0; + var index = 0; + var numberOfChunksLeft = Math.min(stats.size / self.chunkSize); + + // Write a chunk + var writeChunk = function() { + fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { + if(err) return callback(err, self); + + offset = offset + bytesRead; + + // Create a new chunk for the data + var chunk = new Chunk(self, {n:index++}, self.writeConcern); + chunk.write(data, function(err, chunk) { + if(err) return callback(err, self); + + chunk.save({}, function(err, result) { + if(err) return callback(err, self); + + self.position = self.position + data.length; + + // Point to current chunk + self.currentChunk = chunk; + + if(offset >= stats.size) { + fs.close(file); + self.close(function(err, result) { + if(err) return callback(err, self); + return callback(null, self); + }); + } else { + return process.nextTick(writeChunk); + } + }); + }); + }); + } + + // Process the first write + process.nextTick(writeChunk); + }); + }); +} + +define.classMethod('writeFile', {callback: true, promise:true}); + +/** + * Saves this file to the database. This will overwrite the old entry if it + * already exists. This will work properly only if mode was initialized to + * "w" or "w+". + * + * @method + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.close = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return close(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + close(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var close = function(self, callback) { + if(self.mode[0] == "w") { + // Set up options + var options = self.writeConcern; + + if(self.currentChunk != null && self.currentChunk.position > 0) { + self.currentChunk.save({}, function(err, chunk) { + if(err && typeof callback == 'function') return callback(err); + + self.collection(function(err, files) { + if(err && typeof callback == 'function') return callback(err); + + // Build the mongo object + if(self.uploadDate != null) { + files.remove({'_id':self.fileId}, self.writeConcern, function(err, collection) { + if(err && typeof callback == 'function') return callback(err); + + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + }); + } else { + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + } + }); + }); + } else { + self.collection(function(err, files) { + if(err && typeof callback == 'function') return callback(err); + + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + }); + } + } else if(self.mode[0] == "r") { + if(typeof callback == 'function') + callback(null, null); + } else { + if(typeof callback == 'function') + callback(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true})); + } +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + */ +GridStore.prototype.chunkCollection = function(callback) { + if(typeof callback == 'function') + return this.db.collection((this.root + ".chunks"), callback); + return this.db.collection((this.root + ".chunks")); +}; + +define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]}); + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.unlink = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return unlink(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + unlink(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlink = function(self, callback) { + deleteChunks(self, function(err) { + if(err!==null) { + err.message = "at deleteChunks: " + err.message; + return callback(err); + } + + self.collection(function(err, collection) { + if(err!==null) { + err.message = "at collection: " + err.message; + return callback(err); + } + + collection.remove({'_id':self.fileId}, self.writeConcern, function(err) { + callback(err, self); + }); + }); + }); +} + +define.classMethod('unlink', {callback: true, promise:true}); + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + */ +GridStore.prototype.collection = function(callback) { + if(typeof callback == 'function') + this.db.collection(this.root + ".files", callback); + return this.db.collection(this.root + ".files"); +}; + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.readlines = function(separator, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : "\n"; + separator = separator || "\n"; + + // We provided a callback leg + if(typeof callback == 'function') return readlines(self, separator, callback); + + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + readlines(self, separator, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlines = function(self, separator, callback) { + self.read(function(err, data) { + if(err) return callback(err); + + var items = data.toString().split(separator); + items = items.length > 0 ? items.splice(0, items.length - 1) : []; + for(var i = 0; i < items.length; i++) { + items[i] = items[i] + separator; + } + + callback(null, items); + }); +} + +define.classMethod('readlines', {callback: true, promise:true}); + +/** + * Deletes all the chunks of this file in the database if mode was set to "w" or + * "w+" and resets the read/write head to the initial position. + * + * @method + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.rewind = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return rewind(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + rewind(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var rewind = function(self, callback) { + if(self.currentChunk.chunkNumber != 0) { + if(self.mode[0] == "w") { + deleteChunks(self, function(err, gridStore) { + if(err) return callback(err); + self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); + self.position = 0; + callback(null, self); + }); + } else { + self.currentChunk(0, function(err, chunk) { + if(err) return callback(err); + self.currentChunk = chunk; + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + }); + } + } else { + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + } +} + +define.classMethod('rewind', {callback: true, promise:true}); + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. + * + * There are 3 signatures for this method: + * + * (callback) + * (length, callback) + * (length, buffer, callback) + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.read = function(length, buffer, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + // We provided a callback leg + if(typeof callback == 'function') return read(self, length, buffer, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + read(self, length, buffer, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var read = function(self, length, buffer, callback) { + // The data is a c-terminated string and thus the length - 1 + var finalLength = length == null ? self.length - self.position : length; + var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; + // Add a index to buffer to keep track of writing position or apply current index + finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; + + if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { + var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update internal position + self.position = self.position + finalBuffer.length; + // Check if we don't have a file at all + if(finalLength == 0 && finalBuffer.length == 0) return callback(MongoError.create({message: "File does not exist", driver:true}), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update index position + finalBuffer._index += slice.length; + + // Load next chunk and read more + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + if(err) return callback(err); + + if(chunk.length() > 0) { + self.currentChunk = chunk; + self.read(length, finalBuffer, callback); + } else { + if(finalBuffer._index > 0) { + callback(null, finalBuffer) + } else { + callback(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null); + } + } + }); +} + +define.classMethod('read', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + resolve(self.position); + }); +}; + +define.classMethod('tell', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * Moves the read/write head to a new location. + * + * There are 3 signatures for this method + * + * Seek Location Modes + * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. + * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. + * - **GridStore.IO_SEEK_END**, set the position from the end of the file. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.seek = function(position, seekLocation, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + seekLocation = args.length ? args.shift() : null; + + // We provided a callback leg + if(typeof callback == 'function') return seek(self, position, seekLocation, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + seek(self, position, seekLocation, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var seek = function(self, position, seekLocation, callback) { + // Seek only supports read mode + if(self.mode != 'r') { + return callback(MongoError.create({message: "seek is only supported for mode r", driver:true})) + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if(seekLocationFinal == GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if(seekLocationFinal == GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition/self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = (self.position % self.chunkSize); + callback(err, self); + }); + }; + + seekChunk(); +} + +define.classMethod('seek', {callback: true, promise:true}); + +/** + * @ignore + */ +var _open = function(self, options, callback) { + var collection = self.collection(); + // Create the query + var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; + query = null == self.fileId && self.filename == null ? null : query; + options.readPreference = self.readPreference; + + // Fetch the chunks + if(query != null) { + collection.findOne(query, options, function(err, doc) { + if(err) return error(err); + + // Check if the collection for the files exists otherwise prepare the new one + if(doc != null) { + self.fileId = doc._id; + // Prefer a new filename over the existing one if this is a write + self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename; + self.contentType = doc.contentType; + self.internalChunkSize = doc.chunkSize; + self.uploadDate = doc.uploadDate; + self.aliases = doc.aliases; + self.length = doc.length; + self.metadata = doc.metadata; + self.internalMd5 = doc.md5; + } else if (self.mode != 'r') { + self.fileId = self.fileId == null ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + } else { + self.length = 0; + var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId; + return error(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename)), driver:true}), self); + } + + // Process the mode of the object + if(self.mode == "r") { + nthChunk(self, 0, options, function(err, chunk) { + if(err) return error(err); + self.currentChunk = chunk; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w") { + // Delete any existing chunks + deleteChunks(self, options, function(err, result) { + if(err) return error(err); + self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); + self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w+") { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if(err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + }); + } else { + // Write only mode + self.fileId = null == self.fileId ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + + var collection2 = self.chunkCollection(); + // No file exists set up write mode + if(self.mode == "w") { + // Delete any existing chunks + deleteChunks(self, options, function(err, result) { + if(err) return error(err); + self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); + self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w+") { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if(err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + } + + // only pass error to callback once + function error (err) { + if(error.err) return; + callback(error.err = err); + } +}; + +/** + * @ignore + */ +var writeBuffer = function(self, buffer, close, callback) { + if(typeof close === "function") { callback = close; close = null; } + var finalClose = typeof close == 'boolean' ? close : false; + + if(self.mode != "w") { + callback(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename)), driver:true}), null); + } else { + if(self.currentChunk.position + buffer.length >= self.chunkSize) { + // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left + // to a new chunk (recursively) + var previousChunkNumber = self.currentChunk.chunkNumber; + var leftOverDataSize = self.chunkSize - self.currentChunk.position; + var firstChunkData = buffer.slice(0, leftOverDataSize); + var leftOverData = buffer.slice(leftOverDataSize); + // A list of chunks to write out + var chunksToWrite = [self.currentChunk.write(firstChunkData)]; + // If we have more data left than the chunk size let's keep writing new chunks + while(leftOverData.length >= self.chunkSize) { + // Create a new chunk and write to it + var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); + var firstChunkData = leftOverData.slice(0, self.chunkSize); + leftOverData = leftOverData.slice(self.chunkSize); + // Update chunk number + previousChunkNumber = previousChunkNumber + 1; + // Write data + newChunk.write(firstChunkData); + // Push chunk to save list + chunksToWrite.push(newChunk); + } + + // Set current chunk with remaining data + self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); + // If we have left over data write it + if(leftOverData.length > 0) self.currentChunk.write(leftOverData); + + // Update the position for the gridstore + self.position = self.position + buffer.length; + // Total number of chunks to write + var numberOfChunksToWrite = chunksToWrite.length; + + for(var i = 0; i < chunksToWrite.length; i++) { + chunksToWrite[i].save({}, function(err, result) { + if(err) return callback(err); + + numberOfChunksToWrite = numberOfChunksToWrite - 1; + + if(numberOfChunksToWrite <= 0) { + // We care closing the file before returning + if(finalClose) { + return self.close(function(err, result) { + callback(err, self); + }); + } + + // Return normally + return callback(null, self); + } + }); + } + } else { + // Update the position for the gridstore + self.position = self.position + buffer.length; + // We have less data than the chunk size just write it and callback + self.currentChunk.write(buffer); + // We care closing the file before returning + if(finalClose) { + return self.close(function(err, result) { + callback(err, self); + }); + } + // Return normally + return callback(null, self); + } + } +}; + +/** + * Creates a mongoDB object representation of this object. + * + *

+ *        {
+ *          '_id' : , // {number} id for this file
+ *          'filename' : , // {string} name for this file
+ *          'contentType' : , // {string} mime type for this file
+ *          'length' : , // {number} size of this file?
+ *          'chunksize' : , // {number} chunk size used by this file
+ *          'uploadDate' : , // {Date}
+ *          'aliases' : , // {array of string}
+ *          'metadata' : , // {string}
+ *        }
+ *        
+ * + * @ignore + */ +var buildMongoObject = function(self, callback) { + // Calcuate the length + var mongoObject = { + '_id': self.fileId, + 'filename': self.filename, + 'contentType': self.contentType, + 'length': self.position ? self.position : 0, + 'chunkSize': self.chunkSize, + 'uploadDate': self.uploadDate, + 'aliases': self.aliases, + 'metadata': self.metadata + }; + + var md5Command = {filemd5:self.fileId, root:self.root}; + self.db.command(md5Command, function(err, results) { + if(err) return callback(err); + + mongoObject.md5 = results.md5; + callback(null, mongoObject); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +var nthChunk = function(self, chunkNumber, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + options.readPreference = self.readPreference; + // Get the nth chunk + self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) { + if(err) return callback(err); + + var finalChunk = chunk == null ? {} : chunk; + callback(null, new Chunk(self, finalChunk, self.writeConcern)); + }); +}; + +/** + * @ignore + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +var deleteChunks = function(self, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + + if(self.fileId != null) { + self.chunkCollection().remove({'files_id':self.fileId}, options, function(err, result) { + if(err) return callback(err, false); + callback(null, true); + }); + } else { + callback(null, true); + } +}; + +/** +* The collection to be used for holding the files and chunks collection. +* +* @classconstant DEFAULT_ROOT_COLLECTION +**/ +GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; + +/** +* Default file mime type +* +* @classconstant DEFAULT_CONTENT_TYPE +**/ +GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; + +/** +* Seek mode where the given length is absolute. +* +* @classconstant IO_SEEK_SET +**/ +GridStore.IO_SEEK_SET = 0; + +/** +* Seek mode where the given length is an offset to the current read/write head. +* +* @classconstant IO_SEEK_CUR +**/ +GridStore.IO_SEEK_CUR = 1; + +/** +* Seek mode where the given length is an offset to the end of the file. +* +* @classconstant IO_SEEK_END +**/ +GridStore.IO_SEEK_END = 2; + +/** + * Checks if a file exists in the database. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file to look for. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + exists(db, fileIdObject, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Fetch collection + var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + db.collection(rootCollectionFinal + ".files", function(err, collection) { + if(err) return callback(err); + + // Build query + var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) + ? {'filename':fileIdObject} + : {'_id':fileIdObject}; // Attempt to locate file + + // We have a specific query + if(fileIdObject != null + && typeof fileIdObject == 'object' + && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, {readPreference:readPreference}, function(err, item) { + if(err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +} + +define.staticMethod('exist', {callback: true, promise:true}); + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return list(db, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + list(db, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if(rootCollection != null && typeof rootCollection == 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Check if we are returning by id not filename + var byId = options['id'] != null ? options['id'] : false; + // Fetch item + var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + var items = []; + db.collection((rootCollectionFinal + ".files"), function(err, collection) { + if(err) return callback(err); + + collection.find({}, {readPreference:readPreference}, function(err, cursor) { + if(err) return callback(err); + + cursor.each(function(err, item) { + if(item != null) { + items.push(byId ? item._id : item.filename); + } else { + callback(err, items); + } + }); + }); + }); +} + +define.staticMethod('list', {callback: true, promise:true}); + +/** + * Reads the contents of a file. + * + * This method has the following signatures + * + * (db, name, callback) + * (db, name, length, callback) + * (db, name, length, offset, callback) + * (db, name, length, offset, options, callback) + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file. + * @param {number} [length] The size of data to read. + * @param {number} [offset] The offset from the head of the file of which to start reading from. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ + +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readStatic(db, name, length, offset, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + new GridStore(db, name, "r", options).open(function(err, gridStore) { + if(err) return callback(err); + // Make sure we are not reading out of bounds + if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); + if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); + if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); + + if(offset != null) { + gridStore.seek(offset, function(err, gridStore) { + if(err) return callback(err); + gridStore.read(length, callback); + }); + } else { + gridStore.read(length, callback); + } + }); +} + +define.staticMethod('read', {callback: true, promise:true}); + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readlinesStatic(db, name, separator, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + var finalSeperator = separator == null ? "\n" : separator; + new GridStore(db, name, "r", options).open(function(err, gridStore) { + if(err) return callback(err); + gridStore.readlines(finalSeperator, callback); + }); +} + +define.staticMethod('readlines', {callback: true, promise:true}); + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options=null] Optional settings. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.unlink = function(db, names, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback); + + // Return promise + return new promiseLibrary(function(resolve, reject) { + unlinkStatic(self, db, names, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(db, options); + + // List of names + if(names.constructor == Array) { + var tc = 0; + for(var i = 0; i < names.length; i++) { + ++tc; + GridStore.unlink(db, names[i], options, function(result) { + if(--tc == 0) { + callback(null, self); + } + }); + } + } else { + new GridStore(db, names, "w", options).open(function(err, gridStore) { + if(err) return callback(err); + deleteChunks(gridStore, function(err, result) { + if(err) return callback(err); + gridStore.collection(function(err, collection) { + if(err) return callback(err); + collection.remove({'_id':gridStore.fileId}, writeConcern, function(err, result) { + callback(err, self); + }); + }); + }); + }); + } +} + +define.staticMethod('unlink', {callback: true, promise:true}); + +/** + * @ignore + */ +var _writeNormal = function(self, data, close, callback) { + // If we have a buffer write it using the writeBuffer method + if(Buffer.isBuffer(data)) { + return writeBuffer(self, data, close, callback); + } else { + return writeBuffer(self, new Buffer(data, 'binary'), close, callback); + } +} + +/** + * @ignore + */ +var _setWriteConcernHash = function(options) { + var finalOptions = {}; + if(options.w != null) finalOptions.w = options.w; + if(options.journal == true) finalOptions.j = options.journal; + if(options.j == true) finalOptions.j = options.j; + if(options.fsync == true) finalOptions.fsync = options.fsync; + if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; + return finalOptions; +} + +/** + * @ignore + */ +var _getWriteConcern = function(self, options) { + // Final options + var finalOptions = {w:1}; + options = options || {}; + + // Local options verification + if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { + finalOptions = _setWriteConcernHash(options); + } else if(options.safe != null && typeof options.safe == 'object') { + finalOptions = _setWriteConcernHash(options.safe); + } else if(typeof options.safe == "boolean") { + finalOptions = {w: (options.safe ? 1 : 0)}; + } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { + finalOptions = _setWriteConcernHash(self.options); + } else if(self.safe && (self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean')) { + finalOptions = _setWriteConcernHash(self.safe); + } else if(typeof self.safe == "boolean") { + finalOptions = {w: (self.safe ? 1 : 0)}; + } + + // Ensure we don't have an invalid combination of write concerns + if(finalOptions.w < 1 + && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw MongoError.create({message: "No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true", driver:true}); + + // Return the options + return finalOptions; +} + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + */ +var GridStoreStream = function(gs) { + var self = this; + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +} + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if(!self.gs.isOpen) { + self.gs.open(function(err) { + if(err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } +} + +// Called by stream +GridStoreStream.prototype._read = function(n) { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if(err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if(self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if(buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if(buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if(self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + } + + // Set read length + var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if(!self.gs.isOpen) { + self.gs.open(function(err, gs) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if(err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +} + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +} + +GridStoreStream.prototype.write = function(chunk, encoding, callback) { + var self = this; + if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true})) + // Do we have to open the gridstore + if(!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +} + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if(chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); + }); + } + + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); +} + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/util/retroImporter/node_modules/mongodb/lib/metadata.js b/util/retroImporter/node_modules/mongodb/lib/metadata.js new file mode 100644 index 0000000..7dae562 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/metadata.js @@ -0,0 +1,64 @@ +var f = require('util').format; + +var Define = function(name, object, stream) { + this.name = name; + this.object = object; + this.stream = typeof stream == 'boolean' ? stream : false; + this.instrumentations = {}; +} + +Define.prototype.classMethod = function(name, options) { + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +var generateKey = function(keys, options) { + var parts = []; + for(var i = 0; i < keys.length; i++) { + parts.push(f('%s=%s', keys[i], options[keys[i]])); + } + + return parts.join(); +} + +Define.prototype.staticMethod = function(name, options) { + options.static = true; + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +Define.prototype.generate = function(keys, options) { + // Generate the return object + var object = { + name: this.name, obj: this.object, stream: this.stream, + instrumentations: [] + } + + for(var name in this.instrumentations) { + object.instrumentations.push(this.instrumentations[name]); + } + + return object; +} + +module.exports = Define; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/lib/mongo_client.js b/util/retroImporter/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 0000000..3ce2ad6 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,463 @@ +"use strict"; + +var parse = require('./url_parser') + , Server = require('./server') + , Mongos = require('./mongos') + , ReplSet = require('./replset') + , Define = require('./metadata') + , ReadPreference = require('./read_preference') + , Db = require('./db'); + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new MongoClient instance + * @class + * @return {MongoClient} a MongoClient instance. + */ +function MongoClient() { + /** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The connected database. + */ + + /** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ + this.connect = MongoClient.connect; +} + +var define = MongoClient.define = new Define('MongoClient', MongoClient, false); + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.connect = function(url, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Return a promise + if(typeof callback != 'function') { + return new promiseLibrary(function(resolve, reject) { + connect(url, options, function(err, db) { + if(err) return reject(err); + resolve(db); + }); + }); + } + + // Fallback to callback based connect + connect(url, options, callback); +} + +define.staticMethod('connect', {callback: true, promise:true}); + +var connect = function(url, options, callback) { + var serverOptions = options.server || {}; + var mongosOptions = options.mongos || {}; + var replSetServersOptions = options.replSet || options.replSetServers || {}; + var dbOptions = options.db || {}; + + // If callback is null throw an exception + if(callback == null) + throw new Error("no callback function provided"); + + // Parse the string + var object = parse(url, options); + + // Merge in any options for db in options object + if(dbOptions) { + for(var name in dbOptions) object.db_options[name] = dbOptions[name]; + } + + // Added the url to the options + object.db_options.url = url; + + // Merge in any options for server in options object + if(serverOptions) { + for(var name in serverOptions) object.server_options[name] = serverOptions[name]; + } + + // Merge in any replicaset server options + if(replSetServersOptions) { + for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; + } + + if(replSetServersOptions.ssl + || replSetServersOptions.sslValidate + || replSetServersOptions.sslCA + || replSetServersOptions.sslCert + || replSetServersOptions.sslKey + || replSetServersOptions.sslPass) { + object.server_options.ssl = replSetServersOptions.ssl; + object.server_options.sslValidate = replSetServersOptions.sslValidate; + object.server_options.sslCA = replSetServersOptions.sslCA; + object.server_options.sslCert = replSetServersOptions.sslCert; + object.server_options.sslKey = replSetServersOptions.sslKey; + object.server_options.sslPass = replSetServersOptions.sslPass; + } + + // Merge in any replicaset server options + if(mongosOptions) { + for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; + } + + if(typeof object.server_options.poolSize == 'number') { + if(!object.mongos_options.poolSize) object.mongos_options.poolSize = object.server_options.poolSize; + if(!object.rs_options.poolSize) object.rs_options.poolSize = object.server_options.poolSize; + } + + if(mongosOptions.ssl + || mongosOptions.sslValidate + || mongosOptions.sslCA + || mongosOptions.sslCert + || mongosOptions.sslKey + || mongosOptions.sslPass) { + object.server_options.ssl = mongosOptions.ssl; + object.server_options.sslValidate = mongosOptions.sslValidate; + object.server_options.sslCA = mongosOptions.sslCA; + object.server_options.sslCert = mongosOptions.sslCert; + object.server_options.sslKey = mongosOptions.sslKey; + object.server_options.sslPass = mongosOptions.sslPass; + } + + // Set the promise library + object.db_options.promiseLibrary = options.promiseLibrary; + + // We need to ensure that the list of servers are only either direct members or mongos + // they cannot be a mix of monogs and mongod's + var totalNumberOfServers = object.servers.length; + var totalNumberOfMongosServers = 0; + var totalNumberOfMongodServers = 0; + var serverConfig = null; + var errorServers = {}; + + // Failure modes + if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host"); + + // If we have no db setting for the native parser try to set the c++ one first + object.db_options.native_parser = _setNativeParser(object.db_options); + // If no auto_reconnect is set, set it to true as default for single servers + if(typeof object.server_options.auto_reconnect != 'boolean') { + object.server_options.auto_reconnect = true; + } + + // If we have more than a server, it could be replicaset or mongos list + // need to verify that it's one or the other and fail if it's a mix + // Connect to all servers and run ismaster + for(var i = 0; i < object.servers.length; i++) { + // Set up socket options + var providedSocketOptions = object.server_options.socketOptions || {}; + + var _server_options = { + poolSize:1 + , socketOptions: { + connectTimeoutMS: providedSocketOptions.connectTimeoutMS || 30000 + , socketTimeoutMS: providedSocketOptions.socketTimeoutMS || 30000 + } + , auto_reconnect:false}; + + // Ensure we have ssl setup for the servers + if(object.server_options.ssl) { + _server_options.ssl = object.server_options.ssl; + _server_options.sslValidate = object.server_options.sslValidate; + _server_options.sslCA = object.server_options.sslCA; + _server_options.sslCert = object.server_options.sslCert; + _server_options.sslKey = object.server_options.sslKey; + _server_options.sslPass = object.server_options.sslPass; + } else if(object.rs_options.ssl) { + _server_options.ssl = object.rs_options.ssl; + _server_options.sslValidate = object.rs_options.sslValidate; + _server_options.sslCA = object.rs_options.sslCA; + _server_options.sslCert = object.rs_options.sslCert; + _server_options.sslKey = object.rs_options.sslKey; + _server_options.sslPass = object.rs_options.sslPass; + } + + // Error + var error = null; + // Set up the Server object + var _server = object.servers[i].domain_socket + ? new Server(object.servers[i].domain_socket, _server_options) + : new Server(object.servers[i].host, object.servers[i].port, _server_options); + + var connectFunction = function(__server) { + // Attempt connect + new Db(object.dbName, __server, {w:1, native_parser:false, promiseLibrary:options.promiseLibrary}).open(function(err, db) { + // Update number of servers + totalNumberOfServers = totalNumberOfServers - 1; + + // If no error do the correct checks + if(!err) { + // Close the connection + db.close(); + var isMasterDoc = db.serverConfig.isMasterDoc; + + // Check what type of server we have + if(isMasterDoc.setName) { + totalNumberOfMongodServers++; + } + + if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; + } else { + error = err; + errorServers[__server.host + ":" + __server.port] = __server; + } + + if(totalNumberOfServers == 0) { + // Error out + if(totalNumberOfMongodServers == 0 && totalNumberOfMongosServers == 0 && error) { + return callback(error, null); + } + + // If we have a mix of mongod and mongos, throw an error + if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { + if(db) db.close(); + return process.nextTick(function() { + try { + callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); + } catch (err) { + throw err + } + }) + } + + if(totalNumberOfMongodServers == 0 + && totalNumberOfMongosServers == 0 + && object.servers.length == 1 + && (!object.rs_options.replicaSet || !object.rs_options.rs_name)) { + + var obj = object.servers[0]; + serverConfig = obj.domain_socket ? + new Server(obj.domain_socket, object.server_options) + : new Server(obj.host, obj.port, object.server_options); + + } else if(totalNumberOfMongodServers > 0 + || totalNumberOfMongosServers > 0 + || object.rs_options.replicaSet || object.rs_options.rs_name) { + + var finalServers = object.servers + .filter(function(serverObj) { + return errorServers[serverObj.host + ":" + serverObj.port] == null; + }) + .map(function(serverObj) { + return new Server(serverObj.host, serverObj.port, object.server_options); + }); + + // Clean out any error servers + errorServers = {}; + + // Set up the final configuration + if(totalNumberOfMongodServers > 0) { + try { + + // If no replicaset name was provided, we wish to perform a + // direct connection + if(totalNumberOfMongodServers == 1 + && (!object.rs_options.replicaSet && !object.rs_options.rs_name)) { + serverConfig = finalServers[0]; + } else if(totalNumberOfMongodServers == 1) { + object.rs_options.replicaSet = object.rs_options.replicaSet || object.rs_options.rs_name; + serverConfig = new ReplSet(finalServers, object.rs_options); + } else { + serverConfig = new ReplSet(finalServers, object.rs_options); + } + + } catch(err) { + return callback(err, null); + } + } else { + serverConfig = new Mongos(finalServers, object.mongos_options); + } + } + + if(serverConfig == null) { + return process.nextTick(function() { + try { + callback(new Error("Could not locate any valid servers in initial seed list")); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + + // Ensure no firing of open event before we are ready + serverConfig.emitOpen = false; + // Set up all options etc and connect to the database + _finishConnecting(serverConfig, object, options, callback) + } + }); + } + + // Wrap the context of the call + connectFunction(_server); + } +} + +var _setNativeParser = function(db_options) { + if(typeof db_options.native_parser == 'boolean') return db_options.native_parser; + + try { + require('mongodb-core').BSON.BSONNative.BSON; + return true; + } catch(err) { + return false; + } +} + +var _finishConnecting = function(serverConfig, object, options, callback) { + // If we have a readPreference passed in by the db options + if(typeof object.db_options.readPreference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.readPreference); + } else if(typeof object.db_options.read_preference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.read_preference); + } + + // Do we have readPreference tags + if(object.db_options.readPreference && object.db_options.readPreferenceTags) { + object.db_options.readPreference.tags = object.db_options.readPreferenceTags; + } else if(object.db_options.readPreference && object.db_options.read_preference_tags) { + object.db_options.readPreference.tags = object.db_options.read_preference_tags; + } + + // Get the socketTimeoutMS + var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0; + + // If we have a replset, override with replicaset socket timeout option if available + if(serverConfig instanceof ReplSet) { + socketTimeoutMS = object.rs_options.socketOptions.socketTimeoutMS || socketTimeoutMS; + } + + // Set socketTimeout to the same as the connectTimeoutMS or 30 sec + serverConfig.connectTimeoutMS = serverConfig.connectTimeoutMS || 30000; + serverConfig.socketTimeoutMS = serverConfig.connectTimeoutMS; + + // Set up the db options + var db = new Db(object.dbName, serverConfig, object.db_options); + // Open the db + db.open(function(err, db){ + + if(err) { + return process.nextTick(function() { + try { + callback(err, null); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + + // Reset the socket timeout + serverConfig.socketTimeoutMS = socketTimeoutMS || 0; + + // Return object + if(err == null && object.auth){ + // What db to authenticate against + var authentication_db = db; + if(object.db_options && object.db_options.authSource) { + authentication_db = db.db(object.db_options.authSource); + } + + // Build options object + var options = {}; + if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism; + if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName; + + // Authenticate + authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){ + if(success){ + process.nextTick(function() { + try { + callback(null, db); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } else { + if(db) db.close(); + process.nextTick(function() { + try { + callback(err ? err : new Error('Could not authenticate user ' + object.auth[0]), null); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + }); + } else { + process.nextTick(function() { + try { + callback(err, db); + } catch (err) { + if(db) db.close(); + throw err + } + }) + } + }); +} + +module.exports = MongoClient diff --git a/util/retroImporter/node_modules/mongodb/lib/mongos.js b/util/retroImporter/node_modules/mongodb/lib/mongos.js new file mode 100644 index 0000000..6087d76 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/mongos.js @@ -0,0 +1,491 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , MongoCR = require('mongodb-core').MongoCR + , CMongos = require('mongodb-core').Mongos + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Server = require('./server') + , Store = require('./topology_base').Store + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Mongos = require('mongodb').Mongos, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using Mongos + * var server = new Server('localhost', 27017); + * var db = new Db('test', new Mongos([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @return {Mongos} a Mongos instance. + */ +var Mongos = function(servers, options) { + if(!(this instanceof Mongos)) return new Mongos(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Ensure we change the sslCA option to ca if available + if(options.sslCA) finalOptions.ca = options.sslCA; + if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; + if(options.sslKey) finalOptions.key = options.sslKey; + if(options.sslCert) finalOptions.cert = options.sslCert; + if(options.sslPass) finalOptions.passphrase = options.sslPass; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + if(options.socketOptions.socketTimeoutMS) + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Create the Mongos + var mongos = new CMongos(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + // Add auth prbufferMaxEntriesoviders + mongos.addAuthProvider('mongocr', new MongoCR()); + + // Internal state + this.s = { + // Create the Mongos + mongos: mongos + // Server capabilities + , sCapabilities: sCapabilities + // Debug turned on + , debug: debug + // Store option defaults + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Actual store of callbacks + , store: store + // Options + , options: options + } + + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return self.s.mongos.lastIsMaster(); } + }); + + // Last ismaster + Object.defineProperty(this, 'numberOfConnectedServers', { + enumerable:true, get: function() { + return self.s.mongos.s.mongosState.connectedServers().length; + } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.mongos.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.mongos.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(Mongos, EventEmitter); + +var define = Mongos.define = new Define('Mongos', Mongos, false); + +// Connect +Mongos.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.mongos.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect'); + self.s.store.execute(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.mongos.removeAllListeners(e); + }); + + // Set up listeners + self.s.mongos.once('timeout', errorHandler('timeout')); + self.s.mongos.once('error', errorHandler('error')); + self.s.mongos.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Set up serverConfig listeners + self.s.mongos.on('joined', relay('joined')); + self.s.mongos.on('left', relay('left')); + self.s.mongos.on('fullsetup', relay('fullsetup')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + self.s.mongos.once('timeout', connectErrorHandler('timeout')); + self.s.mongos.once('error', connectErrorHandler('error')); + self.s.mongos.once('close', connectErrorHandler('close')); + self.s.mongos.once('connect', connectHandler); + // Reconnect server + self.s.mongos.on('reconnect', reconnectHandler); + + // Start connection + self.s.mongos.connect(_options); +} + +Mongos.prototype.parserType = function() { + return this.s.mongos.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Server capabilities +Mongos.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.mongos.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); + this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Mongos.prototype.command = function(ns, cmd, options, callback) { + this.s.mongos.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Mongos.prototype.insert = function(ns, ops, options, callback) { + this.s.mongos.insert(ns, ops, options, function(e, m) { + callback(e, m) + }); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Mongos.prototype.update = function(ns, ops, options, callback) { + this.s.mongos.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Mongos.prototype.remove = function(ns, ops, options, callback) { + this.s.mongos.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// IsConnected +Mongos.prototype.isConnected = function() { + return this.s.mongos.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Mongos.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.mongos.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Mongos.prototype.setBSONParserType = function(type) { + return this.s.mongos.setBSONParserType(type); +} + +Mongos.prototype.lastIsMaster = function() { + return this.s.mongos.lastIsMaster(); +} + +Mongos.prototype.close = function(forceClosed) { + this.s.mongos.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Mongos.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.mongos.auth.apply(this.s.mongos, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Mongos.prototype.connections = function() { + return this.s.mongos.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +module.exports = Mongos; diff --git a/util/retroImporter/node_modules/mongodb/lib/read_preference.js b/util/retroImporter/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 0000000..73b253a --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,104 @@ +"use strict"; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * ReadPreference = require('mongodb').ReadPreference, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * test.equal(null, err); + * // Perform a read + * var cursor = db.collection('t').find({}); + * cursor.setReadPreference(ReadPreference.PRIMARY); + * cursor.toArray(function(err, docs) { + * test.equal(null, err); + * db.close(); + * }); + * }); + */ + +/** + * Creates a new ReadPreference instance + * + * Read Preferences + * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). + * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. + * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. + * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. + * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. + * + * @class + * @param {string} mode The ReadPreference mode as listed above. + * @param {object} tags An object representing read preference tags. + * @property {string} mode The ReadPreference mode. + * @property {object} tags The ReadPreference tags. + * @return {ReadPreference} a ReadPreference instance. + */ +var ReadPreference = function(mode, tags) { + if(!(this instanceof ReadPreference)) + return new ReadPreference(mode, tags); + this._type = 'ReadPreference'; + this.mode = mode; + this.tags = tags; +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +ReadPreference.isValid = function(_mode) { + return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED + || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED + || _mode == ReadPreference.NEAREST + || _mode == true || _mode == false || _mode == null); +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +ReadPreference.prototype.isValid = function(mode) { + var _mode = typeof mode == 'string' ? mode : this.mode; + return ReadPreference.isValid(_mode); +} + +/** + * @ignore + */ +ReadPreference.prototype.toObject = function() { + var object = {mode:this.mode}; + + if(this.tags != null) { + object['tags'] = this.tags; + } + + return object; +} + +/** + * @ignore + */ +ReadPreference.PRIMARY = 'primary'; +ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; +ReadPreference.SECONDARY = 'secondary'; +ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; +ReadPreference.NEAREST = 'nearest' + +/** + * @ignore + */ +module.exports = ReadPreference; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/lib/replset.js b/util/retroImporter/node_modules/mongodb/lib/replset.js new file mode 100644 index 0000000..8a71b42 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/replset.js @@ -0,0 +1,555 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , Server = require('./server') + , Mongos = require('./mongos') + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , ReadPreference = require('./read_preference') + , MongoCR = require('mongodb-core').MongoCR + , MongoError = require('mongodb-core').MongoError + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , CServer = require('mongodb-core').Server + , CReplSet = require('mongodb-core').ReplSet + , CoreReadPreference = require('mongodb-core').ReadPreference + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {string} options.replicaSet The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @return {ReplSet} a ReplSet instance. + */ +var ReplSet = function(servers, options) { + if(!(this instanceof ReplSet)) return new ReplSet(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + } + + // Get the name + var replicaSet = options.replicaSet || options.rs_name; + + // Set up options + finalOptions.setName = replicaSet; + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + if(options.connectWithNoPrimary == true) { + finalOptions.secondaryOnlyConnectionAllowed = true; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Translate the options + if(options.sslCA) finalOptions.ca = options.sslCA; + if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; + if(options.sslKey) finalOptions.key = options.sslKey; + if(options.sslCert) finalOptions.cert = options.sslCert; + if(options.sslPass) finalOptions.passphrase = options.sslPass; + + // Create the ReplSet + var replset = new CReplSet(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + // Add auth prbufferMaxEntriesoviders + replset.addAuthProvider('mongocr', new MongoCR()); + + // Listen to reconnect event + replset.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + replset: replset + // Server capabilities + , sCapabilities: null + // Debug tag + , tag: options.tag + // Store options + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Store + , store: store + // Options + , options: options + } + + // Debug + if(debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable:true, get: function() { return replset; } + }); + } + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return replset.lastIsMaster(); } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return replset.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return replset.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(ReplSet, EventEmitter); + +var define = ReplSet.define = new Define('ReplSet', ReplSet, false); + +// Ensure the right read Preference object +var translateReadPreference = function(options) { + if(typeof options.readPreference == 'string') { + options.readPreference = new CoreReadPreference(options.readPreference); + } else if(options.readPreference instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(options.readPreference.mode + , options.readPreference.tags); + } + + return options; +} + +ReplSet.prototype.parserType = function() { + return this.s.replset.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Connect method +ReplSet.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.replset.removeAllListeners(e); + }); + + // Set up listeners + self.s.replset.once('timeout', errorHandler('timeout')); + self.s.replset.once('error', errorHandler('error')); + self.s.replset.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + } + } + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if(t == 'start') { + self.emit('ha_connect', t, state); + } else if(t == 'end') { + self.emit('ha_ismaster', t, state); + } + } + + // Set up serverConfig listeners + self.s.replset.on('joined', replsetRelay('joined')); + self.s.replset.on('left', relay('left')); + self.s.replset.on('ping', relay('ping')); + self.s.replset.on('ha', relayHa); + + self.s.replset.on('fullsetup', function(topology) { + self.emit('fullsetup', null, self); + }); + + self.s.replset.on('all', function(topology) { + self.emit('all', null, self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.replset.removeListener(e, connectErrorHandler); + }); + + self.s.replset.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.replset.destroy(); + + // Try to callback + try { + callback(err); + } catch(err) { + if(!self.s.replset.isConnected()) + process.nextTick(function() { throw err; }) + } + } + } + + // Set up listeners + self.s.replset.once('timeout', connectErrorHandler('timeout')); + self.s.replset.once('error', connectErrorHandler('error')); + self.s.replset.once('close', connectErrorHandler('close')); + self.s.replset.once('connect', connectHandler); + + // Start connection + self.s.replset.connect(_options); +} + +// Server capabilities +ReplSet.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.replset.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); + this.s.sCapabilities = new ServerCapabilities(this.s.replset.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +ReplSet.prototype.command = function(ns, cmd, options, callback) { + options = translateReadPreference(options); + this.s.replset.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +ReplSet.prototype.insert = function(ns, ops, options, callback) { + this.s.replset.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +ReplSet.prototype.update = function(ns, ops, options, callback) { + this.s.replset.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +ReplSet.prototype.remove = function(ns, ops, options, callback) { + this.s.replset.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// IsConnected +ReplSet.prototype.isConnected = function() { + return this.s.replset.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +ReplSet.prototype.setBSONParserType = function(type) { + return this.s.replset.setBSONParserType(type); +} + +// Insert +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + return this.s.replset.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +ReplSet.prototype.lastIsMaster = function() { + return this.s.replset.lastIsMaster(); +} + +ReplSet.prototype.close = function(forceClosed) { + var self = this; + this.s.replset.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); +} + +define.classMethod('close', {callback: false, promise:false}); + +ReplSet.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.replset.auth.apply(this.s.replset, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +ReplSet.prototype.connections = function() { + return this.s.replset.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +module.exports = ReplSet; diff --git a/util/retroImporter/node_modules/mongodb/lib/server.js b/util/retroImporter/node_modules/mongodb/lib/server.js new file mode 100644 index 0000000..eff7771 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/server.js @@ -0,0 +1,437 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , CServer = require('mongodb-core').Server + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using single Server + * var db = new Db('test', new Server('localhost', 27017);); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options=null] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=false] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @return {Server} a Server instance. + */ +var Server = function(host, port, options) { + options = options || {}; + if(!(this instanceof Server)) return new Server(host, port, options); + EventEmitter.call(this); + var self = this; + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if(host.indexOf('\/') != -1) { + if(port != null && typeof port == 'object') { + options = port; + port = null; + } + } else if(port == null) { + throw MongoError.create({message: 'port must be specified', driver:true}); + } + + // Clone options + var clonedOptions = shallowClone(options); + clonedOptions.host = host; + clonedOptions.port = port; + + // Reconnect + var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; + var emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + var poolSize = typeof options.poolSize == 'number' ? options.poolSize : 5; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + clonedOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + clonedOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + if(typeof options.socketOptions.keepAlive == 'number') { + clonedOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + clonedOptions.keepAlive = true; + } + + if(typeof options.socketOptions.noDelay == 'boolean') { + clonedOptions.noDelay = options.socketOptions.noDelay; + } + } + + // Add the cursor factory function + clonedOptions.cursorFactory = Cursor; + clonedOptions.reconnect = reconnect; + clonedOptions.emitError = emitError; + clonedOptions.size = poolSize; + + // Translate the options + if(clonedOptions.sslCA) clonedOptions.ca = clonedOptions.sslCA; + if(typeof clonedOptions.sslValidate == 'boolean') clonedOptions.rejectUnauthorized = clonedOptions.sslValidate; + if(clonedOptions.sslKey) clonedOptions.key = clonedOptions.sslKey; + if(clonedOptions.sslCert) clonedOptions.cert = clonedOptions.sslCert; + if(clonedOptions.sslPass) clonedOptions.passphrase = clonedOptions.sslPass; + + // Add the non connection store + clonedOptions.disconnectHandler = store; + + // Create an instance of a server instance from mongodb-core + var server = new CServer(clonedOptions); + // Server capabilities + var sCapabilities = null; + + // Define the internal properties + this.s = { + // Create an instance of a server instance from mongodb-core + server: server + // Server capabilities + , sCapabilities: null + // Cloned options + , clonedOptions: clonedOptions + // Reconnect + , reconnect: reconnect + // Emit error + , emitError: emitError + // Pool size + , poolSize: poolSize + // Store Options + , storeOptions: storeOptions + // Store + , store: store + // Host + , host: host + // Port + , port: port + // Options + , options: options + } + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.server.bson; + } + }); + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { + return self.s.server.lastIsMaster(); + } + }); + + // Last ismaster + Object.defineProperty(this, 'poolSize', { + enumerable:true, get: function() { return self.s.server.connections().length; } + }); + + Object.defineProperty(this, 'autoReconnect', { + enumerable:true, get: function() { return self.s.reconnect; } + }); + + Object.defineProperty(this, 'host', { + enumerable:true, get: function() { return self.s.host; } + }); + + Object.defineProperty(this, 'port', { + enumerable:true, get: function() { return self.s.port; } + }); +} + +inherits(Server, EventEmitter); + +var define = Server.define = new Define('Server', Server, false); + +Server.prototype.parserType = function() { + return this.s.server.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Connect +Server.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.server.removeListener(e, connectHandlers[e]); + }); + + self.s.server.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect', self); + self.s.store.execute(); + } + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.server.removeAllListeners(e); + }); + + // Set up listeners + self.s.server.once('timeout', errorHandler('timeout')); + self.s.server.once('error', errorHandler('error')); + self.s.server.on('close', errorHandler('close')); + // Only called on destroy + self.s.server.once('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + console.log(err.stack) + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Add the event handlers + self.s.server.once('timeout', connectHandlers.timeout); + self.s.server.once('error', connectHandlers.error); + self.s.server.once('close', connectHandlers.close); + self.s.server.once('connect', connectHandler); + // Reconnect server + self.s.server.on('reconnect', reconnectHandler); + + // Start connection + self.s.server.connect(_options); +} + +// Server capabilities +Server.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.server.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); + this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Server.prototype.command = function(ns, cmd, options, callback) { + this.s.server.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Server.prototype.insert = function(ns, ops, options, callback) { + this.s.server.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Server.prototype.update = function(ns, ops, options, callback) { + this.s.server.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Server.prototype.remove = function(ns, ops, options, callback) { + this.s.server.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// IsConnected +Server.prototype.isConnected = function() { + return this.s.server.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Server.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.server.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Server.prototype.setBSONParserType = function(type) { + return this.s.server.setBSONParserType(type); +} + +Server.prototype.lastIsMaster = function() { + return this.s.server.lastIsMaster(); +} + +Server.prototype.close = function(forceClosed) { + this.s.server.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Server.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.server.auth.apply(this.s.server, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Server.prototype.connections = function() { + return this.s.server.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +module.exports = Server; diff --git a/util/retroImporter/node_modules/mongodb/lib/topology_base.js b/util/retroImporter/node_modules/mongodb/lib/topology_base.js new file mode 100644 index 0000000..000f7ec --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/topology_base.js @@ -0,0 +1,152 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError + , f = require('util').format; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || {force:false, bufferMaxEntries: -1} + + // Internal state + this.s = { + storedOps: storedOps + , storeOptions: storeOptions + , topology: topology + } + + Object.defineProperty(this, 'length', { + enumerable:true, get: function() { return self.s.storedOps.length; } + }); +} + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true})); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, n: ns, o: ops, op: options, c: callback}) +} + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, m: method, o: object, p: params, c: callback}) +} + +Store.prototype.flush = function() { + while(this.s.storedOps.length > 0) { + this.s.storedOps.shift().c(MongoError.create({message: f("no connection available for operation"), driver:true })); + } +} + +Store.prototype.execute = function() { + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Execute all the stored ops + while(ops.length > 0) { + var op = ops.shift(); + + if(op.t == 'cursor') { + op.o[op.m].apply(op.o, op.p); + } else { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } +} + +Store.prototype.all = function() { + return this.s.storedOps; +} + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true + , get: function () { return value; } + }); + } + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + + if(ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if(ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if(ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if(ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + // If no min or max wire version set to 0 + if(ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if(ismaster.maxWireVersion == null) { + ismaster.maxWireVersion = 0; + } + + // Map up read only parameters + setup_get_property(this, "hasAggregationCursor", aggregationCursor); + setup_get_property(this, "hasWriteCommands", writeCommands); + setup_get_property(this, "hasTextSearch", textSearch); + setup_get_property(this, "hasAuthCommands", authCommands); + setup_get_property(this, "hasListCollectionsCommand", listCollections); + setup_get_property(this, "hasListIndexesCommand", listIndexes); + setup_get_property(this, "minWireVersion", ismaster.minWireVersion); + setup_get_property(this, "maxWireVersion", ismaster.maxWireVersion); + setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); +} + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; diff --git a/util/retroImporter/node_modules/mongodb/lib/url_parser.js b/util/retroImporter/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 0000000..eccc1e0 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,295 @@ +"use strict"; + +var ReadPreference = require('./read_preference'); + +module.exports = function(url, options) { + // Ensure we have a default options object if none set + options = options || {}; + // Variables + var connection_part = ''; + var auth_part = ''; + var query_string_part = ''; + var dbName = 'admin'; + + // Must start with mongodb + if(url.indexOf("mongodb://") != 0) + throw Error("URL must be in the format mongodb://user:pass@host:port/dbname"); + // If we have a ? mark cut the query elements off + if(url.indexOf("?") != -1) { + query_string_part = url.substr(url.indexOf("?") + 1); + connection_part = url.substring("mongodb://".length, url.indexOf("?")) + } else { + connection_part = url.substring("mongodb://".length); + } + + // Check if we have auth params + if(connection_part.indexOf("@") != -1) { + auth_part = connection_part.split("@")[0]; + connection_part = connection_part.split("@")[1]; + } + + // Check if the connection string has a db + if(connection_part.indexOf(".sock") != -1) { + if(connection_part.indexOf(".sock/") != -1) { + dbName = connection_part.split(".sock/")[1]; + connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); + } + } else if(connection_part.indexOf("/") != -1) { + dbName = connection_part.split("/")[1]; + connection_part = connection_part.split("/")[0]; + } + + // Result object + var object = {}; + + // Pick apart the authentication part of the string + var authPart = auth_part || ''; + var auth = authPart.split(':', 2); + + // Decode the URI components + auth[0] = decodeURIComponent(auth[0]); + if(auth[1]){ + auth[1] = decodeURIComponent(auth[1]); + } + + // Add auth to final object if we have 2 elements + if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; + + // Variables used for temporary storage + var hostPart; + var urlOptions; + var servers; + var serverOptions = {socketOptions: {}}; + var dbOptions = {read_preference_tags: []}; + var replSetServersOptions = {socketOptions: {}}; + // Add server options to final object + object.server_options = serverOptions; + object.db_options = dbOptions; + object.rs_options = replSetServersOptions; + object.mongos_options = {}; + + // Let's check if we are using a domain socket + if(url.match(/\.sock/)) { + // Split out the socket part + var domainSocket = url.substring( + url.indexOf("mongodb://") + "mongodb://".length + , url.lastIndexOf(".sock") + ".sock".length); + // Clean out any auth stuff if any + if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; + servers = [{domain_socket: domainSocket}]; + } else { + // Split up the db + hostPart = connection_part; + // Deduplicate servers + var deduplicatedServers = {}; + + // Parse all server results + servers = hostPart.split(',').map(function(h) { + var _host, _port, ipv6match; + //check if it matches [IPv6]:port, where the port number is optional + if ((ipv6match = /\[([^\]]+)\](?:\:(.+))?/.exec(h))) { + _host = ipv6match[1]; + _port = parseInt(ipv6match[2], 10) || 27017; + } else { + //otherwise assume it's IPv4, or plain hostname + var hostPort = h.split(':', 2); + _host = hostPort[0] || 'localhost'; + _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; + // Check for localhost?safe=true style case + if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; + } + + // No entry returned for duplicate servr + if(deduplicatedServers[_host + "_" + _port]) return null; + deduplicatedServers[_host + "_" + _port] = 1; + + // Return the mapped object + return {host: _host, port: _port}; + }).filter(function(x) { + return x != null; + }); + } + + // Get the db name + object.dbName = dbName || 'admin'; + // Split up all the options + urlOptions = (query_string_part || '').split(/[&;]/); + // Ugh, we have to figure out which options go to which constructor manually. + urlOptions.forEach(function(opt) { + if(!opt) return; + var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; + // Options implementations + switch(name) { + case 'slaveOk': + case 'slave_ok': + serverOptions.slave_ok = (value == 'true'); + dbOptions.slaveOk = (value == 'true'); + break; + case 'maxPoolSize': + case 'poolSize': + serverOptions.poolSize = parseInt(value, 10); + replSetServersOptions.poolSize = parseInt(value, 10); + break; + case 'autoReconnect': + case 'auto_reconnect': + serverOptions.auto_reconnect = (value == 'true'); + break; + case 'minPoolSize': + throw new Error("minPoolSize not supported"); + case 'maxIdleTimeMS': + throw new Error("maxIdleTimeMS not supported"); + case 'waitQueueMultiple': + throw new Error("waitQueueMultiple not supported"); + case 'waitQueueTimeoutMS': + throw new Error("waitQueueTimeoutMS not supported"); + case 'uuidRepresentation': + throw new Error("uuidRepresentation not supported"); + case 'ssl': + if(value == 'prefer') { + serverOptions.ssl = value; + replSetServersOptions.ssl = value; + break; + } + serverOptions.ssl = (value == 'true'); + replSetServersOptions.ssl = (value == 'true'); + break; + case 'replicaSet': + case 'rs_name': + replSetServersOptions.rs_name = value; + break; + case 'reconnectWait': + replSetServersOptions.reconnectWait = parseInt(value, 10); + break; + case 'retries': + replSetServersOptions.retries = parseInt(value, 10); + break; + case 'readSecondary': + case 'read_secondary': + replSetServersOptions.read_secondary = (value == 'true'); + break; + case 'fsync': + dbOptions.fsync = (value == 'true'); + break; + case 'journal': + dbOptions.j = (value == 'true'); + break; + case 'safe': + dbOptions.safe = (value == 'true'); + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = (value == 'true'); + break; + case 'readConcernLevel': + dbOptions.readConcern = {level: value}; + break; + case 'connectTimeoutMS': + serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + break; + case 'socketTimeoutMS': + serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + break; + case 'w': + dbOptions.w = parseInt(value, 10); + if(isNaN(dbOptions.w)) dbOptions.w = value; + break; + case 'authSource': + dbOptions.authSource = value; + break; + case 'gssapiServiceName': + dbOptions.gssapiServiceName = value; + break; + case 'authMechanism': + if(value == 'GSSAPI') { + // If no password provided decode only the principal + if(object.auth == null) { + var urlDecodeAuthPart = decodeURIComponent(authPart); + if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); + object.auth = {user: urlDecodeAuthPart, password: null}; + } else { + object.auth.user = decodeURIComponent(object.auth.user); + } + } else if(value == 'MONGODB-X509') { + object.auth = {user: decodeURIComponent(authPart)}; + } + + // Only support GSSAPI or MONGODB-CR for now + if(value != 'GSSAPI' + && value != 'MONGODB-X509' + && value != 'MONGODB-CR' + && value != 'DEFAULT' + && value != 'SCRAM-SHA-1' + && value != 'PLAIN') + throw new Error("only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + // Split up into key, value pairs + var values = value.split(','); + var o = {}; + // For each value split into key, value + values.forEach(function(x) { + var v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if(typeof o.SERVICE_NAME == 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + break; + case 'wtimeoutMS': + dbOptions.wtimeout = parseInt(value, 10); + break; + case 'readPreference': + if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); + dbOptions.read_preference = value; + break; + case 'readPreferenceTags': + // Decode the value + value = decodeURIComponent(value); + // Contains the tag object + var tagObject = {}; + if(value == null || value == '') { + dbOptions.read_preference_tags.push(tagObject); + break; + } + + // Split up the tags + var tags = value.split(/\,/); + for(var i = 0; i < tags.length; i++) { + var parts = tags[i].trim().split(/\:/); + tagObject[parts[0]] = parts[1]; + } + + // Set the preferences tags + dbOptions.read_preference_tags.push(tagObject); + break; + default: + break; + } + }); + + // No tags: should be null (not []) + if(dbOptions.read_preference_tags.length === 0) { + dbOptions.read_preference_tags = null; + } + + // Validate if there are an invalid write concern combinations + if((dbOptions.w == -1 || dbOptions.w == 0) && ( + dbOptions.journal == true + || dbOptions.fsync == true + || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") + + // If no read preference set it to primary + if(!dbOptions.read_preference) dbOptions.read_preference = 'primary'; + + // Add servers to result + object.servers = servers; + // Returned parsed object + return object; +} diff --git a/util/retroImporter/node_modules/mongodb/lib/utils.js b/util/retroImporter/node_modules/mongodb/lib/utils.js new file mode 100644 index 0000000..cb20e67 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/lib/utils.js @@ -0,0 +1,234 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError, + f = require('util').format; + +var shallowClone = function(obj) { + var copy = {}; + for(var name in obj) copy[name] = obj[name]; + return copy; +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +var formatSortValue = exports.formatSortValue = function(sortDirection) { + var value = ("" + sortDirection).toLowerCase(); + + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new Error("Illegal sort clause, must be of the form " + + "[['field1', '(ascending|descending)'], " + + "['field2', '(ascending|descending)']]"); + } +}; + +var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { + var orderBy = {}; + if(sortValue == null) return null; + if (Array.isArray(sortValue)) { + if(sortValue.length === 0) { + return null; + } + + for(var i = 0; i < sortValue.length; i++) { + if(sortValue[i].constructor == String) { + orderBy[sortValue[i]] = 1; + } else { + orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); + } + } + } else if(sortValue != null && typeof sortValue == 'object') { + orderBy = sortValue; + } else if (typeof sortValue == 'string') { + orderBy[sortValue] = 1; + } else { + throw new Error("Illegal sort clause, must be of the form " + + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); + } + + return orderBy; +}; + +var checkCollectionName = function checkCollectionName (collectionName) { + if('string' !== typeof collectionName) { + throw Error("collection name must be a String"); + } + + if(!collectionName || collectionName.indexOf('..') != -1) { + throw Error("collection names cannot be empty"); + } + + if(collectionName.indexOf('$') != -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { + throw Error("collection names must not contain '$'"); + } + + if(collectionName.match(/^\.|\.$/) != null) { + throw Error("collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the colletion name + if(!!~collectionName.indexOf("\x00")) { + throw new Error("collection names cannot contain a null character"); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if(callback == null) return; + if(value2) return callback(err, value1, value2); + return callback(err, value1); + } catch(err) { + process.nextTick(function() { throw err; }); + return false; + } + + return true; +} + +/** + * Wrap a Mongo error document in an Error instance + * @ignore + * @api private + */ +var toError = function(error) { + if (error instanceof Error) return error; + + var msg = error.err || error.errmsg || error.errMessage || error; + var e = MongoError.create({message: msg, driver:true}); + + // Get all object keys + var keys = typeof error == 'object' + ? Object.keys(error) + : []; + + for(var i = 0; i < keys.length; i++) { + e[keys[i]] = error[keys[i]]; + } + + return e; +} + +/** + * @ignore + */ +var normalizeHintField = function normalizeHintField(hint) { + var finalHint = null; + + if(typeof hint == 'string') { + finalHint = hint; + } else if(Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(function(param) { + finalHint[param] = 1; + }); + } else if(hint != null && typeof hint == 'object') { + finalHint = {}; + for (var name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var parseIndexOptions = function(fieldOrSpec) { + var fieldHash = {}; + var indexes = []; + var keys; + + // Get all the fields accordingly + if('string' == typeof fieldOrSpec) { + // 'type' + indexes.push(fieldOrSpec + '_' + 1); + fieldHash[fieldOrSpec] = 1; + } else if(Array.isArray(fieldOrSpec)) { + fieldOrSpec.forEach(function(f) { + if('string' == typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if(Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if(isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(function(k) { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if(isObject(fieldOrSpec)) { + // {location:'2d', type:1} + keys = Object.keys(fieldOrSpec); + keys.forEach(function(key) { + indexes.push(key + '_' + fieldOrSpec[key]); + fieldHash[key] = fieldOrSpec[key]; + }); + } + + return { + name: indexes.join("_"), keys: keys, fieldHash: fieldHash + } +} + +var isObject = exports.isObject = function (arg) { + return '[object Object]' == toString.call(arg) +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +var decorateCommand = function(command, options, exclude) { + for(var name in options) { + if(exclude[name] == null) command[name] = options[name]; + } + + return command; +} + +exports.shallowClone = shallowClone; +exports.getSingleProperty = getSingleProperty; +exports.checkCollectionName = checkCollectionName; +exports.toError = toError; +exports.formattedOrderClause = formattedOrderClause; +exports.parseIndexOptions = parseIndexOptions; +exports.normalizeHintField = normalizeHintField; +exports.handleCallback = handleCallback; +exports.decorateCommand = decorateCommand; +exports.isObject = isObject; +exports.debugOptions = debugOptions; diff --git a/util/retroImporter/node_modules/mongodb/load.js b/util/retroImporter/node_modules/mongodb/load.js new file mode 100644 index 0000000..01b570e --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/load.js @@ -0,0 +1,32 @@ +var MongoClient = require('./').MongoClient; + +MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { + var col = db.collection('test'); + col.ensureIndex({dt:-1}, function() { + var docs = []; + for(var i = 0; i < 100; i++) { + docs.push({a:i, dt:i, ot:i}); + } + console.log("------------------------------- 0") + + col.insertMany(docs, function() { + // Start firing finds + + for(var i = 0; i < 100; i++) { + setInterval(function() { + col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) { + console.log("-------------------------------- 1") + }); + }, 10) + } + + // while(true) { + // + // // console.log("------------------------------- 1") + // col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) { + // console.log("-------------------------------- 1") + // }); + // } + }); + }); +}); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md new file mode 100644 index 0000000..e06b496 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md @@ -0,0 +1,9 @@ +# Master + +# 2.0.0 + +* re-sync with RSVP. Many large performance improvements and bugfixes. + +# 1.0.0 + +* first subset of RSVP diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE new file mode 100644 index 0000000..954ec59 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/README.md b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/README.md new file mode 100644 index 0000000..ca8678e --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/README.md @@ -0,0 +1,61 @@ +# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) + +This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js), if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). + +For API details and how to use promises, see the JavaScript Promises HTML5Rocks article. + +## Downloads + +* [es6-promise](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.js) +* [es6-promise-min](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise-min.js) + +## Node.js + +To install: + +```sh +npm install es6-promise +``` + +To use: + +```js +var Promise = require('es6-promise').Promise; +``` + +## Usage in IE<9 + +`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example. + +However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production: + +```js +promise['catch'](function(err) { + // ... +}); +``` + +Or use `.then` instead: + +```js +promise.then(undefined, function(err) { + // ... +}); +``` + +## Auto-polyfill + +To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: + +```js +require('es6-promise').polyfill(); +``` + +Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. + +## Building & Testing + +* `npm run build` to build +* `npm test` to run tests +* `npm start` to run a build watcher, and webserver to test +* `npm run test:server` for a testem test runner and watching builder diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js new file mode 100644 index 0000000..308f3ac --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js @@ -0,0 +1,957 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 2.1.1 + */ + +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + function lib$es6$promise$asap$$asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + lib$es6$promise$asap$$scheduleFlush(); + } + } + + var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + var nextTick = process.nextTick; + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // setImmediate should be used instead instead + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function() { + nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertex() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFullfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$default(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { + return lib$es6$promise$utils$$isArray(input); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; + + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + var lib$es6$promise$promise$$counter = 0; + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$default(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js new file mode 100644 index 0000000..0552e12 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js @@ -0,0 +1,9 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 2.1.1 + */ + +(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;function lib$es6$promise$asap$$asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){lib$es6$promise$asap$$scheduleFlush()}}var lib$es6$promise$asap$$default=lib$es6$promise$asap$$asap;var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){var nextTick=process.nextTick;var version=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);if(Array.isArray(version)&&version[1]==="0"&&version[2]==="10"){nextTick=setImmediate}return function(){nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i +// +// 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. + +// when used in node, this will actually load the util module we depend on +// versus loading the builtin util module as happens otherwise +// this is a bug in node module loading as far as I am concerned +var util = require('util/'); + +var pSlice = Array.prototype.slice; +var hasOwn = Object.prototype.hasOwnProperty; + +// 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 = module.exports = ok; + +// 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.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } + else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = stackStartFunction.name; + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function replacer(key, value) { + if (util.isUndefined(value)) { + return '' + value; + } + if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { + return value.toString(); + } + if (util.isFunction(value) || util.isRegExp(value)) { + return value.toString(); + } + return value; +} + +function truncate(s, n) { + if (util.isString(s)) { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} + +function getMessage(self) { + return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + + self.operator + ' ' + + truncate(JSON.stringify(self.expected, replacer), 128); +} + +// 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);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = 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; + + } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + if (actual.length != expected.length) return false; + + for (var i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) return false; + } + + 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 (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!util.isObject(actual) && !util.isObject(expected)) { + return actual == expected; + + // 7.5 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 isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b) { + if (util.isNullOrUndefined(a) || util.isNullOrUndefined(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 = objectKeys(a), + kb = objectKeys(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 expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } + + return false; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (util.isString(expected)) { + message = expected; + expected = null; + } + + try { + block(); + } catch (e) { + actual = e; + } + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 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*/message) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); +}; + +assert.ifError = function(err) { if (err) {throw err;}}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +},{"util/":6}],3:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],4:[function(require,module,exports){ +// shim for using process in browser + +var process = module.exports = {}; + +process.nextTick = (function () { + var canSetImmediate = typeof window !== 'undefined' + && window.setImmediate; + var canMutationObserver = typeof window !== 'undefined' + && window.MutationObserver; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; + + if (canSetImmediate) { + return function (f) { return window.setImmediate(f) }; + } + + var queue = []; + + if (canMutationObserver) { + var hiddenDiv = document.createElement("div"); + var observer = new MutationObserver(function () { + var queueList = queue.slice(); + queue.length = 0; + queueList.forEach(function (fn) { + fn(); + }); + }); + + observer.observe(hiddenDiv, { attributes: true }); + + return function nextTick(fn) { + if (!queue.length) { + hiddenDiv.setAttribute('yes', 'no'); + } + queue.push(fn); + }; + } + + if (canPost) { + window.addEventListener('message', function (ev) { + var source = ev.source; + if ((source === window || source === null) && ev.data === 'process-tick') { + ev.stopPropagation(); + if (queue.length > 0) { + var fn = queue.shift(); + fn(); + } + } + }, true); + + return function nextTick(fn) { + queue.push(fn); + window.postMessage('process-tick', '*'); + }; + } + + return function nextTick(fn) { + setTimeout(fn, 0); + }; +})(); + +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +// TODO(shtylman) +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; + +},{}],5:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],6:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":5,"_process":4,"inherits":3}],7:[function(require,module,exports){ +require("./tests/2.1.2"); +require("./tests/2.1.3"); +require("./tests/2.2.1"); +require("./tests/2.2.2"); +require("./tests/2.2.3"); +require("./tests/2.2.4"); +require("./tests/2.2.5"); +require("./tests/2.2.6"); +require("./tests/2.2.7"); +require("./tests/2.3.1"); +require("./tests/2.3.2"); +require("./tests/2.3.3"); +require("./tests/2.3.4"); + +},{"./tests/2.1.2":8,"./tests/2.1.3":9,"./tests/2.2.1":10,"./tests/2.2.2":11,"./tests/2.2.3":12,"./tests/2.2.4":13,"./tests/2.2.5":14,"./tests/2.2.6":15,"./tests/2.2.7":16,"./tests/2.3.1":17,"./tests/2.3.2":18,"./tests/2.3.3":19,"./tests/2.3.4":20}],8:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; + +var adapter = global.adapter; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.1.2.1: When fulfilled, a promise: must not transition to any other state.", function () { + testFulfilled(dummy, function (promise, done) { + var onFulfilledCalled = false; + + promise.then(function onFulfilled() { + onFulfilledCalled = true; + }, function onRejected() { + assert.strictEqual(onFulfilledCalled, false); + done(); + }); + + setTimeout(done, 100); + }); + + specify("trying to fulfill then immediately reject", function (done) { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }, function onRejected() { + assert.strictEqual(onFulfilledCalled, false); + done(); + }); + + d.resolve(dummy); + d.reject(dummy); + setTimeout(done, 100); + }); + + specify("trying to fulfill then reject, delayed", function (done) { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }, function onRejected() { + assert.strictEqual(onFulfilledCalled, false); + done(); + }); + + setTimeout(function () { + d.resolve(dummy); + d.reject(dummy); + }, 50); + setTimeout(done, 100); + }); + + specify("trying to fulfill immediately then reject delayed", function (done) { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }, function onRejected() { + assert.strictEqual(onFulfilledCalled, false); + done(); + }); + + d.resolve(dummy); + setTimeout(function () { + d.reject(dummy); + }, 50); + setTimeout(done, 100); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],9:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testRejected = require("./helpers/testThreeCases").testRejected; + +var adapter = global.adapter; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.1.3.1: When rejected, a promise: must not transition to any other state.", function () { + testRejected(dummy, function (promise, done) { + var onRejectedCalled = false; + + promise.then(function onFulfilled() { + assert.strictEqual(onRejectedCalled, false); + done(); + }, function onRejected() { + onRejectedCalled = true; + }); + + setTimeout(done, 100); + }); + + specify("trying to reject then immediately fulfill", function (done) { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(function onFulfilled() { + assert.strictEqual(onRejectedCalled, false); + done(); + }, function onRejected() { + onRejectedCalled = true; + }); + + d.reject(dummy); + d.resolve(dummy); + setTimeout(done, 100); + }); + + specify("trying to reject then fulfill, delayed", function (done) { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(function onFulfilled() { + assert.strictEqual(onRejectedCalled, false); + done(); + }, function onRejected() { + onRejectedCalled = true; + }); + + setTimeout(function () { + d.reject(dummy); + d.resolve(dummy); + }, 50); + setTimeout(done, 100); + }); + + specify("trying to reject immediately then fulfill delayed", function (done) { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(function onFulfilled() { + assert.strictEqual(onRejectedCalled, false); + done(); + }, function onRejected() { + onRejectedCalled = true; + }); + + d.reject(dummy); + setTimeout(function () { + d.resolve(dummy); + }, 50); + setTimeout(done, 100); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],10:[function(require,module,exports){ +(function (global){ +"use strict"; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.2.1: Both `onFulfilled` and `onRejected` are optional arguments.", function () { + describe("2.2.1.1: If `onFulfilled` is not a function, it must be ignored.", function () { + describe("applied to a directly-rejected promise", function () { + function testNonFunction(nonFunction, stringRepresentation) { + specify("`onFulfilled` is " + stringRepresentation, function (done) { + rejected(dummy).then(nonFunction, function () { + done(); + }); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + }); + + describe("applied to a promise rejected and then chained off of", function () { + function testNonFunction(nonFunction, stringRepresentation) { + specify("`onFulfilled` is " + stringRepresentation, function (done) { + rejected(dummy).then(function () { }, undefined).then(nonFunction, function () { + done(); + }); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + }); + }); + + describe("2.2.1.2: If `onRejected` is not a function, it must be ignored.", function () { + describe("applied to a directly-fulfilled promise", function () { + function testNonFunction(nonFunction, stringRepresentation) { + specify("`onRejected` is " + stringRepresentation, function (done) { + resolved(dummy).then(function () { + done(); + }, nonFunction); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + }); + + describe("applied to a promise fulfilled and then chained off of", function () { + function testNonFunction(nonFunction, stringRepresentation) { + specify("`onFulfilled` is " + stringRepresentation, function (done) { + resolved(dummy).then(undefined, function () { }).then(function () { + done(); + }, nonFunction); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],11:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality + +describe("2.2.2: If `onFulfilled` is a function,", function () { + describe("2.2.2.1: it must be called after `promise` is fulfilled, with `promise`’s fulfillment value as its " + + "first argument.", function () { + testFulfilled(sentinel, function (promise, done) { + promise.then(function onFulfilled(value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("2.2.2.2: it must not be called before `promise` is fulfilled", function () { + specify("fulfilled after a delay", function (done) { + var d = deferred(); + var isFulfilled = false; + + d.promise.then(function onFulfilled() { + assert.strictEqual(isFulfilled, true); + done(); + }); + + setTimeout(function () { + d.resolve(dummy); + isFulfilled = true; + }, 50); + }); + + specify("never fulfilled", function (done) { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + done(); + }); + + setTimeout(function () { + assert.strictEqual(onFulfilledCalled, false); + done(); + }, 150); + }); + }); + + describe("2.2.2.3: it must not be called more than once.", function () { + specify("already-fulfilled", function (done) { + var timesCalled = 0; + + resolved(dummy).then(function onFulfilled() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + }); + + specify("trying to fulfill a pending promise more than once, immediately", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + d.resolve(dummy); + d.resolve(dummy); + }); + + specify("trying to fulfill a pending promise more than once, delayed", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + setTimeout(function () { + d.resolve(dummy); + d.resolve(dummy); + }, 50); + }); + + specify("trying to fulfill a pending promise more than once, immediately then delayed", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + d.resolve(dummy); + setTimeout(function () { + d.resolve(dummy); + }, 50); + }); + + specify("when multiple `then` calls are made, spaced apart in time", function (done) { + var d = deferred(); + var timesCalled = [0, 0, 0]; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[0], 1); + }); + + setTimeout(function () { + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[1], 1); + }); + }, 50); + + setTimeout(function () { + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[2], 1); + done(); + }); + }, 100); + + setTimeout(function () { + d.resolve(dummy); + }, 150); + }); + + specify("when `then` is interleaved with fulfillment", function (done) { + var d = deferred(); + var timesCalled = [0, 0]; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[0], 1); + }); + + d.resolve(dummy); + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[1], 1); + done(); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],12:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testRejected = require("./helpers/testThreeCases").testRejected; + +var adapter = global.adapter; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality + +describe("2.2.3: If `onRejected` is a function,", function () { + describe("2.2.3.1: it must be called after `promise` is rejected, with `promise`’s rejection reason as its " + + "first argument.", function () { + testRejected(sentinel, function (promise, done) { + promise.then(null, function onRejected(reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("2.2.3.2: it must not be called before `promise` is rejected", function () { + specify("rejected after a delay", function (done) { + var d = deferred(); + var isRejected = false; + + d.promise.then(null, function onRejected() { + assert.strictEqual(isRejected, true); + done(); + }); + + setTimeout(function () { + d.reject(dummy); + isRejected = true; + }, 50); + }); + + specify("never rejected", function (done) { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(null, function onRejected() { + onRejectedCalled = true; + done(); + }); + + setTimeout(function () { + assert.strictEqual(onRejectedCalled, false); + done(); + }, 150); + }); + }); + + describe("2.2.3.3: it must not be called more than once.", function () { + specify("already-rejected", function (done) { + var timesCalled = 0; + + rejected(dummy).then(null, function onRejected() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + }); + + specify("trying to reject a pending promise more than once, immediately", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + d.reject(dummy); + d.reject(dummy); + }); + + specify("trying to reject a pending promise more than once, delayed", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + setTimeout(function () { + d.reject(dummy); + d.reject(dummy); + }, 50); + }); + + specify("trying to reject a pending promise more than once, immediately then delayed", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + d.reject(dummy); + setTimeout(function () { + d.reject(dummy); + }, 50); + }); + + specify("when multiple `then` calls are made, spaced apart in time", function (done) { + var d = deferred(); + var timesCalled = [0, 0, 0]; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[0], 1); + }); + + setTimeout(function () { + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[1], 1); + }); + }, 50); + + setTimeout(function () { + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[2], 1); + done(); + }); + }, 100); + + setTimeout(function () { + d.reject(dummy); + }, 150); + }); + + specify("when `then` is interleaved with rejection", function (done) { + var d = deferred(); + var timesCalled = [0, 0]; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[0], 1); + }); + + d.reject(dummy); + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[1], 1); + done(); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],13:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; +var testRejected = require("./helpers/testThreeCases").testRejected; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.2.4: `onFulfilled` or `onRejected` must not be called until the execution context stack contains only " + + "platform code.", function () { + describe("`then` returns before the promise becomes fulfilled or rejected", function () { + testFulfilled(dummy, function (promise, done) { + var thenHasReturned = false; + + promise.then(function onFulfilled() { + assert.strictEqual(thenHasReturned, true); + done(); + }); + + thenHasReturned = true; + }); + testRejected(dummy, function (promise, done) { + var thenHasReturned = false; + + promise.then(null, function onRejected() { + assert.strictEqual(thenHasReturned, true); + done(); + }); + + thenHasReturned = true; + }); + }); + + describe("Clean-stack execution ordering tests (fulfillment case)", function () { + specify("when `onFulfilled` is added immediately before the promise is fulfilled", + function () { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }); + + d.resolve(dummy); + + assert.strictEqual(onFulfilledCalled, false); + }); + + specify("when `onFulfilled` is added immediately after the promise is fulfilled", + function () { + var d = deferred(); + var onFulfilledCalled = false; + + d.resolve(dummy); + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }); + + assert.strictEqual(onFulfilledCalled, false); + }); + + specify("when one `onFulfilled` is added inside another `onFulfilled`", function (done) { + var promise = resolved(); + var firstOnFulfilledFinished = false; + + promise.then(function () { + promise.then(function () { + assert.strictEqual(firstOnFulfilledFinished, true); + done(); + }); + firstOnFulfilledFinished = true; + }); + }); + + specify("when `onFulfilled` is added inside an `onRejected`", function (done) { + var promise = rejected(); + var promise2 = resolved(); + var firstOnRejectedFinished = false; + + promise.then(null, function () { + promise2.then(function () { + assert.strictEqual(firstOnRejectedFinished, true); + done(); + }); + firstOnRejectedFinished = true; + }); + }); + + specify("when the promise is fulfilled asynchronously", function (done) { + var d = deferred(); + var firstStackFinished = false; + + setTimeout(function () { + d.resolve(dummy); + firstStackFinished = true; + }, 0); + + d.promise.then(function () { + assert.strictEqual(firstStackFinished, true); + done(); + }); + }); + }); + + describe("Clean-stack execution ordering tests (rejection case)", function () { + specify("when `onRejected` is added immediately before the promise is rejected", + function () { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(null, function onRejected() { + onRejectedCalled = true; + }); + + d.reject(dummy); + + assert.strictEqual(onRejectedCalled, false); + }); + + specify("when `onRejected` is added immediately after the promise is rejected", + function () { + var d = deferred(); + var onRejectedCalled = false; + + d.reject(dummy); + + d.promise.then(null, function onRejected() { + onRejectedCalled = true; + }); + + assert.strictEqual(onRejectedCalled, false); + }); + + specify("when `onRejected` is added inside an `onFulfilled`", function (done) { + var promise = resolved(); + var promise2 = rejected(); + var firstOnFulfilledFinished = false; + + promise.then(function () { + promise2.then(null, function () { + assert.strictEqual(firstOnFulfilledFinished, true); + done(); + }); + firstOnFulfilledFinished = true; + }); + }); + + specify("when one `onRejected` is added inside another `onRejected`", function (done) { + var promise = rejected(); + var firstOnRejectedFinished = false; + + promise.then(null, function () { + promise.then(null, function () { + assert.strictEqual(firstOnRejectedFinished, true); + done(); + }); + firstOnRejectedFinished = true; + }); + }); + + specify("when the promise is rejected asynchronously", function (done) { + var d = deferred(); + var firstStackFinished = false; + + setTimeout(function () { + d.reject(dummy); + firstStackFinished = true; + }, 0); + + d.promise.then(null, function () { + assert.strictEqual(firstStackFinished, true); + done(); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],14:[function(require,module,exports){ +(function (global){ +/*jshint strict: false */ + +var assert = require("assert"); + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +function impimentsUseStrictCorrectly() { + "use strict"; + function test() { + /*jshint validthis:true */ + return !this; + } + return test(); +} +describe("2.2.5 `onFulfilled` and `onRejected` must be called as functions (i.e. with no `this` value).", function () { + if (impimentsUseStrictCorrectly()) { + describe("strict mode", function () { + specify("fulfilled", function (done) { + resolved(dummy).then(function onFulfilled() { + "use strict"; + + assert.strictEqual(this, undefined); + done(); + }); + }); + + specify("rejected", function (done) { + rejected(dummy).then(null, function onRejected() { + "use strict"; + + assert.strictEqual(this, undefined); + done(); + }); + }); + }); + } + describe("sloppy mode", function () { + specify("fulfilled", function (done) { + resolved(dummy).then(function onFulfilled() { + assert.strictEqual(this, global); + done(); + }); + }); + + specify("rejected", function (done) { + rejected(dummy).then(null, function onRejected() { + assert.strictEqual(this, global); + done(); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"assert":2}],15:[function(require,module,exports){ +"use strict"; + +var assert = require("assert"); +var sinon = require("sinon"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; +var testRejected = require("./helpers/testThreeCases").testRejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var other = { other: "other" }; // a value we don't want to be strict equal to +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality +var sentinel2 = { sentinel2: "sentinel2" }; +var sentinel3 = { sentinel3: "sentinel3" }; + +function callbackAggregator(times, ultimateCallback) { + var soFar = 0; + return function () { + if (++soFar === times) { + ultimateCallback(); + } + }; +} + +describe("2.2.6: `then` may be called multiple times on the same promise.", function () { + describe("2.2.6.1: If/when `promise` is fulfilled, all respective `onFulfilled` callbacks must execute in the " + + "order of their originating calls to `then`.", function () { + describe("multiple boring fulfillment handlers", function () { + testFulfilled(sentinel, function (promise, done) { + var handler1 = sinon.stub().returns(other); + var handler2 = sinon.stub().returns(other); + var handler3 = sinon.stub().returns(other); + + var spy = sinon.spy(); + promise.then(handler1, spy); + promise.then(handler2, spy); + promise.then(handler3, spy); + + promise.then(function (value) { + assert.strictEqual(value, sentinel); + + sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); + sinon.assert.notCalled(spy); + + done(); + }); + }); + }); + + describe("multiple fulfillment handlers, one of which throws", function () { + testFulfilled(sentinel, function (promise, done) { + var handler1 = sinon.stub().returns(other); + var handler2 = sinon.stub().throws(other); + var handler3 = sinon.stub().returns(other); + + var spy = sinon.spy(); + promise.then(handler1, spy); + promise.then(handler2, spy); + promise.then(handler3, spy); + + promise.then(function (value) { + assert.strictEqual(value, sentinel); + + sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); + sinon.assert.notCalled(spy); + + done(); + }); + }); + }); + + describe("results in multiple branching chains with their own fulfillment values", function () { + testFulfilled(dummy, function (promise, done) { + var semiDone = callbackAggregator(3, done); + + promise.then(function () { + return sentinel; + }).then(function (value) { + assert.strictEqual(value, sentinel); + semiDone(); + }); + + promise.then(function () { + throw sentinel2; + }).then(null, function (reason) { + assert.strictEqual(reason, sentinel2); + semiDone(); + }); + + promise.then(function () { + return sentinel3; + }).then(function (value) { + assert.strictEqual(value, sentinel3); + semiDone(); + }); + }); + }); + + describe("`onFulfilled` handlers are called in the original order", function () { + testFulfilled(dummy, function (promise, done) { + var handler1 = sinon.spy(function handler1() {}); + var handler2 = sinon.spy(function handler2() {}); + var handler3 = sinon.spy(function handler3() {}); + + promise.then(handler1); + promise.then(handler2); + promise.then(handler3); + + promise.then(function () { + sinon.assert.callOrder(handler1, handler2, handler3); + done(); + }); + }); + + describe("even when one handler is added inside another handler", function () { + testFulfilled(dummy, function (promise, done) { + var handler1 = sinon.spy(function handler1() {}); + var handler2 = sinon.spy(function handler2() {}); + var handler3 = sinon.spy(function handler3() {}); + + promise.then(function () { + handler1(); + promise.then(handler3); + }); + promise.then(handler2); + + promise.then(function () { + // Give implementations a bit of extra time to flush their internal queue, if necessary. + setTimeout(function () { + sinon.assert.callOrder(handler1, handler2, handler3); + done(); + }, 15); + }); + }); + }); + }); + }); + + describe("2.2.6.2: If/when `promise` is rejected, all respective `onRejected` callbacks must execute in the " + + "order of their originating calls to `then`.", function () { + describe("multiple boring rejection handlers", function () { + testRejected(sentinel, function (promise, done) { + var handler1 = sinon.stub().returns(other); + var handler2 = sinon.stub().returns(other); + var handler3 = sinon.stub().returns(other); + + var spy = sinon.spy(); + promise.then(spy, handler1); + promise.then(spy, handler2); + promise.then(spy, handler3); + + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + + sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); + sinon.assert.notCalled(spy); + + done(); + }); + }); + }); + + describe("multiple rejection handlers, one of which throws", function () { + testRejected(sentinel, function (promise, done) { + var handler1 = sinon.stub().returns(other); + var handler2 = sinon.stub().throws(other); + var handler3 = sinon.stub().returns(other); + + var spy = sinon.spy(); + promise.then(spy, handler1); + promise.then(spy, handler2); + promise.then(spy, handler3); + + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + + sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); + sinon.assert.notCalled(spy); + + done(); + }); + }); + }); + + describe("results in multiple branching chains with their own fulfillment values", function () { + testRejected(sentinel, function (promise, done) { + var semiDone = callbackAggregator(3, done); + + promise.then(null, function () { + return sentinel; + }).then(function (value) { + assert.strictEqual(value, sentinel); + semiDone(); + }); + + promise.then(null, function () { + throw sentinel2; + }).then(null, function (reason) { + assert.strictEqual(reason, sentinel2); + semiDone(); + }); + + promise.then(null, function () { + return sentinel3; + }).then(function (value) { + assert.strictEqual(value, sentinel3); + semiDone(); + }); + }); + }); + + describe("`onRejected` handlers are called in the original order", function () { + testRejected(dummy, function (promise, done) { + var handler1 = sinon.spy(function handler1() {}); + var handler2 = sinon.spy(function handler2() {}); + var handler3 = sinon.spy(function handler3() {}); + + promise.then(null, handler1); + promise.then(null, handler2); + promise.then(null, handler3); + + promise.then(null, function () { + sinon.assert.callOrder(handler1, handler2, handler3); + done(); + }); + }); + + describe("even when one handler is added inside another handler", function () { + testRejected(dummy, function (promise, done) { + var handler1 = sinon.spy(function handler1() {}); + var handler2 = sinon.spy(function handler2() {}); + var handler3 = sinon.spy(function handler3() {}); + + promise.then(null, function () { + handler1(); + promise.then(null, handler3); + }); + promise.then(null, handler2); + + promise.then(null, function () { + // Give implementations a bit of extra time to flush their internal queue, if necessary. + setTimeout(function () { + sinon.assert.callOrder(handler1, handler2, handler3); + done(); + }, 15); + }); + }); + }); + }); + }); +}); + +},{"./helpers/testThreeCases":22,"assert":2,"sinon":24}],16:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; +var testRejected = require("./helpers/testThreeCases").testRejected; +var reasons = require("./helpers/reasons"); + +var adapter = global.adapter; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality +var other = { other: "other" }; // a value we don't want to be strict equal to + +describe("2.2.7: `then` must return a promise: `promise2 = promise1.then(onFulfilled, onRejected)`", function () { + specify("is a promise", function () { + var promise1 = deferred().promise; + var promise2 = promise1.then(); + + assert(typeof promise2 === "object" || typeof promise2 === "function"); + assert.notStrictEqual(promise2, null); + assert.strictEqual(typeof promise2.then, "function"); + }); + + describe("2.2.7.1: If either `onFulfilled` or `onRejected` returns a value `x`, run the Promise Resolution " + + "Procedure `[[Resolve]](promise2, x)`", function () { + specify("see separate 3.3 tests", function () { }); + }); + + describe("2.2.7.2: If either `onFulfilled` or `onRejected` throws an exception `e`, `promise2` must be rejected " + + "with `e` as the reason.", function () { + function testReason(expectedReason, stringRepresentation) { + describe("The reason is " + stringRepresentation, function () { + testFulfilled(dummy, function (promise1, done) { + var promise2 = promise1.then(function onFulfilled() { + throw expectedReason; + }); + + promise2.then(null, function onPromise2Rejected(actualReason) { + assert.strictEqual(actualReason, expectedReason); + done(); + }); + }); + testRejected(dummy, function (promise1, done) { + var promise2 = promise1.then(null, function onRejected() { + throw expectedReason; + }); + + promise2.then(null, function onPromise2Rejected(actualReason) { + assert.strictEqual(actualReason, expectedReason); + done(); + }); + }); + }); + } + + Object.keys(reasons).forEach(function (stringRepresentation) { + testReason(reasons[stringRepresentation], stringRepresentation); + }); + }); + + describe("2.2.7.3: If `onFulfilled` is not a function and `promise1` is fulfilled, `promise2` must be fulfilled " + + "with the same value.", function () { + + function testNonFunction(nonFunction, stringRepresentation) { + describe("`onFulfilled` is " + stringRepresentation, function () { + testFulfilled(sentinel, function (promise1, done) { + var promise2 = promise1.then(nonFunction); + + promise2.then(function onPromise2Fulfilled(value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + testNonFunction([function () { return other; }], "an array containing a function"); + }); + + describe("2.2.7.4: If `onRejected` is not a function and `promise1` is rejected, `promise2` must be rejected " + + "with the same reason.", function () { + + function testNonFunction(nonFunction, stringRepresentation) { + describe("`onRejected` is " + stringRepresentation, function () { + testRejected(sentinel, function (promise1, done) { + var promise2 = promise1.then(null, nonFunction); + + promise2.then(null, function onPromise2Rejected(reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + testNonFunction([function () { return other; }], "an array containing a function"); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/reasons":21,"./helpers/testThreeCases":22,"assert":2}],17:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.3.1: If `promise` and `x` refer to the same object, reject `promise` with a `TypeError' as the reason.", + function () { + specify("via return from a fulfilled promise", function (done) { + var promise = resolved(dummy).then(function () { + return promise; + }); + + promise.then(null, function (reason) { + assert(reason instanceof TypeError); + done(); + }); + }); + + specify("via return from a rejected promise", function (done) { + var promise = rejected(dummy).then(null, function () { + return promise; + }); + + promise.then(null, function (reason) { + assert(reason instanceof TypeError); + done(); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"assert":2}],18:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality + +function testPromiseResolution(xFactory, test) { + specify("via return from a fulfilled promise", function (done) { + var promise = resolved(dummy).then(function onBasePromiseFulfilled() { + return xFactory(); + }); + + test(promise, done); + }); + + specify("via return from a rejected promise", function (done) { + var promise = rejected(dummy).then(null, function onBasePromiseRejected() { + return xFactory(); + }); + + test(promise, done); + }); +} + +describe("2.3.2: If `x` is a promise, adopt its state", function () { + describe("2.3.2.1: If `x` is pending, `promise` must remain pending until `x` is fulfilled or rejected.", + function () { + function xFactory() { + return deferred().promise; + } + + testPromiseResolution(xFactory, function (promise, done) { + var wasFulfilled = false; + var wasRejected = false; + + promise.then( + function onPromiseFulfilled() { + wasFulfilled = true; + }, + function onPromiseRejected() { + wasRejected = true; + } + ); + + setTimeout(function () { + assert.strictEqual(wasFulfilled, false); + assert.strictEqual(wasRejected, false); + done(); + }, 100); + }); + }); + + describe("2.3.2.2: If/when `x` is fulfilled, fulfill `promise` with the same value.", function () { + describe("`x` is already-fulfilled", function () { + function xFactory() { + return resolved(sentinel); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function onPromiseFulfilled(value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("`x` is eventually-fulfilled", function () { + var d = null; + + function xFactory() { + d = deferred(); + setTimeout(function () { + d.resolve(sentinel); + }, 50); + return d.promise; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function onPromiseFulfilled(value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + }); + + describe("2.3.2.3: If/when `x` is rejected, reject `promise` with the same reason.", function () { + describe("`x` is already-rejected", function () { + function xFactory() { + return rejected(sentinel); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function onPromiseRejected(reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`x` is eventually-rejected", function () { + var d = null; + + function xFactory() { + d = deferred(); + setTimeout(function () { + d.reject(sentinel); + }, 50); + return d.promise; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function onPromiseRejected(reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"assert":2}],19:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var thenables = require("./helpers/thenables"); +var reasons = require("./helpers/reasons"); + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality +var other = { other: "other" }; // a value we don't want to be strict equal to +var sentinelArray = [sentinel]; // a sentinel fulfillment value to test when we need an array + +function testPromiseResolution(xFactory, test) { + specify("via return from a fulfilled promise", function (done) { + var promise = resolved(dummy).then(function onBasePromiseFulfilled() { + return xFactory(); + }); + + test(promise, done); + }); + + specify("via return from a rejected promise", function (done) { + var promise = rejected(dummy).then(null, function onBasePromiseRejected() { + return xFactory(); + }); + + test(promise, done); + }); +} + +function testCallingResolvePromise(yFactory, stringRepresentation, test) { + describe("`y` is " + stringRepresentation, function () { + describe("`then` calls `resolvePromise` synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + resolvePromise(yFactory()); + } + }; + } + + testPromiseResolution(xFactory, test); + }); + + describe("`then` calls `resolvePromise` asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + setTimeout(function () { + resolvePromise(yFactory()); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, test); + }); + }); +} + +function testCallingRejectPromise(r, stringRepresentation, test) { + describe("`r` is " + stringRepresentation, function () { + describe("`then` calls `rejectPromise` synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(r); + } + }; + } + + testPromiseResolution(xFactory, test); + }); + + describe("`then` calls `rejectPromise` asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + rejectPromise(r); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, test); + }); + }); +} + +function testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, fulfillmentValue) { + testCallingResolvePromise(yFactory, stringRepresentation, function (promise, done) { + promise.then(function onPromiseFulfilled(value) { + assert.strictEqual(value, fulfillmentValue); + done(); + }); + }); +} + +function testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, rejectionReason) { + testCallingResolvePromise(yFactory, stringRepresentation, function (promise, done) { + promise.then(null, function onPromiseRejected(reason) { + assert.strictEqual(reason, rejectionReason); + done(); + }); + }); +} + +function testCallingRejectPromiseRejectsWith(reason, stringRepresentation) { + testCallingRejectPromise(reason, stringRepresentation, function (promise, done) { + promise.then(null, function onPromiseRejected(rejectionReason) { + assert.strictEqual(rejectionReason, reason); + done(); + }); + }); +} + +describe("2.3.3: Otherwise, if `x` is an object or function,", function () { + describe("2.3.3.1: Let `then` be `x.then`", function () { + describe("`x` is an object with null prototype", function () { + var numberOfTimesThenWasRetrieved = null; + + beforeEach(function () { + numberOfTimesThenWasRetrieved = 0; + }); + + function xFactory() { + return Object.create(null, { + then: { + get: function () { + ++numberOfTimesThenWasRetrieved; + return function thenMethodForX(onFulfilled) { + onFulfilled(); + }; + } + } + }); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + assert.strictEqual(numberOfTimesThenWasRetrieved, 1); + done(); + }); + }); + }); + + describe("`x` is an object with normal Object.prototype", function () { + var numberOfTimesThenWasRetrieved = null; + + beforeEach(function () { + numberOfTimesThenWasRetrieved = 0; + }); + + function xFactory() { + return Object.create(Object.prototype, { + then: { + get: function () { + ++numberOfTimesThenWasRetrieved; + return function thenMethodForX(onFulfilled) { + onFulfilled(); + }; + } + } + }); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + assert.strictEqual(numberOfTimesThenWasRetrieved, 1); + done(); + }); + }); + }); + + describe("`x` is a function", function () { + var numberOfTimesThenWasRetrieved = null; + + beforeEach(function () { + numberOfTimesThenWasRetrieved = 0; + }); + + function xFactory() { + function x() { } + + Object.defineProperty(x, "then", { + get: function () { + ++numberOfTimesThenWasRetrieved; + return function thenMethodForX(onFulfilled) { + onFulfilled(); + }; + } + }); + + return x; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + assert.strictEqual(numberOfTimesThenWasRetrieved, 1); + done(); + }); + }); + }); + }); + + describe("2.3.3.2: If retrieving the property `x.then` results in a thrown exception `e`, reject `promise` with " + + "`e` as the reason.", function () { + function testRejectionViaThrowingGetter(e, stringRepresentation) { + function xFactory() { + return Object.create(Object.prototype, { + then: { + get: function () { + throw e; + } + } + }); + } + + describe("`e` is " + stringRepresentation, function () { + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, e); + done(); + }); + }); + }); + } + + Object.keys(reasons).forEach(function (stringRepresentation) { + testRejectionViaThrowingGetter(reasons[stringRepresentation], stringRepresentation); + }); + }); + + describe("2.3.3.3: If `then` is a function, call it with `x` as `this`, first argument `resolvePromise`, and " + + "second argument `rejectPromise`", function () { + describe("Calls with `x` as `this` and two function arguments", function () { + function xFactory() { + var x = { + then: function (onFulfilled, onRejected) { + assert.strictEqual(this, x); + assert.strictEqual(typeof onFulfilled, "function"); + assert.strictEqual(typeof onRejected, "function"); + onFulfilled(); + } + }; + return x; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + done(); + }); + }); + }); + + describe("Uses the original value of `then`", function () { + var numberOfTimesThenWasRetrieved = null; + + beforeEach(function () { + numberOfTimesThenWasRetrieved = 0; + }); + + function xFactory() { + return Object.create(Object.prototype, { + then: { + get: function () { + if (numberOfTimesThenWasRetrieved === 0) { + return function (onFulfilled) { + onFulfilled(); + }; + } + return null; + } + } + }); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + done(); + }); + }); + }); + + describe("2.3.3.3.1: If/when `resolvePromise` is called with value `y`, run `[[Resolve]](promise, y)`", + function () { + describe("`y` is not a thenable", function () { + testCallingResolvePromiseFulfillsWith(function () { return undefined; }, "`undefined`", undefined); + testCallingResolvePromiseFulfillsWith(function () { return null; }, "`null`", null); + testCallingResolvePromiseFulfillsWith(function () { return false; }, "`false`", false); + testCallingResolvePromiseFulfillsWith(function () { return 5; }, "`5`", 5); + testCallingResolvePromiseFulfillsWith(function () { return sentinel; }, "an object", sentinel); + testCallingResolvePromiseFulfillsWith(function () { return sentinelArray; }, "an array", sentinelArray); + }); + + describe("`y` is a thenable", function () { + Object.keys(thenables.fulfilled).forEach(function (stringRepresentation) { + function yFactory() { + return thenables.fulfilled[stringRepresentation](sentinel); + } + + testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, sentinel); + }); + + Object.keys(thenables.rejected).forEach(function (stringRepresentation) { + function yFactory() { + return thenables.rejected[stringRepresentation](sentinel); + } + + testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, sentinel); + }); + }); + + describe("`y` is a thenable for a thenable", function () { + Object.keys(thenables.fulfilled).forEach(function (outerStringRepresentation) { + var outerThenableFactory = thenables.fulfilled[outerStringRepresentation]; + + Object.keys(thenables.fulfilled).forEach(function (innerStringRepresentation) { + var innerThenableFactory = thenables.fulfilled[innerStringRepresentation]; + + var stringRepresentation = outerStringRepresentation + " for " + innerStringRepresentation; + + function yFactory() { + return outerThenableFactory(innerThenableFactory(sentinel)); + } + + testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, sentinel); + }); + + Object.keys(thenables.rejected).forEach(function (innerStringRepresentation) { + var innerThenableFactory = thenables.rejected[innerStringRepresentation]; + + var stringRepresentation = outerStringRepresentation + " for " + innerStringRepresentation; + + function yFactory() { + return outerThenableFactory(innerThenableFactory(sentinel)); + } + + testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, sentinel); + }); + }); + }); + }); + + describe("2.3.3.3.2: If/when `rejectPromise` is called with reason `r`, reject `promise` with `r`", + function () { + Object.keys(reasons).forEach(function (stringRepresentation) { + testCallingRejectPromiseRejectsWith(reasons[stringRepresentation], stringRepresentation); + }); + }); + + describe("2.3.3.3.3: If both `resolvePromise` and `rejectPromise` are called, or multiple calls to the same " + + "argument are made, the first call takes precedence, and any further calls are ignored.", + function () { + describe("calling `resolvePromise` then `rejectPromise`, both synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(sentinel); + rejectPromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` synchronously then `rejectPromise` asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(sentinel); + + setTimeout(function () { + rejectPromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` then `rejectPromise`, both asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + resolvePromise(sentinel); + }, 0); + + setTimeout(function () { + rejectPromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` with an asynchronously-fulfilled promise, then calling " + + "`rejectPromise`, both synchronously", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.resolve(sentinel); + }, 50); + + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(d.promise); + rejectPromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` with an asynchronously-rejected promise, then calling " + + "`rejectPromise`, both synchronously", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.reject(sentinel); + }, 50); + + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(d.promise); + rejectPromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` then `resolvePromise`, both synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + resolvePromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` synchronously then `resolvePromise` asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + + setTimeout(function () { + resolvePromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` then `resolvePromise`, both asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + rejectPromise(sentinel); + }, 0); + + setTimeout(function () { + resolvePromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` twice synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + resolvePromise(sentinel); + resolvePromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` twice, first synchronously then asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + resolvePromise(sentinel); + + setTimeout(function () { + resolvePromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` twice, both times asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + setTimeout(function () { + resolvePromise(sentinel); + }, 0); + + setTimeout(function () { + resolvePromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` with an asynchronously-fulfilled promise, then calling it again, both " + + "times synchronously", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.resolve(sentinel); + }, 50); + + return { + then: function (resolvePromise) { + resolvePromise(d.promise); + resolvePromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` with an asynchronously-rejected promise, then calling it again, both " + + "times synchronously", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.reject(sentinel); + }, 50); + + return { + then: function (resolvePromise) { + resolvePromise(d.promise); + resolvePromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` twice synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + rejectPromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` twice, first synchronously then asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + + setTimeout(function () { + rejectPromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` twice, both times asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + rejectPromise(sentinel); + }, 0); + + setTimeout(function () { + rejectPromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("saving and abusing `resolvePromise` and `rejectPromise`", function () { + var savedResolvePromise, savedRejectPromise; + + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + savedResolvePromise = resolvePromise; + savedRejectPromise = rejectPromise; + } + }; + } + + beforeEach(function () { + savedResolvePromise = null; + savedRejectPromise = null; + }); + + testPromiseResolution(xFactory, function (promise, done) { + var timesFulfilled = 0; + var timesRejected = 0; + + promise.then( + function () { + ++timesFulfilled; + }, + function () { + ++timesRejected; + } + ); + + if (savedResolvePromise && savedRejectPromise) { + savedResolvePromise(dummy); + savedResolvePromise(dummy); + savedRejectPromise(dummy); + savedRejectPromise(dummy); + } + + setTimeout(function () { + savedResolvePromise(dummy); + savedResolvePromise(dummy); + savedRejectPromise(dummy); + savedRejectPromise(dummy); + }, 50); + + setTimeout(function () { + assert.strictEqual(timesFulfilled, 1); + assert.strictEqual(timesRejected, 0); + done(); + }, 100); + }); + }); + }); + + describe("2.3.3.3.4: If calling `then` throws an exception `e`,", function () { + describe("2.3.3.3.4.1: If `resolvePromise` or `rejectPromise` have been called, ignore it.", function () { + describe("`resolvePromise` was called with a non-thenable", function () { + function xFactory() { + return { + then: function (resolvePromise) { + resolvePromise(sentinel); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("`resolvePromise` was called with an asynchronously-fulfilled promise", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.resolve(sentinel); + }, 50); + + return { + then: function (resolvePromise) { + resolvePromise(d.promise); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("`resolvePromise` was called with an asynchronously-rejected promise", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.reject(sentinel); + }, 50); + + return { + then: function (resolvePromise) { + resolvePromise(d.promise); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`rejectPromise` was called", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`resolvePromise` then `rejectPromise` were called", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(sentinel); + rejectPromise(other); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("`rejectPromise` then `resolvePromise` were called", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + resolvePromise(other); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + }); + + describe("2.3.3.3.4.2: Otherwise, reject `promise` with `e` as the reason.", function () { + describe("straightforward case", function () { + function xFactory() { + return { + then: function () { + throw sentinel; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`resolvePromise` is called asynchronously before the `throw`", function () { + function xFactory() { + return { + then: function (resolvePromise) { + setTimeout(function () { + resolvePromise(other); + }, 0); + throw sentinel; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`rejectPromise` is called asynchronously before the `throw`", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + rejectPromise(other); + }, 0); + throw sentinel; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + }); + }); + }); + + describe("2.3.3.4: If `then` is not a function, fulfill promise with `x`", function () { + function testFulfillViaNonFunction(then, stringRepresentation) { + var x = null; + + beforeEach(function () { + x = { then: then }; + }); + + function xFactory() { + return x; + } + + describe("`then` is " + stringRepresentation, function () { + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, x); + done(); + }); + }); + }); + } + + testFulfillViaNonFunction(5, "`5`"); + testFulfillViaNonFunction({}, "an object"); + testFulfillViaNonFunction([function () { }], "an array containing a function"); + testFulfillViaNonFunction(/a-b/i, "a regular expression"); + testFulfillViaNonFunction(Object.create(Function.prototype), "an object inheriting from `Function.prototype`"); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/reasons":21,"./helpers/thenables":23,"assert":2}],20:[function(require,module,exports){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; +var testRejected = require("./helpers/testThreeCases").testRejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.3.4: If `x` is not an object or function, fulfill `promise` with `x`", function () { + function testValue(expectedValue, stringRepresentation, beforeEachHook, afterEachHook) { + describe("The value is " + stringRepresentation, function () { + if (typeof beforeEachHook === "function") { + beforeEach(beforeEachHook); + } + if (typeof afterEachHook === "function") { + afterEach(afterEachHook); + } + + testFulfilled(dummy, function (promise1, done) { + var promise2 = promise1.then(function onFulfilled() { + return expectedValue; + }); + + promise2.then(function onPromise2Fulfilled(actualValue) { + assert.strictEqual(actualValue, expectedValue); + done(); + }); + }); + testRejected(dummy, function (promise1, done) { + var promise2 = promise1.then(null, function onRejected() { + return expectedValue; + }); + + promise2.then(function onPromise2Fulfilled(actualValue) { + assert.strictEqual(actualValue, expectedValue); + done(); + }); + }); + }); + } + + testValue(undefined, "`undefined`"); + testValue(null, "`null`"); + testValue(false, "`false`"); + testValue(true, "`true`"); + testValue(0, "`0`"); + + testValue( + true, + "`true` with `Boolean.prototype` modified to have a `then` method", + function () { + Boolean.prototype.then = function () {}; + }, + function () { + delete Boolean.prototype.then; + } + ); + + testValue( + 1, + "`1` with `Number.prototype` modified to have a `then` method", + function () { + Number.prototype.then = function () {}; + }, + function () { + delete Number.prototype.then; + } + ); +}); + +},{"./helpers/testThreeCases":22,"assert":2}],21:[function(require,module,exports){ +(function (global){ +"use strict"; + +// This module exports some valid rejection reason factories, keyed by human-readable versions of their names. + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; + +var dummy = { dummy: "dummy" }; + +exports["`undefined`"] = function () { + return undefined; +}; + +exports["`null`"] = function () { + return null; +}; + +exports["`false`"] = function () { + return false; +}; + +exports["`0`"] = function () { + return 0; +}; + +exports["an error"] = function () { + return new Error(); +}; + +exports["an error without a stack"] = function () { + var error = new Error(); + delete error.stack; + + return error; +}; + +exports["a date"] = function () { + return new Date(); +}; + +exports["an object"] = function () { + return {}; +}; + +exports["an always-pending thenable"] = function () { + return { then: function () { } }; +}; + +exports["a fulfilled promise"] = function () { + return resolved(dummy); +}; + +exports["a rejected promise"] = function () { + return rejected(dummy); +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],22:[function(require,module,exports){ +(function (global){ +"use strict"; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +exports.testFulfilled = function (value, test) { + specify("already-fulfilled", function (done) { + test(resolved(value), done); + }); + + specify("immediately-fulfilled", function (done) { + var d = deferred(); + test(d.promise, done); + d.resolve(value); + }); + + specify("eventually-fulfilled", function (done) { + var d = deferred(); + test(d.promise, done); + setTimeout(function () { + d.resolve(value); + }, 50); + }); +}; + +exports.testRejected = function (reason, test) { + specify("already-rejected", function (done) { + test(rejected(reason), done); + }); + + specify("immediately-rejected", function (done) { + var d = deferred(); + test(d.promise, done); + d.reject(reason); + }); + + specify("eventually-rejected", function (done) { + var d = deferred(); + test(d.promise, done); + setTimeout(function () { + d.reject(reason); + }, 50); + }); +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],23:[function(require,module,exports){ +(function (global){ +"use strict"; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var other = { other: "other" }; // a value we don't want to be strict equal to + +exports.fulfilled = { + "a synchronously-fulfilled custom thenable": function (value) { + return { + then: function (onFulfilled) { + onFulfilled(value); + } + }; + }, + + "an asynchronously-fulfilled custom thenable": function (value) { + return { + then: function (onFulfilled) { + setTimeout(function () { + onFulfilled(value); + }, 0); + } + }; + }, + + "a synchronously-fulfilled one-time thenable": function (value) { + var numberOfTimesThenRetrieved = 0; + return Object.create(null, { + then: { + get: function () { + if (numberOfTimesThenRetrieved === 0) { + ++numberOfTimesThenRetrieved; + return function (onFulfilled) { + onFulfilled(value); + }; + } + return null; + } + } + }); + }, + + "a thenable that tries to fulfill twice": function (value) { + return { + then: function (onFulfilled) { + onFulfilled(value); + onFulfilled(other); + } + }; + }, + + "a thenable that fulfills but then throws": function (value) { + return { + then: function (onFulfilled) { + onFulfilled(value); + throw other; + } + }; + }, + + "an already-fulfilled promise": function (value) { + return resolved(value); + }, + + "an eventually-fulfilled promise": function (value) { + var d = deferred(); + setTimeout(function () { + d.resolve(value); + }, 50); + return d.promise; + } +}; + +exports.rejected = { + "a synchronously-rejected custom thenable": function (reason) { + return { + then: function (onFulfilled, onRejected) { + onRejected(reason); + } + }; + }, + + "an asynchronously-rejected custom thenable": function (reason) { + return { + then: function (onFulfilled, onRejected) { + setTimeout(function () { + onRejected(reason); + }, 0); + } + }; + }, + + "a synchronously-rejected one-time thenable": function (reason) { + var numberOfTimesThenRetrieved = 0; + return Object.create(null, { + then: { + get: function () { + if (numberOfTimesThenRetrieved === 0) { + ++numberOfTimesThenRetrieved; + return function (onFulfilled, onRejected) { + onRejected(reason); + }; + } + return null; + } + } + }); + }, + + "a thenable that immediately throws in `then`": function (reason) { + return { + then: function () { + throw reason; + } + }; + }, + + "an object with a throwing `then` accessor": function (reason) { + return Object.create(null, { + then: { + get: function () { + throw reason; + } + } + }); + }, + + "an already-rejected promise": function (reason) { + return rejected(reason); + }, + + "an eventually-rejected promise": function (reason) { + var d = deferred(); + setTimeout(function () { + d.reject(reason); + }, 50); + return d.promise; + } +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],24:[function(require,module,exports){ +/** + * Sinon core utilities. For internal use only. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +var sinon = (function () { + var sinon; + var isNode = typeof module !== "undefined" && module.exports && typeof require === "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + sinon = module.exports = require("./sinon/util/core"); + require("./sinon/extend"); + require("./sinon/typeOf"); + require("./sinon/times_in_words"); + require("./sinon/spy"); + require("./sinon/call"); + require("./sinon/behavior"); + require("./sinon/stub"); + require("./sinon/mock"); + require("./sinon/collection"); + require("./sinon/assert"); + require("./sinon/sandbox"); + require("./sinon/test"); + require("./sinon/test_case"); + require("./sinon/match"); + require("./sinon/format"); + require("./sinon/log_error"); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + sinon = module.exports; + } else { + sinon = {}; + } + + return sinon; +}()); + +},{"./sinon/assert":25,"./sinon/behavior":26,"./sinon/call":27,"./sinon/collection":28,"./sinon/extend":29,"./sinon/format":30,"./sinon/log_error":31,"./sinon/match":32,"./sinon/mock":33,"./sinon/sandbox":34,"./sinon/spy":35,"./sinon/stub":36,"./sinon/test":37,"./sinon/test_case":38,"./sinon/times_in_words":39,"./sinon/typeOf":40,"./sinon/util/core":41}],25:[function(require,module,exports){ +(function (global){ +/** + * @depend times_in_words.js + * @depend util/core.js + * @depend match.js + * @depend format.js + */ +/** + * Assertions matching the test spy retrieval interface. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon, global) { + var slice = Array.prototype.slice; + + function makeApi(sinon) { + var assert; + + function verifyIsStub() { + var method; + + for (var i = 0, l = arguments.length; i < l; ++i) { + method = arguments[i]; + + if (!method) { + assert.fail("fake is not a spy"); + } + + if (method.proxy) { + verifyIsStub(method.proxy); + } else { + if (typeof method != "function") { + assert.fail(method + " is not a function"); + } + + if (typeof method.getCall != "function") { + assert.fail(method + " is not stubbed"); + } + } + + } + } + + function failAssertion(object, msg) { + object = object || global; + var failMethod = object.fail || assert.fail; + failMethod.call(object, msg); + } + + function mirrorPropAsAssertion(name, method, message) { + if (arguments.length == 2) { + message = method; + method = name; + } + + assert[name] = function (fake) { + verifyIsStub(fake); + + var args = slice.call(arguments, 1); + var failed = false; + + if (typeof method == "function") { + failed = !method(fake); + } else { + failed = typeof fake[method] == "function" ? + !fake[method].apply(fake, args) : !fake[method]; + } + + if (failed) { + failAssertion(this, (fake.printf || fake.proxy.printf).apply(fake, [message].concat(args))); + } else { + assert.pass(name); + } + }; + } + + function exposedName(prefix, prop) { + return !prefix || /^fail/.test(prop) ? prop : + prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1); + } + + assert = { + failException: "AssertError", + + fail: function fail(message) { + var error = new Error(message); + error.name = this.failException || assert.failException; + + throw error; + }, + + pass: function pass(assertion) {}, + + callOrder: function assertCallOrder() { + verifyIsStub.apply(null, arguments); + var expected = "", actual = ""; + + if (!sinon.calledInOrder(arguments)) { + try { + expected = [].join.call(arguments, ", "); + var calls = slice.call(arguments); + var i = calls.length; + while (i) { + if (!calls[--i].called) { + calls.splice(i, 1); + } + } + actual = sinon.orderByFirstCall(calls).join(", "); + } catch (e) { + // If this fails, we'll just fall back to the blank string + } + + failAssertion(this, "expected " + expected + " to be " + + "called in order but were called as " + actual); + } else { + assert.pass("callOrder"); + } + }, + + callCount: function assertCallCount(method, count) { + verifyIsStub(method); + + if (method.callCount != count) { + var msg = "expected %n to be called " + sinon.timesInWords(count) + + " but was called %c%C"; + failAssertion(this, method.printf(msg)); + } else { + assert.pass("callCount"); + } + }, + + expose: function expose(target, options) { + if (!target) { + throw new TypeError("target is null or undefined"); + } + + var o = options || {}; + var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix; + var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail; + + for (var method in this) { + if (method != "expose" && (includeFail || !/^(fail)/.test(method))) { + target[exposedName(prefix, method)] = this[method]; + } + } + + return target; + }, + + match: function match(actual, expectation) { + var matcher = sinon.match(expectation); + if (matcher.test(actual)) { + assert.pass("match"); + } else { + var formatted = [ + "expected value to match", + " expected = " + sinon.format(expectation), + " actual = " + sinon.format(actual) + ] + failAssertion(this, formatted.join("\n")); + } + } + }; + + mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called"); + mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; }, + "expected %n to not have been called but was called %c%C"); + mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C"); + mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C"); + mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C"); + mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t"); + mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t"); + mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new"); + mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new"); + mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C"); + mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C"); + mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C"); + mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C"); + mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C"); + mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C"); + mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C"); + mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C"); + mirrorPropAsAssertion("threw", "%n did not throw exception%C"); + mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C"); + + sinon.assert = assert; + return assert; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./match"); + require("./format"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } + +}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./format":30,"./match":32,"./util/core":41}],26:[function(require,module,exports){ +(function (process){ +/** + * @depend util/core.js + * @depend extend.js + */ +/** + * Stub behavior + * + * @author Christian Johansen (christian@cjohansen.no) + * @author Tim Fischbach (mail@timfischbach.de) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + var slice = Array.prototype.slice; + var join = Array.prototype.join; + var useLeftMostCallback = -1; + var useRightMostCallback = -2; + + var nextTick = (function () { + if (typeof process === "object" && typeof process.nextTick === "function") { + return process.nextTick; + } else if (typeof setImmediate === "function") { + return setImmediate; + } else { + return function (callback) { + setTimeout(callback, 0); + }; + } + })(); + + function throwsException(error, message) { + if (typeof error == "string") { + this.exception = new Error(message || ""); + this.exception.name = error; + } else if (!error) { + this.exception = new Error("Error"); + } else { + this.exception = error; + } + + return this; + } + + function getCallback(behavior, args) { + var callArgAt = behavior.callArgAt; + + if (callArgAt >= 0) { + return args[callArgAt]; + } + + var argumentList; + + if (callArgAt === useLeftMostCallback) { + argumentList = args; + } + + if (callArgAt === useRightMostCallback) { + argumentList = slice.call(args).reverse(); + } + + var callArgProp = behavior.callArgProp; + + for (var i = 0, l = argumentList.length; i < l; ++i) { + if (!callArgProp && typeof argumentList[i] == "function") { + return argumentList[i]; + } + + if (callArgProp && argumentList[i] && + typeof argumentList[i][callArgProp] == "function") { + return argumentList[i][callArgProp]; + } + } + + return null; + } + + function makeApi(sinon) { + function getCallbackError(behavior, func, args) { + if (behavior.callArgAt < 0) { + var msg; + + if (behavior.callArgProp) { + msg = sinon.functionName(behavior.stub) + + " expected to yield to '" + behavior.callArgProp + + "', but no object with such a property was passed."; + } else { + msg = sinon.functionName(behavior.stub) + + " expected to yield, but no callback was passed."; + } + + if (args.length > 0) { + msg += " Received [" + join.call(args, ", ") + "]"; + } + + return msg; + } + + return "argument at index " + behavior.callArgAt + " is not a function: " + func; + } + + function callCallback(behavior, args) { + if (typeof behavior.callArgAt == "number") { + var func = getCallback(behavior, args); + + if (typeof func != "function") { + throw new TypeError(getCallbackError(behavior, func, args)); + } + + if (behavior.callbackAsync) { + nextTick(function () { + func.apply(behavior.callbackContext, behavior.callbackArguments); + }); + } else { + func.apply(behavior.callbackContext, behavior.callbackArguments); + } + } + } + + var proto = { + create: function create(stub) { + var behavior = sinon.extend({}, sinon.behavior); + delete behavior.create; + behavior.stub = stub; + + return behavior; + }, + + isPresent: function isPresent() { + return (typeof this.callArgAt == "number" || + this.exception || + typeof this.returnArgAt == "number" || + this.returnThis || + this.returnValueDefined); + }, + + invoke: function invoke(context, args) { + callCallback(this, args); + + if (this.exception) { + throw this.exception; + } else if (typeof this.returnArgAt == "number") { + return args[this.returnArgAt]; + } else if (this.returnThis) { + return context; + } + + return this.returnValue; + }, + + onCall: function onCall(index) { + return this.stub.onCall(index); + }, + + onFirstCall: function onFirstCall() { + return this.stub.onFirstCall(); + }, + + onSecondCall: function onSecondCall() { + return this.stub.onSecondCall(); + }, + + onThirdCall: function onThirdCall() { + return this.stub.onThirdCall(); + }, + + withArgs: function withArgs(/* arguments */) { + throw new Error("Defining a stub by invoking \"stub.onCall(...).withArgs(...)\" is not supported. " + + "Use \"stub.withArgs(...).onCall(...)\" to define sequential behavior for calls with certain arguments."); + }, + + callsArg: function callsArg(pos) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + + this.callArgAt = pos; + this.callbackArguments = []; + this.callbackContext = undefined; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + callsArgOn: function callsArgOn(pos, context) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + if (typeof context != "object") { + throw new TypeError("argument context is not an object"); + } + + this.callArgAt = pos; + this.callbackArguments = []; + this.callbackContext = context; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + callsArgWith: function callsArgWith(pos) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + + this.callArgAt = pos; + this.callbackArguments = slice.call(arguments, 1); + this.callbackContext = undefined; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + callsArgOnWith: function callsArgWith(pos, context) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + if (typeof context != "object") { + throw new TypeError("argument context is not an object"); + } + + this.callArgAt = pos; + this.callbackArguments = slice.call(arguments, 2); + this.callbackContext = context; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + yields: function () { + this.callArgAt = useLeftMostCallback; + this.callbackArguments = slice.call(arguments, 0); + this.callbackContext = undefined; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + yieldsRight: function () { + this.callArgAt = useRightMostCallback; + this.callbackArguments = slice.call(arguments, 0); + this.callbackContext = undefined; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + yieldsOn: function (context) { + if (typeof context != "object") { + throw new TypeError("argument context is not an object"); + } + + this.callArgAt = useLeftMostCallback; + this.callbackArguments = slice.call(arguments, 1); + this.callbackContext = context; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + yieldsTo: function (prop) { + this.callArgAt = useLeftMostCallback; + this.callbackArguments = slice.call(arguments, 1); + this.callbackContext = undefined; + this.callArgProp = prop; + this.callbackAsync = false; + + return this; + }, + + yieldsToOn: function (prop, context) { + if (typeof context != "object") { + throw new TypeError("argument context is not an object"); + } + + this.callArgAt = useLeftMostCallback; + this.callbackArguments = slice.call(arguments, 2); + this.callbackContext = context; + this.callArgProp = prop; + this.callbackAsync = false; + + return this; + }, + + throws: throwsException, + throwsException: throwsException, + + returns: function returns(value) { + this.returnValue = value; + this.returnValueDefined = true; + + return this; + }, + + returnsArg: function returnsArg(pos) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + + this.returnArgAt = pos; + + return this; + }, + + returnsThis: function returnsThis() { + this.returnThis = true; + + return this; + } + }; + + // create asynchronous versions of callsArg* and yields* methods + for (var method in proto) { + // need to avoid creating anotherasync versions of the newly added async methods + if (proto.hasOwnProperty(method) && + method.match(/^(callsArg|yields)/) && + !method.match(/Async/)) { + proto[method + "Async"] = (function (syncFnName) { + return function () { + var result = this[syncFnName].apply(this, arguments); + this.callbackAsync = true; + return result; + }; + })(method); + } + } + + sinon.behavior = proto; + return proto; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./extend"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +}).call(this,require('_process')) +},{"./extend":29,"./util/core":41,"_process":4}],27:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend match.js + * @depend format.js + */ +/** + * Spy calls + * + * @author Christian Johansen (christian@cjohansen.no) + * @author Maximilian Antoni (mail@maxantoni.de) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + * Copyright (c) 2013 Maximilian Antoni + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + function throwYieldError(proxy, text, args) { + var msg = sinon.functionName(proxy) + text; + if (args.length) { + msg += " Received [" + slice.call(args).join(", ") + "]"; + } + throw new Error(msg); + } + + var slice = Array.prototype.slice; + + var callProto = { + calledOn: function calledOn(thisValue) { + if (sinon.match && sinon.match.isMatcher(thisValue)) { + return thisValue.test(this.thisValue); + } + return this.thisValue === thisValue; + }, + + calledWith: function calledWith() { + var l = arguments.length; + if (l > this.args.length) { + return false; + } + for (var i = 0; i < l; i += 1) { + if (!sinon.deepEqual(arguments[i], this.args[i])) { + return false; + } + } + + return true; + }, + + calledWithMatch: function calledWithMatch() { + var l = arguments.length; + if (l > this.args.length) { + return false; + } + for (var i = 0; i < l; i += 1) { + var actual = this.args[i]; + var expectation = arguments[i]; + if (!sinon.match || !sinon.match(expectation).test(actual)) { + return false; + } + } + return true; + }, + + calledWithExactly: function calledWithExactly() { + return arguments.length == this.args.length && + this.calledWith.apply(this, arguments); + }, + + notCalledWith: function notCalledWith() { + return !this.calledWith.apply(this, arguments); + }, + + notCalledWithMatch: function notCalledWithMatch() { + return !this.calledWithMatch.apply(this, arguments); + }, + + returned: function returned(value) { + return sinon.deepEqual(value, this.returnValue); + }, + + threw: function threw(error) { + if (typeof error === "undefined" || !this.exception) { + return !!this.exception; + } + + return this.exception === error || this.exception.name === error; + }, + + calledWithNew: function calledWithNew() { + return this.proxy.prototype && this.thisValue instanceof this.proxy; + }, + + calledBefore: function (other) { + return this.callId < other.callId; + }, + + calledAfter: function (other) { + return this.callId > other.callId; + }, + + callArg: function (pos) { + this.args[pos](); + }, + + callArgOn: function (pos, thisValue) { + this.args[pos].apply(thisValue); + }, + + callArgWith: function (pos) { + this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); + }, + + callArgOnWith: function (pos, thisValue) { + var args = slice.call(arguments, 2); + this.args[pos].apply(thisValue, args); + }, + + yield: function () { + this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); + }, + + yieldOn: function (thisValue) { + var args = this.args; + for (var i = 0, l = args.length; i < l; ++i) { + if (typeof args[i] === "function") { + args[i].apply(thisValue, slice.call(arguments, 1)); + return; + } + } + throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); + }, + + yieldTo: function (prop) { + this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); + }, + + yieldToOn: function (prop, thisValue) { + var args = this.args; + for (var i = 0, l = args.length; i < l; ++i) { + if (args[i] && typeof args[i][prop] === "function") { + args[i][prop].apply(thisValue, slice.call(arguments, 2)); + return; + } + } + throwYieldError(this.proxy, " cannot yield to '" + prop + + "' since no callback was passed.", args); + }, + + toString: function () { + var callStr = this.proxy.toString() + "("; + var args = []; + + for (var i = 0, l = this.args.length; i < l; ++i) { + args.push(sinon.format(this.args[i])); + } + + callStr = callStr + args.join(", ") + ")"; + + if (typeof this.returnValue != "undefined") { + callStr += " => " + sinon.format(this.returnValue); + } + + if (this.exception) { + callStr += " !" + this.exception.name; + + if (this.exception.message) { + callStr += "(" + this.exception.message + ")"; + } + } + + return callStr; + } + }; + + callProto.invokeCallback = callProto.yield; + + function createSpyCall(spy, thisValue, args, returnValue, exception, id) { + if (typeof id !== "number") { + throw new TypeError("Call id is not a number"); + } + var proxyCall = sinon.create(callProto); + proxyCall.proxy = spy; + proxyCall.thisValue = thisValue; + proxyCall.args = args; + proxyCall.returnValue = returnValue; + proxyCall.exception = exception; + proxyCall.callId = id; + + return proxyCall; + } + createSpyCall.toString = callProto.toString; // used by mocks + + sinon.spyCall = createSpyCall; + return createSpyCall; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./match"); + require("./format"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./format":30,"./match":32,"./util/core":41}],28:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend spy.js + * @depend stub.js + * @depend mock.js + */ +/** + * Collections of stubs, spies and mocks. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + var push = [].push; + var hasOwnProperty = Object.prototype.hasOwnProperty; + + function getFakes(fakeCollection) { + if (!fakeCollection.fakes) { + fakeCollection.fakes = []; + } + + return fakeCollection.fakes; + } + + function each(fakeCollection, method) { + var fakes = getFakes(fakeCollection); + + for (var i = 0, l = fakes.length; i < l; i += 1) { + if (typeof fakes[i][method] == "function") { + fakes[i][method](); + } + } + } + + function compact(fakeCollection) { + var fakes = getFakes(fakeCollection); + var i = 0; + while (i < fakes.length) { + fakes.splice(i, 1); + } + } + + function makeApi(sinon) { + var collection = { + verify: function resolve() { + each(this, "verify"); + }, + + restore: function restore() { + each(this, "restore"); + compact(this); + }, + + reset: function restore() { + each(this, "reset"); + }, + + verifyAndRestore: function verifyAndRestore() { + var exception; + + try { + this.verify(); + } catch (e) { + exception = e; + } + + this.restore(); + + if (exception) { + throw exception; + } + }, + + add: function add(fake) { + push.call(getFakes(this), fake); + return fake; + }, + + spy: function spy() { + return this.add(sinon.spy.apply(sinon, arguments)); + }, + + stub: function stub(object, property, value) { + if (property) { + var original = object[property]; + + if (typeof original != "function") { + if (!hasOwnProperty.call(object, property)) { + throw new TypeError("Cannot stub non-existent own property " + property); + } + + object[property] = value; + + return this.add({ + restore: function () { + object[property] = original; + } + }); + } + } + if (!property && !!object && typeof object == "object") { + var stubbedObj = sinon.stub.apply(sinon, arguments); + + for (var prop in stubbedObj) { + if (typeof stubbedObj[prop] === "function") { + this.add(stubbedObj[prop]); + } + } + + return stubbedObj; + } + + return this.add(sinon.stub.apply(sinon, arguments)); + }, + + mock: function mock() { + return this.add(sinon.mock.apply(sinon, arguments)); + }, + + inject: function inject(obj) { + var col = this; + + obj.spy = function () { + return col.spy.apply(col, arguments); + }; + + obj.stub = function () { + return col.stub.apply(col, arguments); + }; + + obj.mock = function () { + return col.mock.apply(col, arguments); + }; + + return obj; + } + }; + + sinon.collection = collection; + return collection; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./mock"); + require("./spy"); + require("./stub"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./mock":33,"./spy":35,"./stub":36,"./util/core":41}],29:[function(require,module,exports){ +/** + * @depend util/core.js + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + + // Adapted from https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug + var hasDontEnumBug = (function () { + var obj = { + constructor: function () { + return "0"; + }, + toString: function () { + return "1"; + }, + valueOf: function () { + return "2"; + }, + toLocaleString: function () { + return "3"; + }, + prototype: function () { + return "4"; + }, + isPrototypeOf: function () { + return "5"; + }, + propertyIsEnumerable: function () { + return "6"; + }, + hasOwnProperty: function () { + return "7"; + }, + length: function () { + return "8"; + }, + unique: function () { + return "9" + } + }; + + var result = []; + for (var prop in obj) { + result.push(obj[prop]()); + } + return result.join("") !== "0123456789"; + })(); + + /* Public: Extend target in place with all (own) properties from sources in-order. Thus, last source will + * override properties in previous sources. + * + * target - The Object to extend + * sources - Objects to copy properties from. + * + * Returns the extended target + */ + function extend(target /*, sources */) { + var sources = Array.prototype.slice.call(arguments, 1), + source, i, prop; + + for (i = 0; i < sources.length; i++) { + source = sources[i]; + + for (prop in source) { + if (source.hasOwnProperty(prop)) { + target[prop] = source[prop]; + } + } + + // Make sure we copy (own) toString method even when in JScript with DontEnum bug + // See https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug + if (hasDontEnumBug && source.hasOwnProperty("toString") && source.toString !== target.toString) { + target.toString = source.toString; + } + } + + return target; + }; + + sinon.extend = extend; + return sinon.extend; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./util/core":41}],30:[function(require,module,exports){ +/** + * @depend util/core.js + */ +/** + * Format functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2014 Christian Johansen + */ +"use strict"; + +(function (sinon, formatio) { + function makeApi(sinon) { + function valueFormatter(value) { + return "" + value; + } + + function getFormatioFormatter() { + var formatter = formatio.configure({ + quoteStrings: false, + limitChildrenCount: 250 + }); + + function format() { + return formatter.ascii.apply(formatter, arguments); + }; + + return format; + } + + function getNodeFormatter(value) { + function format(value) { + return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; + }; + + try { + var util = require("util"); + } catch (e) { + /* Node, but no util module - would be very old, but better safe than sorry */ + } + + return util ? format : valueFormatter; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function", + formatter; + + if (isNode) { + try { + formatio = require("formatio"); + } catch (e) {} + } + + if (formatio) { + formatter = getFormatioFormatter() + } else if (isNode) { + formatter = getNodeFormatter(); + } else { + formatter = valueFormatter; + } + + sinon.format = formatter; + return sinon.format; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}( + (typeof sinon == "object" && sinon || null), + (typeof formatio == "object" && formatio) +)); + +},{"./util/core":41,"formatio":48,"util":6}],31:[function(require,module,exports){ +/** + * @depend util/core.js + */ +/** + * Logs errors + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2014 Christian Johansen + */ +"use strict"; + +(function (sinon) { + // cache a reference to setTimeout, so that our reference won't be stubbed out + // when using fake timers and errors will still get logged + // https://github.com/cjohansen/Sinon.JS/issues/381 + var realSetTimeout = setTimeout; + + function makeApi(sinon) { + + function log() {} + + function logError(label, err) { + var msg = label + " threw exception: "; + + sinon.log(msg + "[" + err.name + "] " + err.message); + + if (err.stack) { + sinon.log(err.stack); + } + + logError.setTimeout(function () { + err.message = msg + err.message; + throw err; + }, 0); + }; + + // wrap realSetTimeout with something we can stub in tests + logError.setTimeout = function (func, timeout) { + realSetTimeout(func, timeout); + } + + var exports = {}; + exports.log = sinon.log = log; + exports.logError = sinon.logError = logError; + + return exports; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./util/core":41}],32:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend typeOf.js + */ +/*jslint eqeqeq: false, onevar: false, plusplus: false*/ +/*global module, require, sinon*/ +/** + * Match functions + * + * @author Maximilian Antoni (mail@maxantoni.de) + * @license BSD + * + * Copyright (c) 2012 Maximilian Antoni + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + function assertType(value, type, name) { + var actual = sinon.typeOf(value); + if (actual !== type) { + throw new TypeError("Expected type of " + name + " to be " + + type + ", but was " + actual); + } + } + + var matcher = { + toString: function () { + return this.message; + } + }; + + function isMatcher(object) { + return matcher.isPrototypeOf(object); + } + + function matchObject(expectation, actual) { + if (actual === null || actual === undefined) { + return false; + } + for (var key in expectation) { + if (expectation.hasOwnProperty(key)) { + var exp = expectation[key]; + var act = actual[key]; + if (match.isMatcher(exp)) { + if (!exp.test(act)) { + return false; + } + } else if (sinon.typeOf(exp) === "object") { + if (!matchObject(exp, act)) { + return false; + } + } else if (!sinon.deepEqual(exp, act)) { + return false; + } + } + } + return true; + } + + matcher.or = function (m2) { + if (!arguments.length) { + throw new TypeError("Matcher expected"); + } else if (!isMatcher(m2)) { + m2 = match(m2); + } + var m1 = this; + var or = sinon.create(matcher); + or.test = function (actual) { + return m1.test(actual) || m2.test(actual); + }; + or.message = m1.message + ".or(" + m2.message + ")"; + return or; + }; + + matcher.and = function (m2) { + if (!arguments.length) { + throw new TypeError("Matcher expected"); + } else if (!isMatcher(m2)) { + m2 = match(m2); + } + var m1 = this; + var and = sinon.create(matcher); + and.test = function (actual) { + return m1.test(actual) && m2.test(actual); + }; + and.message = m1.message + ".and(" + m2.message + ")"; + return and; + }; + + var match = function (expectation, message) { + var m = sinon.create(matcher); + var type = sinon.typeOf(expectation); + switch (type) { + case "object": + if (typeof expectation.test === "function") { + m.test = function (actual) { + return expectation.test(actual) === true; + }; + m.message = "match(" + sinon.functionName(expectation.test) + ")"; + return m; + } + var str = []; + for (var key in expectation) { + if (expectation.hasOwnProperty(key)) { + str.push(key + ": " + expectation[key]); + } + } + m.test = function (actual) { + return matchObject(expectation, actual); + }; + m.message = "match(" + str.join(", ") + ")"; + break; + case "number": + m.test = function (actual) { + return expectation == actual; + }; + break; + case "string": + m.test = function (actual) { + if (typeof actual !== "string") { + return false; + } + return actual.indexOf(expectation) !== -1; + }; + m.message = "match(\"" + expectation + "\")"; + break; + case "regexp": + m.test = function (actual) { + if (typeof actual !== "string") { + return false; + } + return expectation.test(actual); + }; + break; + case "function": + m.test = expectation; + if (message) { + m.message = message; + } else { + m.message = "match(" + sinon.functionName(expectation) + ")"; + } + break; + default: + m.test = function (actual) { + return sinon.deepEqual(expectation, actual); + }; + } + if (!m.message) { + m.message = "match(" + expectation + ")"; + } + return m; + }; + + match.isMatcher = isMatcher; + + match.any = match(function () { + return true; + }, "any"); + + match.defined = match(function (actual) { + return actual !== null && actual !== undefined; + }, "defined"); + + match.truthy = match(function (actual) { + return !!actual; + }, "truthy"); + + match.falsy = match(function (actual) { + return !actual; + }, "falsy"); + + match.same = function (expectation) { + return match(function (actual) { + return expectation === actual; + }, "same(" + expectation + ")"); + }; + + match.typeOf = function (type) { + assertType(type, "string", "type"); + return match(function (actual) { + return sinon.typeOf(actual) === type; + }, "typeOf(\"" + type + "\")"); + }; + + match.instanceOf = function (type) { + assertType(type, "function", "type"); + return match(function (actual) { + return actual instanceof type; + }, "instanceOf(" + sinon.functionName(type) + ")"); + }; + + function createPropertyMatcher(propertyTest, messagePrefix) { + return function (property, value) { + assertType(property, "string", "property"); + var onlyProperty = arguments.length === 1; + var message = messagePrefix + "(\"" + property + "\""; + if (!onlyProperty) { + message += ", " + value; + } + message += ")"; + return match(function (actual) { + if (actual === undefined || actual === null || + !propertyTest(actual, property)) { + return false; + } + return onlyProperty || sinon.deepEqual(value, actual[property]); + }, message); + }; + } + + match.has = createPropertyMatcher(function (actual, property) { + if (typeof actual === "object") { + return property in actual; + } + return actual[property] !== undefined; + }, "has"); + + match.hasOwn = createPropertyMatcher(function (actual, property) { + return actual.hasOwnProperty(property); + }, "hasOwn"); + + match.bool = match.typeOf("boolean"); + match.number = match.typeOf("number"); + match.string = match.typeOf("string"); + match.object = match.typeOf("object"); + match.func = match.typeOf("function"); + match.array = match.typeOf("array"); + match.regexp = match.typeOf("regexp"); + match.date = match.typeOf("date"); + + sinon.match = match; + return match; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./typeOf"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./typeOf":40,"./util/core":41}],33:[function(require,module,exports){ +/** + * @depend times_in_words.js + * @depend util/core.js + * @depend call.js + * @depend extend.js + * @depend match.js + * @depend spy.js + * @depend stub.js + * @depend format.js + */ +/** + * Mock functions. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + var push = [].push; + var match = sinon.match; + + function mock(object) { + if (!object) { + return sinon.expectation.create("Anonymous mock"); + } + + return mock.create(object); + } + + function each(collection, callback) { + if (!collection) { + return; + } + + for (var i = 0, l = collection.length; i < l; i += 1) { + callback(collection[i]); + } + } + + sinon.extend(mock, { + create: function create(object) { + if (!object) { + throw new TypeError("object is null"); + } + + var mockObject = sinon.extend({}, mock); + mockObject.object = object; + delete mockObject.create; + + return mockObject; + }, + + expects: function expects(method) { + if (!method) { + throw new TypeError("method is falsy"); + } + + if (!this.expectations) { + this.expectations = {}; + this.proxies = []; + } + + if (!this.expectations[method]) { + this.expectations[method] = []; + var mockObject = this; + + sinon.wrapMethod(this.object, method, function () { + return mockObject.invokeMethod(method, this, arguments); + }); + + push.call(this.proxies, method); + } + + var expectation = sinon.expectation.create(method); + push.call(this.expectations[method], expectation); + + return expectation; + }, + + restore: function restore() { + var object = this.object; + + each(this.proxies, function (proxy) { + if (typeof object[proxy].restore == "function") { + object[proxy].restore(); + } + }); + }, + + verify: function verify() { + var expectations = this.expectations || {}; + var messages = [], met = []; + + each(this.proxies, function (proxy) { + each(expectations[proxy], function (expectation) { + if (!expectation.met()) { + push.call(messages, expectation.toString()); + } else { + push.call(met, expectation.toString()); + } + }); + }); + + this.restore(); + + if (messages.length > 0) { + sinon.expectation.fail(messages.concat(met).join("\n")); + } else if (met.length > 0) { + sinon.expectation.pass(messages.concat(met).join("\n")); + } + + return true; + }, + + invokeMethod: function invokeMethod(method, thisValue, args) { + var expectations = this.expectations && this.expectations[method]; + var length = expectations && expectations.length || 0, i; + + for (i = 0; i < length; i += 1) { + if (!expectations[i].met() && + expectations[i].allowsCall(thisValue, args)) { + return expectations[i].apply(thisValue, args); + } + } + + var messages = [], available, exhausted = 0; + + for (i = 0; i < length; i += 1) { + if (expectations[i].allowsCall(thisValue, args)) { + available = available || expectations[i]; + } else { + exhausted += 1; + } + push.call(messages, " " + expectations[i].toString()); + } + + if (exhausted === 0) { + return available.apply(thisValue, args); + } + + messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ + proxy: method, + args: args + })); + + sinon.expectation.fail(messages.join("\n")); + } + }); + + var times = sinon.timesInWords; + var slice = Array.prototype.slice; + + function callCountInWords(callCount) { + if (callCount == 0) { + return "never called"; + } else { + return "called " + times(callCount); + } + } + + function expectedCallCountInWords(expectation) { + var min = expectation.minCalls; + var max = expectation.maxCalls; + + if (typeof min == "number" && typeof max == "number") { + var str = times(min); + + if (min != max) { + str = "at least " + str + " and at most " + times(max); + } + + return str; + } + + if (typeof min == "number") { + return "at least " + times(min); + } + + return "at most " + times(max); + } + + function receivedMinCalls(expectation) { + var hasMinLimit = typeof expectation.minCalls == "number"; + return !hasMinLimit || expectation.callCount >= expectation.minCalls; + } + + function receivedMaxCalls(expectation) { + if (typeof expectation.maxCalls != "number") { + return false; + } + + return expectation.callCount == expectation.maxCalls; + } + + function verifyMatcher(possibleMatcher, arg) { + if (match && match.isMatcher(possibleMatcher)) { + return possibleMatcher.test(arg); + } else { + return true; + } + } + + sinon.expectation = { + minCalls: 1, + maxCalls: 1, + + create: function create(methodName) { + var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); + delete expectation.create; + expectation.method = methodName; + + return expectation; + }, + + invoke: function invoke(func, thisValue, args) { + this.verifyCallAllowed(thisValue, args); + + return sinon.spy.invoke.apply(this, arguments); + }, + + atLeast: function atLeast(num) { + if (typeof num != "number") { + throw new TypeError("'" + num + "' is not number"); + } + + if (!this.limitsSet) { + this.maxCalls = null; + this.limitsSet = true; + } + + this.minCalls = num; + + return this; + }, + + atMost: function atMost(num) { + if (typeof num != "number") { + throw new TypeError("'" + num + "' is not number"); + } + + if (!this.limitsSet) { + this.minCalls = null; + this.limitsSet = true; + } + + this.maxCalls = num; + + return this; + }, + + never: function never() { + return this.exactly(0); + }, + + once: function once() { + return this.exactly(1); + }, + + twice: function twice() { + return this.exactly(2); + }, + + thrice: function thrice() { + return this.exactly(3); + }, + + exactly: function exactly(num) { + if (typeof num != "number") { + throw new TypeError("'" + num + "' is not a number"); + } + + this.atLeast(num); + return this.atMost(num); + }, + + met: function met() { + return !this.failed && receivedMinCalls(this); + }, + + verifyCallAllowed: function verifyCallAllowed(thisValue, args) { + if (receivedMaxCalls(this)) { + this.failed = true; + sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); + } + + if ("expectedThis" in this && this.expectedThis !== thisValue) { + sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + + this.expectedThis); + } + + if (!("expectedArguments" in this)) { + return; + } + + if (!args) { + sinon.expectation.fail(this.method + " received no arguments, expected " + + sinon.format(this.expectedArguments)); + } + + if (args.length < this.expectedArguments.length) { + sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) + + "), expected " + sinon.format(this.expectedArguments)); + } + + if (this.expectsExactArgCount && + args.length != this.expectedArguments.length) { + sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) + + "), expected " + sinon.format(this.expectedArguments)); + } + + for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { + + if (!verifyMatcher(this.expectedArguments[i], args[i])) { + sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + + ", didn't match " + this.expectedArguments.toString()); + } + + if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { + sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + + ", expected " + sinon.format(this.expectedArguments)); + } + } + }, + + allowsCall: function allowsCall(thisValue, args) { + if (this.met() && receivedMaxCalls(this)) { + return false; + } + + if ("expectedThis" in this && this.expectedThis !== thisValue) { + return false; + } + + if (!("expectedArguments" in this)) { + return true; + } + + args = args || []; + + if (args.length < this.expectedArguments.length) { + return false; + } + + if (this.expectsExactArgCount && + args.length != this.expectedArguments.length) { + return false; + } + + for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { + if (!verifyMatcher(this.expectedArguments[i], args[i])) { + return false; + } + + if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { + return false; + } + } + + return true; + }, + + withArgs: function withArgs() { + this.expectedArguments = slice.call(arguments); + return this; + }, + + withExactArgs: function withExactArgs() { + this.withArgs.apply(this, arguments); + this.expectsExactArgCount = true; + return this; + }, + + on: function on(thisValue) { + this.expectedThis = thisValue; + return this; + }, + + toString: function () { + var args = (this.expectedArguments || []).slice(); + + if (!this.expectsExactArgCount) { + push.call(args, "[...]"); + } + + var callStr = sinon.spyCall.toString.call({ + proxy: this.method || "anonymous mock expectation", + args: args + }); + + var message = callStr.replace(", [...", "[, ...") + " " + + expectedCallCountInWords(this); + + if (this.met()) { + return "Expectation met: " + message; + } + + return "Expected " + message + " (" + + callCountInWords(this.callCount) + ")"; + }, + + verify: function verify() { + if (!this.met()) { + sinon.expectation.fail(this.toString()); + } else { + sinon.expectation.pass(this.toString()); + } + + return true; + }, + + pass: function pass(message) { + sinon.assert.pass(message); + }, + + fail: function fail(message) { + var exception = new Error(message); + exception.name = "ExpectationError"; + + throw exception; + } + }; + + sinon.mock = mock; + return mock; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./times_in_words"); + require("./call"); + require("./extend"); + require("./match"); + require("./spy"); + require("./stub"); + require("./format"); + + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./call":27,"./extend":29,"./format":30,"./match":32,"./spy":35,"./stub":36,"./times_in_words":39,"./util/core":41}],34:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend extend.js + * @depend collection.js + * @depend util/fake_timers.js + * @depend util/fake_server_with_clock.js + */ +/** + * Manages fake collections as well as fake utilities such as Sinon's + * timers and fake XHR implementation in one convenient object. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function () { + function makeApi(sinon) { + var push = [].push; + + function exposeValue(sandbox, config, key, value) { + if (!value) { + return; + } + + if (config.injectInto && !(key in config.injectInto)) { + config.injectInto[key] = value; + sandbox.injectedKeys.push(key); + } else { + push.call(sandbox.args, value); + } + } + + function prepareSandboxFromConfig(config) { + var sandbox = sinon.create(sinon.sandbox); + + if (config.useFakeServer) { + if (typeof config.useFakeServer == "object") { + sandbox.serverPrototype = config.useFakeServer; + } + + sandbox.useFakeServer(); + } + + if (config.useFakeTimers) { + if (typeof config.useFakeTimers == "object") { + sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); + } else { + sandbox.useFakeTimers(); + } + } + + return sandbox; + } + + sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { + useFakeTimers: function useFakeTimers() { + this.clock = sinon.useFakeTimers.apply(sinon, arguments); + + return this.add(this.clock); + }, + + serverPrototype: sinon.fakeServer, + + useFakeServer: function useFakeServer() { + var proto = this.serverPrototype || sinon.fakeServer; + + if (!proto || !proto.create) { + return null; + } + + this.server = proto.create(); + return this.add(this.server); + }, + + inject: function (obj) { + sinon.collection.inject.call(this, obj); + + if (this.clock) { + obj.clock = this.clock; + } + + if (this.server) { + obj.server = this.server; + obj.requests = this.server.requests; + } + + obj.match = sinon.match; + + return obj; + }, + + restore: function () { + sinon.collection.restore.apply(this, arguments); + this.restoreContext(); + }, + + restoreContext: function () { + if (this.injectedKeys) { + for (var i = 0, j = this.injectedKeys.length; i < j; i++) { + delete this.injectInto[this.injectedKeys[i]]; + } + this.injectedKeys = []; + } + }, + + create: function (config) { + if (!config) { + return sinon.create(sinon.sandbox); + } + + var sandbox = prepareSandboxFromConfig(config); + sandbox.args = sandbox.args || []; + sandbox.injectedKeys = []; + sandbox.injectInto = config.injectInto; + var prop, value, exposed = sandbox.inject({}); + + if (config.properties) { + for (var i = 0, l = config.properties.length; i < l; i++) { + prop = config.properties[i]; + value = exposed[prop] || prop == "sandbox" && sandbox; + exposeValue(sandbox, config, prop, value); + } + } else { + exposeValue(sandbox, config, "sandbox", value); + } + + return sandbox; + }, + + match: sinon.match + }); + + sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; + + return sinon.sandbox; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./extend"); + require("./util/fake_server_with_clock"); + require("./util/fake_timers"); + require("./collection"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}()); + +},{"./collection":28,"./extend":29,"./util/core":41,"./util/fake_server_with_clock":44,"./util/fake_timers":45}],35:[function(require,module,exports){ +/** + * @depend times_in_words.js + * @depend util/core.js + * @depend extend.js + * @depend call.js + * @depend format.js + */ +/** + * Spy functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + + function makeApi(sinon) { + var push = Array.prototype.push; + var slice = Array.prototype.slice; + var callId = 0; + + function spy(object, property, types) { + if (!property && typeof object == "function") { + return spy.create(object); + } + + if (!object && !property) { + return spy.create(function () { }); + } + + if (types) { + var methodDesc = sinon.getPropertyDescriptor(object, property); + for (var i = 0; i < types.length; i++) { + methodDesc[types[i]] = spy.create(methodDesc[types[i]]); + } + return sinon.wrapMethod(object, property, methodDesc); + } else { + var method = object[property]; + return sinon.wrapMethod(object, property, spy.create(method)); + } + } + + function matchingFake(fakes, args, strict) { + if (!fakes) { + return; + } + + for (var i = 0, l = fakes.length; i < l; i++) { + if (fakes[i].matches(args, strict)) { + return fakes[i]; + } + } + } + + function incrementCallCount() { + this.called = true; + this.callCount += 1; + this.notCalled = false; + this.calledOnce = this.callCount == 1; + this.calledTwice = this.callCount == 2; + this.calledThrice = this.callCount == 3; + } + + function createCallProperties() { + this.firstCall = this.getCall(0); + this.secondCall = this.getCall(1); + this.thirdCall = this.getCall(2); + this.lastCall = this.getCall(this.callCount - 1); + } + + var vars = "a,b,c,d,e,f,g,h,i,j,k,l"; + function createProxy(func, proxyLength) { + // Retain the function length: + var p; + if (proxyLength) { + eval("p = (function proxy(" + vars.substring(0, proxyLength * 2 - 1) + + ") { return p.invoke(func, this, slice.call(arguments)); });"); + } else { + p = function proxy() { + return p.invoke(func, this, slice.call(arguments)); + }; + } + return p; + } + + var uuid = 0; + + // Public API + var spyApi = { + reset: function () { + if (this.invoking) { + var err = new Error("Cannot reset Sinon function while invoking it. " + + "Move the call to .reset outside of the callback."); + err.name = "InvalidResetException"; + throw err; + } + + this.called = false; + this.notCalled = true; + this.calledOnce = false; + this.calledTwice = false; + this.calledThrice = false; + this.callCount = 0; + this.firstCall = null; + this.secondCall = null; + this.thirdCall = null; + this.lastCall = null; + this.args = []; + this.returnValues = []; + this.thisValues = []; + this.exceptions = []; + this.callIds = []; + if (this.fakes) { + for (var i = 0; i < this.fakes.length; i++) { + this.fakes[i].reset(); + } + } + + return this; + }, + + create: function create(func, spyLength) { + var name; + + if (typeof func != "function") { + func = function () { }; + } else { + name = sinon.functionName(func); + } + + if (!spyLength) { + spyLength = func.length; + } + + var proxy = createProxy(func, spyLength); + + sinon.extend(proxy, spy); + delete proxy.create; + sinon.extend(proxy, func); + + proxy.reset(); + proxy.prototype = func.prototype; + proxy.displayName = name || "spy"; + proxy.toString = sinon.functionToString; + proxy.instantiateFake = sinon.spy.create; + proxy.id = "spy#" + uuid++; + + return proxy; + }, + + invoke: function invoke(func, thisValue, args) { + var matching = matchingFake(this.fakes, args); + var exception, returnValue; + + incrementCallCount.call(this); + push.call(this.thisValues, thisValue); + push.call(this.args, args); + push.call(this.callIds, callId++); + + // Make call properties available from within the spied function: + createCallProperties.call(this); + + try { + this.invoking = true; + + if (matching) { + returnValue = matching.invoke(func, thisValue, args); + } else { + returnValue = (this.func || func).apply(thisValue, args); + } + + var thisCall = this.getCall(this.callCount - 1); + if (thisCall.calledWithNew() && typeof returnValue !== "object") { + returnValue = thisValue; + } + } catch (e) { + exception = e; + } finally { + delete this.invoking; + } + + push.call(this.exceptions, exception); + push.call(this.returnValues, returnValue); + + // Make return value and exception available in the calls: + createCallProperties.call(this); + + if (exception !== undefined) { + throw exception; + } + + return returnValue; + }, + + named: function named(name) { + this.displayName = name; + return this; + }, + + getCall: function getCall(i) { + if (i < 0 || i >= this.callCount) { + return null; + } + + return sinon.spyCall(this, this.thisValues[i], this.args[i], + this.returnValues[i], this.exceptions[i], + this.callIds[i]); + }, + + getCalls: function () { + var calls = []; + var i; + + for (i = 0; i < this.callCount; i++) { + calls.push(this.getCall(i)); + } + + return calls; + }, + + calledBefore: function calledBefore(spyFn) { + if (!this.called) { + return false; + } + + if (!spyFn.called) { + return true; + } + + return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; + }, + + calledAfter: function calledAfter(spyFn) { + if (!this.called || !spyFn.called) { + return false; + } + + return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; + }, + + withArgs: function () { + var args = slice.call(arguments); + + if (this.fakes) { + var match = matchingFake(this.fakes, args, true); + + if (match) { + return match; + } + } else { + this.fakes = []; + } + + var original = this; + var fake = this.instantiateFake(); + fake.matchingAguments = args; + fake.parent = this; + push.call(this.fakes, fake); + + fake.withArgs = function () { + return original.withArgs.apply(original, arguments); + }; + + for (var i = 0; i < this.args.length; i++) { + if (fake.matches(this.args[i])) { + incrementCallCount.call(fake); + push.call(fake.thisValues, this.thisValues[i]); + push.call(fake.args, this.args[i]); + push.call(fake.returnValues, this.returnValues[i]); + push.call(fake.exceptions, this.exceptions[i]); + push.call(fake.callIds, this.callIds[i]); + } + } + createCallProperties.call(fake); + + return fake; + }, + + matches: function (args, strict) { + var margs = this.matchingAguments; + + if (margs.length <= args.length && + sinon.deepEqual(margs, args.slice(0, margs.length))) { + return !strict || margs.length == args.length; + } + }, + + printf: function (format) { + var spy = this; + var args = slice.call(arguments, 1); + var formatter; + + return (format || "").replace(/%(.)/g, function (match, specifyer) { + formatter = spyApi.formatters[specifyer]; + + if (typeof formatter == "function") { + return formatter.call(null, spy, args); + } else if (!isNaN(parseInt(specifyer, 10))) { + return sinon.format(args[specifyer - 1]); + } + + return "%" + specifyer; + }); + } + }; + + function delegateToCalls(method, matchAny, actual, notCalled) { + spyApi[method] = function () { + if (!this.called) { + if (notCalled) { + return notCalled.apply(this, arguments); + } + return false; + } + + var currentCall; + var matches = 0; + + for (var i = 0, l = this.callCount; i < l; i += 1) { + currentCall = this.getCall(i); + + if (currentCall[actual || method].apply(currentCall, arguments)) { + matches += 1; + + if (matchAny) { + return true; + } + } + } + + return matches === this.callCount; + }; + } + + delegateToCalls("calledOn", true); + delegateToCalls("alwaysCalledOn", false, "calledOn"); + delegateToCalls("calledWith", true); + delegateToCalls("calledWithMatch", true); + delegateToCalls("alwaysCalledWith", false, "calledWith"); + delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch"); + delegateToCalls("calledWithExactly", true); + delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly"); + delegateToCalls("neverCalledWith", false, "notCalledWith", + function () { return true; }); + delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", + function () { return true; }); + delegateToCalls("threw", true); + delegateToCalls("alwaysThrew", false, "threw"); + delegateToCalls("returned", true); + delegateToCalls("alwaysReturned", false, "returned"); + delegateToCalls("calledWithNew", true); + delegateToCalls("alwaysCalledWithNew", false, "calledWithNew"); + delegateToCalls("callArg", false, "callArgWith", function () { + throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); + }); + spyApi.callArgWith = spyApi.callArg; + delegateToCalls("callArgOn", false, "callArgOnWith", function () { + throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); + }); + spyApi.callArgOnWith = spyApi.callArgOn; + delegateToCalls("yield", false, "yield", function () { + throw new Error(this.toString() + " cannot yield since it was not yet invoked."); + }); + // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. + spyApi.invokeCallback = spyApi.yield; + delegateToCalls("yieldOn", false, "yieldOn", function () { + throw new Error(this.toString() + " cannot yield since it was not yet invoked."); + }); + delegateToCalls("yieldTo", false, "yieldTo", function (property) { + throw new Error(this.toString() + " cannot yield to '" + property + + "' since it was not yet invoked."); + }); + delegateToCalls("yieldToOn", false, "yieldToOn", function (property) { + throw new Error(this.toString() + " cannot yield to '" + property + + "' since it was not yet invoked."); + }); + + spyApi.formatters = { + c: function (spy) { + return sinon.timesInWords(spy.callCount); + }, + + n: function (spy) { + return spy.toString(); + }, + + C: function (spy) { + var calls = []; + + for (var i = 0, l = spy.callCount; i < l; ++i) { + var stringifiedCall = " " + spy.getCall(i).toString(); + if (/\n/.test(calls[i - 1])) { + stringifiedCall = "\n" + stringifiedCall; + } + push.call(calls, stringifiedCall); + } + + return calls.length > 0 ? "\n" + calls.join("\n") : ""; + }, + + t: function (spy) { + var objects = []; + + for (var i = 0, l = spy.callCount; i < l; ++i) { + push.call(objects, sinon.format(spy.thisValues[i])); + } + + return objects.join(", "); + }, + + "*": function (spy, args) { + var formatted = []; + + for (var i = 0, l = args.length; i < l; ++i) { + push.call(formatted, sinon.format(args[i])); + } + + return formatted.join(", "); + } + }; + + sinon.extend(spy, spyApi); + + spy.spyCall = sinon.spyCall; + sinon.spy = spy; + + return spy; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./call"); + require("./extend"); + require("./times_in_words"); + require("./format"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./call":27,"./extend":29,"./format":30,"./times_in_words":39,"./util/core":41}],36:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend extend.js + * @depend spy.js + * @depend behavior.js + */ +/** + * Stub functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + function stub(object, property, func) { + if (!!func && typeof func != "function" && typeof func != "object") { + throw new TypeError("Custom stub should be a function or a property descriptor"); + } + + var wrapper; + + if (func) { + if (typeof func == "function") { + wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; + } else { + wrapper = func; + if (sinon.spy && sinon.spy.create) { + var types = sinon.objectKeys(wrapper); + for (var i = 0; i < types.length; i++) { + wrapper[types[i]] = sinon.spy.create(wrapper[types[i]]); + } + } + } + } else { + var stubLength = 0; + if (typeof object == "object" && typeof object[property] == "function") { + stubLength = object[property].length; + } + wrapper = stub.create(stubLength); + } + + if (!object && typeof property === "undefined") { + return sinon.stub.create(); + } + + if (typeof property === "undefined" && typeof object == "object") { + for (var prop in object) { + if (typeof object[prop] === "function") { + stub(object, prop); + } + } + + return object; + } + + return sinon.wrapMethod(object, property, wrapper); + } + + function getDefaultBehavior(stub) { + return stub.defaultBehavior || getParentBehaviour(stub) || sinon.behavior.create(stub); + } + + function getParentBehaviour(stub) { + return (stub.parent && getCurrentBehavior(stub.parent)); + } + + function getCurrentBehavior(stub) { + var behavior = stub.behaviors[stub.callCount - 1]; + return behavior && behavior.isPresent() ? behavior : getDefaultBehavior(stub); + } + + var uuid = 0; + + var proto = { + create: function create(stubLength) { + var functionStub = function () { + return getCurrentBehavior(functionStub).invoke(this, arguments); + }; + + functionStub.id = "stub#" + uuid++; + var orig = functionStub; + functionStub = sinon.spy.create(functionStub, stubLength); + functionStub.func = orig; + + sinon.extend(functionStub, stub); + functionStub.instantiateFake = sinon.stub.create; + functionStub.displayName = "stub"; + functionStub.toString = sinon.functionToString; + + functionStub.defaultBehavior = null; + functionStub.behaviors = []; + + return functionStub; + }, + + resetBehavior: function () { + var i; + + this.defaultBehavior = null; + this.behaviors = []; + + delete this.returnValue; + delete this.returnArgAt; + this.returnThis = false; + + if (this.fakes) { + for (i = 0; i < this.fakes.length; i++) { + this.fakes[i].resetBehavior(); + } + } + }, + + onCall: function onCall(index) { + if (!this.behaviors[index]) { + this.behaviors[index] = sinon.behavior.create(this); + } + + return this.behaviors[index]; + }, + + onFirstCall: function onFirstCall() { + return this.onCall(0); + }, + + onSecondCall: function onSecondCall() { + return this.onCall(1); + }, + + onThirdCall: function onThirdCall() { + return this.onCall(2); + } + }; + + for (var method in sinon.behavior) { + if (sinon.behavior.hasOwnProperty(method) && + !proto.hasOwnProperty(method) && + method != "create" && + method != "withArgs" && + method != "invoke") { + proto[method] = (function (behaviorMethod) { + return function () { + this.defaultBehavior = this.defaultBehavior || sinon.behavior.create(this); + this.defaultBehavior[behaviorMethod].apply(this.defaultBehavior, arguments); + return this; + }; + }(method)); + } + } + + sinon.extend(stub, proto); + sinon.stub = stub; + + return stub; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./behavior"); + require("./spy"); + require("./extend"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./behavior":26,"./extend":29,"./spy":35,"./util/core":41}],37:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend sandbox.js + */ +/** + * Test function, sandboxes fakes + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + var slice = Array.prototype.slice; + + function test(callback) { + var type = typeof callback; + + if (type != "function") { + throw new TypeError("sinon.test needs to wrap a test function, got " + type); + } + + function sinonSandboxedTest() { + var config = sinon.getConfig(sinon.config); + config.injectInto = config.injectIntoThis && this || config.injectInto; + var sandbox = sinon.sandbox.create(config); + var args = slice.call(arguments); + var oldDone = args.length && args[args.length - 1]; + var exception, result; + + if (typeof oldDone == "function") { + args[args.length - 1] = function sinonDone(result) { + if (result) { + sandbox.restore(); + throw exception; + } else { + sandbox.verifyAndRestore(); + } + oldDone(result); + }; + } + + try { + result = callback.apply(this, args.concat(sandbox.args)); + } catch (e) { + exception = e; + } + + if (typeof oldDone != "function") { + if (typeof exception !== "undefined") { + sandbox.restore(); + throw exception; + } else { + sandbox.verifyAndRestore(); + } + } + + return result; + } + + if (callback.length) { + return function sinonAsyncSandboxedTest(callback) { + return sinonSandboxedTest.apply(this, arguments); + }; + } + + return sinonSandboxedTest; + } + + test.config = { + injectIntoThis: true, + injectInto: null, + properties: ["spy", "stub", "mock", "clock", "server", "requests"], + useFakeTimers: true, + useFakeServer: true + }; + + sinon.test = test; + return test; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./sandbox"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (sinon) { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./sandbox":34,"./util/core":41}],38:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend test.js + */ +/** + * Test case, sandboxes all test functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + function createTest(property, setUp, tearDown) { + return function () { + if (setUp) { + setUp.apply(this, arguments); + } + + var exception, result; + + try { + result = property.apply(this, arguments); + } catch (e) { + exception = e; + } + + if (tearDown) { + tearDown.apply(this, arguments); + } + + if (exception) { + throw exception; + } + + return result; + }; + } + + function makeApi(sinon) { + function testCase(tests, prefix) { + /*jsl:ignore*/ + if (!tests || typeof tests != "object") { + throw new TypeError("sinon.testCase needs an object with test functions"); + } + /*jsl:end*/ + + prefix = prefix || "test"; + var rPrefix = new RegExp("^" + prefix); + var methods = {}, testName, property, method; + var setUp = tests.setUp; + var tearDown = tests.tearDown; + + for (testName in tests) { + if (tests.hasOwnProperty(testName)) { + property = tests[testName]; + + if (/^(setUp|tearDown)$/.test(testName)) { + continue; + } + + if (typeof property == "function" && rPrefix.test(testName)) { + method = property; + + if (setUp || tearDown) { + method = createTest(property, setUp, tearDown); + } + + methods[testName] = sinon.test(method); + } else { + methods[testName] = tests[testName]; + } + } + } + + return methods; + } + + sinon.testCase = testCase; + return testCase; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./test"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./test":37,"./util/core":41}],39:[function(require,module,exports){ +/** + * @depend util/core.js + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + + function timesInWords(count) { + switch (count) { + case 1: + return "once"; + case 2: + return "twice"; + case 3: + return "thrice"; + default: + return (count || 0) + " times"; + } + } + + sinon.timesInWords = timesInWords; + return sinon.timesInWords; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./util/core":41}],40:[function(require,module,exports){ +/** + * @depend util/core.js + */ +/** + * Format functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2014 Christian Johansen + */ +"use strict"; + +(function (sinon, formatio) { + function makeApi(sinon) { + function typeOf(value) { + if (value === null) { + return "null"; + } else if (value === undefined) { + return "undefined"; + } + var string = Object.prototype.toString.call(value); + return string.substring(8, string.length - 1).toLowerCase(); + }; + + sinon.typeOf = typeOf; + return sinon.typeOf; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}( + (typeof sinon == "object" && sinon || null), + (typeof formatio == "object" && formatio) +)); + +},{"./util/core":41}],41:[function(require,module,exports){ +/** + * @depend ../../sinon.js + */ +/** + * Sinon core utilities. For internal use only. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + var div = typeof document != "undefined" && document.createElement("div"); + var hasOwn = Object.prototype.hasOwnProperty; + + function isDOMNode(obj) { + var success = false; + + try { + obj.appendChild(div); + success = div.parentNode == obj; + } catch (e) { + return false; + } finally { + try { + obj.removeChild(div); + } catch (e) { + // Remove failed, not much we can do about that + } + } + + return success; + } + + function isElement(obj) { + return div && obj && obj.nodeType === 1 && isDOMNode(obj); + } + + function isFunction(obj) { + return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply); + } + + function isReallyNaN(val) { + return typeof val === "number" && isNaN(val); + } + + function mirrorProperties(target, source) { + for (var prop in source) { + if (!hasOwn.call(target, prop)) { + target[prop] = source[prop]; + } + } + } + + function isRestorable(obj) { + return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon; + } + + // Cheap way to detect if we have ES5 support. + var hasES5Support = "keys" in Object; + + function makeApi(sinon) { + sinon.wrapMethod = function wrapMethod(object, property, method) { + if (!object) { + throw new TypeError("Should wrap property of object"); + } + + if (typeof method != "function" && typeof method != "object") { + throw new TypeError("Method wrapper should be a function or a property descriptor"); + } + + function checkWrappedMethod(wrappedMethod) { + if (!isFunction(wrappedMethod)) { + error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + + property + " as function"); + } else if (wrappedMethod.restore && wrappedMethod.restore.sinon) { + error = new TypeError("Attempted to wrap " + property + " which is already wrapped"); + } else if (wrappedMethod.calledBefore) { + var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; + error = new TypeError("Attempted to wrap " + property + " which is already " + verb); + } + + if (error) { + if (wrappedMethod && wrappedMethod.stackTrace) { + error.stack += "\n--------------\n" + wrappedMethod.stackTrace; + } + throw error; + } + } + + var error, wrappedMethod; + + // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem + // when using hasOwn.call on objects from other frames. + var owned = object.hasOwnProperty ? object.hasOwnProperty(property) : hasOwn.call(object, property); + + if (hasES5Support) { + var methodDesc = (typeof method == "function") ? {value: method} : method, + wrappedMethodDesc = sinon.getPropertyDescriptor(object, property), + i; + + if (!wrappedMethodDesc) { + error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + + property + " as function"); + } else if (wrappedMethodDesc.restore && wrappedMethodDesc.restore.sinon) { + error = new TypeError("Attempted to wrap " + property + " which is already wrapped"); + } + if (error) { + if (wrappedMethodDesc && wrappedMethodDesc.stackTrace) { + error.stack += "\n--------------\n" + wrappedMethodDesc.stackTrace; + } + throw error; + } + + var types = sinon.objectKeys(methodDesc); + for (i = 0; i < types.length; i++) { + wrappedMethod = wrappedMethodDesc[types[i]]; + checkWrappedMethod(wrappedMethod); + } + + mirrorProperties(methodDesc, wrappedMethodDesc); + for (i = 0; i < types.length; i++) { + mirrorProperties(methodDesc[types[i]], wrappedMethodDesc[types[i]]); + } + Object.defineProperty(object, property, methodDesc); + } else { + wrappedMethod = object[property]; + checkWrappedMethod(wrappedMethod); + object[property] = method; + method.displayName = property; + } + + method.displayName = property; + + // Set up a stack trace which can be used later to find what line of + // code the original method was created on. + method.stackTrace = (new Error("Stack Trace for original")).stack; + + method.restore = function () { + // For prototype properties try to reset by delete first. + // If this fails (ex: localStorage on mobile safari) then force a reset + // via direct assignment. + if (!owned) { + try { + delete object[property]; + } catch (e) {} + // For native code functions `delete` fails without throwing an error + // on Chrome < 43, PhantomJS, etc. + // Use strict equality comparison to check failures then force a reset + // via direct assignment. + if (object[property] === method) { + object[property] = wrappedMethod; + } + } else if (hasES5Support) { + Object.defineProperty(object, property, wrappedMethodDesc); + } + + if (!hasES5Support && object[property] === method) { + object[property] = wrappedMethod; + } + }; + + method.restore.sinon = true; + + if (!hasES5Support) { + mirrorProperties(method, wrappedMethod); + } + + return method; + }; + + sinon.create = function create(proto) { + var F = function () {}; + F.prototype = proto; + return new F(); + }; + + sinon.deepEqual = function deepEqual(a, b) { + if (sinon.match && sinon.match.isMatcher(a)) { + return a.test(b); + } + + if (typeof a != "object" || typeof b != "object") { + if (isReallyNaN(a) && isReallyNaN(b)) { + return true; + } else { + return a === b; + } + } + + if (isElement(a) || isElement(b)) { + return a === b; + } + + if (a === b) { + return true; + } + + if ((a === null && b !== null) || (a !== null && b === null)) { + return false; + } + + if (a instanceof RegExp && b instanceof RegExp) { + return (a.source === b.source) && (a.global === b.global) && + (a.ignoreCase === b.ignoreCase) && (a.multiline === b.multiline); + } + + var aString = Object.prototype.toString.call(a); + if (aString != Object.prototype.toString.call(b)) { + return false; + } + + if (aString == "[object Date]") { + return a.valueOf() === b.valueOf(); + } + + var prop, aLength = 0, bLength = 0; + + if (aString == "[object Array]" && a.length !== b.length) { + return false; + } + + for (prop in a) { + aLength += 1; + + if (!(prop in b)) { + return false; + } + + if (!deepEqual(a[prop], b[prop])) { + return false; + } + } + + for (prop in b) { + bLength += 1; + } + + return aLength == bLength; + }; + + sinon.functionName = function functionName(func) { + var name = func.displayName || func.name; + + // Use function decomposition as a last resort to get function + // name. Does not rely on function decomposition to work - if it + // doesn't debugging will be slightly less informative + // (i.e. toString will say 'spy' rather than 'myFunc'). + if (!name) { + var matches = func.toString().match(/function ([^\s\(]+)/); + name = matches && matches[1]; + } + + return name; + }; + + sinon.functionToString = function toString() { + if (this.getCall && this.callCount) { + var thisValue, prop, i = this.callCount; + + while (i--) { + thisValue = this.getCall(i).thisValue; + + for (prop in thisValue) { + if (thisValue[prop] === this) { + return prop; + } + } + } + } + + return this.displayName || "sinon fake"; + }; + + sinon.objectKeys = function objectKeys(obj) { + if (obj !== Object(obj)) { + throw new TypeError("sinon.objectKeys called on a non-object"); + } + + var keys = []; + var key; + for (key in obj) { + if (hasOwn.call(obj, key)) { + keys.push(key); + } + } + + return keys; + }; + + sinon.getPropertyDescriptor = function getPropertyDescriptor(object, property) { + var proto = object, descriptor; + while (proto && !(descriptor = Object.getOwnPropertyDescriptor(proto, property))) { + proto = Object.getPrototypeOf(proto); + } + return descriptor; + } + + sinon.getConfig = function (custom) { + var config = {}; + custom = custom || {}; + var defaults = sinon.defaultConfig; + + for (var prop in defaults) { + if (defaults.hasOwnProperty(prop)) { + config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; + } + } + + return config; + }; + + sinon.defaultConfig = { + injectIntoThis: true, + injectInto: null, + properties: ["spy", "stub", "mock", "clock", "server", "requests"], + useFakeTimers: true, + useFakeServer: true + }; + + sinon.timesInWords = function timesInWords(count) { + return count == 1 && "once" || + count == 2 && "twice" || + count == 3 && "thrice" || + (count || 0) + " times"; + }; + + sinon.calledInOrder = function (spies) { + for (var i = 1, l = spies.length; i < l; i++) { + if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) { + return false; + } + } + + return true; + }; + + sinon.orderByFirstCall = function (spies) { + return spies.sort(function (a, b) { + // uuid, won't ever be equal + var aCall = a.getCall(0); + var bCall = b.getCall(0); + var aId = aCall && aCall.callId || -1; + var bId = bCall && bCall.callId || -1; + + return aId < bId ? -1 : 1; + }); + }; + + sinon.createStubInstance = function (constructor) { + if (typeof constructor !== "function") { + throw new TypeError("The constructor should be a function."); + } + return sinon.stub(sinon.create(constructor.prototype)); + }; + + sinon.restore = function (object) { + if (object !== null && typeof object === "object") { + for (var prop in object) { + if (isRestorable(object[prop])) { + object[prop].restore(); + } + } + } else if (isRestorable(object)) { + object.restore(); + } + }; + + return sinon; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports) { + makeApi(exports); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{}],42:[function(require,module,exports){ +/** + * Minimal Event interface implementation + * + * Original implementation by Sven Fuchs: https://gist.github.com/995028 + * Modifications and tests by Christian Johansen. + * + * @author Sven Fuchs (svenfuchs@artweb-design.de) + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2011 Sven Fuchs, Christian Johansen + */ +"use strict"; + +if (typeof sinon == "undefined") { + this.sinon = {}; +} + +(function () { + var push = [].push; + + function makeApi(sinon) { + sinon.Event = function Event(type, bubbles, cancelable, target) { + this.initEvent(type, bubbles, cancelable, target); + }; + + sinon.Event.prototype = { + initEvent: function (type, bubbles, cancelable, target) { + this.type = type; + this.bubbles = bubbles; + this.cancelable = cancelable; + this.target = target; + }, + + stopPropagation: function () {}, + + preventDefault: function () { + this.defaultPrevented = true; + } + }; + + sinon.ProgressEvent = function ProgressEvent(type, progressEventRaw, target) { + this.initEvent(type, false, false, target); + this.loaded = progressEventRaw.loaded || null; + this.total = progressEventRaw.total || null; + this.lengthComputable = !!progressEventRaw.total; + }; + + sinon.ProgressEvent.prototype = new sinon.Event(); + + sinon.ProgressEvent.prototype.constructor = sinon.ProgressEvent; + + sinon.CustomEvent = function CustomEvent(type, customData, target) { + this.initEvent(type, false, false, target); + this.detail = customData.detail || null; + }; + + sinon.CustomEvent.prototype = new sinon.Event(); + + sinon.CustomEvent.prototype.constructor = sinon.CustomEvent; + + sinon.EventTarget = { + addEventListener: function addEventListener(event, listener) { + this.eventListeners = this.eventListeners || {}; + this.eventListeners[event] = this.eventListeners[event] || []; + push.call(this.eventListeners[event], listener); + }, + + removeEventListener: function removeEventListener(event, listener) { + var listeners = this.eventListeners && this.eventListeners[event] || []; + + for (var i = 0, l = listeners.length; i < l; ++i) { + if (listeners[i] == listener) { + return listeners.splice(i, 1); + } + } + }, + + dispatchEvent: function dispatchEvent(event) { + var type = event.type; + var listeners = this.eventListeners && this.eventListeners[type] || []; + + for (var i = 0; i < listeners.length; i++) { + if (typeof listeners[i] == "function") { + listeners[i].call(this, event); + } else { + listeners[i].handleEvent(event); + } + } + + return !!event.defaultPrevented; + } + }; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require) { + var sinon = require("./core"); + makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require); + } else { + makeApi(sinon); + } +}()); + +},{"./core":41}],43:[function(require,module,exports){ +/** + * @depend fake_xdomain_request.js + * @depend fake_xml_http_request.js + * @depend ../format.js + * @depend ../log_error.js + */ +/** + * The Sinon "server" mimics a web server that receives requests from + * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, + * both synchronously and asynchronously. To respond synchronuously, canned + * answers have to be provided upfront. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +if (typeof sinon == "undefined") { + var sinon = {}; +} + +(function () { + var push = [].push; + function F() {} + + function create(proto) { + F.prototype = proto; + return new F(); + } + + function responseArray(handler) { + var response = handler; + + if (Object.prototype.toString.call(handler) != "[object Array]") { + response = [200, {}, handler]; + } + + if (typeof response[2] != "string") { + throw new TypeError("Fake server response body should be string, but was " + + typeof response[2]); + } + + return response; + } + + var wloc = typeof window !== "undefined" ? window.location : {}; + var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); + + function matchOne(response, reqMethod, reqUrl) { + var rmeth = response.method; + var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); + var url = response.url; + var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); + + return matchMethod && matchUrl; + } + + function match(response, request) { + var requestUrl = request.url; + + if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { + requestUrl = requestUrl.replace(rCurrLoc, ""); + } + + if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { + if (typeof response.response == "function") { + var ru = response.url; + var args = [request].concat(ru && typeof ru.exec == "function" ? ru.exec(requestUrl).slice(1) : []); + return response.response.apply(response, args); + } + + return true; + } + + return false; + } + + function makeApi(sinon) { + sinon.fakeServer = { + create: function () { + var server = create(this); + if (!sinon.xhr.supportsCORS) { + this.xhr = sinon.useFakeXDomainRequest(); + } else { + this.xhr = sinon.useFakeXMLHttpRequest(); + } + server.requests = []; + + this.xhr.onCreate = function (xhrObj) { + server.addRequest(xhrObj); + }; + + return server; + }, + + addRequest: function addRequest(xhrObj) { + var server = this; + push.call(this.requests, xhrObj); + + xhrObj.onSend = function () { + server.handleRequest(this); + + if (server.respondImmediately) { + server.respond(); + } else if (server.autoRespond && !server.responding) { + setTimeout(function () { + server.responding = false; + server.respond(); + }, server.autoRespondAfter || 10); + + server.responding = true; + } + }; + }, + + getHTTPMethod: function getHTTPMethod(request) { + if (this.fakeHTTPMethods && /post/i.test(request.method)) { + var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); + return !!matches ? matches[1] : request.method; + } + + return request.method; + }, + + handleRequest: function handleRequest(xhr) { + if (xhr.async) { + if (!this.queue) { + this.queue = []; + } + + push.call(this.queue, xhr); + } else { + this.processRequest(xhr); + } + }, + + log: function log(response, request) { + var str; + + str = "Request:\n" + sinon.format(request) + "\n\n"; + str += "Response:\n" + sinon.format(response) + "\n\n"; + + sinon.log(str); + }, + + respondWith: function respondWith(method, url, body) { + if (arguments.length == 1 && typeof method != "function") { + this.response = responseArray(method); + return; + } + + if (!this.responses) { this.responses = []; } + + if (arguments.length == 1) { + body = method; + url = method = null; + } + + if (arguments.length == 2) { + body = url; + url = method; + method = null; + } + + push.call(this.responses, { + method: method, + url: url, + response: typeof body == "function" ? body : responseArray(body) + }); + }, + + respond: function respond() { + if (arguments.length > 0) { + this.respondWith.apply(this, arguments); + } + + var queue = this.queue || []; + var requests = queue.splice(0, queue.length); + var request; + + while (request = requests.shift()) { + this.processRequest(request); + } + }, + + processRequest: function processRequest(request) { + try { + if (request.aborted) { + return; + } + + var response = this.response || [404, {}, ""]; + + if (this.responses) { + for (var l = this.responses.length, i = l - 1; i >= 0; i--) { + if (match.call(this, this.responses[i], request)) { + response = this.responses[i].response; + break; + } + } + } + + if (request.readyState != 4) { + this.log(response, request); + + request.respond(response[0], response[1], response[2]); + } + } catch (e) { + sinon.logError("Fake server request processing", e); + } + }, + + restore: function restore() { + return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); + } + }; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./core"); + require("./fake_xdomain_request"); + require("./fake_xml_http_request"); + require("../format"); + makeApi(sinon); + module.exports = sinon; + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else { + makeApi(sinon); + } +}()); + +},{"../format":30,"./core":41,"./fake_xdomain_request":46,"./fake_xml_http_request":47}],44:[function(require,module,exports){ +/** + * @depend fake_server.js + * @depend fake_timers.js + */ +/** + * Add-on for sinon.fakeServer that automatically handles a fake timer along with + * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery + * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, + * it polls the object for completion with setInterval. Dispite the direct + * motivation, there is nothing jQuery-specific in this file, so it can be used + * in any environment where the ajax implementation depends on setInterval or + * setTimeout. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function () { + function makeApi(sinon) { + function Server() {} + Server.prototype = sinon.fakeServer; + + sinon.fakeServerWithClock = new Server(); + + sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { + if (xhr.async) { + if (typeof setTimeout.clock == "object") { + this.clock = setTimeout.clock; + } else { + this.clock = sinon.useFakeTimers(); + this.resetClock = true; + } + + if (!this.longestTimeout) { + var clockSetTimeout = this.clock.setTimeout; + var clockSetInterval = this.clock.setInterval; + var server = this; + + this.clock.setTimeout = function (fn, timeout) { + server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); + + return clockSetTimeout.apply(this, arguments); + }; + + this.clock.setInterval = function (fn, timeout) { + server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); + + return clockSetInterval.apply(this, arguments); + }; + } + } + + return sinon.fakeServer.addRequest.call(this, xhr); + }; + + sinon.fakeServerWithClock.respond = function respond() { + var returnVal = sinon.fakeServer.respond.apply(this, arguments); + + if (this.clock) { + this.clock.tick(this.longestTimeout || 0); + this.longestTimeout = 0; + + if (this.resetClock) { + this.clock.restore(); + this.resetClock = false; + } + } + + return returnVal; + }; + + sinon.fakeServerWithClock.restore = function restore() { + if (this.clock) { + this.clock.restore(); + } + + return sinon.fakeServer.restore.apply(this, arguments); + }; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require) { + var sinon = require("./core"); + require("./fake_server"); + require("./fake_timers"); + makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require); + } else { + makeApi(sinon); + } +}()); + +},{"./core":41,"./fake_server":43,"./fake_timers":45}],45:[function(require,module,exports){ +(function (global){ +/*global lolex */ + +/** + * Fake timer API + * setTimeout + * setInterval + * clearTimeout + * clearInterval + * tick + * reset + * Date + * + * Inspired by jsUnitMockTimeOut from JsUnit + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +if (typeof sinon == "undefined") { + var sinon = {}; +} + +(function (global) { + function makeApi(sinon, lol) { + var llx = typeof lolex !== "undefined" ? lolex : lol; + + sinon.useFakeTimers = function () { + var now, methods = Array.prototype.slice.call(arguments); + + if (typeof methods[0] === "string") { + now = 0; + } else { + now = methods.shift(); + } + + var clock = llx.install(now || 0, methods); + clock.restore = clock.uninstall; + return clock; + }; + + sinon.clock = { + create: function (now) { + return llx.createClock(now); + } + }; + + sinon.timers = { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined), + clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate : undefined), + setInterval: setInterval, + clearInterval: clearInterval, + Date: Date + }; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, epxorts, module, lolex) { + var sinon = require("./core"); + makeApi(sinon, lolex); + module.exports = sinon; + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module, require("lolex")); + } else { + makeApi(sinon); + } +}(typeof global != "undefined" && typeof global !== "function" ? global : this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./core":41,"lolex":50}],46:[function(require,module,exports){ +/** + * @depend core.js + * @depend ../extend.js + * @depend event.js + * @depend ../log_error.js + */ +/** + * Fake XDomainRequest object + */ +"use strict"; + +if (typeof sinon == "undefined") { + this.sinon = {}; +} + +// wrapper for global +(function (global) { + var xdr = { XDomainRequest: global.XDomainRequest }; + xdr.GlobalXDomainRequest = global.XDomainRequest; + xdr.supportsXDR = typeof xdr.GlobalXDomainRequest != "undefined"; + xdr.workingXDR = xdr.supportsXDR ? xdr.GlobalXDomainRequest : false; + + function makeApi(sinon) { + sinon.xdr = xdr; + + function FakeXDomainRequest() { + this.readyState = FakeXDomainRequest.UNSENT; + this.requestBody = null; + this.requestHeaders = {}; + this.status = 0; + this.timeout = null; + + if (typeof FakeXDomainRequest.onCreate == "function") { + FakeXDomainRequest.onCreate(this); + } + } + + function verifyState(xdr) { + if (xdr.readyState !== FakeXDomainRequest.OPENED) { + throw new Error("INVALID_STATE_ERR"); + } + + if (xdr.sendFlag) { + throw new Error("INVALID_STATE_ERR"); + } + } + + function verifyRequestSent(xdr) { + if (xdr.readyState == FakeXDomainRequest.UNSENT) { + throw new Error("Request not sent"); + } + if (xdr.readyState == FakeXDomainRequest.DONE) { + throw new Error("Request done"); + } + } + + function verifyResponseBodyType(body) { + if (typeof body != "string") { + var error = new Error("Attempted to respond to fake XDomainRequest with " + + body + ", which is not a string."); + error.name = "InvalidBodyException"; + throw error; + } + } + + sinon.extend(FakeXDomainRequest.prototype, sinon.EventTarget, { + open: function open(method, url) { + this.method = method; + this.url = url; + + this.responseText = null; + this.sendFlag = false; + + this.readyStateChange(FakeXDomainRequest.OPENED); + }, + + readyStateChange: function readyStateChange(state) { + this.readyState = state; + var eventName = ""; + switch (this.readyState) { + case FakeXDomainRequest.UNSENT: + break; + case FakeXDomainRequest.OPENED: + break; + case FakeXDomainRequest.LOADING: + if (this.sendFlag) { + //raise the progress event + eventName = "onprogress"; + } + break; + case FakeXDomainRequest.DONE: + if (this.isTimeout) { + eventName = "ontimeout" + } else if (this.errorFlag || (this.status < 200 || this.status > 299)) { + eventName = "onerror"; + } else { + eventName = "onload" + } + break; + } + + // raising event (if defined) + if (eventName) { + if (typeof this[eventName] == "function") { + try { + this[eventName](); + } catch (e) { + sinon.logError("Fake XHR " + eventName + " handler", e); + } + } + } + }, + + send: function send(data) { + verifyState(this); + + if (!/^(get|head)$/i.test(this.method)) { + this.requestBody = data; + } + this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; + + this.errorFlag = false; + this.sendFlag = true; + this.readyStateChange(FakeXDomainRequest.OPENED); + + if (typeof this.onSend == "function") { + this.onSend(this); + } + }, + + abort: function abort() { + this.aborted = true; + this.responseText = null; + this.errorFlag = true; + + if (this.readyState > sinon.FakeXDomainRequest.UNSENT && this.sendFlag) { + this.readyStateChange(sinon.FakeXDomainRequest.DONE); + this.sendFlag = false; + } + }, + + setResponseBody: function setResponseBody(body) { + verifyRequestSent(this); + verifyResponseBodyType(body); + + var chunkSize = this.chunkSize || 10; + var index = 0; + this.responseText = ""; + + do { + this.readyStateChange(FakeXDomainRequest.LOADING); + this.responseText += body.substring(index, index + chunkSize); + index += chunkSize; + } while (index < body.length); + + this.readyStateChange(FakeXDomainRequest.DONE); + }, + + respond: function respond(status, contentType, body) { + // content-type ignored, since XDomainRequest does not carry this + // we keep the same syntax for respond(...) as for FakeXMLHttpRequest to ease + // test integration across browsers + this.status = typeof status == "number" ? status : 200; + this.setResponseBody(body || ""); + }, + + simulatetimeout: function simulatetimeout() { + this.status = 0; + this.isTimeout = true; + // Access to this should actually throw an error + this.responseText = undefined; + this.readyStateChange(FakeXDomainRequest.DONE); + } + }); + + sinon.extend(FakeXDomainRequest, { + UNSENT: 0, + OPENED: 1, + LOADING: 3, + DONE: 4 + }); + + sinon.useFakeXDomainRequest = function useFakeXDomainRequest() { + sinon.FakeXDomainRequest.restore = function restore(keepOnCreate) { + if (xdr.supportsXDR) { + global.XDomainRequest = xdr.GlobalXDomainRequest; + } + + delete sinon.FakeXDomainRequest.restore; + + if (keepOnCreate !== true) { + delete sinon.FakeXDomainRequest.onCreate; + } + }; + if (xdr.supportsXDR) { + global.XDomainRequest = sinon.FakeXDomainRequest; + } + return sinon.FakeXDomainRequest; + }; + + sinon.FakeXDomainRequest = FakeXDomainRequest; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./core"); + require("../extend"); + require("./event"); + require("../log_error"); + makeApi(sinon); + module.exports = sinon; + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else { + makeApi(sinon); + } +})(this); + +},{"../extend":29,"../log_error":31,"./core":41,"./event":42}],47:[function(require,module,exports){ +(function (global){ +/** + * @depend core.js + * @depend ../extend.js + * @depend event.js + * @depend ../log_error.js + */ +/** + * Fake XMLHttpRequest object + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (global) { + + var supportsProgress = typeof ProgressEvent !== "undefined"; + var supportsCustomEvent = typeof CustomEvent !== "undefined"; + var sinonXhr = { XMLHttpRequest: global.XMLHttpRequest }; + sinonXhr.GlobalXMLHttpRequest = global.XMLHttpRequest; + sinonXhr.GlobalActiveXObject = global.ActiveXObject; + sinonXhr.supportsActiveX = typeof sinonXhr.GlobalActiveXObject != "undefined"; + sinonXhr.supportsXHR = typeof sinonXhr.GlobalXMLHttpRequest != "undefined"; + sinonXhr.workingXHR = sinonXhr.supportsXHR ? sinonXhr.GlobalXMLHttpRequest : sinonXhr.supportsActiveX + ? function () { return new sinonXhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; + sinonXhr.supportsCORS = sinonXhr.supportsXHR && "withCredentials" in (new sinonXhr.GlobalXMLHttpRequest()); + + /*jsl:ignore*/ + var unsafeHeaders = { + "Accept-Charset": true, + "Accept-Encoding": true, + Connection: true, + "Content-Length": true, + Cookie: true, + Cookie2: true, + "Content-Transfer-Encoding": true, + Date: true, + Expect: true, + Host: true, + "Keep-Alive": true, + Referer: true, + TE: true, + Trailer: true, + "Transfer-Encoding": true, + Upgrade: true, + "User-Agent": true, + Via: true + }; + /*jsl:end*/ + + function FakeXMLHttpRequest() { + this.readyState = FakeXMLHttpRequest.UNSENT; + this.requestHeaders = {}; + this.requestBody = null; + this.status = 0; + this.statusText = ""; + this.upload = new UploadProgress(); + if (sinonXhr.supportsCORS) { + this.withCredentials = false; + } + + var xhr = this; + var events = ["loadstart", "load", "abort", "loadend"]; + + function addEventListener(eventName) { + xhr.addEventListener(eventName, function (event) { + var listener = xhr["on" + eventName]; + + if (listener && typeof listener == "function") { + listener.call(this, event); + } + }); + } + + for (var i = events.length - 1; i >= 0; i--) { + addEventListener(events[i]); + } + + if (typeof FakeXMLHttpRequest.onCreate == "function") { + FakeXMLHttpRequest.onCreate(this); + } + } + + // An upload object is created for each + // FakeXMLHttpRequest and allows upload + // events to be simulated using uploadProgress + // and uploadError. + function UploadProgress() { + this.eventListeners = { + progress: [], + load: [], + abort: [], + error: [] + } + } + + UploadProgress.prototype.addEventListener = function addEventListener(event, listener) { + this.eventListeners[event].push(listener); + }; + + UploadProgress.prototype.removeEventListener = function removeEventListener(event, listener) { + var listeners = this.eventListeners[event] || []; + + for (var i = 0, l = listeners.length; i < l; ++i) { + if (listeners[i] == listener) { + return listeners.splice(i, 1); + } + } + }; + + UploadProgress.prototype.dispatchEvent = function dispatchEvent(event) { + var listeners = this.eventListeners[event.type] || []; + + for (var i = 0, listener; (listener = listeners[i]) != null; i++) { + listener(event); + } + }; + + function verifyState(xhr) { + if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { + throw new Error("INVALID_STATE_ERR"); + } + + if (xhr.sendFlag) { + throw new Error("INVALID_STATE_ERR"); + } + } + + function getHeader(headers, header) { + header = header.toLowerCase(); + + for (var h in headers) { + if (h.toLowerCase() == header) { + return h; + } + } + + return null; + } + + // filtering to enable a white-list version of Sinon FakeXhr, + // where whitelisted requests are passed through to real XHR + function each(collection, callback) { + if (!collection) { + return; + } + + for (var i = 0, l = collection.length; i < l; i += 1) { + callback(collection[i]); + } + } + function some(collection, callback) { + for (var index = 0; index < collection.length; index++) { + if (callback(collection[index]) === true) { + return true; + } + } + return false; + } + // largest arity in XHR is 5 - XHR#open + var apply = function (obj, method, args) { + switch (args.length) { + case 0: return obj[method](); + case 1: return obj[method](args[0]); + case 2: return obj[method](args[0], args[1]); + case 3: return obj[method](args[0], args[1], args[2]); + case 4: return obj[method](args[0], args[1], args[2], args[3]); + case 5: return obj[method](args[0], args[1], args[2], args[3], args[4]); + } + }; + + FakeXMLHttpRequest.filters = []; + FakeXMLHttpRequest.addFilter = function addFilter(fn) { + this.filters.push(fn) + }; + var IE6Re = /MSIE 6/; + FakeXMLHttpRequest.defake = function defake(fakeXhr, xhrArgs) { + var xhr = new sinonXhr.workingXHR(); + each([ + "open", + "setRequestHeader", + "send", + "abort", + "getResponseHeader", + "getAllResponseHeaders", + "addEventListener", + "overrideMimeType", + "removeEventListener" + ], function (method) { + fakeXhr[method] = function () { + return apply(xhr, method, arguments); + }; + }); + + var copyAttrs = function (args) { + each(args, function (attr) { + try { + fakeXhr[attr] = xhr[attr] + } catch (e) { + if (!IE6Re.test(navigator.userAgent)) { + throw e; + } + } + }); + }; + + var stateChange = function stateChange() { + fakeXhr.readyState = xhr.readyState; + if (xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { + copyAttrs(["status", "statusText"]); + } + if (xhr.readyState >= FakeXMLHttpRequest.LOADING) { + copyAttrs(["responseText", "response"]); + } + if (xhr.readyState === FakeXMLHttpRequest.DONE) { + copyAttrs(["responseXML"]); + } + if (fakeXhr.onreadystatechange) { + fakeXhr.onreadystatechange.call(fakeXhr, { target: fakeXhr }); + } + }; + + if (xhr.addEventListener) { + for (var event in fakeXhr.eventListeners) { + if (fakeXhr.eventListeners.hasOwnProperty(event)) { + each(fakeXhr.eventListeners[event], function (handler) { + xhr.addEventListener(event, handler); + }); + } + } + xhr.addEventListener("readystatechange", stateChange); + } else { + xhr.onreadystatechange = stateChange; + } + apply(xhr, "open", xhrArgs); + }; + FakeXMLHttpRequest.useFilters = false; + + function verifyRequestOpened(xhr) { + if (xhr.readyState != FakeXMLHttpRequest.OPENED) { + throw new Error("INVALID_STATE_ERR - " + xhr.readyState); + } + } + + function verifyRequestSent(xhr) { + if (xhr.readyState == FakeXMLHttpRequest.DONE) { + throw new Error("Request done"); + } + } + + function verifyHeadersReceived(xhr) { + if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { + throw new Error("No headers received"); + } + } + + function verifyResponseBodyType(body) { + if (typeof body != "string") { + var error = new Error("Attempted to respond to fake XMLHttpRequest with " + + body + ", which is not a string."); + error.name = "InvalidBodyException"; + throw error; + } + } + + FakeXMLHttpRequest.parseXML = function parseXML(text) { + var xmlDoc; + + if (typeof DOMParser != "undefined") { + var parser = new DOMParser(); + xmlDoc = parser.parseFromString(text, "text/xml"); + } else { + xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); + xmlDoc.async = "false"; + xmlDoc.loadXML(text); + } + + return xmlDoc; + }; + + FakeXMLHttpRequest.statusCodes = { + 100: "Continue", + 101: "Switching Protocols", + 200: "OK", + 201: "Created", + 202: "Accepted", + 203: "Non-Authoritative Information", + 204: "No Content", + 205: "Reset Content", + 206: "Partial Content", + 207: "Multi-Status", + 300: "Multiple Choice", + 301: "Moved Permanently", + 302: "Found", + 303: "See Other", + 304: "Not Modified", + 305: "Use Proxy", + 307: "Temporary Redirect", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 409: "Conflict", + 410: "Gone", + 411: "Length Required", + 412: "Precondition Failed", + 413: "Request Entity Too Large", + 414: "Request-URI Too Long", + 415: "Unsupported Media Type", + 416: "Requested Range Not Satisfiable", + 417: "Expectation Failed", + 422: "Unprocessable Entity", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Gateway Timeout", + 505: "HTTP Version Not Supported" + }; + + function makeApi(sinon) { + sinon.xhr = sinonXhr; + + sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { + async: true, + + open: function open(method, url, async, username, password) { + this.method = method; + this.url = url; + this.async = typeof async == "boolean" ? async : true; + this.username = username; + this.password = password; + this.responseText = null; + this.responseXML = null; + this.requestHeaders = {}; + this.sendFlag = false; + + if (FakeXMLHttpRequest.useFilters === true) { + var xhrArgs = arguments; + var defake = some(FakeXMLHttpRequest.filters, function (filter) { + return filter.apply(this, xhrArgs) + }); + if (defake) { + return FakeXMLHttpRequest.defake(this, arguments); + } + } + this.readyStateChange(FakeXMLHttpRequest.OPENED); + }, + + readyStateChange: function readyStateChange(state) { + this.readyState = state; + + if (typeof this.onreadystatechange == "function") { + try { + this.onreadystatechange(); + } catch (e) { + sinon.logError("Fake XHR onreadystatechange handler", e); + } + } + + this.dispatchEvent(new sinon.Event("readystatechange")); + + switch (this.readyState) { + case FakeXMLHttpRequest.DONE: + this.dispatchEvent(new sinon.Event("load", false, false, this)); + this.dispatchEvent(new sinon.Event("loadend", false, false, this)); + this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); + if (supportsProgress) { + this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); + this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); + } + break; + } + }, + + setRequestHeader: function setRequestHeader(header, value) { + verifyState(this); + + if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { + throw new Error("Refused to set unsafe header \"" + header + "\""); + } + + if (this.requestHeaders[header]) { + this.requestHeaders[header] += "," + value; + } else { + this.requestHeaders[header] = value; + } + }, + + // Helps testing + setResponseHeaders: function setResponseHeaders(headers) { + verifyRequestOpened(this); + this.responseHeaders = {}; + + for (var header in headers) { + if (headers.hasOwnProperty(header)) { + this.responseHeaders[header] = headers[header]; + } + } + + if (this.async) { + this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); + } else { + this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; + } + }, + + // Currently treats ALL data as a DOMString (i.e. no Document) + send: function send(data) { + verifyState(this); + + if (!/^(get|head)$/i.test(this.method)) { + var contentType = getHeader(this.requestHeaders, "Content-Type"); + if (this.requestHeaders[contentType]) { + var value = this.requestHeaders[contentType].split(";"); + this.requestHeaders[contentType] = value[0] + ";charset=utf-8"; + } else if (!(data instanceof FormData)) { + this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; + } + + this.requestBody = data; + } + + this.errorFlag = false; + this.sendFlag = this.async; + this.readyStateChange(FakeXMLHttpRequest.OPENED); + + if (typeof this.onSend == "function") { + this.onSend(this); + } + + this.dispatchEvent(new sinon.Event("loadstart", false, false, this)); + }, + + abort: function abort() { + this.aborted = true; + this.responseText = null; + this.errorFlag = true; + this.requestHeaders = {}; + + if (this.readyState > FakeXMLHttpRequest.UNSENT && this.sendFlag) { + this.readyStateChange(FakeXMLHttpRequest.DONE); + this.sendFlag = false; + } + + this.readyState = FakeXMLHttpRequest.UNSENT; + + this.dispatchEvent(new sinon.Event("abort", false, false, this)); + + this.upload.dispatchEvent(new sinon.Event("abort", false, false, this)); + + if (typeof this.onerror === "function") { + this.onerror(); + } + }, + + getResponseHeader: function getResponseHeader(header) { + if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { + return null; + } + + if (/^Set-Cookie2?$/i.test(header)) { + return null; + } + + header = getHeader(this.responseHeaders, header); + + return this.responseHeaders[header] || null; + }, + + getAllResponseHeaders: function getAllResponseHeaders() { + if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { + return ""; + } + + var headers = ""; + + for (var header in this.responseHeaders) { + if (this.responseHeaders.hasOwnProperty(header) && + !/^Set-Cookie2?$/i.test(header)) { + headers += header + ": " + this.responseHeaders[header] + "\r\n"; + } + } + + return headers; + }, + + setResponseBody: function setResponseBody(body) { + verifyRequestSent(this); + verifyHeadersReceived(this); + verifyResponseBodyType(body); + + var chunkSize = this.chunkSize || 10; + var index = 0; + this.responseText = ""; + + do { + if (this.async) { + this.readyStateChange(FakeXMLHttpRequest.LOADING); + } + + this.responseText += body.substring(index, index + chunkSize); + index += chunkSize; + } while (index < body.length); + + var type = this.getResponseHeader("Content-Type"); + + if (this.responseText && + (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { + try { + this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); + } catch (e) { + // Unable to parse XML - no biggie + } + } + + this.readyStateChange(FakeXMLHttpRequest.DONE); + }, + + respond: function respond(status, headers, body) { + this.status = typeof status == "number" ? status : 200; + this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; + this.setResponseHeaders(headers || {}); + this.setResponseBody(body || ""); + }, + + uploadProgress: function uploadProgress(progressEventRaw) { + if (supportsProgress) { + this.upload.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw)); + } + }, + + downloadProgress: function downloadProgress(progressEventRaw) { + if (supportsProgress) { + this.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw)); + } + }, + + uploadError: function uploadError(error) { + if (supportsCustomEvent) { + this.upload.dispatchEvent(new sinon.CustomEvent("error", {detail: error})); + } + } + }); + + sinon.extend(FakeXMLHttpRequest, { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 + }); + + sinon.useFakeXMLHttpRequest = function () { + FakeXMLHttpRequest.restore = function restore(keepOnCreate) { + if (sinonXhr.supportsXHR) { + global.XMLHttpRequest = sinonXhr.GlobalXMLHttpRequest; + } + + if (sinonXhr.supportsActiveX) { + global.ActiveXObject = sinonXhr.GlobalActiveXObject; + } + + delete FakeXMLHttpRequest.restore; + + if (keepOnCreate !== true) { + delete FakeXMLHttpRequest.onCreate; + } + }; + if (sinonXhr.supportsXHR) { + global.XMLHttpRequest = FakeXMLHttpRequest; + } + + if (sinonXhr.supportsActiveX) { + global.ActiveXObject = function ActiveXObject(objId) { + if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { + + return new FakeXMLHttpRequest(); + } + + return new sinonXhr.GlobalActiveXObject(objId); + }; + } + + return FakeXMLHttpRequest; + }; + + sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./core"); + require("../extend"); + require("./event"); + require("../log_error"); + makeApi(sinon); + module.exports = sinon; + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (typeof sinon === "undefined") { + return; + } else { + makeApi(sinon); + } + +})(typeof global !== "undefined" ? global : this); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../extend":29,"../log_error":31,"./core":41,"./event":42}],48:[function(require,module,exports){ +(function (global){ +((typeof define === "function" && define.amd && function (m) { + define("formatio", ["samsam"], m); +}) || (typeof module === "object" && function (m) { + module.exports = m(require("samsam")); +}) || function (m) { this.formatio = m(this.samsam); } +)(function (samsam) { + "use strict"; + + var formatio = { + excludeConstructors: ["Object", /^.$/], + quoteStrings: true, + limitChildrenCount: 0 + }; + + var hasOwn = Object.prototype.hasOwnProperty; + + var specialObjects = []; + if (typeof global !== "undefined") { + specialObjects.push({ object: global, value: "[object global]" }); + } + if (typeof document !== "undefined") { + specialObjects.push({ + object: document, + value: "[object HTMLDocument]" + }); + } + if (typeof window !== "undefined") { + specialObjects.push({ object: window, value: "[object Window]" }); + } + + function functionName(func) { + if (!func) { return ""; } + if (func.displayName) { return func.displayName; } + if (func.name) { return func.name; } + var matches = func.toString().match(/function\s+([^\(]+)/m); + return (matches && matches[1]) || ""; + } + + function constructorName(f, object) { + var name = functionName(object && object.constructor); + var excludes = f.excludeConstructors || + formatio.excludeConstructors || []; + + var i, l; + for (i = 0, l = excludes.length; i < l; ++i) { + if (typeof excludes[i] === "string" && excludes[i] === name) { + return ""; + } else if (excludes[i].test && excludes[i].test(name)) { + return ""; + } + } + + return name; + } + + function isCircular(object, objects) { + if (typeof object !== "object") { return false; } + var i, l; + for (i = 0, l = objects.length; i < l; ++i) { + if (objects[i] === object) { return true; } + } + return false; + } + + function ascii(f, object, processed, indent) { + if (typeof object === "string") { + var qs = f.quoteStrings; + var quote = typeof qs !== "boolean" || qs; + return processed || quote ? '"' + object + '"' : object; + } + + if (typeof object === "function" && !(object instanceof RegExp)) { + return ascii.func(object); + } + + processed = processed || []; + + if (isCircular(object, processed)) { return "[Circular]"; } + + if (Object.prototype.toString.call(object) === "[object Array]") { + return ascii.array.call(f, object, processed); + } + + if (!object) { return String((1/object) === -Infinity ? "-0" : object); } + if (samsam.isElement(object)) { return ascii.element(object); } + + if (typeof object.toString === "function" && + object.toString !== Object.prototype.toString) { + return object.toString(); + } + + var i, l; + for (i = 0, l = specialObjects.length; i < l; i++) { + if (object === specialObjects[i].object) { + return specialObjects[i].value; + } + } + + return ascii.object.call(f, object, processed, indent); + } + + ascii.func = function (func) { + return "function " + functionName(func) + "() {}"; + }; + + ascii.array = function (array, processed) { + processed = processed || []; + processed.push(array); + var pieces = []; + var i, l; + l = (this.limitChildrenCount > 0) ? + Math.min(this.limitChildrenCount, array.length) : array.length; + + for (i = 0; i < l; ++i) { + pieces.push(ascii(this, array[i], processed)); + } + + if(l < array.length) + pieces.push("[... " + (array.length - l) + " more elements]"); + + return "[" + pieces.join(", ") + "]"; + }; + + ascii.object = function (object, processed, indent) { + processed = processed || []; + processed.push(object); + indent = indent || 0; + var pieces = [], properties = samsam.keys(object).sort(); + var length = 3; + var prop, str, obj, i, k, l; + l = (this.limitChildrenCount > 0) ? + Math.min(this.limitChildrenCount, properties.length) : properties.length; + + for (i = 0; i < l; ++i) { + prop = properties[i]; + obj = object[prop]; + + if (isCircular(obj, processed)) { + str = "[Circular]"; + } else { + str = ascii(this, obj, processed, indent + 2); + } + + str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; + length += str.length; + pieces.push(str); + } + + var cons = constructorName(this, object); + var prefix = cons ? "[" + cons + "] " : ""; + var is = ""; + for (i = 0, k = indent; i < k; ++i) { is += " "; } + + if(l < properties.length) + pieces.push("[... " + (properties.length - l) + " more elements]"); + + if (length + indent > 80) { + return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + + is + "}"; + } + return prefix + "{ " + pieces.join(", ") + " }"; + }; + + ascii.element = function (element) { + var tagName = element.tagName.toLowerCase(); + var attrs = element.attributes, attr, pairs = [], attrName, i, l, val; + + for (i = 0, l = attrs.length; i < l; ++i) { + attr = attrs.item(i); + attrName = attr.nodeName.toLowerCase().replace("html:", ""); + val = attr.nodeValue; + if (attrName !== "contenteditable" || val !== "inherit") { + if (!!val) { pairs.push(attrName + "=\"" + val + "\""); } + } + } + + var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); + var content = element.innerHTML; + + if (content.length > 20) { + content = content.substr(0, 20) + "[...]"; + } + + var res = formatted + pairs.join(" ") + ">" + content + + ""; + + return res.replace(/ contentEditable="inherit"/, ""); + }; + + function Formatio(options) { + for (var opt in options) { + this[opt] = options[opt]; + } + } + + Formatio.prototype = { + functionName: functionName, + + configure: function (options) { + return new Formatio(options); + }, + + constructorName: function (object) { + return constructorName(this, object); + }, + + ascii: function (object, processed, indent) { + return ascii(this, object, processed, indent); + } + }; + + return Formatio.prototype; +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"samsam":49}],49:[function(require,module,exports){ +((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) || + (typeof module === "object" && + function (m) { module.exports = m(); }) || // Node + function (m) { this.samsam = m(); } // Browser globals +)(function () { + var o = Object.prototype; + var div = typeof document !== "undefined" && document.createElement("div"); + + function isNaN(value) { + // Unlike global isNaN, this avoids type coercion + // typeof check avoids IE host object issues, hat tip to + // lodash + var val = value; // JsLint thinks value !== value is "weird" + return typeof value === "number" && value !== val; + } + + function getClass(value) { + // Returns the internal [[Class]] by calling Object.prototype.toString + // with the provided value as this. Return value is a string, naming the + // internal class, e.g. "Array" + return o.toString.call(value).split(/[ \]]/)[1]; + } + + /** + * @name samsam.isArguments + * @param Object object + * + * Returns ``true`` if ``object`` is an ``arguments`` object, + * ``false`` otherwise. + */ + function isArguments(object) { + if (getClass(object) === 'Arguments') { return true; } + if (typeof object !== "object" || typeof object.length !== "number" || + getClass(object) === "Array") { + return false; + } + if (typeof object.callee == "function") { return true; } + try { + object[object.length] = 6; + delete object[object.length]; + } catch (e) { + return true; + } + return false; + } + + /** + * @name samsam.isElement + * @param Object object + * + * Returns ``true`` if ``object`` is a DOM element node. Unlike + * Underscore.js/lodash, this function will return ``false`` if ``object`` + * is an *element-like* object, i.e. a regular object with a ``nodeType`` + * property that holds the value ``1``. + */ + function isElement(object) { + if (!object || object.nodeType !== 1 || !div) { return false; } + try { + object.appendChild(div); + object.removeChild(div); + } catch (e) { + return false; + } + return true; + } + + /** + * @name samsam.keys + * @param Object object + * + * Return an array of own property names. + */ + function keys(object) { + var ks = [], prop; + for (prop in object) { + if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); } + } + return ks; + } + + /** + * @name samsam.isDate + * @param Object value + * + * Returns true if the object is a ``Date``, or *date-like*. Duck typing + * of date objects work by checking that the object has a ``getTime`` + * function whose return value equals the return value from the object's + * ``valueOf``. + */ + function isDate(value) { + return typeof value.getTime == "function" && + value.getTime() == value.valueOf(); + } + + /** + * @name samsam.isNegZero + * @param Object value + * + * Returns ``true`` if ``value`` is ``-0``. + */ + function isNegZero(value) { + return value === 0 && 1 / value === -Infinity; + } + + /** + * @name samsam.equal + * @param Object obj1 + * @param Object obj2 + * + * Returns ``true`` if two objects are strictly equal. Compared to + * ``===`` there are two exceptions: + * + * - NaN is considered equal to NaN + * - -0 and +0 are not considered equal + */ + function identical(obj1, obj2) { + if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) { + return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2); + } + } + + + /** + * @name samsam.deepEqual + * @param Object obj1 + * @param Object obj2 + * + * Deep equal comparison. Two values are "deep equal" if: + * + * - They are equal, according to samsam.identical + * - They are both date objects representing the same time + * - They are both arrays containing elements that are all deepEqual + * - They are objects with the same set of properties, and each property + * in ``obj1`` is deepEqual to the corresponding property in ``obj2`` + * + * Supports cyclic objects. + */ + function deepEqualCyclic(obj1, obj2) { + + // used for cyclic comparison + // contain already visited objects + var objects1 = [], + objects2 = [], + // contain pathes (position in the object structure) + // of the already visited objects + // indexes same as in objects arrays + paths1 = [], + paths2 = [], + // contains combinations of already compared objects + // in the manner: { "$1['ref']$2['ref']": true } + compared = {}; + + /** + * used to check, if the value of a property is an object + * (cyclic logic is only needed for objects) + * only needed for cyclic logic + */ + function isObject(value) { + + if (typeof value === 'object' && value !== null && + !(value instanceof Boolean) && + !(value instanceof Date) && + !(value instanceof Number) && + !(value instanceof RegExp) && + !(value instanceof String)) { + + return true; + } + + return false; + } + + /** + * returns the index of the given object in the + * given objects array, -1 if not contained + * only needed for cyclic logic + */ + function getIndex(objects, obj) { + + var i; + for (i = 0; i < objects.length; i++) { + if (objects[i] === obj) { + return i; + } + } + + return -1; + } + + // does the recursion for the deep equal check + return (function deepEqual(obj1, obj2, path1, path2) { + var type1 = typeof obj1; + var type2 = typeof obj2; + + // == null also matches undefined + if (obj1 === obj2 || + isNaN(obj1) || isNaN(obj2) || + obj1 == null || obj2 == null || + type1 !== "object" || type2 !== "object") { + + return identical(obj1, obj2); + } + + // Elements are only equal if identical(expected, actual) + if (isElement(obj1) || isElement(obj2)) { return false; } + + var isDate1 = isDate(obj1), isDate2 = isDate(obj2); + if (isDate1 || isDate2) { + if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) { + return false; + } + } + + if (obj1 instanceof RegExp && obj2 instanceof RegExp) { + if (obj1.toString() !== obj2.toString()) { return false; } + } + + var class1 = getClass(obj1); + var class2 = getClass(obj2); + var keys1 = keys(obj1); + var keys2 = keys(obj2); + + if (isArguments(obj1) || isArguments(obj2)) { + if (obj1.length !== obj2.length) { return false; } + } else { + if (type1 !== type2 || class1 !== class2 || + keys1.length !== keys2.length) { + return false; + } + } + + var key, i, l, + // following vars are used for the cyclic logic + value1, value2, + isObject1, isObject2, + index1, index2, + newPath1, newPath2; + + for (i = 0, l = keys1.length; i < l; i++) { + key = keys1[i]; + if (!o.hasOwnProperty.call(obj2, key)) { + return false; + } + + // Start of the cyclic logic + + value1 = obj1[key]; + value2 = obj2[key]; + + isObject1 = isObject(value1); + isObject2 = isObject(value2); + + // determine, if the objects were already visited + // (it's faster to check for isObject first, than to + // get -1 from getIndex for non objects) + index1 = isObject1 ? getIndex(objects1, value1) : -1; + index2 = isObject2 ? getIndex(objects2, value2) : -1; + + // determine the new pathes of the objects + // - for non cyclic objects the current path will be extended + // by current property name + // - for cyclic objects the stored path is taken + newPath1 = index1 !== -1 + ? paths1[index1] + : path1 + '[' + JSON.stringify(key) + ']'; + newPath2 = index2 !== -1 + ? paths2[index2] + : path2 + '[' + JSON.stringify(key) + ']'; + + // stop recursion if current objects are already compared + if (compared[newPath1 + newPath2]) { + return true; + } + + // remember the current objects and their pathes + if (index1 === -1 && isObject1) { + objects1.push(value1); + paths1.push(newPath1); + } + if (index2 === -1 && isObject2) { + objects2.push(value2); + paths2.push(newPath2); + } + + // remember that the current objects are already compared + if (isObject1 && isObject2) { + compared[newPath1 + newPath2] = true; + } + + // End of cyclic logic + + // neither value1 nor value2 is a cycle + // continue with next level + if (!deepEqual(value1, value2, newPath1, newPath2)) { + return false; + } + } + + return true; + + }(obj1, obj2, '$1', '$2')); + } + + var match; + + function arrayContains(array, subset) { + if (subset.length === 0) { return true; } + var i, l, j, k; + for (i = 0, l = array.length; i < l; ++i) { + if (match(array[i], subset[0])) { + for (j = 0, k = subset.length; j < k; ++j) { + if (!match(array[i + j], subset[j])) { return false; } + } + return true; + } + } + return false; + } + + /** + * @name samsam.match + * @param Object object + * @param Object matcher + * + * Compare arbitrary value ``object`` with matcher. + */ + match = function match(object, matcher) { + if (matcher && typeof matcher.test === "function") { + return matcher.test(object); + } + + if (typeof matcher === "function") { + return matcher(object) === true; + } + + if (typeof matcher === "string") { + matcher = matcher.toLowerCase(); + var notNull = typeof object === "string" || !!object; + return notNull && + (String(object)).toLowerCase().indexOf(matcher) >= 0; + } + + if (typeof matcher === "number") { + return matcher === object; + } + + if (typeof matcher === "boolean") { + return matcher === object; + } + + if (typeof(matcher) === "undefined") { + return typeof(object) === "undefined"; + } + + if (matcher === null) { + return object === null; + } + + if (getClass(object) === "Array" && getClass(matcher) === "Array") { + return arrayContains(object, matcher); + } + + if (matcher && typeof matcher === "object") { + if (matcher === object) { + return true; + } + var prop; + for (prop in matcher) { + var value = object[prop]; + if (typeof value === "undefined" && + typeof object.getAttribute === "function") { + value = object.getAttribute(prop); + } + if (matcher[prop] === null || typeof matcher[prop] === 'undefined') { + if (value !== matcher[prop]) { + return false; + } + } else if (typeof value === "undefined" || !match(value, matcher[prop])) { + return false; + } + } + return true; + } + + throw new Error("Matcher was not a string, a number, a " + + "function, a boolean or an object"); + }; + + return { + isArguments: isArguments, + isElement: isElement, + isDate: isDate, + isNegZero: isNegZero, + identical: identical, + deepEqual: deepEqualCyclic, + match: match, + keys: keys + }; +}); + +},{}],50:[function(require,module,exports){ +(function (global){ +/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ +/*global global*/ +/** + * @author Christian Johansen (christian@cjohansen.no) and contributors + * @license BSD + * + * Copyright (c) 2010-2014 Christian Johansen + */ +"use strict"; + +// node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref() +// browsers, a number. +// see https://github.com/cjohansen/Sinon.JS/pull/436 +var timeoutResult = setTimeout(function() {}, 0); +var addTimerReturnsObject = typeof timeoutResult === "object"; +clearTimeout(timeoutResult); + +var NativeDate = Date; +var id = 1; + +/** + * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into + * number of milliseconds. This is used to support human-readable strings passed + * to clock.tick() + */ +function parseTime(str) { + if (!str) { + return 0; + } + + var strings = str.split(":"); + var l = strings.length, i = l; + var ms = 0, parsed; + + if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { + throw new Error("tick only understands numbers and 'h:m:s'"); + } + + while (i--) { + parsed = parseInt(strings[i], 10); + + if (parsed >= 60) { + throw new Error("Invalid time " + str); + } + + ms += parsed * Math.pow(60, (l - i - 1)); + } + + return ms * 1000; +} + +/** + * Used to grok the `now` parameter to createClock. + */ +function getEpoch(epoch) { + if (!epoch) { return 0; } + if (typeof epoch.getTime === "function") { return epoch.getTime(); } + if (typeof epoch === "number") { return epoch; } + throw new TypeError("now should be milliseconds since UNIX epoch"); +} + +function inRange(from, to, timer) { + return timer && timer.callAt >= from && timer.callAt <= to; +} + +function mirrorDateProperties(target, source) { + if (source.now) { + target.now = function now() { + return target.clock.now; + }; + } else { + delete target.now; + } + + if (source.toSource) { + target.toSource = function toSource() { + return source.toSource(); + }; + } else { + delete target.toSource; + } + + target.toString = function toString() { + return source.toString(); + }; + + target.prototype = source.prototype; + target.parse = source.parse; + target.UTC = source.UTC; + target.prototype.toUTCString = source.prototype.toUTCString; + + for (var prop in source) { + if (source.hasOwnProperty(prop)) { + target[prop] = source[prop]; + } + } + + return target; +} + +function createDate() { + function ClockDate(year, month, date, hour, minute, second, ms) { + // Defensive and verbose to avoid potential harm in passing + // explicit undefined when user does not pass argument + switch (arguments.length) { + case 0: + return new NativeDate(ClockDate.clock.now); + case 1: + return new NativeDate(year); + case 2: + return new NativeDate(year, month); + case 3: + return new NativeDate(year, month, date); + case 4: + return new NativeDate(year, month, date, hour); + case 5: + return new NativeDate(year, month, date, hour, minute); + case 6: + return new NativeDate(year, month, date, hour, minute, second); + default: + return new NativeDate(year, month, date, hour, minute, second, ms); + } + } + + return mirrorDateProperties(ClockDate, NativeDate); +} + +function addTimer(clock, timer) { + if (typeof timer.func === "undefined") { + throw new Error("Callback must be provided to timer calls"); + } + + if (!clock.timers) { + clock.timers = {}; + } + + timer.id = id++; + timer.createdAt = clock.now; + timer.callAt = clock.now + (timer.delay || 0); + + clock.timers[timer.id] = timer; + + if (addTimerReturnsObject) { + return { + id: timer.id, + ref: function() {}, + unref: function() {} + }; + } + else { + return timer.id; + } +} + +function firstTimerInRange(clock, from, to) { + var timers = clock.timers, timer = null; + + for (var id in timers) { + if (!inRange(from, to, timers[id])) { + continue; + } + + if (!timer || ~compareTimers(timer, timers[id])) { + timer = timers[id]; + } + } + + return timer; +} + +function compareTimers(a, b) { + // Sort first by absolute timing + if (a.callAt < b.callAt) { + return -1; + } + if (a.callAt > b.callAt) { + return 1; + } + + // Sort next by immediate, immediate timers take precedence + if (a.immediate && !b.immediate) { + return -1; + } + if (!a.immediate && b.immediate) { + return 1; + } + + // Sort next by creation time, earlier-created timers take precedence + if (a.createdAt < b.createdAt) { + return -1; + } + if (a.createdAt > b.createdAt) { + return 1; + } + + // Sort next by id, lower-id timers take precedence + if (a.id < b.id) { + return -1; + } + if (a.id > b.id) { + return 1; + } + + // As timer ids are unique, no fallback `0` is necessary +} + +function callTimer(clock, timer) { + if (typeof timer.interval == "number") { + clock.timers[timer.id].callAt += timer.interval; + } else { + delete clock.timers[timer.id]; + } + + try { + if (typeof timer.func == "function") { + timer.func.apply(null, timer.args); + } else { + eval(timer.func); + } + } catch (e) { + var exception = e; + } + + if (!clock.timers[timer.id]) { + if (exception) { + throw exception; + } + return; + } + + if (exception) { + throw exception; + } +} + +function uninstall(clock, target) { + var method; + + for (var i = 0, l = clock.methods.length; i < l; i++) { + method = clock.methods[i]; + + if (target[method].hadOwnProperty) { + target[method] = clock["_" + method]; + } else { + try { + delete target[method]; + } catch (e) {} + } + } + + // Prevent multiple executions which will completely remove these props + clock.methods = []; +} + +function hijackMethod(target, method, clock) { + clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method); + clock["_" + method] = target[method]; + + if (method == "Date") { + var date = mirrorDateProperties(clock[method], target[method]); + target[method] = date; + } else { + target[method] = function () { + return clock[method].apply(clock, arguments); + }; + + for (var prop in clock[method]) { + if (clock[method].hasOwnProperty(prop)) { + target[method][prop] = clock[method][prop]; + } + } + } + + target[method].clock = clock; +} + +var timers = { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined), + clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate: undefined), + setInterval: setInterval, + clearInterval: clearInterval, + Date: Date +}; + +var keys = Object.keys || function (obj) { + var ks = []; + for (var key in obj) { + ks.push(key); + } + return ks; +}; + +exports.timers = timers; + +var createClock = exports.createClock = function (now) { + var clock = { + now: getEpoch(now), + timeouts: {}, + Date: createDate() + }; + + clock.Date.clock = clock; + + clock.setTimeout = function setTimeout(func, timeout) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: timeout + }); + }; + + clock.clearTimeout = function clearTimeout(timerId) { + if (!timerId) { + // null appears to be allowed in most browsers, and appears to be + // relied upon by some libraries, like Bootstrap carousel + return; + } + if (!clock.timers) { + clock.timers = []; + } + // in Node, timerId is an object with .ref()/.unref(), and + // its .id field is the actual timer id. + if (typeof timerId === "object") { + timerId = timerId.id + } + if (timerId in clock.timers) { + delete clock.timers[timerId]; + } + }; + + clock.setInterval = function setInterval(func, timeout) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: timeout, + interval: timeout + }); + }; + + clock.clearInterval = function clearInterval(timerId) { + clock.clearTimeout(timerId); + }; + + clock.setImmediate = function setImmediate(func) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 1), + immediate: true + }); + }; + + clock.clearImmediate = function clearImmediate(timerId) { + clock.clearTimeout(timerId); + }; + + clock.tick = function tick(ms) { + ms = typeof ms == "number" ? ms : parseTime(ms); + var tickFrom = clock.now, tickTo = clock.now + ms, previous = clock.now; + var timer = firstTimerInRange(clock, tickFrom, tickTo); + + var firstException; + while (timer && tickFrom <= tickTo) { + if (clock.timers[timer.id]) { + tickFrom = clock.now = timer.callAt; + try { + callTimer(clock, timer); + } catch (e) { + firstException = firstException || e; + } + } + + timer = firstTimerInRange(clock, previous, tickTo); + previous = tickFrom; + } + + clock.now = tickTo; + + if (firstException) { + throw firstException; + } + + return clock.now; + }; + + clock.reset = function reset() { + clock.timers = {}; + }; + + return clock; +}; + +exports.install = function install(target, now, toFake) { + if (typeof target === "number") { + toFake = now; + now = target; + target = null; + } + + if (!target) { + target = global; + } + + var clock = createClock(now); + + clock.uninstall = function () { + uninstall(clock, target); + }; + + clock.methods = toFake || []; + + if (clock.methods.length === 0) { + clock.methods = keys(timers); + } + + for (var i = 0, l = clock.methods.length; i < l; i++) { + hijackMethod(target, clock.methods[i], clock); + } + + return clock; +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],51:[function(require,module,exports){ +(function (process,global){ +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + function lib$es6$promise$asap$$asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + lib$es6$promise$asap$$scheduleFlush(); + } + } + + var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + var nextTick = process.nextTick; + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // setImmediate should be used instead instead + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function() { + nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertex() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFullfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$default(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { + return lib$es6$promise$utils$$isArray(input); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; + + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + var lib$es6$promise$promise$$counter = 0; + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$default(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + +//# sourceMappingURL=es6-promise.js.map +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":4}],52:[function(require,module,exports){ +(function (global){ +/*global describe, specify, it, assert */ + +if (typeof Object.getPrototypeOf !== "function") { + Object.getPrototypeOf = "".__proto__ === String.prototype + ? function (object) { + return object.__proto__; + } + : function (object) { + // May break if the constructor has been tampered with + return object.constructor.prototype; + }; +} + +function keysOf(object) { + var results = []; + + for (var key in object) { + if (object.hasOwnProperty(key)) { + results.push(key); + } + } + + return results; +} + +var g = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this; +var Promise = g.adapter.Promise; +var assert = require('assert'); + +function objectEquals(obj1, obj2) { + for (var i in obj1) { + if (obj1.hasOwnProperty(i)) { + if (!obj2.hasOwnProperty(i)) return false; + if (obj1[i] != obj2[i]) return false; + } + } + for (var i in obj2) { + if (obj2.hasOwnProperty(i)) { + if (!obj1.hasOwnProperty(i)) return false; + if (obj1[i] != obj2[i]) return false; + } + } + return true; +} + +describe("extensions", function() { + describe("Promise constructor", function() { + it('should exist and have length 1', function() { + assert(Promise); + assert.equal(Promise.length, 1); + }); + + it('should fulfill if `resolve` is called with a value', function(done) { + var promise = new Promise(function(resolve) { resolve('value'); }); + + promise.then(function(value) { + assert.equal(value, 'value'); + done(); + }); + }); + + it('should reject if `reject` is called with a reason', function(done) { + var promise = new Promise(function(resolve, reject) { reject('reason'); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'reason'); + done(); + }); + }); + + it('should be a constructor', function() { + var promise = new Promise(function() {}); + + assert.equal(Object.getPrototypeOf(promise), Promise.prototype, '[[Prototype]] equals Promise.prototype'); + assert.equal(promise.constructor, Promise, 'constructor property of instances is set correctly'); + assert.equal(Promise.prototype.constructor, Promise, 'constructor property of prototype is set correctly'); + }); + + it('should NOT work without `new`', function() { + assert.throws(function(){ + Promise(function(resolve) { resolve('value'); }); + }, TypeError) + }); + + it('should throw a `TypeError` if not given a function', function() { + assert.throws(function () { + new Promise(); + }, TypeError); + + assert.throws(function () { + new Promise({}); + }, TypeError); + + assert.throws(function () { + new Promise('boo!'); + }, TypeError); + }); + + it('should reject on resolver exception', function(done) { + new Promise(function() { + throw 'error'; + }).then(null, function(e) { + assert.equal(e, 'error'); + done(); + }); + }); + + it('should not resolve multiple times', function(done) { + var resolver, rejector, fulfilled = 0, rejected = 0; + var thenable = { + then: function(resolve, reject) { + resolver = resolve; + rejector = reject; + } + }; + + var promise = new Promise(function(resolve) { + resolve(1); + }); + + promise.then(function(value){ + return thenable; + }).then(function(value){ + fulfilled++; + }, function(reason) { + rejected++; + }); + + setTimeout(function() { + resolver(1); + resolver(1); + rejector(1); + rejector(1); + + setTimeout(function() { + assert.equal(fulfilled, 1); + assert.equal(rejected, 0); + done(); + }, 20); + }, 20); + + }); + + describe('assimilation', function() { + it('should assimilate if `resolve` is called with a fulfilled promise', function(done) { + var originalPromise = new Promise(function(resolve) { resolve('original value'); }); + var promise = new Promise(function(resolve) { resolve(originalPromise); }); + + promise.then(function(value) { + assert.equal(value, 'original value'); + done(); + }); + }); + + it('should assimilate if `resolve` is called with a rejected promise', function(done) { + var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); + var promise = new Promise(function(resolve) { resolve(originalPromise); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'original reason'); + done(); + }); + }); + + it('should assimilate if `resolve` is called with a fulfilled thenable', function(done) { + var originalThenable = { + then: function (onFulfilled) { + setTimeout(function() { onFulfilled('original value'); }, 0); + } + }; + var promise = new Promise(function(resolve) { resolve(originalThenable); }); + + promise.then(function(value) { + assert.equal(value, 'original value'); + done(); + }); + }); + + it('should assimilate if `resolve` is called with a rejected thenable', function(done) { + var originalThenable = { + then: function (onFulfilled, onRejected) { + setTimeout(function() { onRejected('original reason'); }, 0); + } + }; + var promise = new Promise(function(resolve) { resolve(originalThenable); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'original reason'); + done(); + }); + }); + + + it('should assimilate two levels deep, for fulfillment of self fulfilling promises', function(done) { + var originalPromise, promise; + originalPromise = new Promise(function(resolve) { + setTimeout(function() { + resolve(originalPromise); + }, 0) + }); + + promise = new Promise(function(resolve) { + setTimeout(function() { + resolve(originalPromise); + }, 0); + }); + + promise.then(function(value) { + assert(false); + done(); + })['catch'](function(reason) { + assert.equal(reason.message, "You cannot resolve a promise with itself"); + assert(reason instanceof TypeError); + done(); + }); + }); + + it('should assimilate two levels deep, for fulfillment', function(done) { + var originalPromise = new Promise(function(resolve) { resolve('original value'); }); + var nextPromise = new Promise(function(resolve) { resolve(originalPromise); }); + var promise = new Promise(function(resolve) { resolve(nextPromise); }); + + promise.then(function(value) { + assert.equal(value, 'original value'); + done(); + }); + }); + + it('should assimilate two levels deep, for rejection', function(done) { + var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); + var nextPromise = new Promise(function(resolve) { resolve(originalPromise); }); + var promise = new Promise(function(resolve) { resolve(nextPromise); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'original reason'); + done(); + }); + }); + + it('should assimilate three levels deep, mixing thenables and promises (fulfilled case)', function(done) { + var originalPromise = new Promise(function(resolve) { resolve('original value'); }); + var intermediateThenable = { + then: function (onFulfilled) { + setTimeout(function() { onFulfilled(originalPromise); }, 0); + } + }; + var promise = new Promise(function(resolve) { resolve(intermediateThenable); }); + + promise.then(function(value) { + assert.equal(value, 'original value'); + done(); + }); + }); + + it('should assimilate three levels deep, mixing thenables and promises (rejected case)', function(done) { + var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); + var intermediateThenable = { + then: function (onFulfilled) { + setTimeout(function() { onFulfilled(originalPromise); }, 0); + } + }; + var promise = new Promise(function(resolve) { resolve(intermediateThenable); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'original reason'); + done(); + }); + }); + }); + }); + + describe("Promise.all", function() { + testAll(function(){ + return Promise.all.apply(Promise, arguments); + }); + }); + + function testAll(all) { + it('should exist', function() { + assert(all); + }); + + it('throws when not passed an array', function(done) { + var nothing = assertRejection(all()); + var string = assertRejection(all('')); + var object = assertRejection(all({})); + + Promise.all([ + nothing, + string, + object + ]).then(function(){ done(); }); + }); + + specify('fulfilled only after all of the other promises are fulfilled', function(done) { + var firstResolved, secondResolved, firstResolver, secondResolver; + + var first = new Promise(function(resolve) { + firstResolver = resolve; + }); + first.then(function() { + firstResolved = true; + }); + + var second = new Promise(function(resolve) { + secondResolver = resolve; + }); + second.then(function() { + secondResolved = true; + }); + + setTimeout(function() { + firstResolver(true); + }, 0); + + setTimeout(function() { + secondResolver(true); + }, 0); + + all([first, second]).then(function() { + assert(firstResolved); + assert(secondResolved); + done(); + }); + }); + + specify('rejected as soon as a promise is rejected', function(done) { + var firstResolver, secondResolver; + + var first = new Promise(function(resolve, reject) { + firstResolver = { resolve: resolve, reject: reject }; + }); + + var second = new Promise(function(resolve, reject) { + secondResolver = { resolve: resolve, reject: reject }; + }); + + setTimeout(function() { + firstResolver.reject({}); + }, 0); + + var firstWasRejected, secondCompleted; + + first['catch'](function(){ + firstWasRejected = true; + }); + + second.then(function(){ + secondCompleted = true; + }, function() { + secondCompleted = true; + }); + + all([first, second]).then(function() { + assert(false); + }, function() { + assert(firstWasRejected); + assert(!secondCompleted); + done(); + }); + }); + + specify('passes the resolved values of each promise to the callback in the correct order', function(done) { + var firstResolver, secondResolver, thirdResolver; + + var first = new Promise(function(resolve, reject) { + firstResolver = { resolve: resolve, reject: reject }; + }); + + var second = new Promise(function(resolve, reject) { + secondResolver = { resolve: resolve, reject: reject }; + }); + + var third = new Promise(function(resolve, reject) { + thirdResolver = { resolve: resolve, reject: reject }; + }); + + thirdResolver.resolve(3); + firstResolver.resolve(1); + secondResolver.resolve(2); + + all([first, second, third]).then(function(results) { + assert(results.length === 3); + assert(results[0] === 1); + assert(results[1] === 2); + assert(results[2] === 3); + done(); + }); + }); + + specify('resolves an empty array passed to all()', function(done) { + all([]).then(function(results) { + assert(results.length === 0); + done(); + }); + }); + + specify('works with null', function(done) { + all([null]).then(function(results) { + assert.equal(results[0], null); + done(); + }); + }); + + specify('works with a mix of promises and thenables and non-promises', function(done) { + var promise = new Promise(function(resolve) { resolve(1); }); + var syncThenable = { then: function (onFulfilled) { onFulfilled(2); } }; + var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } }; + var nonPromise = 4; + + all([promise, syncThenable, asyncThenable, nonPromise]).then(function(results) { + assert(objectEquals(results, [1, 2, 3, 4])); + done(); + })['catch'](done); + }); + } + + describe("reject", function(){ + specify("it should exist", function(){ + assert(Promise.reject); + }); + + describe('it rejects', function(){ + var reason = 'the reason', + promise = Promise.reject(reason); + + promise.then(function(){ + assert(false, 'should not fulfill'); + }, function(actualReason){ + assert.equal(reason, actualReason); + }); + }); + }); + + function assertRejection(promise) { + return promise.then(function(){ + assert(false, 'expected rejection, but got fulfillment'); + }, function(reason){ + assert(reason instanceof Error); + }); + } + + describe('race', function() { + it("should exist", function() { + assert(Promise.race); + }); + + it("throws when not passed an array", function(done) { + var nothing = assertRejection(Promise.race()); + var string = assertRejection(Promise.race('')); + var object = assertRejection(Promise.race({})); + + Promise.all([ + nothing, + string, + object + ]).then(function(){ done(); }); + }); + + specify('fulfilled after one of the other promises are fulfilled', function(done) { + var firstResolved, secondResolved, firstResolver, secondResolver; + + var first = new Promise(function(resolve) { + firstResolver = resolve; + }); + first.then(function() { + firstResolved = true; + }); + + var second = new Promise(function(resolve) { + secondResolver = resolve; + }); + second.then(function() { + secondResolved = true; + }); + + setTimeout(function() { + firstResolver(true); + }, 100); + + setTimeout(function() { + secondResolver(true); + }, 0); + + Promise.race([first, second]).then(function() { + assert(secondResolved); + assert.equal(firstResolved, undefined); + done(); + }); + }); + + specify('the race begins on nextTurn and prioritized by array entry', function(done) { + var firstResolver, secondResolver, nonPromise = 5; + + var first = new Promise(function(resolve, reject) { + resolve(true); + }); + + var second = new Promise(function(resolve, reject) { + resolve(false); + }); + + Promise.race([first, second, nonPromise]).then(function(value) { + assert.equal(value, true); + done(); + }); + }); + + specify('rejected as soon as a promise is rejected', function(done) { + var firstResolver, secondResolver; + + var first = new Promise(function(resolve, reject) { + firstResolver = { resolve: resolve, reject: reject }; + }); + + var second = new Promise(function(resolve, reject) { + secondResolver = { resolve: resolve, reject: reject }; + }); + + setTimeout(function() { + firstResolver.reject({}); + }, 0); + + var firstWasRejected, secondCompleted; + + first['catch'](function(){ + firstWasRejected = true; + }); + + second.then(function(){ + secondCompleted = true; + }, function() { + secondCompleted = true; + }); + + Promise.race([first, second]).then(function() { + assert(false); + }, function() { + assert(firstWasRejected); + assert(!secondCompleted); + done(); + }); + }); + + specify('resolves an empty array to forever pending Promise', function(done) { + var foreverPendingPromise = Promise.race([]), + wasSettled = false; + + foreverPendingPromise.then(function() { + wasSettled = true; + }, function() { + wasSettled = true; + }); + + setTimeout(function() { + assert(!wasSettled); + done(); + }, 100); + }); + + specify('works with a mix of promises and thenables', function(done) { + var promise = new Promise(function(resolve) { setTimeout(function() { resolve(1); }, 10); }), + syncThenable = { then: function (onFulfilled) { onFulfilled(2); } }; + + Promise.race([promise, syncThenable]).then(function(result) { + assert(result, 2); + done(); + }); + }); + + specify('works with a mix of thenables and non-promises', function (done) { + var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } }, + nonPromise = 4; + + Promise.race([asyncThenable, nonPromise]).then(function(result) { + assert(result, 4); + done(); + }); + }); + }); + + describe("resolve", function(){ + specify("it should exist", function(){ + assert(Promise.resolve); + }); + + describe("1. If x is a promise, adopt its state ", function(){ + specify("1.1 If x is pending, promise must remain pending until x is fulfilled or rejected.", function(done){ + var expectedValue, resolver, thenable, wrapped; + + expectedValue = 'the value'; + thenable = { + then: function(resolve, reject){ + resolver = resolve; + } + }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(function(value){ + assert(value === expectedValue); + done(); + }); + + setTimeout(function(){ + resolver(expectedValue); + }, 10); + }); + + specify("1.2 If/when x is fulfilled, fulfill promise with the same value.", function(done){ + var expectedValue, thenable, wrapped; + + expectedValue = 'the value'; + thenable = { + then: function(resolve, reject){ + resolve(expectedValue); + } + }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(function(value){ + assert(value === expectedValue); + done(); + }) + }); + + specify("1.3 If/when x is rejected, reject promise with the same reason.", function(done){ + var expectedError, thenable, wrapped; + + expectedError = new Error(); + thenable = { + then: function(resolve, reject){ + reject(expectedError); + } + }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(null, function(error){ + assert(error === expectedError); + done(); + }); + }); + }); + + describe("2. Otherwise, if x is an object or function,", function(){ + specify("2.1 Let then x.then", function(done){ + var accessCount, resolver, wrapped, thenable; + + accessCount = 0; + thenable = { }; + + // we likely don't need to test this, if the browser doesn't support it + if (typeof Object.defineProperty !== "function") { done(); return; } + + Object.defineProperty(thenable, 'then', { + get: function(){ + accessCount++; + + if (accessCount > 1) { + throw new Error(); + } + + return function(){ }; + } + }); + + assert(accessCount === 0); + + wrapped = Promise.resolve(thenable); + + assert(accessCount === 1); + + done(); + }); + + specify("2.2 If retrieving the property x.then results in a thrown exception e, reject promise with e as the reason.", function(done){ + var wrapped, thenable, expectedError; + + expectedError = new Error(); + thenable = { }; + + // we likely don't need to test this, if the browser doesn't support it + if (typeof Object.defineProperty !== "function") { done(); return; } + + Object.defineProperty(thenable, 'then', { + get: function(){ + throw expectedError; + } + }); + + wrapped = Promise.resolve(thenable); + + wrapped.then(null, function(error){ + assert(error === expectedError, 'incorrect exception was thrown'); + done(); + }); + }); + + describe('2.3. If then is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise, where', function(){ + specify('2.3.1 If/when resolvePromise is called with a value y, run Resolve(promise, y)', function(done){ + var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis; + + thenable = { + then: function(resolve, reject){ + calledThis = this; + resolver = resolve; + rejector = reject; + } + }; + + expectedSuccess = 'success'; + wrapped = Promise.resolve(thenable); + + wrapped.then(function(success){ + assert(calledThis === thenable, 'this must be the thenable'); + assert(success === expectedSuccess, 'rejected promise with x'); + done(); + }); + + setTimeout(function() { + resolver(expectedSuccess); + }, 20); + }); + + specify('2.3.2 If/when rejectPromise is called with a reason r, reject promise with r.', function(done){ + var expectedError, resolver, rejector, thenable, wrapped, calledThis; + + thenable = { + then: function(resolve, reject){ + calledThis = this; + resolver = resolve; + rejector = reject; + } + }; + + expectedError = new Error(); + + wrapped = Promise.resolve(thenable); + + wrapped.then(null, function(error){ + assert(error === expectedError, 'rejected promise with x'); + done(); + }); + + setTimeout(function() { + rejector(expectedError); + }, 20); + }); + + specify("2.3.3 If both resolvePromise and rejectPromise are called, or multiple calls to the same argument are made, the first call takes precedence, and any further calls are ignored", function(done){ + var expectedError, expectedSuccess, resolver, rejector, thenable, wrapped, calledThis, + calledRejected, calledResolved; + + calledRejected = 0; + calledResolved = 0; + + thenable = { + then: function(resolve, reject){ + calledThis = this; + resolver = resolve; + rejector = reject; + } + }; + + expectedError = new Error(); + + wrapped = Promise.resolve(thenable); + + wrapped.then(function(){ + calledResolved++; + }, function(error){ + calledRejected++; + assert(calledResolved === 0, 'never resolved'); + assert(calledRejected === 1, 'rejected only once'); + assert(error === expectedError, 'rejected promise with x'); + }); + + setTimeout(function() { + rejector(expectedError); + rejector(expectedError); + + rejector('foo'); + + resolver('bar'); + resolver('baz'); + }, 20); + + setTimeout(function(){ + assert(calledRejected === 1, 'only rejected once'); + assert(calledResolved === 0, 'never resolved'); + done(); + }, 50); + }); + + describe("2.3.4 If calling then throws an exception e", function(){ + specify("2.3.4.1 If resolvePromise or rejectPromise have been called, ignore it.", function(done){ + var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis, + calledRejected, calledResolved; + + expectedSuccess = 'success'; + + thenable = { + then: function(resolve, reject){ + resolve(expectedSuccess); + throw expectedError; + } + }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(function(success){ + assert(success === expectedSuccess, 'resolved not errored'); + done(); + }); + }); + + specify("2.3.4.2 Otherwise, reject promise with e as the reason.", function(done) { + var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount; + + expectedError = new Error(); + callCount = 0; + + thenable = { then: function() { throw expectedError; } }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(null, function(error){ + callCount++; + assert(expectedError === error, 'expected the correct error to be rejected'); + done(); + }); + + assert(callCount === 0, 'expected async, was sync'); + }); + }); + }); + + specify("2.4 If then is not a function, fulfill promise with x", function(done){ + var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount; + + thenable = { then: 3 }; + callCount = 0; + wrapped = Promise.resolve(thenable); + + wrapped.then(function(success){ + callCount++; + assert(thenable === success, 'fulfilled promise with x'); + done(); + }); + + assert(callCount === 0, 'expected async, was sync'); + }); + }); + + describe("3. If x is not an object or function, ", function(){ + specify("fulfill promise with x.", function(done){ + var thenable, callCount, wrapped; + + thenable = null; + callCount = 0; + wrapped = Promise.resolve(thenable); + + wrapped.then(function(success){ + callCount++; + assert(success === thenable, 'fulfilled promise with x'); + done(); + }, function(a){ + assert(false, 'should not also reject'); + }); + + assert(callCount === 0, 'expected async, was sync'); + }); + }); + }); + + if (typeof Worker !== 'undefined') { + describe('web worker', function () { + it('should work', function (done) { + this.timeout(2000); + var worker = new Worker('worker.js'); + worker.addEventListener('error', function(reason) { + done(new Error("Test failed:" + reason)); + }); + worker.addEventListener('message', function (e) { + worker.terminate(); + assert.equal(e.data, 'pong'); + done(); + }); + worker.postMessage('ping'); + }); + }); + } +}); + +// thanks to @wizardwerdna for the test case -> https://github.com/tildeio/rsvp.js/issues/66 +// Only run these tests in node (phantomjs cannot handle them) +if (typeof module !== 'undefined' && module.exports) { + + describe("using reduce to sum integers using promises", function(){ + it("should build the promise pipeline without error", function(){ + var array, iters, pZero, i; + + array = []; + iters = 1000; + + for (i=1; i<=iters; i++) { + array.push(i); + } + + pZero = Promise.resolve(0); + + array.reduce(function(promise, nextVal) { + return promise.then(function(currentVal) { + return Promise.resolve(currentVal + nextVal); + }); + }, pZero); + }); + + it("should get correct answer without blowing the nextTick stack", function(done){ + var pZero, array, iters, result, i; + + pZero = Promise.resolve(0); + + array = []; + iters = 1000; + + for (i=1; i<=iters; i++) { + array.push(i); + } + + result = array.reduce(function(promise, nextVal) { + return promise.then(function(currentVal) { + return Promise.resolve(currentVal + nextVal); + }); + }, pZero); + + result.then(function(value){ + assert.equal(value, (iters*(iters+1)/2)); + done(); + }); + }); + }); +} + +// Kudos to @Octane at https://github.com/getify/native-promise-only/issues/5 for this, and @getify for pinging me. +describe("Thenables should not be able to run code during assimilation", function () { + specify("resolving to a thenable", function () { + var thenCalled = false; + var thenable = { + then: function () { + thenCalled = true; + } + }; + + Promise.resolve(thenable); + assert.strictEqual(thenCalled, false); + }); + + specify("resolving to an evil promise", function () { + var thenCalled = false; + var evilPromise = Promise.resolve(); + evilPromise.then = function () { + thenCalled = true; + }; + + Promise.resolve(evilPromise); + assert.strictEqual(thenCalled, false); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"assert":2}],53:[function(require,module,exports){ +(function (global){ +var assert = require('assert'); +var g = typeof window !== 'undefined' ? + window : typeof global !== 'undefined' ? global : this; + +var Promise = g.ES6Promise || require('./es6-promise').Promise; + +function defer() { + var deferred = {}; + + deferred.promise = new Promise(function(resolve, reject) { + deferred.resolve = resolve; + deferred.reject = reject; + }); + + return deferred; +} +var resolve = Promise.resolve; +var reject = Promise.reject; + + +module.exports = g.adapter = { + resolved: function(a) { return Promise.resolve(a); }, + rejected: function(a) { return Promise.reject(a); }, + deferred: defer, + Promise: Promise +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./es6-promise":51,"assert":2}]},{},[1]); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js new file mode 100644 index 0000000..5b096d6 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js @@ -0,0 +1,950 @@ +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + function lib$es6$promise$asap$$asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + lib$es6$promise$asap$$scheduleFlush(); + } + } + + var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + var nextTick = process.nextTick; + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // setImmediate should be used instead instead + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function() { + nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertex() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFullfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$default(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { + return lib$es6$promise$utils$$isArray(input); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; + + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + var lib$es6$promise$promise$$counter = 0; + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$default(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + +//# sourceMappingURL=es6-promise.js.map \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js new file mode 100644 index 0000000..34a1f52 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js @@ -0,0 +1 @@ +(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;function lib$es6$promise$asap$$asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){lib$es6$promise$asap$$scheduleFlush()}}var lib$es6$promise$asap$$default=lib$es6$promise$asap$$asap;var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){var nextTick=process.nextTick;var version=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);if(Array.isArray(version)&&version[1]==="0"&&version[2]==="10"){nextTick=setImmediate}return function(){nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i + + + rsvp.js Tests + + + +
+ + + + + + + + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js new file mode 100644 index 0000000..4817c9e --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js @@ -0,0 +1,902 @@ +/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ +;(function () { + // Detect the `define` function exposed by asynchronous module loaders. The + // strict `define` check is necessary for compatibility with `r.js`. + var isLoader = typeof define === "function" && define.amd; + + // A set of types used to distinguish objects from primitives. + var objectTypes = { + "function": true, + "object": true + }; + + // Detect the `exports` object exposed by CommonJS implementations. + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + // Use the `global` object exposed by Node (including Browserify via + // `insert-module-globals`), Narwhal, and Ringo as the default context, + // and the `window` object in browsers. Rhino exports a `global` function + // instead. + var root = objectTypes[typeof window] && window || this, + freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; + + if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { + root = freeGlobal; + } + + // Public: Initializes JSON 3 using the given `context` object, attaching the + // `stringify` and `parse` functions to the specified `exports` object. + function runInContext(context, exports) { + context || (context = root["Object"]()); + exports || (exports = root["Object"]()); + + // Native constructor aliases. + var Number = context["Number"] || root["Number"], + String = context["String"] || root["String"], + Object = context["Object"] || root["Object"], + Date = context["Date"] || root["Date"], + SyntaxError = context["SyntaxError"] || root["SyntaxError"], + TypeError = context["TypeError"] || root["TypeError"], + Math = context["Math"] || root["Math"], + nativeJSON = context["JSON"] || root["JSON"]; + + // Delegate to the native `stringify` and `parse` implementations. + if (typeof nativeJSON == "object" && nativeJSON) { + exports.stringify = nativeJSON.stringify; + exports.parse = nativeJSON.parse; + } + + // Convenience aliases. + var objectProto = Object.prototype, + getClass = objectProto.toString, + isProperty, forEach, undef; + + // Test the `Date#getUTC*` methods. Based on work by @Yaffle. + var isExtended = new Date(-3509827334573292); + try { + // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical + // results for certain dates in Opera >= 10.53. + isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && + // Safari < 2.0.2 stores the internal millisecond time value correctly, + // but clips the values returned by the date methods to the range of + // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]). + isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; + } catch (exception) {} + + // Internal: Determines whether the native `JSON.stringify` and `parse` + // implementations are spec-compliant. Based on work by Ken Snyder. + function has(name) { + if (has[name] !== undef) { + // Return cached feature test result. + return has[name]; + } + var isSupported; + if (name == "bug-string-char-index") { + // IE <= 7 doesn't support accessing string characters using square + // bracket notation. IE 8 only supports this for primitives. + isSupported = "a"[0] != "a"; + } else if (name == "json") { + // Indicates whether both `JSON.stringify` and `JSON.parse` are + // supported. + isSupported = has("json-stringify") && has("json-parse"); + } else { + var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; + // Test `JSON.stringify`. + if (name == "json-stringify") { + var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; + if (stringifySupported) { + // A test function object with a custom `toJSON` method. + (value = function () { + return 1; + }).toJSON = value; + try { + stringifySupported = + // Firefox 3.1b1 and b2 serialize string, number, and boolean + // primitives as object literals. + stringify(0) === "0" && + // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object + // literals. + stringify(new Number()) === "0" && + stringify(new String()) == '""' && + // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or + // does not define a canonical JSON representation (this applies to + // objects with `toJSON` properties as well, *unless* they are nested + // within an object or array). + stringify(getClass) === undef && + // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and + // FF 3.1b3 pass this test. + stringify(undef) === undef && + // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, + // respectively, if the value is omitted entirely. + stringify() === undef && + // FF 3.1b1, 2 throw an error if the given value is not a number, + // string, array, object, Boolean, or `null` literal. This applies to + // objects with custom `toJSON` methods as well, unless they are nested + // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` + // methods entirely. + stringify(value) === "1" && + stringify([value]) == "[1]" && + // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of + // `"[null]"`. + stringify([undef]) == "[null]" && + // YUI 3.0.0b1 fails to serialize `null` literals. + stringify(null) == "null" && + // FF 3.1b1, 2 halts serialization if an array contains a function: + // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 + // elides non-JSON values from objects and arrays, unless they + // define custom `toJSON` methods. + stringify([undef, getClass, null]) == "[null,null,null]" && + // Simple serialization test. FF 3.1b1 uses Unicode escape sequences + // where character escape codes are expected (e.g., `\b` => `\u0008`). + stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && + // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. + stringify(null, value) === "1" && + stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && + // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly + // serialize extended years. + stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && + // The milliseconds are optional in ES 5, but required in 5.1. + stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && + // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative + // four-digit years instead of six-digit years. Credits: @Yaffle. + stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && + // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond + // values less than 1000. Credits: @Yaffle. + stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; + } catch (exception) { + stringifySupported = false; + } + } + isSupported = stringifySupported; + } + // Test `JSON.parse`. + if (name == "json-parse") { + var parse = exports.parse; + if (typeof parse == "function") { + try { + // FF 3.1b1, b2 will throw an exception if a bare literal is provided. + // Conforming implementations should also coerce the initial argument to + // a string prior to parsing. + if (parse("0") === 0 && !parse(false)) { + // Simple parsing test. + value = parse(serialized); + var parseSupported = value["a"].length == 5 && value["a"][0] === 1; + if (parseSupported) { + try { + // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. + parseSupported = !parse('"\t"'); + } catch (exception) {} + if (parseSupported) { + try { + // FF 4.0 and 4.0.1 allow leading `+` signs and leading + // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow + // certain octal literals. + parseSupported = parse("01") !== 1; + } catch (exception) {} + } + if (parseSupported) { + try { + // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal + // points. These environments, along with FF 3.1b1 and 2, + // also allow trailing commas in JSON objects and arrays. + parseSupported = parse("1.") !== 1; + } catch (exception) {} + } + } + } + } catch (exception) { + parseSupported = false; + } + } + isSupported = parseSupported; + } + } + return has[name] = !!isSupported; + } + + if (!has("json")) { + // Common `[[Class]]` name aliases. + var functionClass = "[object Function]", + dateClass = "[object Date]", + numberClass = "[object Number]", + stringClass = "[object String]", + arrayClass = "[object Array]", + booleanClass = "[object Boolean]"; + + // Detect incomplete support for accessing string characters by index. + var charIndexBuggy = has("bug-string-char-index"); + + // Define additional utility methods if the `Date` methods are buggy. + if (!isExtended) { + var floor = Math.floor; + // A mapping between the months of the year and the number of days between + // January 1st and the first of the respective month. + var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + // Internal: Calculates the number of days between the Unix epoch and the + // first day of the given month. + var getDay = function (year, month) { + return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); + }; + } + + // Internal: Determines if a property is a direct property of the given + // object. Delegates to the native `Object#hasOwnProperty` method. + if (!(isProperty = objectProto.hasOwnProperty)) { + isProperty = function (property) { + var members = {}, constructor; + if ((members.__proto__ = null, members.__proto__ = { + // The *proto* property cannot be set multiple times in recent + // versions of Firefox and SeaMonkey. + "toString": 1 + }, members).toString != getClass) { + // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but + // supports the mutable *proto* property. + isProperty = function (property) { + // Capture and break the object's prototype chain (see section 8.6.2 + // of the ES 5.1 spec). The parenthesized expression prevents an + // unsafe transformation by the Closure Compiler. + var original = this.__proto__, result = property in (this.__proto__ = null, this); + // Restore the original prototype chain. + this.__proto__ = original; + return result; + }; + } else { + // Capture a reference to the top-level `Object` constructor. + constructor = members.constructor; + // Use the `constructor` property to simulate `Object#hasOwnProperty` in + // other environments. + isProperty = function (property) { + var parent = (this.constructor || constructor).prototype; + return property in this && !(property in parent && this[property] === parent[property]); + }; + } + members = null; + return isProperty.call(this, property); + }; + } + + // Internal: Normalizes the `for...in` iteration algorithm across + // environments. Each enumerated key is yielded to a `callback` function. + forEach = function (object, callback) { + var size = 0, Properties, members, property; + + // Tests for bugs in the current environment's `for...in` algorithm. The + // `valueOf` property inherits the non-enumerable flag from + // `Object.prototype` in older versions of IE, Netscape, and Mozilla. + (Properties = function () { + this.valueOf = 0; + }).prototype.valueOf = 0; + + // Iterate over a new instance of the `Properties` class. + members = new Properties(); + for (property in members) { + // Ignore all properties inherited from `Object.prototype`. + if (isProperty.call(members, property)) { + size++; + } + } + Properties = members = null; + + // Normalize the iteration algorithm. + if (!size) { + // A list of non-enumerable properties inherited from `Object.prototype`. + members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; + // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable + // properties. + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, length; + var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; + for (property in object) { + // Gecko <= 1.0 enumerates the `prototype` property of functions under + // certain conditions; IE does not. + if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { + callback(property); + } + } + // Manually invoke the callback for each non-enumerable property. + for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); + }; + } else if (size == 2) { + // Safari <= 2.0.4 enumerates shadowed properties twice. + forEach = function (object, callback) { + // Create a set of iterated properties. + var members = {}, isFunction = getClass.call(object) == functionClass, property; + for (property in object) { + // Store each property name to prevent double enumeration. The + // `prototype` property of functions is not enumerated due to cross- + // environment inconsistencies. + if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { + callback(property); + } + } + }; + } else { + // No bugs detected; use the standard `for...in` algorithm. + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, isConstructor; + for (property in object) { + if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { + callback(property); + } + } + // Manually invoke the callback for the `constructor` property due to + // cross-environment inconsistencies. + if (isConstructor || isProperty.call(object, (property = "constructor"))) { + callback(property); + } + }; + } + return forEach(object, callback); + }; + + // Public: Serializes a JavaScript `value` as a JSON string. The optional + // `filter` argument may specify either a function that alters how object and + // array members are serialized, or an array of strings and numbers that + // indicates which properties should be serialized. The optional `width` + // argument may be either a string or number that specifies the indentation + // level of the output. + if (!has("json-stringify")) { + // Internal: A map of control characters and their escaped equivalents. + var Escapes = { + 92: "\\\\", + 34: '\\"', + 8: "\\b", + 12: "\\f", + 10: "\\n", + 13: "\\r", + 9: "\\t" + }; + + // Internal: Converts `value` into a zero-padded string such that its + // length is at least equal to `width`. The `width` must be <= 6. + var leadingZeroes = "000000"; + var toPaddedString = function (width, value) { + // The `|| 0` expression is necessary to work around a bug in + // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. + return (leadingZeroes + (value || 0)).slice(-width); + }; + + // Internal: Double-quotes a string `value`, replacing all ASCII control + // characters (characters with code unit values between 0 and 31) with + // their escaped equivalents. This is an implementation of the + // `Quote(value)` operation defined in ES 5.1 section 15.12.3. + var unicodePrefix = "\\u00"; + var quote = function (value) { + var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; + var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); + for (; index < length; index++) { + var charCode = value.charCodeAt(index); + // If the character is a control character, append its Unicode or + // shorthand escape sequence; otherwise, append the character as-is. + switch (charCode) { + case 8: case 9: case 10: case 12: case 13: case 34: case 92: + result += Escapes[charCode]; + break; + default: + if (charCode < 32) { + result += unicodePrefix + toPaddedString(2, charCode.toString(16)); + break; + } + result += useCharIndex ? symbols[index] : value.charAt(index); + } + } + return result + '"'; + }; + + // Internal: Recursively serializes an object. Implements the + // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. + var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { + var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; + try { + // Necessary for host object support. + value = object[property]; + } catch (exception) {} + if (typeof value == "object" && value) { + className = getClass.call(value); + if (className == dateClass && !isProperty.call(value, "toJSON")) { + if (value > -1 / 0 && value < 1 / 0) { + // Dates are serialized according to the `Date#toJSON` method + // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 + // for the ISO 8601 date time string format. + if (getDay) { + // Manually compute the year, month, date, hours, minutes, + // seconds, and milliseconds if the `getUTC*` methods are + // buggy. Adapted from @Yaffle's `date-shim` project. + date = floor(value / 864e5); + for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); + for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); + date = 1 + date - getDay(year, month); + // The `time` value specifies the time within the day (see ES + // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used + // to compute `A modulo B`, as the `%` operator does not + // correspond to the `modulo` operation for negative numbers. + time = (value % 864e5 + 864e5) % 864e5; + // The hours, minutes, seconds, and milliseconds are obtained by + // decomposing the time within the day. See section 15.9.1.10. + hours = floor(time / 36e5) % 24; + minutes = floor(time / 6e4) % 60; + seconds = floor(time / 1e3) % 60; + milliseconds = time % 1e3; + } else { + year = value.getUTCFullYear(); + month = value.getUTCMonth(); + date = value.getUTCDate(); + hours = value.getUTCHours(); + minutes = value.getUTCMinutes(); + seconds = value.getUTCSeconds(); + milliseconds = value.getUTCMilliseconds(); + } + // Serialize extended years correctly. + value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + + // Months, dates, hours, minutes, and seconds should have two + // digits; milliseconds should have three. + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + + // Milliseconds are optional in ES 5.0, but required in 5.1. + "." + toPaddedString(3, milliseconds) + "Z"; + } else { + value = null; + } + } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { + // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the + // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3 + // ignores all `toJSON` methods on these objects unless they are + // defined directly on an instance. + value = value.toJSON(property); + } + } + if (callback) { + // If a replacement function was provided, call it to obtain the value + // for serialization. + value = callback.call(object, property, value); + } + if (value === null) { + return "null"; + } + className = getClass.call(value); + if (className == booleanClass) { + // Booleans are represented literally. + return "" + value; + } else if (className == numberClass) { + // JSON numbers must be finite. `Infinity` and `NaN` are serialized as + // `"null"`. + return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; + } else if (className == stringClass) { + // Strings are double-quoted and escaped. + return quote("" + value); + } + // Recursively serialize objects and arrays. + if (typeof value == "object") { + // Check for cyclic structures. This is a linear search; performance + // is inversely proportional to the number of unique nested objects. + for (length = stack.length; length--;) { + if (stack[length] === value) { + // Cyclic structures cannot be serialized by `JSON.stringify`. + throw TypeError(); + } + } + // Add the object to the stack of traversed objects. + stack.push(value); + results = []; + // Save the current indentation level and indent one additional level. + prefix = indentation; + indentation += whitespace; + if (className == arrayClass) { + // Recursively serialize array elements. + for (index = 0, length = value.length; index < length; index++) { + element = serialize(index, value, callback, properties, whitespace, indentation, stack); + results.push(element === undef ? "null" : element); + } + result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; + } else { + // Recursively serialize object members. Members are selected from + // either a user-specified list of property names, or the object + // itself. + forEach(properties || value, function (property) { + var element = serialize(property, value, callback, properties, whitespace, indentation, stack); + if (element !== undef) { + // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} + // is not the empty string, let `member` {quote(property) + ":"} + // be the concatenation of `member` and the `space` character." + // The "`space` character" refers to the literal space + // character, not the `space` {width} argument provided to + // `JSON.stringify`. + results.push(quote(property) + ":" + (whitespace ? " " : "") + element); + } + }); + result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; + } + // Remove the object from the traversed object stack. + stack.pop(); + return result; + } + }; + + // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. + exports.stringify = function (source, filter, width) { + var whitespace, callback, properties, className; + if (objectTypes[typeof filter] && filter) { + if ((className = getClass.call(filter)) == functionClass) { + callback = filter; + } else if (className == arrayClass) { + // Convert the property names array into a makeshift set. + properties = {}; + for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); + } + } + if (width) { + if ((className = getClass.call(width)) == numberClass) { + // Convert the `width` to an integer and create a string containing + // `width` number of space characters. + if ((width -= width % 1) > 0) { + for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); + } + } else if (className == stringClass) { + whitespace = width.length <= 10 ? width : width.slice(0, 10); + } + } + // Opera <= 7.54u2 discards the values associated with empty string keys + // (`""`) only if they are used directly within an object member list + // (e.g., `!("" in { "": 1})`). + return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); + }; + } + + // Public: Parses a JSON source string. + if (!has("json-parse")) { + var fromCharCode = String.fromCharCode; + + // Internal: A map of escaped control characters and their unescaped + // equivalents. + var Unescapes = { + 92: "\\", + 34: '"', + 47: "/", + 98: "\b", + 116: "\t", + 110: "\n", + 102: "\f", + 114: "\r" + }; + + // Internal: Stores the parser state. + var Index, Source; + + // Internal: Resets the parser state and throws a `SyntaxError`. + var abort = function () { + Index = Source = null; + throw SyntaxError(); + }; + + // Internal: Returns the next token, or `"$"` if the parser has reached + // the end of the source string. A token may be a string, number, `null` + // literal, or Boolean literal. + var lex = function () { + var source = Source, length = source.length, value, begin, position, isSigned, charCode; + while (Index < length) { + charCode = source.charCodeAt(Index); + switch (charCode) { + case 9: case 10: case 13: case 32: + // Skip whitespace tokens, including tabs, carriage returns, line + // feeds, and space characters. + Index++; + break; + case 123: case 125: case 91: case 93: case 58: case 44: + // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at + // the current position. + value = charIndexBuggy ? source.charAt(Index) : source[Index]; + Index++; + return value; + case 34: + // `"` delimits a JSON string; advance to the next character and + // begin parsing the string. String tokens are prefixed with the + // sentinel `@` character to distinguish them from punctuators and + // end-of-string tokens. + for (value = "@", Index++; Index < length;) { + charCode = source.charCodeAt(Index); + if (charCode < 32) { + // Unescaped ASCII control characters (those with a code unit + // less than the space character) are not permitted. + abort(); + } else if (charCode == 92) { + // A reverse solidus (`\`) marks the beginning of an escaped + // control character (including `"`, `\`, and `/`) or Unicode + // escape sequence. + charCode = source.charCodeAt(++Index); + switch (charCode) { + case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: + // Revive escaped control characters. + value += Unescapes[charCode]; + Index++; + break; + case 117: + // `\u` marks the beginning of a Unicode escape sequence. + // Advance to the first character and validate the + // four-digit code point. + begin = ++Index; + for (position = Index + 4; Index < position; Index++) { + charCode = source.charCodeAt(Index); + // A valid sequence comprises four hexdigits (case- + // insensitive) that form a single hexadecimal value. + if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { + // Invalid Unicode escape sequence. + abort(); + } + } + // Revive the escaped character. + value += fromCharCode("0x" + source.slice(begin, Index)); + break; + default: + // Invalid escape sequence. + abort(); + } + } else { + if (charCode == 34) { + // An unescaped double-quote character marks the end of the + // string. + break; + } + charCode = source.charCodeAt(Index); + begin = Index; + // Optimize for the common case where a string is valid. + while (charCode >= 32 && charCode != 92 && charCode != 34) { + charCode = source.charCodeAt(++Index); + } + // Append the string as-is. + value += source.slice(begin, Index); + } + } + if (source.charCodeAt(Index) == 34) { + // Advance to the next character and return the revived string. + Index++; + return value; + } + // Unterminated string. + abort(); + default: + // Parse numbers and literals. + begin = Index; + // Advance past the negative sign, if one is specified. + if (charCode == 45) { + isSigned = true; + charCode = source.charCodeAt(++Index); + } + // Parse an integer or floating-point value. + if (charCode >= 48 && charCode <= 57) { + // Leading zeroes are interpreted as octal literals. + if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { + // Illegal octal literal. + abort(); + } + isSigned = false; + // Parse the integer component. + for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); + // Floats cannot contain a leading decimal point; however, this + // case is already accounted for by the parser. + if (source.charCodeAt(Index) == 46) { + position = ++Index; + // Parse the decimal component. + for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + // Illegal trailing decimal. + abort(); + } + Index = position; + } + // Parse exponents. The `e` denoting the exponent is + // case-insensitive. + charCode = source.charCodeAt(Index); + if (charCode == 101 || charCode == 69) { + charCode = source.charCodeAt(++Index); + // Skip past the sign following the exponent, if one is + // specified. + if (charCode == 43 || charCode == 45) { + Index++; + } + // Parse the exponential component. + for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + // Illegal empty exponent. + abort(); + } + Index = position; + } + // Coerce the parsed value to a JavaScript number. + return +source.slice(begin, Index); + } + // A negative sign may only precede numbers. + if (isSigned) { + abort(); + } + // `true`, `false`, and `null` literals. + if (source.slice(Index, Index + 4) == "true") { + Index += 4; + return true; + } else if (source.slice(Index, Index + 5) == "false") { + Index += 5; + return false; + } else if (source.slice(Index, Index + 4) == "null") { + Index += 4; + return null; + } + // Unrecognized token. + abort(); + } + } + // Return the sentinel `$` character if the parser has reached the end + // of the source string. + return "$"; + }; + + // Internal: Parses a JSON `value` token. + var get = function (value) { + var results, hasMembers; + if (value == "$") { + // Unexpected end of input. + abort(); + } + if (typeof value == "string") { + if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { + // Remove the sentinel `@` character. + return value.slice(1); + } + // Parse object and array literals. + if (value == "[") { + // Parses a JSON array, returning a new JavaScript array. + results = []; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + // A closing square bracket marks the end of the array literal. + if (value == "]") { + break; + } + // If the array literal contains elements, the current token + // should be a comma separating the previous element from the + // next. + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "]") { + // Unexpected trailing `,` in array literal. + abort(); + } + } else { + // A `,` must separate each array element. + abort(); + } + } + // Elisions and leading commas are not permitted. + if (value == ",") { + abort(); + } + results.push(get(value)); + } + return results; + } else if (value == "{") { + // Parses a JSON object, returning a new JavaScript object. + results = {}; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + // A closing curly brace marks the end of the object literal. + if (value == "}") { + break; + } + // If the object literal contains members, the current token + // should be a comma separator. + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "}") { + // Unexpected trailing `,` in object literal. + abort(); + } + } else { + // A `,` must separate each object member. + abort(); + } + } + // Leading commas are not permitted, object property names must be + // double-quoted strings, and a `:` must separate each property + // name and value. + if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { + abort(); + } + results[value.slice(1)] = get(lex()); + } + return results; + } + // Unexpected token encountered. + abort(); + } + return value; + }; + + // Internal: Updates a traversed object member. + var update = function (source, property, callback) { + var element = walk(source, property, callback); + if (element === undef) { + delete source[property]; + } else { + source[property] = element; + } + }; + + // Internal: Recursively traverses a parsed JSON object, invoking the + // `callback` function for each value. This is an implementation of the + // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. + var walk = function (source, property, callback) { + var value = source[property], length; + if (typeof value == "object" && value) { + // `forEach` can't be used to traverse an array in Opera <= 8.54 + // because its `Object#hasOwnProperty` implementation returns `false` + // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). + if (getClass.call(value) == arrayClass) { + for (length = value.length; length--;) { + update(value, length, callback); + } + } else { + forEach(value, function (property) { + update(value, property, callback); + }); + } + } + return callback.call(source, property, value); + }; + + // Public: `JSON.parse`. See ES 5.1 section 15.12.2. + exports.parse = function (source, callback) { + var result, value; + Index = 0; + Source = "" + source; + result = get(lex()); + // If a JSON string contains multiple tokens, it is invalid. + if (lex() != "$") { + abort(); + } + // Reset the parser state. + Index = Source = null; + return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; + }; + } + } + + exports["runInContext"] = runInContext; + return exports; + } + + if (freeExports && !isLoader) { + // Export for CommonJS environments. + runInContext(root, freeExports); + } else { + // Export for web browsers and JavaScript engines. + var nativeJSON = root.JSON, + previousJSON = root["JSON3"], + isRestored = false; + + var JSON3 = runInContext(root, (root["JSON3"] = { + // Public: Restores the original value of the global `JSON` object and + // returns a reference to the `JSON3` object. + "noConflict": function () { + if (!isRestored) { + isRestored = true; + root.JSON = nativeJSON; + root["JSON3"] = previousJSON; + nativeJSON = previousJSON = null; + } + return JSON3; + } + })); + + root.JSON = { + "parse": JSON3.parse, + "stringify": JSON3.stringify + }; + } + + // Export for asynchronous module loaders. + if (isLoader) { + define(function () { + return JSON3; + }); + } +}).call(this); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css new file mode 100644 index 0000000..42b9798 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css @@ -0,0 +1,270 @@ +@charset "utf-8"; + +body { + margin:0; +} + +#mocha { + font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; + margin: 60px 50px; +} + +#mocha ul, +#mocha li { + margin: 0; + padding: 0; +} + +#mocha ul { + list-style: none; +} + +#mocha h1, +#mocha h2 { + margin: 0; +} + +#mocha h1 { + margin-top: 15px; + font-size: 1em; + font-weight: 200; +} + +#mocha h1 a { + text-decoration: none; + color: inherit; +} + +#mocha h1 a:hover { + text-decoration: underline; +} + +#mocha .suite .suite h1 { + margin-top: 0; + font-size: .8em; +} + +#mocha .hidden { + display: none; +} + +#mocha h2 { + font-size: 12px; + font-weight: normal; + cursor: pointer; +} + +#mocha .suite { + margin-left: 15px; +} + +#mocha .test { + margin-left: 15px; + overflow: hidden; +} + +#mocha .test.pending:hover h2::after { + content: '(pending)'; + font-family: arial, sans-serif; +} + +#mocha .test.pass.medium .duration { + background: #c09853; +} + +#mocha .test.pass.slow .duration { + background: #b94a48; +} + +#mocha .test.pass::before { + content: '✓'; + font-size: 12px; + display: block; + float: left; + margin-right: 5px; + color: #00d6b2; +} + +#mocha .test.pass .duration { + font-size: 9px; + margin-left: 5px; + padding: 2px 5px; + color: #fff; + -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + -ms-border-radius: 5px; + -o-border-radius: 5px; + border-radius: 5px; +} + +#mocha .test.pass.fast .duration { + display: none; +} + +#mocha .test.pending { + color: #0b97c4; +} + +#mocha .test.pending::before { + content: '◦'; + color: #0b97c4; +} + +#mocha .test.fail { + color: #c00; +} + +#mocha .test.fail pre { + color: black; +} + +#mocha .test.fail::before { + content: '✖'; + font-size: 12px; + display: block; + float: left; + margin-right: 5px; + color: #c00; +} + +#mocha .test pre.error { + color: #c00; + max-height: 300px; + overflow: auto; +} + +/** + * (1): approximate for browsers not supporting calc + * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border) + * ^^ seriously + */ +#mocha .test pre { + display: block; + float: left; + clear: left; + font: 12px/1.5 monaco, monospace; + margin: 5px; + padding: 15px; + border: 1px solid #eee; + max-width: 85%; /*(1)*/ + max-width: calc(100% - 42px); /*(2)*/ + word-wrap: break-word; + border-bottom-color: #ddd; + -webkit-border-radius: 3px; + -webkit-box-shadow: 0 1px 3px #eee; + -moz-border-radius: 3px; + -moz-box-shadow: 0 1px 3px #eee; + border-radius: 3px; +} + +#mocha .test h2 { + position: relative; +} + +#mocha .test a.replay { + position: absolute; + top: 3px; + right: 0; + text-decoration: none; + vertical-align: middle; + display: block; + width: 15px; + height: 15px; + line-height: 15px; + text-align: center; + background: #eee; + font-size: 15px; + -moz-border-radius: 15px; + border-radius: 15px; + -webkit-transition: opacity 200ms; + -moz-transition: opacity 200ms; + transition: opacity 200ms; + opacity: 0.3; + color: #888; +} + +#mocha .test:hover a.replay { + opacity: 1; +} + +#mocha-report.pass .test.fail { + display: none; +} + +#mocha-report.fail .test.pass { + display: none; +} + +#mocha-report.pending .test.pass, +#mocha-report.pending .test.fail { + display: none; +} +#mocha-report.pending .test.pass.pending { + display: block; +} + +#mocha-error { + color: #c00; + font-size: 1.5em; + font-weight: 100; + letter-spacing: 1px; +} + +#mocha-stats { + position: fixed; + top: 15px; + right: 10px; + font-size: 12px; + margin: 0; + color: #888; + z-index: 1; +} + +#mocha-stats .progress { + float: right; + padding-top: 0; +} + +#mocha-stats em { + color: black; +} + +#mocha-stats a { + text-decoration: none; + color: inherit; +} + +#mocha-stats a:hover { + border-bottom: 1px solid #eee; +} + +#mocha-stats li { + display: inline-block; + margin: 0 5px; + list-style: none; + padding-top: 11px; +} + +#mocha-stats canvas { + width: 40px; + height: 40px; +} + +#mocha code .comment { color: #ddd; } +#mocha code .init { color: #2f6fad; } +#mocha code .string { color: #5890ad; } +#mocha code .keyword { color: #8a6343; } +#mocha code .number { color: #2f6fad; } + +@media screen and (max-device-width: 480px) { + #mocha { + margin: 60px 0px; + } + + #mocha #stats { + position: absolute; + } +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js new file mode 100644 index 0000000..e8bee79 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js @@ -0,0 +1,6095 @@ +;(function(){ + +// CommonJS require() + +function require(p){ + var path = require.resolve(p) + , mod = require.modules[path]; + if (!mod) throw new Error('failed to require "' + p + '"'); + if (!mod.exports) { + mod.exports = {}; + mod.call(mod.exports, mod, mod.exports, require.relative(path)); + } + return mod.exports; + } + +require.modules = {}; + +require.resolve = function (path){ + var orig = path + , reg = path + '.js' + , index = path + '/index.js'; + return require.modules[reg] && reg + || require.modules[index] && index + || orig; + }; + +require.register = function (path, fn){ + require.modules[path] = fn; + }; + +require.relative = function (parent) { + return function(p){ + if ('.' != p.charAt(0)) return require(p); + + var path = parent.split('/') + , segs = p.split('/'); + path.pop(); + + for (var i = 0; i < segs.length; i++) { + var seg = segs[i]; + if ('..' == seg) path.pop(); + else if ('.' != seg) path.push(seg); + } + + return require(path.join('/')); + }; + }; + + +require.register("browser/debug.js", function(module, exports, require){ + +module.exports = function(type){ + return function(){ + } +}; + +}); // module: browser/debug.js + +require.register("browser/diff.js", function(module, exports, require){ +/* See LICENSE file for terms of use */ + +/* + * Text diff implementation. + * + * This library supports the following APIS: + * JsDiff.diffChars: Character by character diff + * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * JsDiff.diffLines: Line based diff + * + * JsDiff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ +var JsDiff = (function() { + /*jshint maxparams: 5*/ + function clonePath(path) { + return { newPos: path.newPos, components: path.components.slice(0) }; + } + function removeEmpty(array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + } + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + + return n; + } + + var Diff = function(ignoreWhitespace) { + this.ignoreWhitespace = ignoreWhitespace; + }; + Diff.prototype = { + diff: function(oldString, newString) { + // Handle the identity case (this is due to unrolling editLength == 0 + if (newString === oldString) { + return [{ value: newString }]; + } + if (!newString) { + return [{ value: oldString, removed: true }]; + } + if (!oldString) { + return [{ value: newString, added: true }]; + } + + newString = this.tokenize(newString); + oldString = this.tokenize(oldString); + + var newLen = newString.length, oldLen = oldString.length; + var maxEditLength = newLen + oldLen; + var bestPath = [{ newPos: -1, components: [] }]; + + // Seed editLength = 0 + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { + return bestPath[0].components; + } + + for (var editLength = 1; editLength <= maxEditLength; editLength++) { + for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { + var basePath; + var addPath = bestPath[diagonalPath-1], + removePath = bestPath[diagonalPath+1]; + oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath-1] = undefined; + } + + var canAdd = addPath && addPath.newPos+1 < newLen; + var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = undefined; + continue; + } + + // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { + basePath = clonePath(removePath); + this.pushComponent(basePath.components, oldString[oldPos], undefined, true); + } else { + basePath = clonePath(addPath); + basePath.newPos++; + this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); + } + + var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); + + if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { + return basePath.components; + } else { + bestPath[diagonalPath] = basePath; + } + } + } + }, + + pushComponent: function(components, value, added, removed) { + var last = components[components.length-1]; + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length-1] = + {value: this.join(last.value, value), added: added, removed: removed }; + } else { + components.push({value: value, added: added, removed: removed }); + } + }, + extractCommon: function(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath; + while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { + newPos++; + oldPos++; + + this.pushComponent(basePath.components, newString[newPos], undefined, undefined); + } + basePath.newPos = newPos; + return oldPos; + }, + + equals: function(left, right) { + var reWhitespace = /\S/; + if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { + return true; + } else { + return left === right; + } + }, + join: function(left, right) { + return left + right; + }, + tokenize: function(value) { + return value; + } + }; + + var CharDiff = new Diff(); + + var WordDiff = new Diff(true); + var WordWithSpaceDiff = new Diff(); + WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { + return removeEmpty(value.split(/(\s+|\b)/)); + }; + + var CssDiff = new Diff(true); + CssDiff.tokenize = function(value) { + return removeEmpty(value.split(/([{}:;,]|\s+)/)); + }; + + var LineDiff = new Diff(); + LineDiff.tokenize = function(value) { + var retLines = [], + lines = value.split(/^/m); + + for(var i = 0; i < lines.length; i++) { + var line = lines[i], + lastLine = lines[i - 1]; + + // Merge lines that may contain windows new lines + if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') { + retLines[retLines.length - 1] += '\n'; + } else if (line) { + retLines.push(line); + } + } + + return retLines; + }; + + return { + Diff: Diff, + + diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, + diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, + diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, + diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, + + diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, + + createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { + var ret = []; + + ret.push('Index: ' + fileName); + ret.push('==================================================================='); + ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); + ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); + + var diff = LineDiff.diff(oldStr, newStr); + if (!diff[diff.length-1].value) { + diff.pop(); // Remove trailing newline add + } + diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function(entry) { return ' ' + entry; }); + } + function eofNL(curRange, i, current) { + var last = diff[diff.length-2], + isLast = i === diff.length-2, + isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); + + // Figure out if this is the last line for the given file and missing NL + if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { + curRange.push('\\ No newline at end of file'); + } + } + + var oldRangeStart = 0, newRangeStart = 0, curRange = [], + oldLine = 1, newLine = 1; + for (var i = 0; i < diff.length; i++) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + if (!oldRangeStart) { + var prev = diff[i-1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = contextLines(prev.lines.slice(-4)); + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); + eofNL(curRange, i, current); + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= 8 && i < diff.length-2) { + // Overlapping + curRange.push.apply(curRange, contextLines(lines)); + } else { + // end the range and output + var contextSize = Math.min(lines.length, 4); + ret.push( + '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) + + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) + + ' @@'); + ret.push.apply(ret, curRange); + ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); + if (lines.length <= 4) { + eofNL(ret, i, current); + } + + oldRangeStart = 0; newRangeStart = 0; curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; + } + } + + return ret.join('\n') + '\n'; + }, + + applyPatch: function(oldStr, uniDiff) { + var diffstr = uniDiff.split('\n'); + var diff = []; + var remEOFNL = false, + addEOFNL = false; + + for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { + if(diffstr[i][0] === '@') { + var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); + diff.unshift({ + start:meh[3], + oldlength:meh[2], + oldlines:[], + newlength:meh[4], + newlines:[] + }); + } else if(diffstr[i][0] === '+') { + diff[0].newlines.push(diffstr[i].substr(1)); + } else if(diffstr[i][0] === '-') { + diff[0].oldlines.push(diffstr[i].substr(1)); + } else if(diffstr[i][0] === ' ') { + diff[0].newlines.push(diffstr[i].substr(1)); + diff[0].oldlines.push(diffstr[i].substr(1)); + } else if(diffstr[i][0] === '\\') { + if (diffstr[i-1][0] === '+') { + remEOFNL = true; + } else if(diffstr[i-1][0] === '-') { + addEOFNL = true; + } + } + } + + var str = oldStr.split('\n'); + for (var i = diff.length - 1; i >= 0; i--) { + var d = diff[i]; + for (var j = 0; j < d.oldlength; j++) { + if(str[d.start-1+j] !== d.oldlines[j]) { + return false; + } + } + Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); + } + + if (remEOFNL) { + while (!str[str.length-1]) { + str.pop(); + } + } else if (addEOFNL) { + str.push(''); + } + return str.join('\n'); + }, + + convertChangesToXML: function(changes){ + var ret = []; + for ( var i = 0; i < changes.length; i++) { + var change = changes[i]; + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + return ret.join(''); + }, + + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + convertChangesToDMP: function(changes){ + var ret = [], change; + for ( var i = 0; i < changes.length; i++) { + change = changes[i]; + ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); + } + return ret; + } + }; +})(); + +if (typeof module !== 'undefined') { + module.exports = JsDiff; +} + +}); // module: browser/diff.js + +require.register("browser/escape-string-regexp.js", function(module, exports, require){ +'use strict'; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +}); // module: browser/escape-string-regexp.js + +require.register("browser/events.js", function(module, exports, require){ + +/** + * Module exports. + */ + +exports.EventEmitter = EventEmitter; + +/** + * Check if `obj` is an array. + */ + +function isArray(obj) { + return '[object Array]' == {}.toString.call(obj); +} + +/** + * Event emitter constructor. + * + * @api public + */ + +function EventEmitter(){}; + +/** + * Adds a listener. + * + * @api public + */ + +EventEmitter.prototype.on = function (name, fn) { + if (!this.$events) { + this.$events = {}; + } + + if (!this.$events[name]) { + this.$events[name] = fn; + } else if (isArray(this.$events[name])) { + this.$events[name].push(fn); + } else { + this.$events[name] = [this.$events[name], fn]; + } + + return this; +}; + +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +/** + * Adds a volatile listener. + * + * @api public + */ + +EventEmitter.prototype.once = function (name, fn) { + var self = this; + + function on () { + self.removeListener(name, on); + fn.apply(this, arguments); + }; + + on.listener = fn; + this.on(name, on); + + return this; +}; + +/** + * Removes a listener. + * + * @api public + */ + +EventEmitter.prototype.removeListener = function (name, fn) { + if (this.$events && this.$events[name]) { + var list = this.$events[name]; + + if (isArray(list)) { + var pos = -1; + + for (var i = 0, l = list.length; i < l; i++) { + if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { + pos = i; + break; + } + } + + if (pos < 0) { + return this; + } + + list.splice(pos, 1); + + if (!list.length) { + delete this.$events[name]; + } + } else if (list === fn || (list.listener && list.listener === fn)) { + delete this.$events[name]; + } + } + + return this; +}; + +/** + * Removes all listeners for an event. + * + * @api public + */ + +EventEmitter.prototype.removeAllListeners = function (name) { + if (name === undefined) { + this.$events = {}; + return this; + } + + if (this.$events && this.$events[name]) { + this.$events[name] = null; + } + + return this; +}; + +/** + * Gets all listeners for a certain event. + * + * @api public + */ + +EventEmitter.prototype.listeners = function (name) { + if (!this.$events) { + this.$events = {}; + } + + if (!this.$events[name]) { + this.$events[name] = []; + } + + if (!isArray(this.$events[name])) { + this.$events[name] = [this.$events[name]]; + } + + return this.$events[name]; +}; + +/** + * Emits an event. + * + * @api public + */ + +EventEmitter.prototype.emit = function (name) { + if (!this.$events) { + return false; + } + + var handler = this.$events[name]; + + if (!handler) { + return false; + } + + var args = [].slice.call(arguments, 1); + + if ('function' == typeof handler) { + handler.apply(this, args); + } else if (isArray(handler)) { + var listeners = handler.slice(); + + for (var i = 0, l = listeners.length; i < l; i++) { + listeners[i].apply(this, args); + } + } else { + return false; + } + + return true; +}; +}); // module: browser/events.js + +require.register("browser/fs.js", function(module, exports, require){ + +}); // module: browser/fs.js + +require.register("browser/glob.js", function(module, exports, require){ + +}); // module: browser/glob.js + +require.register("browser/path.js", function(module, exports, require){ + +}); // module: browser/path.js + +require.register("browser/progress.js", function(module, exports, require){ +/** + * Expose `Progress`. + */ + +module.exports = Progress; + +/** + * Initialize a new `Progress` indicator. + */ + +function Progress() { + this.percent = 0; + this.size(0); + this.fontSize(11); + this.font('helvetica, arial, sans-serif'); +} + +/** + * Set progress size to `n`. + * + * @param {Number} n + * @return {Progress} for chaining + * @api public + */ + +Progress.prototype.size = function(n){ + this._size = n; + return this; +}; + +/** + * Set text to `str`. + * + * @param {String} str + * @return {Progress} for chaining + * @api public + */ + +Progress.prototype.text = function(str){ + this._text = str; + return this; +}; + +/** + * Set font size to `n`. + * + * @param {Number} n + * @return {Progress} for chaining + * @api public + */ + +Progress.prototype.fontSize = function(n){ + this._fontSize = n; + return this; +}; + +/** + * Set font `family`. + * + * @param {String} family + * @return {Progress} for chaining + */ + +Progress.prototype.font = function(family){ + this._font = family; + return this; +}; + +/** + * Update percentage to `n`. + * + * @param {Number} n + * @return {Progress} for chaining + */ + +Progress.prototype.update = function(n){ + this.percent = n; + return this; +}; + +/** + * Draw on `ctx`. + * + * @param {CanvasRenderingContext2d} ctx + * @return {Progress} for chaining + */ + +Progress.prototype.draw = function(ctx){ + try { + var percent = Math.min(this.percent, 100) + , size = this._size + , half = size / 2 + , x = half + , y = half + , rad = half - 1 + , fontSize = this._fontSize; + + ctx.font = fontSize + 'px ' + this._font; + + var angle = Math.PI * 2 * (percent / 100); + ctx.clearRect(0, 0, size, size); + + // outer circle + ctx.strokeStyle = '#9f9f9f'; + ctx.beginPath(); + ctx.arc(x, y, rad, 0, angle, false); + ctx.stroke(); + + // inner circle + ctx.strokeStyle = '#eee'; + ctx.beginPath(); + ctx.arc(x, y, rad - 1, 0, angle, true); + ctx.stroke(); + + // text + var text = this._text || (percent | 0) + '%' + , w = ctx.measureText(text).width; + + ctx.fillText( + text + , x - w / 2 + 1 + , y + fontSize / 2 - 1); + } catch (ex) {} //don't fail if we can't render progress + return this; +}; + +}); // module: browser/progress.js + +require.register("browser/tty.js", function(module, exports, require){ + +exports.isatty = function(){ + return true; +}; + +exports.getWindowSize = function(){ + if ('innerHeight' in global) { + return [global.innerHeight, global.innerWidth]; + } else { + // In a Web Worker, the DOM Window is not available. + return [640, 480]; + } +}; + +}); // module: browser/tty.js + +require.register("context.js", function(module, exports, require){ + +/** + * Expose `Context`. + */ + +module.exports = Context; + +/** + * Initialize a new `Context`. + * + * @api private + */ + +function Context(){} + +/** + * Set or get the context `Runnable` to `runnable`. + * + * @param {Runnable} runnable + * @return {Context} + * @api private + */ + +Context.prototype.runnable = function(runnable){ + if (0 == arguments.length) return this._runnable; + this.test = this._runnable = runnable; + return this; +}; + +/** + * Set test timeout `ms`. + * + * @param {Number} ms + * @return {Context} self + * @api private + */ + +Context.prototype.timeout = function(ms){ + if (arguments.length === 0) return this.runnable().timeout(); + this.runnable().timeout(ms); + return this; +}; + +/** + * Set test timeout `enabled`. + * + * @param {Boolean} enabled + * @return {Context} self + * @api private + */ + +Context.prototype.enableTimeouts = function (enabled) { + this.runnable().enableTimeouts(enabled); + return this; +}; + + +/** + * Set test slowness threshold `ms`. + * + * @param {Number} ms + * @return {Context} self + * @api private + */ + +Context.prototype.slow = function(ms){ + this.runnable().slow(ms); + return this; +}; + +/** + * Inspect the context void of `._runnable`. + * + * @return {String} + * @api private + */ + +Context.prototype.inspect = function(){ + return JSON.stringify(this, function(key, val){ + if ('_runnable' == key) return; + if ('test' == key) return; + return val; + }, 2); +}; + +}); // module: context.js + +require.register("hook.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Runnable = require('./runnable'); + +/** + * Expose `Hook`. + */ + +module.exports = Hook; + +/** + * Initialize a new `Hook` with the given `title` and callback `fn`. + * + * @param {String} title + * @param {Function} fn + * @api private + */ + +function Hook(title, fn) { + Runnable.call(this, title, fn); + this.type = 'hook'; +} + +/** + * Inherit from `Runnable.prototype`. + */ + +function F(){}; +F.prototype = Runnable.prototype; +Hook.prototype = new F; +Hook.prototype.constructor = Hook; + + +/** + * Get or set the test `err`. + * + * @param {Error} err + * @return {Error} + * @api public + */ + +Hook.prototype.error = function(err){ + if (0 == arguments.length) { + var err = this._error; + this._error = null; + return err; + } + + this._error = err; +}; + +}); // module: hook.js + +require.register("interfaces/bdd.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') + , Test = require('../test') + , utils = require('../utils') + , escapeRe = require('browser/escape-string-regexp'); + +/** + * BDD-style interface: + * + * describe('Array', function(){ + * describe('#indexOf()', function(){ + * it('should return -1 when not present', function(){ + * + * }); + * + * it('should return the index when present', function(){ + * + * }); + * }); + * }); + * + */ + +module.exports = function(suite){ + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha){ + + /** + * Execute before running tests. + */ + + context.before = function(name, fn){ + suites[0].beforeAll(name, fn); + }; + + /** + * Execute after running tests. + */ + + context.after = function(name, fn){ + suites[0].afterAll(name, fn); + }; + + /** + * Execute before each test case. + */ + + context.beforeEach = function(name, fn){ + suites[0].beforeEach(name, fn); + }; + + /** + * Execute after each test case. + */ + + context.afterEach = function(name, fn){ + suites[0].afterEach(name, fn); + }; + + /** + * Describe a "suite" with the given `title` + * and callback `fn` containing nested suites + * and/or tests. + */ + + context.describe = context.context = function(title, fn){ + var suite = Suite.create(suites[0], title); + suite.file = file; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + return suite; + }; + + /** + * Pending describe. + */ + + context.xdescribe = + context.xcontext = + context.describe.skip = function(title, fn){ + var suite = Suite.create(suites[0], title); + suite.pending = true; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + }; + + /** + * Exclusive suite. + */ + + context.describe.only = function(title, fn){ + var suite = context.describe(title, fn); + mocha.grep(suite.fullTitle()); + return suite; + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.it = context.specify = function(title, fn){ + var suite = suites[0]; + if (suite.pending) fn = null; + var test = new Test(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.it.only = function(title, fn){ + var test = context.it(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); + return test; + }; + + /** + * Pending test case. + */ + + context.xit = + context.xspecify = + context.it.skip = function(title){ + context.it(title); + }; + }); +}; + +}); // module: interfaces/bdd.js + +require.register("interfaces/exports.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') + , Test = require('../test'); + +/** + * TDD-style interface: + * + * exports.Array = { + * '#indexOf()': { + * 'should return -1 when the value is not present': function(){ + * + * }, + * + * 'should return the correct index when the value is present': function(){ + * + * } + * } + * }; + * + */ + +module.exports = function(suite){ + var suites = [suite]; + + suite.on('require', visit); + + function visit(obj, file) { + var suite; + for (var key in obj) { + if ('function' == typeof obj[key]) { + var fn = obj[key]; + switch (key) { + case 'before': + suites[0].beforeAll(fn); + break; + case 'after': + suites[0].afterAll(fn); + break; + case 'beforeEach': + suites[0].beforeEach(fn); + break; + case 'afterEach': + suites[0].afterEach(fn); + break; + default: + var test = new Test(key, fn); + test.file = file; + suites[0].addTest(test); + } + } else { + suite = Suite.create(suites[0], key); + suites.unshift(suite); + visit(obj[key]); + suites.shift(); + } + } + } +}; + +}); // module: interfaces/exports.js + +require.register("interfaces/index.js", function(module, exports, require){ + +exports.bdd = require('./bdd'); +exports.tdd = require('./tdd'); +exports.qunit = require('./qunit'); +exports.exports = require('./exports'); + +}); // module: interfaces/index.js + +require.register("interfaces/qunit.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') + , Test = require('../test') + , escapeRe = require('browser/escape-string-regexp') + , utils = require('../utils'); + +/** + * QUnit-style interface: + * + * suite('Array'); + * + * test('#length', function(){ + * var arr = [1,2,3]; + * ok(arr.length == 3); + * }); + * + * test('#indexOf()', function(){ + * var arr = [1,2,3]; + * ok(arr.indexOf(1) == 0); + * ok(arr.indexOf(2) == 1); + * ok(arr.indexOf(3) == 2); + * }); + * + * suite('String'); + * + * test('#length', function(){ + * ok('foo'.length == 3); + * }); + * + */ + +module.exports = function(suite){ + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha){ + + /** + * Execute before running tests. + */ + + context.before = function(name, fn){ + suites[0].beforeAll(name, fn); + }; + + /** + * Execute after running tests. + */ + + context.after = function(name, fn){ + suites[0].afterAll(name, fn); + }; + + /** + * Execute before each test case. + */ + + context.beforeEach = function(name, fn){ + suites[0].beforeEach(name, fn); + }; + + /** + * Execute after each test case. + */ + + context.afterEach = function(name, fn){ + suites[0].afterEach(name, fn); + }; + + /** + * Describe a "suite" with the given `title`. + */ + + context.suite = function(title){ + if (suites.length > 1) suites.shift(); + var suite = Suite.create(suites[0], title); + suite.file = file; + suites.unshift(suite); + return suite; + }; + + /** + * Exclusive test-case. + */ + + context.suite.only = function(title, fn){ + var suite = context.suite(title, fn); + mocha.grep(suite.fullTitle()); + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.test = function(title, fn){ + var test = new Test(title, fn); + test.file = file; + suites[0].addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn){ + var test = context.test(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); + }; + + /** + * Pending test case. + */ + + context.test.skip = function(title){ + context.test(title); + }; + }); +}; + +}); // module: interfaces/qunit.js + +require.register("interfaces/tdd.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') + , Test = require('../test') + , escapeRe = require('browser/escape-string-regexp') + , utils = require('../utils'); + +/** + * TDD-style interface: + * + * suite('Array', function(){ + * suite('#indexOf()', function(){ + * suiteSetup(function(){ + * + * }); + * + * test('should return -1 when not present', function(){ + * + * }); + * + * test('should return the index when present', function(){ + * + * }); + * + * suiteTeardown(function(){ + * + * }); + * }); + * }); + * + */ + +module.exports = function(suite){ + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha){ + + /** + * Execute before each test case. + */ + + context.setup = function(name, fn){ + suites[0].beforeEach(name, fn); + }; + + /** + * Execute after each test case. + */ + + context.teardown = function(name, fn){ + suites[0].afterEach(name, fn); + }; + + /** + * Execute before the suite. + */ + + context.suiteSetup = function(name, fn){ + suites[0].beforeAll(name, fn); + }; + + /** + * Execute after the suite. + */ + + context.suiteTeardown = function(name, fn){ + suites[0].afterAll(name, fn); + }; + + /** + * Describe a "suite" with the given `title` + * and callback `fn` containing nested suites + * and/or tests. + */ + + context.suite = function(title, fn){ + var suite = Suite.create(suites[0], title); + suite.file = file; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + return suite; + }; + + /** + * Pending suite. + */ + context.suite.skip = function(title, fn) { + var suite = Suite.create(suites[0], title); + suite.pending = true; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + }; + + /** + * Exclusive test-case. + */ + + context.suite.only = function(title, fn){ + var suite = context.suite(title, fn); + mocha.grep(suite.fullTitle()); + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.test = function(title, fn){ + var suite = suites[0]; + if (suite.pending) fn = null; + var test = new Test(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn){ + var test = context.test(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); + }; + + /** + * Pending test case. + */ + + context.test.skip = function(title){ + context.test(title); + }; + }); +}; + +}); // module: interfaces/tdd.js + +require.register("mocha.js", function(module, exports, require){ +/*! + * mocha + * Copyright(c) 2011 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var path = require('browser/path') + , escapeRe = require('browser/escape-string-regexp') + , utils = require('./utils'); + +/** + * Expose `Mocha`. + */ + +exports = module.exports = Mocha; + +/** + * To require local UIs and reporters when running in node. + */ + +if (typeof process !== 'undefined' && typeof process.cwd === 'function') { + var join = path.join + , cwd = process.cwd(); + module.paths.push(cwd, join(cwd, 'node_modules')); +} + +/** + * Expose internals. + */ + +exports.utils = utils; +exports.interfaces = require('./interfaces'); +exports.reporters = require('./reporters'); +exports.Runnable = require('./runnable'); +exports.Context = require('./context'); +exports.Runner = require('./runner'); +exports.Suite = require('./suite'); +exports.Hook = require('./hook'); +exports.Test = require('./test'); + +/** + * Return image `name` path. + * + * @param {String} name + * @return {String} + * @api private + */ + +function image(name) { + return __dirname + '/../images/' + name + '.png'; +} + +/** + * Setup mocha with `options`. + * + * Options: + * + * - `ui` name "bdd", "tdd", "exports" etc + * - `reporter` reporter instance, defaults to `mocha.reporters.spec` + * - `globals` array of accepted globals + * - `timeout` timeout in milliseconds + * - `bail` bail on the first test failure + * - `slow` milliseconds to wait before considering a test slow + * - `ignoreLeaks` ignore global leaks + * - `grep` string or regexp to filter tests with + * + * @param {Object} options + * @api public + */ + +function Mocha(options) { + options = options || {}; + this.files = []; + this.options = options; + this.grep(options.grep); + this.suite = new exports.Suite('', new exports.Context); + this.ui(options.ui); + this.bail(options.bail); + this.reporter(options.reporter); + if (null != options.timeout) this.timeout(options.timeout); + this.useColors(options.useColors) + if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts); + if (options.slow) this.slow(options.slow); + + this.suite.on('pre-require', function (context) { + exports.afterEach = context.afterEach || context.teardown; + exports.after = context.after || context.suiteTeardown; + exports.beforeEach = context.beforeEach || context.setup; + exports.before = context.before || context.suiteSetup; + exports.describe = context.describe || context.suite; + exports.it = context.it || context.test; + exports.setup = context.setup || context.beforeEach; + exports.suiteSetup = context.suiteSetup || context.before; + exports.suiteTeardown = context.suiteTeardown || context.after; + exports.suite = context.suite || context.describe; + exports.teardown = context.teardown || context.afterEach; + exports.test = context.test || context.it; + }); +} + +/** + * Enable or disable bailing on the first failure. + * + * @param {Boolean} [bail] + * @api public + */ + +Mocha.prototype.bail = function(bail){ + if (0 == arguments.length) bail = true; + this.suite.bail(bail); + return this; +}; + +/** + * Add test `file`. + * + * @param {String} file + * @api public + */ + +Mocha.prototype.addFile = function(file){ + this.files.push(file); + return this; +}; + +/** + * Set reporter to `reporter`, defaults to "spec". + * + * @param {String|Function} reporter name or constructor + * @api public + */ + +Mocha.prototype.reporter = function(reporter){ + if ('function' == typeof reporter) { + this._reporter = reporter; + } else { + reporter = reporter || 'spec'; + var _reporter; + try { _reporter = require('./reporters/' + reporter); } catch (err) {}; + if (!_reporter) try { _reporter = require(reporter); } catch (err) {}; + if (!_reporter && reporter === 'teamcity') + console.warn('The Teamcity reporter was moved to a package named ' + + 'mocha-teamcity-reporter ' + + '(https://npmjs.org/package/mocha-teamcity-reporter).'); + if (!_reporter) throw new Error('invalid reporter "' + reporter + '"'); + this._reporter = _reporter; + } + return this; +}; + +/** + * Set test UI `name`, defaults to "bdd". + * + * @param {String} bdd + * @api public + */ + +Mocha.prototype.ui = function(name){ + name = name || 'bdd'; + this._ui = exports.interfaces[name]; + if (!this._ui) try { this._ui = require(name); } catch (err) {}; + if (!this._ui) throw new Error('invalid interface "' + name + '"'); + this._ui = this._ui(this.suite); + return this; +}; + +/** + * Load registered files. + * + * @api private + */ + +Mocha.prototype.loadFiles = function(fn){ + var self = this; + var suite = this.suite; + var pending = this.files.length; + this.files.forEach(function(file){ + file = path.resolve(file); + suite.emit('pre-require', global, file, self); + suite.emit('require', require(file), file, self); + suite.emit('post-require', global, file, self); + --pending || (fn && fn()); + }); +}; + +/** + * Enable growl support. + * + * @api private + */ + +Mocha.prototype._growl = function(runner, reporter) { + var notify = require('growl'); + + runner.on('end', function(){ + var stats = reporter.stats; + if (stats.failures) { + var msg = stats.failures + ' of ' + runner.total + ' tests failed'; + notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); + } else { + notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { + name: 'mocha' + , title: 'Passed' + , image: image('ok') + }); + } + }); +}; + +/** + * Add regexp to grep, if `re` is a string it is escaped. + * + * @param {RegExp|String} re + * @return {Mocha} + * @api public + */ + +Mocha.prototype.grep = function(re){ + this.options.grep = 'string' == typeof re + ? new RegExp(escapeRe(re)) + : re; + return this; +}; + +/** + * Invert `.grep()` matches. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.invert = function(){ + this.options.invert = true; + return this; +}; + +/** + * Ignore global leaks. + * + * @param {Boolean} ignore + * @return {Mocha} + * @api public + */ + +Mocha.prototype.ignoreLeaks = function(ignore){ + this.options.ignoreLeaks = !!ignore; + return this; +}; + +/** + * Enable global leak checking. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.checkLeaks = function(){ + this.options.ignoreLeaks = false; + return this; +}; + +/** + * Enable growl support. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.growl = function(){ + this.options.growl = true; + return this; +}; + +/** + * Ignore `globals` array or string. + * + * @param {Array|String} globals + * @return {Mocha} + * @api public + */ + +Mocha.prototype.globals = function(globals){ + this.options.globals = (this.options.globals || []).concat(globals); + return this; +}; + +/** + * Emit color output. + * + * @param {Boolean} colors + * @return {Mocha} + * @api public + */ + +Mocha.prototype.useColors = function(colors){ + this.options.useColors = arguments.length && colors != undefined + ? colors + : true; + return this; +}; + +/** + * Use inline diffs rather than +/-. + * + * @param {Boolean} inlineDiffs + * @return {Mocha} + * @api public + */ + +Mocha.prototype.useInlineDiffs = function(inlineDiffs) { + this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined + ? inlineDiffs + : false; + return this; +}; + +/** + * Set the timeout in milliseconds. + * + * @param {Number} timeout + * @return {Mocha} + * @api public + */ + +Mocha.prototype.timeout = function(timeout){ + this.suite.timeout(timeout); + return this; +}; + +/** + * Set slowness threshold in milliseconds. + * + * @param {Number} slow + * @return {Mocha} + * @api public + */ + +Mocha.prototype.slow = function(slow){ + this.suite.slow(slow); + return this; +}; + +/** + * Enable timeouts. + * + * @param {Boolean} enabled + * @return {Mocha} + * @api public + */ + +Mocha.prototype.enableTimeouts = function(enabled) { + this.suite.enableTimeouts(arguments.length && enabled !== undefined + ? enabled + : true); + return this +}; + +/** + * Makes all tests async (accepting a callback) + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.asyncOnly = function(){ + this.options.asyncOnly = true; + return this; +}; + +/** + * Disable syntax highlighting (in browser). + * @returns {Mocha} + * @api public + */ +Mocha.prototype.noHighlighting = function() { + this.options.noHighlighting = true; + return this; +}; + +/** + * Run tests and invoke `fn()` when complete. + * + * @param {Function} fn + * @return {Runner} + * @api public + */ + +Mocha.prototype.run = function(fn){ + if (this.files.length) this.loadFiles(); + var suite = this.suite; + var options = this.options; + options.files = this.files; + var runner = new exports.Runner(suite); + var reporter = new this._reporter(runner, options); + runner.ignoreLeaks = false !== options.ignoreLeaks; + runner.asyncOnly = options.asyncOnly; + if (options.grep) runner.grep(options.grep, options.invert); + if (options.globals) runner.globals(options.globals); + if (options.growl) this._growl(runner, reporter); + exports.reporters.Base.useColors = options.useColors; + exports.reporters.Base.inlineDiffs = options.useInlineDiffs; + return runner.run(fn); +}; + +}); // module: mocha.js + +require.register("ms.js", function(module, exports, require){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options){ + options = options || {}; + if ('string' == typeof val) return parse(val); + return options['long'] ? longFormat(val) : shortFormat(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 's': + return n * s; + case 'ms': + return n; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function shortFormat(ms) { + if (ms >= d) return Math.round(ms / d) + 'd'; + if (ms >= h) return Math.round(ms / h) + 'h'; + if (ms >= m) return Math.round(ms / m) + 'm'; + if (ms >= s) return Math.round(ms / s) + 's'; + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function longFormat(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) return; + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +}); // module: ms.js + +require.register("reporters/base.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var tty = require('browser/tty') + , diff = require('browser/diff') + , ms = require('../ms') + , utils = require('../utils'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date + , setTimeout = global.setTimeout + , setInterval = global.setInterval + , clearTimeout = global.clearTimeout + , clearInterval = global.clearInterval; + +/** + * Check if both stdio streams are associated with a tty. + */ + +var isatty = tty.isatty(1) && tty.isatty(2); + +/** + * Expose `Base`. + */ + +exports = module.exports = Base; + +/** + * Enable coloring by default. + */ + +exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined); + +/** + * Inline diffs instead of +/- + */ + +exports.inlineDiffs = false; + +/** + * Default color map. + */ + +exports.colors = { + 'pass': 90 + , 'fail': 31 + , 'bright pass': 92 + , 'bright fail': 91 + , 'bright yellow': 93 + , 'pending': 36 + , 'suite': 0 + , 'error title': 0 + , 'error message': 31 + , 'error stack': 90 + , 'checkmark': 32 + , 'fast': 90 + , 'medium': 33 + , 'slow': 31 + , 'green': 32 + , 'light': 90 + , 'diff gutter': 90 + , 'diff added': 42 + , 'diff removed': 41 +}; + +/** + * Default symbol map. + */ + +exports.symbols = { + ok: '✓', + err: '✖', + dot: '․' +}; + +// With node.js on Windows: use symbols available in terminal default fonts +if ('win32' == process.platform) { + exports.symbols.ok = '\u221A'; + exports.symbols.err = '\u00D7'; + exports.symbols.dot = '.'; +} + +/** + * Color `str` with the given `type`, + * allowing colors to be disabled, + * as well as user-defined color + * schemes. + * + * @param {String} type + * @param {String} str + * @return {String} + * @api private + */ + +var color = exports.color = function(type, str) { + if (!exports.useColors) return str; + return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; +}; + +/** + * Expose term window size, with some + * defaults for when stderr is not a tty. + */ + +exports.window = { + width: isatty + ? process.stdout.getWindowSize + ? process.stdout.getWindowSize(1)[0] + : tty.getWindowSize()[1] + : 75 +}; + +/** + * Expose some basic cursor interactions + * that are common among reporters. + */ + +exports.cursor = { + hide: function(){ + isatty && process.stdout.write('\u001b[?25l'); + }, + + show: function(){ + isatty && process.stdout.write('\u001b[?25h'); + }, + + deleteLine: function(){ + isatty && process.stdout.write('\u001b[2K'); + }, + + beginningOfLine: function(){ + isatty && process.stdout.write('\u001b[0G'); + }, + + CR: function(){ + if (isatty) { + exports.cursor.deleteLine(); + exports.cursor.beginningOfLine(); + } else { + process.stdout.write('\r'); + } + } +}; + +/** + * Outut the given `failures` as a list. + * + * @param {Array} failures + * @api public + */ + +exports.list = function(failures){ + console.error(); + failures.forEach(function(test, i){ + // format + var fmt = color('error title', ' %s) %s:\n') + + color('error message', ' %s') + + color('error stack', '\n%s\n'); + + // msg + var err = test.err + , message = err.message || '' + , stack = err.stack || message + , index = stack.indexOf(message) + message.length + , msg = stack.slice(0, index) + , actual = err.actual + , expected = err.expected + , escape = true; + + // uncaught + if (err.uncaught) { + msg = 'Uncaught ' + msg; + } + + // explicitly show diff + if (err.showDiff && sameType(actual, expected)) { + escape = false; + err.actual = actual = utils.stringify(actual); + err.expected = expected = utils.stringify(expected); + } + + // actual / expected diff + if (err.showDiff && 'string' == typeof actual && 'string' == typeof expected) { + fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); + var match = message.match(/^([^:]+): expected/); + msg = '\n ' + color('error message', match ? match[1] : msg); + + if (exports.inlineDiffs) { + msg += inlineDiff(err, escape); + } else { + msg += unifiedDiff(err, escape); + } + } + + // indent stack trace without msg + stack = stack.slice(index ? index + 1 : index) + .replace(/^/gm, ' '); + + console.error(fmt, (i + 1), test.fullTitle(), msg, stack); + }); +}; + +/** + * Initialize a new `Base` reporter. + * + * All other reporters generally + * inherit from this reporter, providing + * stats such as test duration, number + * of tests passed / failed etc. + * + * @param {Runner} runner + * @api public + */ + +function Base(runner) { + var self = this + , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } + , failures = this.failures = []; + + if (!runner) return; + this.runner = runner; + + runner.stats = stats; + + runner.on('start', function(){ + stats.start = new Date; + }); + + runner.on('suite', function(suite){ + stats.suites = stats.suites || 0; + suite.root || stats.suites++; + }); + + runner.on('test end', function(test){ + stats.tests = stats.tests || 0; + stats.tests++; + }); + + runner.on('pass', function(test){ + stats.passes = stats.passes || 0; + + var medium = test.slow() / 2; + test.speed = test.duration > test.slow() + ? 'slow' + : test.duration > medium + ? 'medium' + : 'fast'; + + stats.passes++; + }); + + runner.on('fail', function(test, err){ + stats.failures = stats.failures || 0; + stats.failures++; + test.err = err; + failures.push(test); + }); + + runner.on('end', function(){ + stats.end = new Date; + stats.duration = new Date - stats.start; + }); + + runner.on('pending', function(){ + stats.pending++; + }); +} + +/** + * Output common epilogue used by many of + * the bundled reporters. + * + * @api public + */ + +Base.prototype.epilogue = function(){ + var stats = this.stats; + var tests; + var fmt; + + console.log(); + + // passes + fmt = color('bright pass', ' ') + + color('green', ' %d passing') + + color('light', ' (%s)'); + + console.log(fmt, + stats.passes || 0, + ms(stats.duration)); + + // pending + if (stats.pending) { + fmt = color('pending', ' ') + + color('pending', ' %d pending'); + + console.log(fmt, stats.pending); + } + + // failures + if (stats.failures) { + fmt = color('fail', ' %d failing'); + + console.error(fmt, + stats.failures); + + Base.list(this.failures); + console.error(); + } + + console.log(); +}; + +/** + * Pad the given `str` to `len`. + * + * @param {String} str + * @param {String} len + * @return {String} + * @api private + */ + +function pad(str, len) { + str = String(str); + return Array(len - str.length + 1).join(' ') + str; +} + + +/** + * Returns an inline diff between 2 strings with coloured ANSI output + * + * @param {Error} Error with actual/expected + * @return {String} Diff + * @api private + */ + +function inlineDiff(err, escape) { + var msg = errorDiff(err, 'WordsWithSpace', escape); + + // linenos + var lines = msg.split('\n'); + if (lines.length > 4) { + var width = String(lines.length).length; + msg = lines.map(function(str, i){ + return pad(++i, width) + ' |' + ' ' + str; + }).join('\n'); + } + + // legend + msg = '\n' + + color('diff removed', 'actual') + + ' ' + + color('diff added', 'expected') + + '\n\n' + + msg + + '\n'; + + // indent + msg = msg.replace(/^/gm, ' '); + return msg; +} + +/** + * Returns a unified diff between 2 strings + * + * @param {Error} Error with actual/expected + * @return {String} Diff + * @api private + */ + +function unifiedDiff(err, escape) { + var indent = ' '; + function cleanUp(line) { + if (escape) { + line = escapeInvisibles(line); + } + if (line[0] === '+') return indent + colorLines('diff added', line); + if (line[0] === '-') return indent + colorLines('diff removed', line); + if (line.match(/\@\@/)) return null; + if (line.match(/\\ No newline/)) return null; + else return indent + line; + } + function notBlank(line) { + return line != null; + } + msg = diff.createPatch('string', err.actual, err.expected); + var lines = msg.split('\n').splice(4); + return '\n ' + + colorLines('diff added', '+ expected') + ' ' + + colorLines('diff removed', '- actual') + + '\n\n' + + lines.map(cleanUp).filter(notBlank).join('\n'); +} + +/** + * Return a character diff for `err`. + * + * @param {Error} err + * @return {String} + * @api private + */ + +function errorDiff(err, type, escape) { + var actual = escape ? escapeInvisibles(err.actual) : err.actual; + var expected = escape ? escapeInvisibles(err.expected) : err.expected; + return diff['diff' + type](actual, expected).map(function(str){ + if (str.added) return colorLines('diff added', str.value); + if (str.removed) return colorLines('diff removed', str.value); + return str.value; + }).join(''); +} + +/** + * Returns a string with all invisible characters in plain text + * + * @param {String} line + * @return {String} + * @api private + */ +function escapeInvisibles(line) { + return line.replace(/\t/g, '') + .replace(/\r/g, '') + .replace(/\n/g, '\n'); +} + +/** + * Color lines for `str`, using the color `name`. + * + * @param {String} name + * @param {String} str + * @return {String} + * @api private + */ + +function colorLines(name, str) { + return str.split('\n').map(function(str){ + return color(name, str); + }).join('\n'); +} + +/** + * Check that a / b have the same type. + * + * @param {Object} a + * @param {Object} b + * @return {Boolean} + * @api private + */ + +function sameType(a, b) { + a = Object.prototype.toString.call(a); + b = Object.prototype.toString.call(b); + return a == b; +} + +}); // module: reporters/base.js + +require.register("reporters/doc.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , utils = require('../utils'); + +/** + * Expose `Doc`. + */ + +exports = module.exports = Doc; + +/** + * Initialize a new `Doc` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Doc(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , total = runner.total + , indents = 2; + + function indent() { + return Array(indents).join(' '); + } + + runner.on('suite', function(suite){ + if (suite.root) return; + ++indents; + console.log('%s
', indent()); + ++indents; + console.log('%s

%s

', indent(), utils.escape(suite.title)); + console.log('%s
', indent()); + }); + + runner.on('suite end', function(suite){ + if (suite.root) return; + console.log('%s
', indent()); + --indents; + console.log('%s
', indent()); + --indents; + }); + + runner.on('pass', function(test){ + console.log('%s
%s
', indent(), utils.escape(test.title)); + var code = utils.escape(utils.clean(test.fn.toString())); + console.log('%s
%s
', indent(), code); + }); + + runner.on('fail', function(test, err){ + console.log('%s
%s
', indent(), utils.escape(test.title)); + var code = utils.escape(utils.clean(test.fn.toString())); + console.log('%s
%s
', indent(), code); + console.log('%s
%s
', indent(), utils.escape(err)); + }); +} + +}); // module: reporters/doc.js + +require.register("reporters/dot.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , color = Base.color; + +/** + * Expose `Dot`. + */ + +exports = module.exports = Dot; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @param {Runner} runner + * @api public + */ + +function Dot(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , width = Base.window.width * .75 | 0 + , n = -1; + + runner.on('start', function(){ + process.stdout.write('\n '); + }); + + runner.on('pending', function(test){ + if (++n % width == 0) process.stdout.write('\n '); + process.stdout.write(color('pending', Base.symbols.dot)); + }); + + runner.on('pass', function(test){ + if (++n % width == 0) process.stdout.write('\n '); + if ('slow' == test.speed) { + process.stdout.write(color('bright yellow', Base.symbols.dot)); + } else { + process.stdout.write(color(test.speed, Base.symbols.dot)); + } + }); + + runner.on('fail', function(test, err){ + if (++n % width == 0) process.stdout.write('\n '); + process.stdout.write(color('fail', Base.symbols.dot)); + }); + + runner.on('end', function(){ + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Dot.prototype = new F; +Dot.prototype.constructor = Dot; + + +}); // module: reporters/dot.js + +require.register("reporters/html-cov.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var JSONCov = require('./json-cov') + , fs = require('browser/fs'); + +/** + * Expose `HTMLCov`. + */ + +exports = module.exports = HTMLCov; + +/** + * Initialize a new `JsCoverage` reporter. + * + * @param {Runner} runner + * @api public + */ + +function HTMLCov(runner) { + var jade = require('jade') + , file = __dirname + '/templates/coverage.jade' + , str = fs.readFileSync(file, 'utf8') + , fn = jade.compile(str, { filename: file }) + , self = this; + + JSONCov.call(this, runner, false); + + runner.on('end', function(){ + process.stdout.write(fn({ + cov: self.cov + , coverageClass: coverageClass + })); + }); +} + +/** + * Return coverage class for `n`. + * + * @return {String} + * @api private + */ + +function coverageClass(n) { + if (n >= 75) return 'high'; + if (n >= 50) return 'medium'; + if (n >= 25) return 'low'; + return 'terrible'; +} +}); // module: reporters/html-cov.js + +require.register("reporters/html.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , utils = require('../utils') + , Progress = require('../browser/progress') + , escape = utils.escape; + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date + , setTimeout = global.setTimeout + , setInterval = global.setInterval + , clearTimeout = global.clearTimeout + , clearInterval = global.clearInterval; + +/** + * Expose `HTML`. + */ + +exports = module.exports = HTML; + +/** + * Stats template. + */ + +var statsTemplate = ''; + +/** + * Initialize a new `HTML` reporter. + * + * @param {Runner} runner + * @api public + */ + +function HTML(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , total = runner.total + , stat = fragment(statsTemplate) + , items = stat.getElementsByTagName('li') + , passes = items[1].getElementsByTagName('em')[0] + , passesLink = items[1].getElementsByTagName('a')[0] + , failures = items[2].getElementsByTagName('em')[0] + , failuresLink = items[2].getElementsByTagName('a')[0] + , duration = items[3].getElementsByTagName('em')[0] + , canvas = stat.getElementsByTagName('canvas')[0] + , report = fragment('
    ') + , stack = [report] + , progress + , ctx + , root = document.getElementById('mocha'); + + if (canvas.getContext) { + var ratio = window.devicePixelRatio || 1; + canvas.style.width = canvas.width; + canvas.style.height = canvas.height; + canvas.width *= ratio; + canvas.height *= ratio; + ctx = canvas.getContext('2d'); + ctx.scale(ratio, ratio); + progress = new Progress; + } + + if (!root) return error('#mocha div missing, add it to your document'); + + // pass toggle + on(passesLink, 'click', function(){ + unhide(); + var name = /pass/.test(report.className) ? '' : ' pass'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) hideSuitesWithout('test pass'); + }); + + // failure toggle + on(failuresLink, 'click', function(){ + unhide(); + var name = /fail/.test(report.className) ? '' : ' fail'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) hideSuitesWithout('test fail'); + }); + + root.appendChild(stat); + root.appendChild(report); + + if (progress) progress.size(40); + + runner.on('suite', function(suite){ + if (suite.root) return; + + // suite + var url = self.suiteURL(suite); + var el = fragment('
  • %s

  • ', url, escape(suite.title)); + + // container + stack[0].appendChild(el); + stack.unshift(document.createElement('ul')); + el.appendChild(stack[0]); + }); + + runner.on('suite end', function(suite){ + if (suite.root) return; + stack.shift(); + }); + + runner.on('fail', function(test, err){ + if ('hook' == test.type) runner.emit('test end', test); + }); + + runner.on('test end', function(test){ + // TODO: add to stats + var percent = stats.tests / this.total * 100 | 0; + if (progress) progress.update(percent).draw(ctx); + + // update stats + var ms = new Date - stats.start; + text(passes, stats.passes); + text(failures, stats.failures); + text(duration, (ms / 1000).toFixed(2)); + + // test + if ('passed' == test.state) { + var url = self.testURL(test); + var el = fragment('
  • %e%ems

  • ', test.speed, test.title, test.duration, url); + } else if (test.pending) { + var el = fragment('
  • %e

  • ', test.title); + } else { + var el = fragment('
  • %e

  • ', test.title, encodeURIComponent(test.fullTitle())); + var str = test.err.stack || test.err.toString(); + + // FF / Opera do not add the message + if (!~str.indexOf(test.err.message)) { + str = test.err.message + '\n' + str; + } + + // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we + // check for the result of the stringifying. + if ('[object Error]' == str) str = test.err.message; + + // Safari doesn't give you a stack. Let's at least provide a source line. + if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { + str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; + } + + el.appendChild(fragment('
    %e
    ', str)); + } + + // toggle code + // TODO: defer + if (!test.pending) { + var h2 = el.getElementsByTagName('h2')[0]; + + on(h2, 'click', function(){ + pre.style.display = 'none' == pre.style.display + ? 'block' + : 'none'; + }); + + var pre = fragment('
    %e
    ', utils.clean(test.fn.toString())); + el.appendChild(pre); + pre.style.display = 'none'; + } + + // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. + if (stack[0]) stack[0].appendChild(el); + }); +} + +/** + * Provide suite URL + * + * @param {Object} [suite] + */ + +HTML.prototype.suiteURL = function(suite){ + return '?grep=' + encodeURIComponent(suite.fullTitle()); +}; + +/** + * Provide test URL + * + * @param {Object} [test] + */ + +HTML.prototype.testURL = function(test){ + return '?grep=' + encodeURIComponent(test.fullTitle()); +}; + +/** + * Display error `msg`. + */ + +function error(msg) { + document.body.appendChild(fragment('
    %s
    ', msg)); +} + +/** + * Return a DOM fragment from `html`. + */ + +function fragment(html) { + var args = arguments + , div = document.createElement('div') + , i = 1; + + div.innerHTML = html.replace(/%([se])/g, function(_, type){ + switch (type) { + case 's': return String(args[i++]); + case 'e': return escape(args[i++]); + } + }); + + return div.firstChild; +} + +/** + * Check for suites that do not have elements + * with `classname`, and hide them. + */ + +function hideSuitesWithout(classname) { + var suites = document.getElementsByClassName('suite'); + for (var i = 0; i < suites.length; i++) { + var els = suites[i].getElementsByClassName(classname); + if (0 == els.length) suites[i].className += ' hidden'; + } +} + +/** + * Unhide .hidden suites. + */ + +function unhide() { + var els = document.getElementsByClassName('suite hidden'); + for (var i = 0; i < els.length; ++i) { + els[i].className = els[i].className.replace('suite hidden', 'suite'); + } +} + +/** + * Set `el` text to `str`. + */ + +function text(el, str) { + if (el.textContent) { + el.textContent = str; + } else { + el.innerText = str; + } +} + +/** + * Listen on `event` with callback `fn`. + */ + +function on(el, event, fn) { + if (el.addEventListener) { + el.addEventListener(event, fn, false); + } else { + el.attachEvent('on' + event, fn); + } +} + +}); // module: reporters/html.js + +require.register("reporters/index.js", function(module, exports, require){ + +exports.Base = require('./base'); +exports.Dot = require('./dot'); +exports.Doc = require('./doc'); +exports.TAP = require('./tap'); +exports.JSON = require('./json'); +exports.HTML = require('./html'); +exports.List = require('./list'); +exports.Min = require('./min'); +exports.Spec = require('./spec'); +exports.Nyan = require('./nyan'); +exports.XUnit = require('./xunit'); +exports.Markdown = require('./markdown'); +exports.Progress = require('./progress'); +exports.Landing = require('./landing'); +exports.JSONCov = require('./json-cov'); +exports.HTMLCov = require('./html-cov'); +exports.JSONStream = require('./json-stream'); + +}); // module: reporters/index.js + +require.register("reporters/json-cov.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `JSONCov`. + */ + +exports = module.exports = JSONCov; + +/** + * Initialize a new `JsCoverage` reporter. + * + * @param {Runner} runner + * @param {Boolean} output + * @api public + */ + +function JSONCov(runner, output) { + var self = this + , output = 1 == arguments.length ? true : output; + + Base.call(this, runner); + + var tests = [] + , failures = [] + , passes = []; + + runner.on('test end', function(test){ + tests.push(test); + }); + + runner.on('pass', function(test){ + passes.push(test); + }); + + runner.on('fail', function(test){ + failures.push(test); + }); + + runner.on('end', function(){ + var cov = global._$jscoverage || {}; + var result = self.cov = map(cov); + result.stats = self.stats; + result.tests = tests.map(clean); + result.failures = failures.map(clean); + result.passes = passes.map(clean); + if (!output) return; + process.stdout.write(JSON.stringify(result, null, 2 )); + }); +} + +/** + * Map jscoverage data to a JSON structure + * suitable for reporting. + * + * @param {Object} cov + * @return {Object} + * @api private + */ + +function map(cov) { + var ret = { + instrumentation: 'node-jscoverage' + , sloc: 0 + , hits: 0 + , misses: 0 + , coverage: 0 + , files: [] + }; + + for (var filename in cov) { + var data = coverage(filename, cov[filename]); + ret.files.push(data); + ret.hits += data.hits; + ret.misses += data.misses; + ret.sloc += data.sloc; + } + + ret.files.sort(function(a, b) { + return a.filename.localeCompare(b.filename); + }); + + if (ret.sloc > 0) { + ret.coverage = (ret.hits / ret.sloc) * 100; + } + + return ret; +} + +/** + * Map jscoverage data for a single source file + * to a JSON structure suitable for reporting. + * + * @param {String} filename name of the source file + * @param {Object} data jscoverage coverage data + * @return {Object} + * @api private + */ + +function coverage(filename, data) { + var ret = { + filename: filename, + coverage: 0, + hits: 0, + misses: 0, + sloc: 0, + source: {} + }; + + data.source.forEach(function(line, num){ + num++; + + if (data[num] === 0) { + ret.misses++; + ret.sloc++; + } else if (data[num] !== undefined) { + ret.hits++; + ret.sloc++; + } + + ret.source[num] = { + source: line + , coverage: data[num] === undefined + ? '' + : data[num] + }; + }); + + ret.coverage = ret.hits / ret.sloc * 100; + + return ret; +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @param {Object} test + * @return {Object} + * @api private + */ + +function clean(test) { + return { + title: test.title + , fullTitle: test.fullTitle() + , duration: test.duration + } +} + +}); // module: reporters/json-cov.js + +require.register("reporters/json-stream.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , color = Base.color; + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `List` test reporter. + * + * @param {Runner} runner + * @api public + */ + +function List(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , total = runner.total; + + runner.on('start', function(){ + console.log(JSON.stringify(['start', { total: total }])); + }); + + runner.on('pass', function(test){ + console.log(JSON.stringify(['pass', clean(test)])); + }); + + runner.on('fail', function(test, err){ + console.log(JSON.stringify(['fail', clean(test)])); + }); + + runner.on('end', function(){ + process.stdout.write(JSON.stringify(['end', self.stats])); + }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @param {Object} test + * @return {Object} + * @api private + */ + +function clean(test) { + return { + title: test.title + , fullTitle: test.fullTitle() + , duration: test.duration + } +} +}); // module: reporters/json-stream.js + +require.register("reporters/json.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `JSON`. + */ + +exports = module.exports = JSONReporter; + +/** + * Initialize a new `JSON` reporter. + * + * @param {Runner} runner + * @api public + */ + +function JSONReporter(runner) { + var self = this; + Base.call(this, runner); + + var tests = [] + , pending = [] + , failures = [] + , passes = []; + + runner.on('test end', function(test){ + tests.push(test); + }); + + runner.on('pass', function(test){ + passes.push(test); + }); + + runner.on('fail', function(test){ + failures.push(test); + }); + + runner.on('pending', function(test){ + pending.push(test); + }); + + runner.on('end', function(){ + var obj = { + stats: self.stats, + tests: tests.map(clean), + pending: pending.map(clean), + failures: failures.map(clean), + passes: passes.map(clean) + }; + + runner.testResults = obj; + + process.stdout.write(JSON.stringify(obj, null, 2)); + }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @param {Object} test + * @return {Object} + * @api private + */ + +function clean(test) { + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + err: errorJSON(test.err || {}) + } +} + +/** + * Transform `error` into a JSON object. + * @param {Error} err + * @return {Object} + */ + +function errorJSON(err) { + var res = {}; + Object.getOwnPropertyNames(err).forEach(function(key) { + res[key] = err[key]; + }, err); + return res; +} + +}); // module: reporters/json.js + +require.register("reporters/landing.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `Landing`. + */ + +exports = module.exports = Landing; + +/** + * Airplane color. + */ + +Base.colors.plane = 0; + +/** + * Airplane crash color. + */ + +Base.colors['plane crash'] = 31; + +/** + * Runway color. + */ + +Base.colors.runway = 90; + +/** + * Initialize a new `Landing` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Landing(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , width = Base.window.width * .75 | 0 + , total = runner.total + , stream = process.stdout + , plane = color('plane', '✈') + , crashed = -1 + , n = 0; + + function runway() { + var buf = Array(width).join('-'); + return ' ' + color('runway', buf); + } + + runner.on('start', function(){ + stream.write('\n '); + cursor.hide(); + }); + + runner.on('test end', function(test){ + // check if the plane crashed + var col = -1 == crashed + ? width * ++n / total | 0 + : crashed; + + // show the crash + if ('failed' == test.state) { + plane = color('plane crash', '✈'); + crashed = col; + } + + // render landing strip + stream.write('\u001b[4F\n\n'); + stream.write(runway()); + stream.write('\n '); + stream.write(color('runway', Array(col).join('⋅'))); + stream.write(plane) + stream.write(color('runway', Array(width - col).join('⋅') + '\n')); + stream.write(runway()); + stream.write('\u001b[0m'); + }); + + runner.on('end', function(){ + cursor.show(); + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Landing.prototype = new F; +Landing.prototype.constructor = Landing; + +}); // module: reporters/landing.js + +require.register("reporters/list.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `List` test reporter. + * + * @param {Runner} runner + * @api public + */ + +function List(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , n = 0; + + runner.on('start', function(){ + console.log(); + }); + + runner.on('test', function(test){ + process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); + }); + + runner.on('pending', function(test){ + var fmt = color('checkmark', ' -') + + color('pending', ' %s'); + console.log(fmt, test.fullTitle()); + }); + + runner.on('pass', function(test){ + var fmt = color('checkmark', ' '+Base.symbols.dot) + + color('pass', ' %s: ') + + color(test.speed, '%dms'); + cursor.CR(); + console.log(fmt, test.fullTitle(), test.duration); + }); + + runner.on('fail', function(test, err){ + cursor.CR(); + console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); + }); + + runner.on('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +List.prototype = new F; +List.prototype.constructor = List; + + +}); // module: reporters/list.js + +require.register("reporters/markdown.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var Base = require('./base') + , utils = require('../utils'); + +/** + * Expose `Markdown`. + */ + +exports = module.exports = Markdown; + +/** + * Initialize a new `Markdown` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Markdown(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , level = 0 + , buf = ''; + + function title(str) { + return Array(level).join('#') + ' ' + str; + } + + function indent() { + return Array(level).join(' '); + } + + function mapTOC(suite, obj) { + var ret = obj; + obj = obj[suite.title] = obj[suite.title] || { suite: suite }; + suite.suites.forEach(function(suite){ + mapTOC(suite, obj); + }); + return ret; + } + + function stringifyTOC(obj, level) { + ++level; + var buf = ''; + var link; + for (var key in obj) { + if ('suite' == key) continue; + if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; + if (key) buf += Array(level).join(' ') + link; + buf += stringifyTOC(obj[key], level); + } + --level; + return buf; + } + + function generateTOC(suite) { + var obj = mapTOC(suite, {}); + return stringifyTOC(obj, 0); + } + + generateTOC(runner.suite); + + runner.on('suite', function(suite){ + ++level; + var slug = utils.slug(suite.fullTitle()); + buf += '' + '\n'; + buf += title(suite.title) + '\n'; + }); + + runner.on('suite end', function(suite){ + --level; + }); + + runner.on('pass', function(test){ + var code = utils.clean(test.fn.toString()); + buf += test.title + '.\n'; + buf += '\n```js\n'; + buf += code + '\n'; + buf += '```\n\n'; + }); + + runner.on('end', function(){ + process.stdout.write('# TOC\n'); + process.stdout.write(generateTOC(runner.suite)); + process.stdout.write(buf); + }); +} +}); // module: reporters/markdown.js + +require.register("reporters/min.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `Min`. + */ + +exports = module.exports = Min; + +/** + * Initialize a new `Min` minimal test reporter (best used with --watch). + * + * @param {Runner} runner + * @api public + */ + +function Min(runner) { + Base.call(this, runner); + + runner.on('start', function(){ + // clear screen + process.stdout.write('\u001b[2J'); + // set cursor position + process.stdout.write('\u001b[1;3H'); + }); + + runner.on('end', this.epilogue.bind(this)); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Min.prototype = new F; +Min.prototype.constructor = Min; + + +}); // module: reporters/min.js + +require.register("reporters/nyan.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var Base = require('./base') + , color = Base.color; + +/** + * Expose `Dot`. + */ + +exports = module.exports = NyanCat; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @param {Runner} runner + * @api public + */ + +function NyanCat(runner) { + Base.call(this, runner); + var self = this + , stats = this.stats + , width = Base.window.width * .75 | 0 + , rainbowColors = this.rainbowColors = self.generateColors() + , colorIndex = this.colorIndex = 0 + , numerOfLines = this.numberOfLines = 4 + , trajectories = this.trajectories = [[], [], [], []] + , nyanCatWidth = this.nyanCatWidth = 11 + , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) + , scoreboardWidth = this.scoreboardWidth = 5 + , tick = this.tick = 0 + , n = 0; + + runner.on('start', function(){ + Base.cursor.hide(); + self.draw(); + }); + + runner.on('pending', function(test){ + self.draw(); + }); + + runner.on('pass', function(test){ + self.draw(); + }); + + runner.on('fail', function(test, err){ + self.draw(); + }); + + runner.on('end', function(){ + Base.cursor.show(); + for (var i = 0; i < self.numberOfLines; i++) write('\n'); + self.epilogue(); + }); +} + +/** + * Draw the nyan cat + * + * @api private + */ + +NyanCat.prototype.draw = function(){ + this.appendRainbow(); + this.drawScoreboard(); + this.drawRainbow(); + this.drawNyanCat(); + this.tick = !this.tick; +}; + +/** + * Draw the "scoreboard" showing the number + * of passes, failures and pending tests. + * + * @api private + */ + +NyanCat.prototype.drawScoreboard = function(){ + var stats = this.stats; + var colors = Base.colors; + + function draw(color, n) { + write(' '); + write('\u001b[' + color + 'm' + n + '\u001b[0m'); + write('\n'); + } + + draw(colors.green, stats.passes); + draw(colors.fail, stats.failures); + draw(colors.pending, stats.pending); + write('\n'); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Append the rainbow. + * + * @api private + */ + +NyanCat.prototype.appendRainbow = function(){ + var segment = this.tick ? '_' : '-'; + var rainbowified = this.rainbowify(segment); + + for (var index = 0; index < this.numberOfLines; index++) { + var trajectory = this.trajectories[index]; + if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); + trajectory.push(rainbowified); + } +}; + +/** + * Draw the rainbow. + * + * @api private + */ + +NyanCat.prototype.drawRainbow = function(){ + var self = this; + + this.trajectories.forEach(function(line, index) { + write('\u001b[' + self.scoreboardWidth + 'C'); + write(line.join('')); + write('\n'); + }); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Draw the nyan cat + * + * @api private + */ + +NyanCat.prototype.drawNyanCat = function() { + var self = this; + var startWidth = this.scoreboardWidth + this.trajectories[0].length; + var color = '\u001b[' + startWidth + 'C'; + var padding = ''; + + write(color); + write('_,------,'); + write('\n'); + + write(color); + padding = self.tick ? ' ' : ' '; + write('_|' + padding + '/\\_/\\ '); + write('\n'); + + write(color); + padding = self.tick ? '_' : '__'; + var tail = self.tick ? '~' : '^'; + var face; + write(tail + '|' + padding + this.face() + ' '); + write('\n'); + + write(color); + padding = self.tick ? ' ' : ' '; + write(padding + '"" "" '); + write('\n'); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Draw nyan cat face. + * + * @return {String} + * @api private + */ + +NyanCat.prototype.face = function() { + var stats = this.stats; + if (stats.failures) { + return '( x .x)'; + } else if (stats.pending) { + return '( o .o)'; + } else if(stats.passes) { + return '( ^ .^)'; + } else { + return '( - .-)'; + } +}; + +/** + * Move cursor up `n`. + * + * @param {Number} n + * @api private + */ + +NyanCat.prototype.cursorUp = function(n) { + write('\u001b[' + n + 'A'); +}; + +/** + * Move cursor down `n`. + * + * @param {Number} n + * @api private + */ + +NyanCat.prototype.cursorDown = function(n) { + write('\u001b[' + n + 'B'); +}; + +/** + * Generate rainbow colors. + * + * @return {Array} + * @api private + */ + +NyanCat.prototype.generateColors = function(){ + var colors = []; + + for (var i = 0; i < (6 * 7); i++) { + var pi3 = Math.floor(Math.PI / 3); + var n = (i * (1.0 / 6)); + var r = Math.floor(3 * Math.sin(n) + 3); + var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); + var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); + colors.push(36 * r + 6 * g + b + 16); + } + + return colors; +}; + +/** + * Apply rainbow to the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +NyanCat.prototype.rainbowify = function(str){ + var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; + this.colorIndex += 1; + return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; +}; + +/** + * Stdout helper. + */ + +function write(string) { + process.stdout.write(string); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +NyanCat.prototype = new F; +NyanCat.prototype.constructor = NyanCat; + + +}); // module: reporters/nyan.js + +require.register("reporters/progress.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `Progress`. + */ + +exports = module.exports = Progress; + +/** + * General progress bar color. + */ + +Base.colors.progress = 90; + +/** + * Initialize a new `Progress` bar test reporter. + * + * @param {Runner} runner + * @param {Object} options + * @api public + */ + +function Progress(runner, options) { + Base.call(this, runner); + + var self = this + , options = options || {} + , stats = this.stats + , width = Base.window.width * .50 | 0 + , total = runner.total + , complete = 0 + , max = Math.max + , lastN = -1; + + // default chars + options.open = options.open || '['; + options.complete = options.complete || '▬'; + options.incomplete = options.incomplete || Base.symbols.dot; + options.close = options.close || ']'; + options.verbose = false; + + // tests started + runner.on('start', function(){ + console.log(); + cursor.hide(); + }); + + // tests complete + runner.on('test end', function(){ + complete++; + var incomplete = total - complete + , percent = complete / total + , n = width * percent | 0 + , i = width - n; + + if (lastN === n && !options.verbose) { + // Don't re-render the line if it hasn't changed + return; + } + lastN = n; + + cursor.CR(); + process.stdout.write('\u001b[J'); + process.stdout.write(color('progress', ' ' + options.open)); + process.stdout.write(Array(n).join(options.complete)); + process.stdout.write(Array(i).join(options.incomplete)); + process.stdout.write(color('progress', options.close)); + if (options.verbose) { + process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); + } + }); + + // tests are complete, output some stats + // and the failures if any + runner.on('end', function(){ + cursor.show(); + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Progress.prototype = new F; +Progress.prototype.constructor = Progress; + + +}); // module: reporters/progress.js + +require.register("reporters/spec.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `Spec`. + */ + +exports = module.exports = Spec; + +/** + * Initialize a new `Spec` test reporter. + * + * @param {Runner} runner + * @api public + */ + +function Spec(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , indents = 0 + , n = 0; + + function indent() { + return Array(indents).join(' ') + } + + runner.on('start', function(){ + console.log(); + }); + + runner.on('suite', function(suite){ + ++indents; + console.log(color('suite', '%s%s'), indent(), suite.title); + }); + + runner.on('suite end', function(suite){ + --indents; + if (1 == indents) console.log(); + }); + + runner.on('pending', function(test){ + var fmt = indent() + color('pending', ' - %s'); + console.log(fmt, test.title); + }); + + runner.on('pass', function(test){ + if ('fast' == test.speed) { + var fmt = indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s '); + cursor.CR(); + console.log(fmt, test.title); + } else { + var fmt = indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s ') + + color(test.speed, '(%dms)'); + cursor.CR(); + console.log(fmt, test.title, test.duration); + } + }); + + runner.on('fail', function(test, err){ + cursor.CR(); + console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); + }); + + runner.on('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Spec.prototype = new F; +Spec.prototype.constructor = Spec; + + +}); // module: reporters/spec.js + +require.register("reporters/tap.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `TAP`. + */ + +exports = module.exports = TAP; + +/** + * Initialize a new `TAP` reporter. + * + * @param {Runner} runner + * @api public + */ + +function TAP(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , n = 1 + , passes = 0 + , failures = 0; + + runner.on('start', function(){ + var total = runner.grepTotal(runner.suite); + console.log('%d..%d', 1, total); + }); + + runner.on('test end', function(){ + ++n; + }); + + runner.on('pending', function(test){ + console.log('ok %d %s # SKIP -', n, title(test)); + }); + + runner.on('pass', function(test){ + passes++; + console.log('ok %d %s', n, title(test)); + }); + + runner.on('fail', function(test, err){ + failures++; + console.log('not ok %d %s', n, title(test)); + if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); + }); + + runner.on('end', function(){ + console.log('# tests ' + (passes + failures)); + console.log('# pass ' + passes); + console.log('# fail ' + failures); + }); +} + +/** + * Return a TAP-safe title of `test` + * + * @param {Object} test + * @return {String} + * @api private + */ + +function title(test) { + return test.fullTitle().replace(/#/g, ''); +} + +}); // module: reporters/tap.js + +require.register("reporters/xunit.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , utils = require('../utils') + , escape = utils.escape; + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date + , setTimeout = global.setTimeout + , setInterval = global.setInterval + , clearTimeout = global.clearTimeout + , clearInterval = global.clearInterval; + +/** + * Expose `XUnit`. + */ + +exports = module.exports = XUnit; + +/** + * Initialize a new `XUnit` reporter. + * + * @param {Runner} runner + * @api public + */ + +function XUnit(runner) { + Base.call(this, runner); + var stats = this.stats + , tests = [] + , self = this; + + runner.on('pending', function(test){ + tests.push(test); + }); + + runner.on('pass', function(test){ + tests.push(test); + }); + + runner.on('fail', function(test){ + tests.push(test); + }); + + runner.on('end', function(){ + console.log(tag('testsuite', { + name: 'Mocha Tests' + , tests: stats.tests + , failures: stats.failures + , errors: stats.failures + , skipped: stats.tests - stats.failures - stats.passes + , timestamp: (new Date).toUTCString() + , time: (stats.duration / 1000) || 0 + }, false)); + + tests.forEach(test); + console.log(''); + }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +XUnit.prototype = new F; +XUnit.prototype.constructor = XUnit; + + +/** + * Output tag for the given `test.` + */ + +function test(test) { + var attrs = { + classname: test.parent.fullTitle() + , name: test.title + , time: (test.duration / 1000) || 0 + }; + + if ('failed' == test.state) { + var err = test.err; + console.log(tag('testcase', attrs, false, tag('failure', {}, false, cdata(escape(err.message) + "\n" + err.stack)))); + } else if (test.pending) { + console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); + } else { + console.log(tag('testcase', attrs, true) ); + } +} + +/** + * HTML tag helper. + */ + +function tag(name, attrs, close, content) { + var end = close ? '/>' : '>' + , pairs = [] + , tag; + + for (var key in attrs) { + pairs.push(key + '="' + escape(attrs[key]) + '"'); + } + + tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; + if (content) tag += content + ''; +} + +}); // module: reporters/xunit.js + +require.register("runnable.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var EventEmitter = require('browser/events').EventEmitter + , debug = require('browser/debug')('mocha:runnable') + , milliseconds = require('./ms'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date + , setTimeout = global.setTimeout + , setInterval = global.setInterval + , clearTimeout = global.clearTimeout + , clearInterval = global.clearInterval; + +/** + * Object#toString(). + */ + +var toString = Object.prototype.toString; + +/** + * Expose `Runnable`. + */ + +module.exports = Runnable; + +/** + * Initialize a new `Runnable` with the given `title` and callback `fn`. + * + * @param {String} title + * @param {Function} fn + * @api private + */ + +function Runnable(title, fn) { + this.title = title; + this.fn = fn; + this.async = fn && fn.length; + this.sync = ! this.async; + this._timeout = 2000; + this._slow = 75; + this._enableTimeouts = true; + this.timedOut = false; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ + +function F(){}; +F.prototype = EventEmitter.prototype; +Runnable.prototype = new F; +Runnable.prototype.constructor = Runnable; + + +/** + * Set & get timeout `ms`. + * + * @param {Number|String} ms + * @return {Runnable|Number} ms or self + * @api private + */ + +Runnable.prototype.timeout = function(ms){ + if (0 == arguments.length) return this._timeout; + if (ms === 0) this._enableTimeouts = false; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('timeout %d', ms); + this._timeout = ms; + if (this.timer) this.resetTimeout(); + return this; +}; + +/** + * Set & get slow `ms`. + * + * @param {Number|String} ms + * @return {Runnable|Number} ms or self + * @api private + */ + +Runnable.prototype.slow = function(ms){ + if (0 === arguments.length) return this._slow; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('timeout %d', ms); + this._slow = ms; + return this; +}; + +/** + * Set and & get timeout `enabled`. + * + * @param {Boolean} enabled + * @return {Runnable|Boolean} enabled or self + * @api private + */ + +Runnable.prototype.enableTimeouts = function(enabled){ + if (arguments.length === 0) return this._enableTimeouts; + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Return the full title generated by recursively + * concatenating the parent's full title. + * + * @return {String} + * @api public + */ + +Runnable.prototype.fullTitle = function(){ + return this.parent.fullTitle() + ' ' + this.title; +}; + +/** + * Clear the timeout. + * + * @api private + */ + +Runnable.prototype.clearTimeout = function(){ + clearTimeout(this.timer); +}; + +/** + * Inspect the runnable void of private properties. + * + * @return {String} + * @api private + */ + +Runnable.prototype.inspect = function(){ + return JSON.stringify(this, function(key, val){ + if ('_' == key[0]) return; + if ('parent' == key) return '#'; + if ('ctx' == key) return '#'; + return val; + }, 2); +}; + +/** + * Reset the timeout. + * + * @api private + */ + +Runnable.prototype.resetTimeout = function(){ + var self = this; + var ms = this.timeout() || 1e9; + + if (!this._enableTimeouts) return; + this.clearTimeout(); + this.timer = setTimeout(function(){ + if (!self._enableTimeouts) return; + self.callback(new Error('timeout of ' + ms + 'ms exceeded')); + self.timedOut = true; + }, ms); +}; + +/** + * Whitelist these globals for this test run + * + * @api private + */ +Runnable.prototype.globals = function(arr){ + var self = this; + this._allowedGlobals = arr; +}; + +/** + * Run the test and invoke `fn(err)`. + * + * @param {Function} fn + * @api private + */ + +Runnable.prototype.run = function(fn){ + var self = this + , start = new Date + , ctx = this.ctx + , finished + , emitted; + + // Some times the ctx exists but it is not runnable + if (ctx && ctx.runnable) ctx.runnable(this); + + // called multiple times + function multiple(err) { + if (emitted) return; + emitted = true; + self.emit('error', err || new Error('done() called multiple times')); + } + + // finished + function done(err) { + var ms = self.timeout(); + if (self.timedOut) return; + if (finished) return multiple(err); + self.clearTimeout(); + self.duration = new Date - start; + finished = true; + if (!err && self.duration > ms && self._enableTimeouts) err = new Error('timeout of ' + ms + 'ms exceeded'); + fn(err); + } + + // for .resetTimeout() + this.callback = done; + + // explicit async with `done` argument + if (this.async) { + this.resetTimeout(); + + try { + this.fn.call(ctx, function(err){ + if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); + if (null != err) { + if (Object.prototype.toString.call(err) === '[object Object]') { + return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err))); + } else { + return done(new Error('done() invoked with non-Error: ' + err)); + } + } + done(); + }); + } catch (err) { + done(err); + } + return; + } + + if (this.asyncOnly) { + return done(new Error('--async-only option in use without declaring `done()`')); + } + + // sync or promise-returning + try { + if (this.pending) { + done(); + } else { + callFn(this.fn); + } + } catch (err) { + done(err); + } + + function callFn(fn) { + var result = fn.call(ctx); + if (result && typeof result.then === 'function') { + self.resetTimeout(); + result + .then(function() { + done() + }, + function(reason) { + done(reason || new Error('Promise rejected with no or falsy reason')) + }); + } else { + done(); + } + } +}; + +}); // module: runnable.js + +require.register("runner.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var EventEmitter = require('browser/events').EventEmitter + , debug = require('browser/debug')('mocha:runner') + , Test = require('./test') + , utils = require('./utils') + , filter = utils.filter + , keys = utils.keys; + +/** + * Non-enumerable globals. + */ + +var globals = [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'XMLHttpRequest', + 'Date' +]; + +/** + * Expose `Runner`. + */ + +module.exports = Runner; + +/** + * Initialize a `Runner` for the given `suite`. + * + * Events: + * + * - `start` execution started + * - `end` execution complete + * - `suite` (suite) test suite execution started + * - `suite end` (suite) all tests (and sub-suites) have finished + * - `test` (test) test execution started + * - `test end` (test) test completed + * - `hook` (hook) hook execution started + * - `hook end` (hook) hook complete + * - `pass` (test) test passed + * - `fail` (test, err) test failed + * - `pending` (test) test pending + * + * @api public + */ + +function Runner(suite) { + var self = this; + this._globals = []; + this._abort = false; + this.suite = suite; + this.total = suite.total(); + this.failures = 0; + this.on('test end', function(test){ self.checkGlobals(test); }); + this.on('hook end', function(hook){ self.checkGlobals(hook); }); + this.grep(/.*/); + this.globals(this.globalProps().concat(extraGlobals())); +} + +/** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + * + * @param {Function} fn + * @api private + */ + +Runner.immediately = global.setImmediate || process.nextTick; + +/** + * Inherit from `EventEmitter.prototype`. + */ + +function F(){}; +F.prototype = EventEmitter.prototype; +Runner.prototype = new F; +Runner.prototype.constructor = Runner; + + +/** + * Run tests with full titles matching `re`. Updates runner.total + * with number of tests matched. + * + * @param {RegExp} re + * @param {Boolean} invert + * @return {Runner} for chaining + * @api public + */ + +Runner.prototype.grep = function(re, invert){ + debug('grep %s', re); + this._grep = re; + this._invert = invert; + this.total = this.grepTotal(this.suite); + return this; +}; + +/** + * Returns the number of tests matching the grep search for the + * given suite. + * + * @param {Suite} suite + * @return {Number} + * @api public + */ + +Runner.prototype.grepTotal = function(suite) { + var self = this; + var total = 0; + + suite.eachTest(function(test){ + var match = self._grep.test(test.fullTitle()); + if (self._invert) match = !match; + if (match) total++; + }); + + return total; +}; + +/** + * Return a list of global properties. + * + * @return {Array} + * @api private + */ + +Runner.prototype.globalProps = function() { + var props = utils.keys(global); + + // non-enumerables + for (var i = 0; i < globals.length; ++i) { + if (~utils.indexOf(props, globals[i])) continue; + props.push(globals[i]); + } + + return props; +}; + +/** + * Allow the given `arr` of globals. + * + * @param {Array} arr + * @return {Runner} for chaining + * @api public + */ + +Runner.prototype.globals = function(arr){ + if (0 == arguments.length) return this._globals; + debug('globals %j', arr); + this._globals = this._globals.concat(arr); + return this; +}; + +/** + * Check for global variable leaks. + * + * @api private + */ + +Runner.prototype.checkGlobals = function(test){ + if (this.ignoreLeaks) return; + var ok = this._globals; + + var globals = this.globalProps(); + var leaks; + + if (test) { + ok = ok.concat(test._allowedGlobals || []); + } + + if(this.prevGlobalsLength == globals.length) return; + this.prevGlobalsLength = globals.length; + + leaks = filterLeaks(ok, globals); + this._globals = this._globals.concat(leaks); + + if (leaks.length > 1) { + this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); + } else if (leaks.length) { + this.fail(test, new Error('global leak detected: ' + leaks[0])); + } +}; + +/** + * Fail the given `test`. + * + * @param {Test} test + * @param {Error} err + * @api private + */ + +Runner.prototype.fail = function(test, err){ + ++this.failures; + test.state = 'failed'; + + if ('string' == typeof err) { + err = new Error('the string "' + err + '" was thrown, throw an Error :)'); + } + + this.emit('fail', test, err); +}; + +/** + * Fail the given `hook` with `err`. + * + * Hook failures work in the following pattern: + * - If bail, then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter + * execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks + * + * @param {Hook} hook + * @param {Error} err + * @api private + */ + +Runner.prototype.failHook = function(hook, err){ + this.fail(hook, err); + if (this.suite.bail()) { + this.emit('end'); + } +}; + +/** + * Run hook `name` callbacks and then invoke `fn()`. + * + * @param {String} name + * @param {Function} function + * @api private + */ + +Runner.prototype.hook = function(name, fn){ + var suite = this.suite + , hooks = suite['_' + name] + , self = this + , timer; + + function next(i) { + var hook = hooks[i]; + if (!hook) return fn(); + if (self.failures && suite.bail()) return fn(); + self.currentRunnable = hook; + + hook.ctx.currentTest = self.test; + + self.emit('hook', hook); + + hook.on('error', function(err){ + self.failHook(hook, err); + }); + + hook.run(function(err){ + hook.removeAllListeners('error'); + var testError = hook.error(); + if (testError) self.fail(self.test, testError); + if (err) { + self.failHook(hook, err); + + // stop executing hooks, notify callee of hook err + return fn(err); + } + self.emit('hook end', hook); + delete hook.ctx.currentTest; + next(++i); + }); + } + + Runner.immediately(function(){ + next(0); + }); +}; + +/** + * Run hook `name` for the given array of `suites` + * in order, and callback `fn(err, errSuite)`. + * + * @param {String} name + * @param {Array} suites + * @param {Function} fn + * @api private + */ + +Runner.prototype.hooks = function(name, suites, fn){ + var self = this + , orig = this.suite; + + function next(suite) { + self.suite = suite; + + if (!suite) { + self.suite = orig; + return fn(); + } + + self.hook(name, function(err){ + if (err) { + var errSuite = self.suite; + self.suite = orig; + return fn(err, errSuite); + } + + next(suites.pop()); + }); + } + + next(suites.pop()); +}; + +/** + * Run hooks from the top level down. + * + * @param {String} name + * @param {Function} fn + * @api private + */ + +Runner.prototype.hookUp = function(name, fn){ + var suites = [this.suite].concat(this.parents()).reverse(); + this.hooks(name, suites, fn); +}; + +/** + * Run hooks from the bottom up. + * + * @param {String} name + * @param {Function} fn + * @api private + */ + +Runner.prototype.hookDown = function(name, fn){ + var suites = [this.suite].concat(this.parents()); + this.hooks(name, suites, fn); +}; + +/** + * Return an array of parent Suites from + * closest to furthest. + * + * @return {Array} + * @api private + */ + +Runner.prototype.parents = function(){ + var suite = this.suite + , suites = []; + while (suite = suite.parent) suites.push(suite); + return suites; +}; + +/** + * Run the current test and callback `fn(err)`. + * + * @param {Function} fn + * @api private + */ + +Runner.prototype.runTest = function(fn){ + var test = this.test + , self = this; + + if (this.asyncOnly) test.asyncOnly = true; + + try { + test.on('error', function(err){ + self.fail(test, err); + }); + test.run(fn); + } catch (err) { + fn(err); + } +}; + +/** + * Run tests in the given `suite` and invoke + * the callback `fn()` when complete. + * + * @param {Suite} suite + * @param {Function} fn + * @api private + */ + +Runner.prototype.runTests = function(suite, fn){ + var self = this + , tests = suite.tests.slice() + , test; + + + function hookErr(err, errSuite, after) { + // before/after Each hook for errSuite failed: + var orig = self.suite; + + // for failed 'after each' hook start from errSuite parent, + // otherwise start from errSuite itself + self.suite = after ? errSuite.parent : errSuite; + + if (self.suite) { + // call hookUp afterEach + self.hookUp('afterEach', function(err2, errSuite2) { + self.suite = orig; + // some hooks may fail even now + if (err2) return hookErr(err2, errSuite2, true); + // report error suite + fn(errSuite); + }); + } else { + // there is no need calling other 'after each' hooks + self.suite = orig; + fn(errSuite); + } + } + + function next(err, errSuite) { + // if we bail after first err + if (self.failures && suite._bail) return fn(); + + if (self._abort) return fn(); + + if (err) return hookErr(err, errSuite, true); + + // next test + test = tests.shift(); + + // all done + if (!test) return fn(); + + // grep + var match = self._grep.test(test.fullTitle()); + if (self._invert) match = !match; + if (!match) return next(); + + // pending + if (test.pending) { + self.emit('pending', test); + self.emit('test end', test); + return next(); + } + + // execute test and hook(s) + self.emit('test', self.test = test); + self.hookDown('beforeEach', function(err, errSuite){ + + if (err) return hookErr(err, errSuite, false); + + self.currentRunnable = self.test; + self.runTest(function(err){ + test = self.test; + + if (err) { + self.fail(test, err); + self.emit('test end', test); + return self.hookUp('afterEach', next); + } + + test.state = 'passed'; + self.emit('pass', test); + self.emit('test end', test); + self.hookUp('afterEach', next); + }); + }); + } + + this.next = next; + next(); +}; + +/** + * Run the given `suite` and invoke the + * callback `fn()` when complete. + * + * @param {Suite} suite + * @param {Function} fn + * @api private + */ + +Runner.prototype.runSuite = function(suite, fn){ + var total = this.grepTotal(suite) + , self = this + , i = 0; + + debug('run suite %s', suite.fullTitle()); + + if (!total) return fn(); + + this.emit('suite', this.suite = suite); + + function next(errSuite) { + if (errSuite) { + // current suite failed on a hook from errSuite + if (errSuite == suite) { + // if errSuite is current suite + // continue to the next sibling suite + return done(); + } else { + // errSuite is among the parents of current suite + // stop execution of errSuite and all sub-suites + return done(errSuite); + } + } + + if (self._abort) return done(); + + var curr = suite.suites[i++]; + if (!curr) return done(); + self.runSuite(curr, next); + } + + function done(errSuite) { + self.suite = suite; + self.hook('afterAll', function(){ + self.emit('suite end', suite); + fn(errSuite); + }); + } + + this.hook('beforeAll', function(err){ + if (err) return done(); + self.runTests(suite, next); + }); +}; + +/** + * Handle uncaught exceptions. + * + * @param {Error} err + * @api private + */ + +Runner.prototype.uncaught = function(err){ + if (err) { + debug('uncaught exception %s', err !== function () { + return this; + }.call(err) ? err : ( err.message || err )); + } else { + debug('uncaught undefined exception'); + err = new Error('Caught undefined error, did you throw without specifying what?'); + } + err.uncaught = true; + + var runnable = this.currentRunnable; + if (!runnable) return; + + var wasAlreadyDone = runnable.state; + this.fail(runnable, err); + + runnable.clearTimeout(); + + if (wasAlreadyDone) return; + + // recover from test + if ('test' == runnable.type) { + this.emit('test end', runnable); + this.hookUp('afterEach', this.next); + return; + } + + // bail on hooks + this.emit('end'); +}; + +/** + * Run the root suite and invoke `fn(failures)` + * on completion. + * + * @param {Function} fn + * @return {Runner} for chaining + * @api public + */ + +Runner.prototype.run = function(fn){ + var self = this + , fn = fn || function(){}; + + function uncaught(err){ + self.uncaught(err); + } + + debug('start'); + + // callback + this.on('end', function(){ + debug('end'); + process.removeListener('uncaughtException', uncaught); + fn(self.failures); + }); + + // run suites + this.emit('start'); + this.runSuite(this.suite, function(){ + debug('finished running'); + self.emit('end'); + }); + + // uncaught exception + process.on('uncaughtException', uncaught); + + return this; +}; + +/** + * Cleanly abort execution + * + * @return {Runner} for chaining + * @api public + */ +Runner.prototype.abort = function(){ + debug('aborting'); + this._abort = true; +}; + +/** + * Filter leaks with the given globals flagged as `ok`. + * + * @param {Array} ok + * @param {Array} globals + * @return {Array} + * @api private + */ + +function filterLeaks(ok, globals) { + return filter(globals, function(key){ + // Firefox and Chrome exposes iframes as index inside the window object + if (/^d+/.test(key)) return false; + + // in firefox + // if runner runs in an iframe, this iframe's window.getInterface method not init at first + // it is assigned in some seconds + if (global.navigator && /^getInterface/.test(key)) return false; + + // an iframe could be approached by window[iframeIndex] + // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak + if (global.navigator && /^\d+/.test(key)) return false; + + // Opera and IE expose global variables for HTML element IDs (issue #243) + if (/^mocha-/.test(key)) return false; + + var matched = filter(ok, function(ok){ + if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); + return key == ok; + }); + return matched.length == 0 && (!global.navigator || 'onerror' !== key); + }); +} + +/** + * Array of globals dependent on the environment. + * + * @return {Array} + * @api private + */ + + function extraGlobals() { + if (typeof(process) === 'object' && + typeof(process.version) === 'string') { + + var nodeVersion = process.version.split('.').reduce(function(a, v) { + return a << 8 | v; + }); + + // 'errno' was renamed to process._errno in v0.9.11. + + if (nodeVersion < 0x00090B) { + return ['errno']; + } + } + + return []; + } + +}); // module: runner.js + +require.register("suite.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var EventEmitter = require('browser/events').EventEmitter + , debug = require('browser/debug')('mocha:suite') + , milliseconds = require('./ms') + , utils = require('./utils') + , Hook = require('./hook'); + +/** + * Expose `Suite`. + */ + +exports = module.exports = Suite; + +/** + * Create a new `Suite` with the given `title` + * and parent `Suite`. When a suite with the + * same title is already present, that suite + * is returned to provide nicer reporter + * and more flexible meta-testing. + * + * @param {Suite} parent + * @param {String} title + * @return {Suite} + * @api public + */ + +exports.create = function(parent, title){ + var suite = new Suite(title, parent.ctx); + suite.parent = parent; + if (parent.pending) suite.pending = true; + title = suite.fullTitle(); + parent.addSuite(suite); + return suite; +}; + +/** + * Initialize a new `Suite` with the given + * `title` and `ctx`. + * + * @param {String} title + * @param {Context} ctx + * @api private + */ + +function Suite(title, parentContext) { + this.title = title; + var context = function() {}; + context.prototype = parentContext; + this.ctx = new context(); + this.suites = []; + this.tests = []; + this.pending = false; + this._beforeEach = []; + this._beforeAll = []; + this._afterEach = []; + this._afterAll = []; + this.root = !title; + this._timeout = 2000; + this._enableTimeouts = true; + this._slow = 75; + this._bail = false; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ + +function F(){}; +F.prototype = EventEmitter.prototype; +Suite.prototype = new F; +Suite.prototype.constructor = Suite; + + +/** + * Return a clone of this `Suite`. + * + * @return {Suite} + * @api private + */ + +Suite.prototype.clone = function(){ + var suite = new Suite(this.title); + debug('clone'); + suite.ctx = this.ctx; + suite.timeout(this.timeout()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); + suite.bail(this.bail()); + return suite; +}; + +/** + * Set timeout `ms` or short-hand such as "2s". + * + * @param {Number|String} ms + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.timeout = function(ms){ + if (0 == arguments.length) return this._timeout; + if (ms === 0) this._enableTimeouts = false; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('timeout %d', ms); + this._timeout = parseInt(ms, 10); + return this; +}; + +/** + * Set timeout `enabled`. + * + * @param {Boolean} enabled + * @return {Suite|Boolean} self or enabled + * @api private + */ + +Suite.prototype.enableTimeouts = function(enabled){ + if (arguments.length === 0) return this._enableTimeouts; + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Set slow `ms` or short-hand such as "2s". + * + * @param {Number|String} ms + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.slow = function(ms){ + if (0 === arguments.length) return this._slow; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('slow %d', ms); + this._slow = ms; + return this; +}; + +/** + * Sets whether to bail after first error. + * + * @parma {Boolean} bail + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.bail = function(bail){ + if (0 == arguments.length) return this._bail; + debug('bail %s', bail); + this._bail = bail; + return this; +}; + +/** + * Run `fn(test[, done])` before running tests. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.beforeAll = function(title, fn){ + if (this.pending) return this; + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"before all" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + this._beforeAll.push(hook); + this.emit('beforeAll', hook); + return this; +}; + +/** + * Run `fn(test[, done])` after running tests. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.afterAll = function(title, fn){ + if (this.pending) return this; + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"after all" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + this._afterAll.push(hook); + this.emit('afterAll', hook); + return this; +}; + +/** + * Run `fn(test[, done])` before each test case. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.beforeEach = function(title, fn){ + if (this.pending) return this; + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"before each" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + this._beforeEach.push(hook); + this.emit('beforeEach', hook); + return this; +}; + +/** + * Run `fn(test[, done])` after each test case. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.afterEach = function(title, fn){ + if (this.pending) return this; + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"after each" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + this._afterEach.push(hook); + this.emit('afterEach', hook); + return this; +}; + +/** + * Add a test `suite`. + * + * @param {Suite} suite + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.addSuite = function(suite){ + suite.parent = this; + suite.timeout(this.timeout()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); + suite.bail(this.bail()); + this.suites.push(suite); + this.emit('suite', suite); + return this; +}; + +/** + * Add a `test` to this suite. + * + * @param {Test} test + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.addTest = function(test){ + test.parent = this; + test.timeout(this.timeout()); + test.enableTimeouts(this.enableTimeouts()); + test.slow(this.slow()); + test.ctx = this.ctx; + this.tests.push(test); + this.emit('test', test); + return this; +}; + +/** + * Return the full title generated by recursively + * concatenating the parent's full title. + * + * @return {String} + * @api public + */ + +Suite.prototype.fullTitle = function(){ + if (this.parent) { + var full = this.parent.fullTitle(); + if (full) return full + ' ' + this.title; + } + return this.title; +}; + +/** + * Return the total number of tests. + * + * @return {Number} + * @api public + */ + +Suite.prototype.total = function(){ + return utils.reduce(this.suites, function(sum, suite){ + return sum + suite.total(); + }, 0) + this.tests.length; +}; + +/** + * Iterates through each suite recursively to find + * all tests. Applies a function in the format + * `fn(test)`. + * + * @param {Function} fn + * @return {Suite} + * @api private + */ + +Suite.prototype.eachTest = function(fn){ + utils.forEach(this.tests, fn); + utils.forEach(this.suites, function(suite){ + suite.eachTest(fn); + }); + return this; +}; + +}); // module: suite.js + +require.register("test.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Runnable = require('./runnable'); + +/** + * Expose `Test`. + */ + +module.exports = Test; + +/** + * Initialize a new `Test` with the given `title` and callback `fn`. + * + * @param {String} title + * @param {Function} fn + * @api private + */ + +function Test(title, fn) { + Runnable.call(this, title, fn); + this.pending = !fn; + this.type = 'test'; +} + +/** + * Inherit from `Runnable.prototype`. + */ + +function F(){}; +F.prototype = Runnable.prototype; +Test.prototype = new F; +Test.prototype.constructor = Test; + + +}); // module: test.js + +require.register("utils.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var fs = require('browser/fs') + , path = require('browser/path') + , basename = path.basename + , exists = fs.existsSync || path.existsSync + , glob = require('browser/glob') + , join = path.join + , debug = require('browser/debug')('mocha:watch'); + +/** + * Ignored directories. + */ + +var ignore = ['node_modules', '.git']; + +/** + * Escape special characters in the given string of html. + * + * @param {String} html + * @return {String} + * @api private + */ + +exports.escape = function(html){ + return String(html) + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(//g, '>'); +}; + +/** + * Array#forEach (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @param {Object} scope + * @api private + */ + +exports.forEach = function(arr, fn, scope){ + for (var i = 0, l = arr.length; i < l; i++) + fn.call(scope, arr[i], i); +}; + +/** + * Array#map (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @param {Object} scope + * @api private + */ + +exports.map = function(arr, fn, scope){ + var result = []; + for (var i = 0, l = arr.length; i < l; i++) + result.push(fn.call(scope, arr[i], i)); + return result; +}; + +/** + * Array#indexOf (<=IE8) + * + * @parma {Array} arr + * @param {Object} obj to find index of + * @param {Number} start + * @api private + */ + +exports.indexOf = function(arr, obj, start){ + for (var i = start || 0, l = arr.length; i < l; i++) { + if (arr[i] === obj) + return i; + } + return -1; +}; + +/** + * Array#reduce (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @param {Object} initial value + * @api private + */ + +exports.reduce = function(arr, fn, val){ + var rval = val; + + for (var i = 0, l = arr.length; i < l; i++) { + rval = fn(rval, arr[i], i, arr); + } + + return rval; +}; + +/** + * Array#filter (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @api private + */ + +exports.filter = function(arr, fn){ + var ret = []; + + for (var i = 0, l = arr.length; i < l; i++) { + var val = arr[i]; + if (fn(val, i, arr)) ret.push(val); + } + + return ret; +}; + +/** + * Object.keys (<=IE8) + * + * @param {Object} obj + * @return {Array} keys + * @api private + */ + +exports.keys = Object.keys || function(obj) { + var keys = [] + , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 + + for (var key in obj) { + if (has.call(obj, key)) { + keys.push(key); + } + } + + return keys; +}; + +/** + * Watch the given `files` for changes + * and invoke `fn(file)` on modification. + * + * @param {Array} files + * @param {Function} fn + * @api private + */ + +exports.watch = function(files, fn){ + var options = { interval: 100 }; + files.forEach(function(file){ + debug('file %s', file); + fs.watchFile(file, options, function(curr, prev){ + if (prev.mtime < curr.mtime) fn(file); + }); + }); +}; + +/** + * Ignored files. + */ + +function ignored(path){ + return !~ignore.indexOf(path); +} + +/** + * Lookup files in the given `dir`. + * + * @return {Array} + * @api private + */ + +exports.files = function(dir, ext, ret){ + ret = ret || []; + ext = ext || ['js']; + + var re = new RegExp('\\.(' + ext.join('|') + ')$'); + + fs.readdirSync(dir) + .filter(ignored) + .forEach(function(path){ + path = join(dir, path); + if (fs.statSync(path).isDirectory()) { + exports.files(path, ext, ret); + } else if (path.match(re)) { + ret.push(path); + } + }); + + return ret; +}; + +/** + * Compute a slug from the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.slug = function(str){ + return str + .toLowerCase() + .replace(/ +/g, '-') + .replace(/[^-\w]/g, ''); +}; + +/** + * Strip the function definition from `str`, + * and re-indent for pre whitespace. + */ + +exports.clean = function(str) { + str = str + .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '') + .replace(/^function *\(.*\) *{|\(.*\) *=> *{?/, '') + .replace(/\s+\}$/, ''); + + var spaces = str.match(/^\n?( *)/)[1].length + , tabs = str.match(/^\n?(\t*)/)[1].length + , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm'); + + str = str.replace(re, ''); + + return exports.trim(str); +}; + +/** + * Trim the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.trim = function(str){ + return str.replace(/^\s+|\s+$/g, ''); +}; + +/** + * Parse the given `qs`. + * + * @param {String} qs + * @return {Object} + * @api private + */ + +exports.parseQuery = function(qs){ + return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ + var i = pair.indexOf('=') + , key = pair.slice(0, i) + , val = pair.slice(++i); + + obj[key] = decodeURIComponent(val); + return obj; + }, {}); +}; + +/** + * Highlight the given string of `js`. + * + * @param {String} js + * @return {String} + * @api private + */ + +function highlight(js) { + return js + .replace(//g, '>') + .replace(/\/\/(.*)/gm, '//$1') + .replace(/('.*?')/gm, '$1') + .replace(/(\d+\.\d+)/gm, '$1') + .replace(/(\d+)/gm, '$1') + .replace(/\bnew[ \t]+(\w+)/gm, 'new $1') + .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') +} + +/** + * Highlight the contents of tag `name`. + * + * @param {String} name + * @api private + */ + +exports.highlightTags = function(name) { + var code = document.getElementById('mocha').getElementsByTagName(name); + for (var i = 0, len = code.length; i < len; ++i) { + code[i].innerHTML = highlight(code[i].innerHTML); + } +}; + + +/** + * Stringify `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +exports.stringify = function(obj) { + if (obj instanceof RegExp) return obj.toString(); + return JSON.stringify(exports.canonicalize(obj), null, 2).replace(/,(\n|$)/g, '$1'); +}; + +/** + * Return a new object that has the keys in sorted order. + * @param {Object} obj + * @param {Array} [stack] + * @return {Object} + * @api private + */ + +exports.canonicalize = function(obj, stack) { + stack = stack || []; + + if (exports.indexOf(stack, obj) !== -1) return '[Circular]'; + + var canonicalizedObj; + + if ({}.toString.call(obj) === '[object Array]') { + stack.push(obj); + canonicalizedObj = exports.map(obj, function (item) { + return exports.canonicalize(item, stack); + }); + stack.pop(); + } else if (typeof obj === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + exports.forEach(exports.keys(obj).sort(), function (key) { + canonicalizedObj[key] = exports.canonicalize(obj[key], stack); + }); + stack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; + }; + +/** + * Lookup file names at the given `path`. + */ +exports.lookupFiles = function lookupFiles(path, extensions, recursive) { + var files = []; + var re = new RegExp('\\.(' + extensions.join('|') + ')$'); + + if (!exists(path)) { + if (exists(path + '.js')) { + path += '.js'; + } else { + files = glob.sync(path); + if (!files.length) throw new Error("cannot resolve path (or pattern) '" + path + "'"); + return files; + } + } + + try { + var stat = fs.statSync(path); + if (stat.isFile()) return path; + } + catch (ignored) { + return; + } + + fs.readdirSync(path).forEach(function(file){ + file = join(path, file); + try { + var stat = fs.statSync(file); + if (stat.isDirectory()) { + if (recursive) { + files = files.concat(lookupFiles(file, extensions, recursive)); + } + return; + } + } + catch (ignored) { + return; + } + if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') return; + files.push(file); + }); + + return files; +}; + +}); // module: utils.js +// The global object is "self" in Web Workers. +var global = (function() { return this; })(); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; + +/** + * Node shims. + * + * These are meant only to allow + * mocha.js to run untouched, not + * to allow running node code in + * the browser. + */ + +var process = {}; +process.exit = function(status){}; +process.stdout = {}; + +var uncaughtExceptionHandlers = []; + +var originalOnerrorHandler = global.onerror; + +/** + * Remove uncaughtException listener. + * Revert to original onerror handler if previously defined. + */ + +process.removeListener = function(e, fn){ + if ('uncaughtException' == e) { + if (originalOnerrorHandler) { + global.onerror = originalOnerrorHandler; + } else { + global.onerror = function() {}; + } + var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn); + if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); } + } +}; + +/** + * Implements uncaughtException listener. + */ + +process.on = function(e, fn){ + if ('uncaughtException' == e) { + global.onerror = function(err, url, line){ + fn(new Error(err + ' (' + url + ':' + line + ')')); + return true; + }; + uncaughtExceptionHandlers.push(fn); + } +}; + +/** + * Expose mocha. + */ + +var Mocha = global.Mocha = require('mocha'), + mocha = global.mocha = new Mocha({ reporter: 'html' }); + +// The BDD UI is registered by default, but no UI will be functional in the +// browser without an explicit call to the overridden `mocha.ui` (see below). +// Ensure that this default UI does not expose its methods to the global scope. +mocha.suite.removeAllListeners('pre-require'); + +var immediateQueue = [] + , immediateTimeout; + +function timeslice() { + var immediateStart = new Date().getTime(); + while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { + immediateQueue.shift()(); + } + if (immediateQueue.length) { + immediateTimeout = setTimeout(timeslice, 0); + } else { + immediateTimeout = null; + } +} + +/** + * High-performance override of Runner.immediately. + */ + +Mocha.Runner.immediately = function(callback) { + immediateQueue.push(callback); + if (!immediateTimeout) { + immediateTimeout = setTimeout(timeslice, 0); + } +}; + +/** + * Function to allow assertion libraries to throw errors directly into mocha. + * This is useful when running tests in a browser because window.onerror will + * only receive the 'message' attribute of the Error. + */ +mocha.throwError = function(err) { + Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) { + fn(err); + }); + throw err; +}; + +/** + * Override ui to ensure that the ui functions are initialized. + * Normally this would happen in Mocha.prototype.loadFiles. + */ + +mocha.ui = function(ui){ + Mocha.prototype.ui.call(this, ui); + this.suite.emit('pre-require', global, null, this); + return this; +}; + +/** + * Setup mocha with the given setting options. + */ + +mocha.setup = function(opts){ + if ('string' == typeof opts) opts = { ui: opts }; + for (var opt in opts) this[opt](opts[opt]); + return this; +}; + +/** + * Run mocha, returning the Runner. + */ + +mocha.run = function(fn){ + var options = mocha.options; + mocha.globals('location'); + + var query = Mocha.utils.parseQuery(global.location.search || ''); + if (query.grep) mocha.grep(query.grep); + if (query.invert) mocha.invert(); + + return Mocha.prototype.run.call(mocha, function(err){ + // The DOM Document is not available in Web Workers. + var document = global.document; + if (document && document.getElementById('mocha') && options.noHighlighting !== true) { + Mocha.utils.highlightTags('code'); + } + if (fn) fn(err); + }); +}; + +/** + * Expose the process shim. + */ + +Mocha.process = process; +})(); \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js new file mode 100644 index 0000000..7ad9f8a --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js @@ -0,0 +1,16 @@ +importScripts('es6-promise.js'); +new ES6Promise.Promise(function(resolve, reject) { + self.onmessage = function (e) { + if (e.data === 'ping') { + resolve('pong'); + } else { + reject(new Error('wrong message')); + } + }; +}).then(function (result) { + self.postMessage(result); +}, function (err){ + setTimeout(function () { + throw err; + }); +}); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js new file mode 100644 index 0000000..5984f70 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js @@ -0,0 +1,18 @@ +import Promise from './es6-promise/promise'; +import polyfill from './es6-promise/polyfill'; + +var ES6Promise = { + 'Promise': Promise, + 'polyfill': polyfill +}; + +/* global define:true module:true window: true */ +if (typeof define === 'function' && define['amd']) { + define(function() { return ES6Promise; }); +} else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = ES6Promise; +} else if (typeof this !== 'undefined') { + this['ES6Promise'] = ES6Promise; +} + +polyfill(); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js new file mode 100644 index 0000000..daee2c3 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js @@ -0,0 +1,250 @@ +import { + objectOrFunction, + isFunction +} from './utils'; + +import asap from './asap'; + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var GET_THEN_ERROR = new ErrorObject(); + +function selfFullfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function getThen(promise) { + try { + return promise.then; + } catch(error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} + +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then) { + asap(function(promise) { + var sealed = false; + var error = tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function(value) { + resolve(promise, value); + }, function(reason) { + reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + handleOwnThenable(promise, maybeThenable); + } else { + var then = getThen(maybeThenable); + + if (then === GET_THEN_ERROR) { + reject(promise, GET_THEN_ERROR.error); + } else if (then === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then)) { + handleForeignThenable(promise, maybeThenable, then); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function resolve(promise, value) { + if (promise === value) { + reject(promise, selfFullfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { return; } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function reject(promise, reason) { + if (promise._state !== PENDING) { return; } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + FULFILLED] = onFulfillment; + subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} + +var TRY_CATCH_ERROR = new ErrorObject(); + +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + reject(promise, cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + resolve(promise, value); + }, function rejectPromise(reason) { + reject(promise, reason); + }); + } catch(e) { + reject(promise, e); + } +} + +export { + noop, + resolve, + reject, + fulfill, + subscribe, + publish, + publishRejection, + initializePromise, + invokeCallback, + FULFILLED, + REJECTED, + PENDING +}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js new file mode 100644 index 0000000..4f7dcee --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js @@ -0,0 +1,111 @@ +var len = 0; +var toString = {}.toString; +var vertxNext; +export default function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + scheduleFlush(); + } +} + +var browserWindow = (typeof window !== 'undefined') ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + var nextTick = process.nextTick; + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // setImmediate should be used instead instead + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function() { + nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + return function() { + vertxNext(flush); + }; +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + return function() { + setTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i+=2) { + var callback = queue[i]; + var arg = queue[i+1]; + + callback(arg); + + queue[i] = undefined; + queue[i+1] = undefined; + } + + len = 0; +} + +function attemptVertex() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch(e) { + return useSetTimeout(); + } +} + +var scheduleFlush; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && typeof require === 'function') { + scheduleFlush = attemptVertex(); +} else { + scheduleFlush = useSetTimeout(); +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js new file mode 100644 index 0000000..03fdf8c --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js @@ -0,0 +1,113 @@ +import { + isArray, + isMaybeThenable +} from './utils'; + +import { + noop, + reject, + fulfill, + subscribe, + FULFILLED, + REJECTED, + PENDING +} from './-internal'; + +function Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + fulfill(enumerator.promise, enumerator._result); + } + } + } else { + reject(enumerator.promise, enumerator._validationError()); + } +} + +Enumerator.prototype._validateInput = function(input) { + return isArray(input); +}; + +Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); +}; + +Enumerator.prototype._init = function() { + this._result = new Array(this.length); +}; + +export default Enumerator; + +Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } +}; + +Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } +}; + +Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === PENDING) { + enumerator._remaining--; + + if (state === REJECTED) { + reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + fulfill(promise, enumerator._result); + } +}; + +Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function(value) { + enumerator._settledAt(FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(REJECTED, i, reason); + }); +}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js new file mode 100644 index 0000000..6696dfc --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js @@ -0,0 +1,26 @@ +/*global self*/ +import Promise from './promise'; + +export default function polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = Promise; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js new file mode 100644 index 0000000..78fe2ca --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js @@ -0,0 +1,408 @@ +import { + isFunction +} from './utils'; + +import { + noop, + subscribe, + initializePromise, + invokeCallback, + FULFILLED, + REJECTED +} from './-internal'; + +import asap from './asap'; + +import all from './promise/all'; +import race from './promise/race'; +import Resolve from './promise/resolve'; +import Reject from './promise/reject'; + +var counter = 0; + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +export default Promise; +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this._id = counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (noop !== resolver) { + if (!isFunction(resolver)) { + needsResolver(); + } + + if (!(this instanceof Promise)) { + needsNew(); + } + + initializePromise(this, resolver); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = Resolve; +Promise.reject = Reject; + +Promise.prototype = { + constructor: Promise, + +/** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} +*/ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + asap(function(){ + invokeCallback(state, child, callback, result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + +/** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} +*/ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } +}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js new file mode 100644 index 0000000..03033f0 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js @@ -0,0 +1,52 @@ +import Enumerator from '../enumerator'; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = resolve(2); + var promise3 = resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = reject(new Error("2")); + var promise3 = reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +export default function all(entries) { + return new Enumerator(this, entries).promise; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js new file mode 100644 index 0000000..0d7ff13 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js @@ -0,0 +1,104 @@ +import { + isArray +} from "../utils"; + +import { + noop, + resolve, + reject, + subscribe, + PENDING +} from '../-internal'; + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +export default function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(noop); + + if (!isArray(entries)) { + reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + resolve(promise, value); + } + + function onRejection(reason) { + reject(promise, reason); + } + + for (var i = 0; promise._state === PENDING && i < length; i++) { + subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js new file mode 100644 index 0000000..63b86cb --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js @@ -0,0 +1,46 @@ +import { + noop, + reject as _reject +} from '../-internal'; + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +export default function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js new file mode 100644 index 0000000..201a545 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js @@ -0,0 +1,48 @@ +import { + noop, + resolve as _resolve +} from '../-internal'; + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +export default function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js new file mode 100644 index 0000000..31ec6f9 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js @@ -0,0 +1,22 @@ +export function objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); +} + +export function isFunction(x) { + return typeof x === 'function'; +} + +export function isMaybeThenable(x) { + return typeof x === 'object' && x !== null; +} + +var _isArray; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +export var isArray = _isArray; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/package.json b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/package.json new file mode 100644 index 0000000..6fc9a80 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/package.json @@ -0,0 +1,88 @@ +{ + "name": "es6-promise", + "namespace": "es6-promise", + "version": "2.1.1", + "description": "A lightweight library that provides tools for organizing asynchronous code", + "main": "dist/es6-promise.js", + "directories": { + "lib": "lib" + }, + "files": [ + "dist", + "lib" + ], + "devDependencies": { + "bower": "^1.3.9", + "brfs": "0.0.8", + "broccoli-es3-safe-recast": "0.0.8", + "broccoli-es6-module-transpiler": "^0.5.0", + "broccoli-jshint": "^0.5.1", + "broccoli-merge-trees": "^0.1.4", + "broccoli-replace": "^0.2.0", + "broccoli-stew": "0.0.6", + "broccoli-uglify-js": "^0.1.3", + "broccoli-watchify": "^0.2.0", + "ember-cli": "^0.2.2", + "ember-publisher": "0.0.7", + "git-repo-version": "0.0.2", + "json3": "^3.3.2", + "minimatch": "^2.0.1", + "mocha": "^1.20.1", + "promises-aplus-tests-phantom": "^2.1.0-revise", + "release-it": "0.0.10" + }, + "scripts": { + "build": "ember build", + "start": "ember s", + "test": "ember test", + "test:server": "ember test --server", + "test:node": "ember build && mocha ./dist/test/browserify", + "lint": "jshint lib", + "prepublish": "ember build --environment production", + "dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive" + }, + "repository": { + "type": "git", + "url": "git://github.com/jakearchibald/ES6-Promises.git" + }, + "bugs": { + "url": "https://github.com/jakearchibald/ES6-Promises/issues" + }, + "browser": { + "vertx": false + }, + "keywords": [ + "promises", + "futures" + ], + "author": { + "name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors", + "url": "Conversion to ES6 API by Jake Archibald" + }, + "license": "MIT", + "spm": { + "main": "dist/es6-promise.js" + }, + "gitHead": "02cf697c50856f0cd3785f425a2cf819af0e521c", + "homepage": "https://github.com/jakearchibald/ES6-Promises", + "_id": "es6-promise@2.1.1", + "_shasum": "03e8f3c7297928e5478d6ab1d0643251507bdedd", + "_from": "es6-promise@2.1.1", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.1", + "_npmUser": { + "name": "jaffathecake", + "email": "jaffathecake@gmail.com" + }, + "maintainers": [ + { + "name": "jaffathecake", + "email": "jaffathecake@gmail.com" + } + ], + "dist": { + "shasum": "03e8f3c7297928e5478d6ab1d0643251507bdedd", + "tarball": "http://registry.npmjs.org/es6-promise/-/es6-promise-2.1.1.tgz" + }, + "_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-2.1.1.tgz" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md new file mode 100644 index 0000000..a21da87 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md @@ -0,0 +1,246 @@ +1.2.14 09-28-2015 +----------------- +- NODE-547 only emit error if there are any listeners. +- Fixed APM issue with issuing readConcern. + +1.2.13 09-18-2015 +----------------- +- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. + +1.2.12 09-08-2015 +----------------- +- NODE-541 Added initial support for readConcern. + +1.2.11 08-31-2015 +----------------- +- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. +- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. +- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). + +1.2.10 08-14-2015 +----------------- +- Added missing Mongos.prototype.parserType function. + +1.2.9 08-05-2015 +---------------- +- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +- NODE-518 connectTimeoutMS is doubled in 2.0.39. + +1.2.8 07-24-2015 +----------------- +- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. + +1.2.7 07-16-2015 +----------------- +- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. + +1.2.6 07-14-2015 +----------------- +- NODE-505 Query fails to find records that have a 'result' property with an array value. + +1.2.5 07-14-2015 +----------------- +- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. + +1.2.4 07-07-2015 +----------------- +- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. + +1.2.3 06-26-2015 +----------------- +- Minor bug fixes. + +1.2.2 06-22-2015 +----------------- +- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). + +1.2.1 06-17-2015 +----------------- +- Ensure serializeFunctions passed down correctly to wire protocol. + +1.2.0 06-17-2015 +----------------- +- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. +- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. +- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +1.1.33 05-31-2015 +----------------- +- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. + +1.1.32 05-20-2015 +----------------- +- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) + +1.1.31 05-19-2015 +----------------- +- Minor fixes for issues with re-authentication of mongos. + +1.1.30 05-18-2015 +----------------- +- Correctly emit 'all' event when primary + all secondaries have connected. + +1.1.29 05-17-2015 +----------------- +- NODE-464 Only use a single socket against arbiters and hidden servers. +- Ensure we filter out hidden servers from any server queries. + +1.1.28 05-12-2015 +----------------- +- Fixed buffer compare for electionId for < node 12.0.2 + +1.1.27 05-12-2015 +----------------- +- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. + +1.1.26 05-06-2015 +----------------- +- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. +- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. + +1.1.25 04-24-2015 +----------------- +- Handle lack of callback in crud operations when returning error on application closed. + +1.1.24 04-22-2015 +----------------- +- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. + +1.1.23 04-15-2015 +----------------- +- Standardizing mongoErrors and its API (Issue #14) +- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) +- remove mkdirp and rimraf dependencies (Issue #12) +- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) +- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) +- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) + +1.1.22 04-10-2015 +----------------- +- Minor refactorings in cursor code to make extending the cursor simpler. +- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. + +1.1.21 03-26-2015 +----------------- +- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. + +1.1.20 03-24-2015 +----------------- +- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. + +1.1.19 03-21-2015 +----------------- +- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. + +1.1.18 03-17-2015 +----------------- +- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. + +1.1.17 03-16-2015 +----------------- +- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. + +1.1.16 03-06-2015 +----------------- +- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. + +1.1.15 03-04-2015 +----------------- +- Removed check for type in replset pickserver function. + +1.1.14 02-26-2015 +----------------- +- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads + +1.1.13 02-24-2015 +----------------- +- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) + +1.1.12 02-16-2015 +----------------- +- Fixed cursor transforms for buffered document reads from cursor. + +1.1.11 02-02-2015 +----------------- +- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +1.1.10 31-01-2015 +----------------- +- Added tranforms.doc option to cursor to allow for pr. document transformations. + +1.1.9 21-01-2015 +---------------- +- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. +- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. +- Don't treat findOne() as a command cursor. +- Refactored out state changes into methods to simplify read the next method. + +1.1.8 09-12-2015 +---------------- +- Stripped out Object.defineProperty for performance reasons +- Applied more performance optimizations. +- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit + +1.1.7 18-12-2014 +---------------- +- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. + +1.1.6 18-12-2014 +---------------- +- Server manager fixed to support 2.2.X servers for travis test matrix. + +1.1.5 17-12-2014 +---------------- +- Fall back to errmsg when creating MongoError for command errors + +1.1.4 17-12-2014 +---------------- +- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. +- Fixed variable leak in scram. +- Fixed server manager to deal better with killing processes. +- Bumped bson to 0.2.16. + +1.1.3 01-12-2014 +---------------- +- Fixed error handling issue with nonce generation in mongocr. +- Fixed issues with restarting servers when using ssl. +- Using strict for all classes. +- Cleaned up any escaping global variables. + +1.1.2 20-11-2014 +---------------- +- Correctly encoding UTF8 collection names on wire protocol messages. +- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. + +1.1.1 14-11-2014 +---------------- +- Refactored code to use prototype instead of privileged methods. +- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. +- Several deopt optimizations for v8 to improve performance and reduce GC pauses. + +1.0.5 29-10-2014 +---------------- +- Fixed issue with wrong namespace being created for command cursors. + +1.0.4 24-10-2014 +---------------- +- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. + +1.0.3 21-10-2014 +---------------- +- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. + +1.0.2 07-10-2014 +---------------- +- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. +- fixed issue with replset_state logging. + +1.0.1 07-10-2014 +---------------- +- Dependency issue solved + +1.0.0 07-10-2014 +---------------- +- Initial release of mongodb-core diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile new file mode 100644 index 0000000..36e1202 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/README.md new file mode 100644 index 0000000..1c9e4c8 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/README.md @@ -0,0 +1,225 @@ +# Description + +The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. + +## MongoDB Node.JS Core Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/christkv/mongodb-core | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login . +- Navigate to the NODE project . +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +# QuickStart + +The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. + +## Create the package.json file + +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Create a **package.json** using your favorite text editor and fill it in. + +```json +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb-core": "~1.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +## Connecting to MongoDB + +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + test.done(); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + + // Execute the ismaster command + _server.command('system.$cmd', {ismaster: true}, function(err, result) { + + // Perform a document insert + _server.insert('myproject.inserts1', [{a:1}, {a:2}], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(2, results.result.n); + + // Perform a document update + _server.update('myproject.inserts1', [{ + q: {a: 1}, u: {'$set': {b:1}} + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Remove a document + _server.remove('myproject.inserts1', [{ + q: {a: 1}, limit: 1 + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Get a document + var cursor = _server.cursor('integration_tests.inserts_example4', { + find: 'integration_tests.example4' + , query: {a:1} + }); + + // Get the first document + cursor.next(function(err, doc) { + assert.equal(null, err); + assert.equal(2, doc.a); + + // Execute the ismaster command + _server.command("system.$cmd" + , {ismaster: true}, function(err, result) { + assert.equal(null, err) + _server.destroy(); + }); + }); + }); + }); + + test.done(); + }); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. + +* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. +* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. +* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. +* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. +* `command`, Executes a command against MongoDB and returns the result. +* `auth`, Authenticates the current topology using a supported authentication scheme. + +The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. + +## Next steps + +The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md new file mode 100644 index 0000000..fe03ea0 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md @@ -0,0 +1,18 @@ +Testing setup +============= + +Single Server +------------- +mongod --dbpath=./db + +Replicaset +---------- +mongo --nodb +var x = new ReplSetTest({"useHostName":"false", "nodes" : {node0 : {}, node1 : {}, node2 : {}}}) +x.startSet(); +var config = x.getReplSetConfig() +x.initiate(config); + +Mongos +------ +var s = new ShardingTest( "auth1", 1 , 0 , 2 , {rs: true, noChunkSize : true}); \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json new file mode 100644 index 0000000..c5eca92 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json @@ -0,0 +1,60 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/tests/functional/operation_example_tests.js", + "lib/topologies/mongos.js", + "lib/topologies/command_result.js", + "lib/topologies/read_preference.js", + "lib/topologies/replset.js", + "lib/topologies/server.js", + "lib/topologies/session.js", + "lib/topologies/replset_state.js", + "lib/connection/logger.js", + "lib/connection/connection.js", + "lib/cursor.js", + "lib/error.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/index.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/index.js new file mode 100644 index 0000000..8f10860 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/index.js @@ -0,0 +1,18 @@ +module.exports = { + MongoError: require('./lib/error') + , Server: require('./lib/topologies/server') + , ReplSet: require('./lib/topologies/replset') + , Mongos: require('./lib/topologies/mongos') + , Logger: require('./lib/connection/logger') + , Cursor: require('./lib/cursor') + , ReadPreference: require('./lib/topologies/read_preference') + , BSON: require('bson') + // Raw operations + , Query: require('./lib/connection/commands').Query + // Auth mechanisms + , MongoCR: require('./lib/auth/mongocr') + , X509: require('./lib/auth/x509') + , Plain: require('./lib/auth/plain') + , GSSAPI: require('./lib/auth/gssapi') + , ScramSHA1: require('./lib/auth/scram') +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js new file mode 100644 index 0000000..c442b9b --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js @@ -0,0 +1,244 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require('kerberos').Kerberos + // Authentication process for Mongo + MongoAuthProcess = require('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @return {GSSAPI} A cursor instance + */ +var GSSAPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.auth = function(server, pool, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + GSSAPIInitialize(db, username, password, db, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// +// Initialize step +var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, server, connection, callback) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); + + // Perform initialization + mongo_auth_process.init(username, password, function(err, context) { + if(err) return callback(err, false); + + // Perform the first step + mongo_auth_process.transition('', function(err, payload) { + if(err) return callback(err, false); + + // Call the next db step + MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback) { + // Build the sasl start command + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: payload + , autoAuthorize: 1 + }; + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Execute mongodb transition + mongo_auth_process.transition(r.result.payload, function(err, payload) { + if(err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Call next transition for kerberos + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err, false); + + // Call the last and third step + MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build final command + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + mongo_auth_process.transition(null, function(err, payload) { + if(err) return callback(err, null); + callback(null, r); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js new file mode 100644 index 0000000..d0e9f59 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js @@ -0,0 +1,160 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new MongoCR authentication mechanism + * @class + * @return {MongoCR} A cursor instance + */ +var MongoCR = function() { + this.authStore = []; +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var executeMongoCR = function(connection) { + // Let's start the process + server.command(f("%s.$cmd", db) + , { getnonce: 1 } + , { connection: connection }, function(err, r) { + var nonce = null; + var key = null; + + // Adjust the number of connections left + // Get nonce + if(err == null) { + nonce = r.result.nonce; + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password); + key = md5.digest('hex'); + } + + // Execute command + server.command(f("%s.$cmd", db) + , { authenticate: 1, user: username, nonce: nonce, key:key} + , { connection: connection }, function(err, r) { + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + }); + } + + // Get the connection + executeMongoCR(connections.shift()); + } +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = MongoCR; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js new file mode 100644 index 0000000..31ce872 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js @@ -0,0 +1,150 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new Plain authentication mechanism + * @class + * @return {Plain} A cursor instance + */ +var Plain = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Create payload + var payload = new Binary(f("\x00%s\x00%s", username, password)); + + // Let's start the sasl process + var command = { + saslStart: 1 + , mechanism: 'PLAIN' + , payload: payload + , autoAuthorize: 1 + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = Plain; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js new file mode 100644 index 0000000..fe96637 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js @@ -0,0 +1,317 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new ScramSHA1 authentication mechanism + * @class + * @return {ScramSHA1} A cursor instance + */ +var ScramSHA1 = function() { + this.authStore = []; +} + +var parsePayload = function(payload) { + var dict = {}; + var parts = payload.split(','); + + for(var i = 0; i < parts.length; i++) { + var valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +} + +var passwordDigest = function(username, password) { + if(typeof username != 'string') throw new MongoError("username must be a string"); + if(typeof password != 'string') throw new MongoError("password must be a string"); + if(password.length == 0) throw new MongoError("password cannot be empty"); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + return md5.digest('hex'); +} + +// XOR two buffers +var xor = function(a, b) { + if (!Buffer.isBuffer(a)) a = new Buffer(a) + if (!Buffer.isBuffer(b)) b = new Buffer(b) + var res = [] + if (a.length > b.length) { + for (var i = 0; i < b.length; i++) { + res.push(a[i] ^ b[i]) + } + } else { + for (var i = 0; i < a.length; i++) { + res.push(a[i] ^ b[i]) + } + } + return new Buffer(res); +} + +// Create a final digest +var hi = function(data, salt, iterations) { + // Create digest + var digest = function(msg) { + var hmac = crypto.createHmac('sha1', data); + hmac.update(msg); + return new Buffer(hmac.digest('base64'), 'base64'); + } + + // Create variables + salt = Buffer.concat([salt, new Buffer('\x00\x00\x00\x01')]) + var ui = digest(salt); + var u1 = ui; + + for(var i = 0; i < iterations - 1; i++) { + u1 = digest(u1); + ui = xor(ui, u1); + } + + return ui; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var executeScram = function(connection) { + // Clean up the user + username = username.replace('=', "=3D").replace(',', '=2C'); + + // Create a random nonce + var nonce = crypto.randomBytes(24).toString('base64'); + // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' + var firstBare = f("n=%s,r=%s", username, nonce); + + // Build command structure + var cmd = { + saslStart: 1 + , mechanism: 'SCRAM-SHA-1' + , payload: new Binary(f("n,,%s", firstBare)) + , autoAuthorize: 1 + } + + // Handle the error + var handleError = function(err, r) { + if(err) { + numberOfValidConnections = numberOfValidConnections - 1; + errorObject = err; return false; + } else if(r.result['$err']) { + errorObject = r.result; return false; + } else if(r.result['errmsg']) { + errorObject = r.result; return false; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + return true + } + + // Finish up + var finish = function(_count, _numberOfValidConnections) { + if(_count == 0 && _numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(_count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + } + + var handleEnd = function(_err, _r) { + // Handle any error + handleError(_err, _r) + // Adjust the number of connections + count = count - 1; + // Execute the finish + finish(count, numberOfValidConnections); + } + + // Execute start sasl command + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + + // Do we have an error, handle it + if(handleError(err, r) == false) { + count = count - 1; + + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + + return; + } + + // Get the dictionary + var dict = parsePayload(r.result.payload.value()) + + // Unpack dictionary + var iterations = parseInt(dict.i, 10); + var salt = dict.s; + var rnonce = dict.r; + + // Set up start of proof + var withoutProof = f("c=biws,r=%s", rnonce); + var passwordDig = passwordDigest(username, password); + var saltedPassword = hi(passwordDig + , new Buffer(salt, 'base64') + , iterations); + + // Create the client key + var hmac = crypto.createHmac('sha1', saltedPassword); + hmac.update(new Buffer("Client Key")); + var clientKey = new Buffer(hmac.digest('base64'), 'base64'); + + // Create the stored key + var hash = crypto.createHash('sha1'); + hash.update(clientKey); + var storedKey = new Buffer(hash.digest('base64'), 'base64'); + + // Create the authentication message + var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(','); + + // Create client signature + var hmac = crypto.createHmac('sha1', storedKey); + hmac.update(new Buffer(authMsg)); + var clientSig = new Buffer(hmac.digest('base64'), 'base64'); + + // Create client proof + var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64')); + + // Create client final + var clientFinal = [withoutProof, clientProof].join(','); + + // Generate server key + var hmac = crypto.createHmac('sha1', saltedPassword); + hmac.update(new Buffer('Server Key')) + var serverKey = new Buffer(hmac.digest('base64'), 'base64'); + + // Generate server signature + var hmac = crypto.createHmac('sha1', serverKey); + hmac.update(new Buffer(authMsg)) + var serverSig = new Buffer(hmac.digest('base64'), 'base64'); + + // + // Create continue message + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Binary(new Buffer(clientFinal)) + } + + // + // Execute sasl continue + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + if(r && r.result.done == false) { + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Buffer(0) + } + + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + handleEnd(err, r); + }); + } else { + handleEnd(err, r); + } + }); + }); + } + + // Get the connection + executeScram(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + + +module.exports = ScramSHA1; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js new file mode 100644 index 0000000..177ede5 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js @@ -0,0 +1,234 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require('kerberos').Kerberos + // Authentication process for Mongo + MongoAuthProcess = require('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new SSPI authentication mechanism + * @class + * @return {SSPI} A cursor instance + */ +var SSPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.auth = function(server, pool, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + SSIPAuthenticate(username, password, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r && typeof r == 'object' && r.result['$err']) { + errorObject = r.result; + } else if(r && typeof r == 'object' && r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +var SSIPAuthenticate = function(username, password, gssapiServiceName, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: '' + , autoAuthorize: 1 + }; + + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.init(username, password, function(err) { + if(err) return callback(err); + + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err); + + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err); + + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.transition(doc.payload, function(err, payload) { + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + if(doc.done) return callback(null, true); + callback(new Error("Authentication failed"), false); + }); + }); + }); + }); + }); + }); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = SSPI; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js new file mode 100644 index 0000000..641990e --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js @@ -0,0 +1,145 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new X509 authentication mechanism + * @class + * @return {X509} A cursor instance + */ +var X509 = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Let's start the sasl process + var command = { + authenticate: 1 + , mechanism: 'MONGODB-X509' + , user: username + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = X509; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js new file mode 100644 index 0000000..05023b4 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js @@ -0,0 +1,519 @@ +"use strict"; + +var f = require('util').format + , Long = require('bson').Long + , setProperty = require('./utils').setProperty + , getProperty = require('./utils').getProperty + , getSingleProperty = require('./utils').getSingleProperty; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var OP_QUERY = 2004; +var OP_GETMORE = 2005; +var OP_KILL_CURSORS = 2007; + +// Query flags +var OPTS_NONE = 0; +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 0; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if(ns == null) throw new Error("ns must be specified for query"); + if(query == null) throw new Error("query must be specified for query"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new Error("namespace cannot contain a null character"); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = _requestId++; + + // Serialization option + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = false; + this.oplogReply = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +} + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +} + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if(this.tailable) flags |= OPTS_TAILABLE_CURSOR; + if(this.slaveOk) flags |= OPTS_SLAVE; + if(this.oplogReply) flags |= OPTS_OPLOG_REPLAY; + if(this.noCursorTimeout) flags |= OPTS_NO_CURSOR_TIMEOUT; + if(this.awaitData) flags |= OPTS_AWAIT_DATA; + if(this.exhaust) flags |= OPTS_EXHAUST; + if(this.partial) flags |= OPTS_PARTIAL; + + // If batchSize is different to self.numberToReturn + if(self.batchSize != self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(self.ns) + 1 // namespace + + 4 // numberToSkip + + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + + // Add query document + buffers.push(query); + + if(self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, this.checkKeys, true, this.serializeFunctions, this.ignoreUndefined); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = (totalLength) & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (OP_QUERY >> 24) & 0xff; + header[index + 2] = (OP_QUERY >> 16) & 0xff; + header[index + 1] = (OP_QUERY >> 8) & 0xff; + header[index] = (OP_QUERY) & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = (flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = (this.numberToSkip) & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +Query.getRequestId = function() { + return ++_requestId; +} + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; + _buffer[index] = (OP_GETMORE) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getHighBits()) & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +} + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, cursorIds) { + this.requestId = _requestId++; + this.cursorIds = cursorIds; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); + + // Create command buffer + var index = 0; + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = (OP_KILL_CURSORS) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = (this.cursorIds.length) & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for(var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getHighBits()) & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +} + +var Response = function(bson, data, opts) { + opts = opts || {promoteLongs: true}; + this.parsed = false; + + // + // Parse Header + // + this.index = 0; + this.raw = data; + this.data = data; + this.bson = bson; + this.opts = opts; + + // Read the message length + this.length = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the request id for this reply + this.requestId = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the id of the request that triggered the response + this.responseTo = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Skip op-code field + this.index = this.index + 4; + + // Unpack flags + this.responseFlags = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the cursor + var lowBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + var highBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + // Create long object + this.cursorId = new Long(lowBits, highBits); + + // Unpack the starting from + this.startingFrom = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the number of objects returned + this.numberReturned = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) != 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) != 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) != 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) != 0; + this.promoteLongs = typeof opts.promoteLongs == 'boolean' ? opts.promoteLongs : true; +} + +Response.prototype.isParsed = function() { + return this.parsed; +} + +// Validation buffers +var firstBatch = new Buffer('firstBatch', 'utf8'); +var nextBatch = new Buffer('nextBatch', 'utf8'); +var cursorId = new Buffer('id', 'utf8').toString('hex'); + +var documentBuffers = { + firstBatch: firstBatch.toString('hex'), + nextBatch: nextBatch.toString('hex') +}; + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if(this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + + // + // Single document and documentsReturnedIn set + // + if(this.numberReturned == 1 && documentsReturnedIn != null && raw) { + // Calculate the bson size + var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Slice out the buffer containing the command result document + var document = this.data.slice(this.index, this.index + bsonSize); + // Set up field we wish to keep as raw + var fieldsAsRaw = {} + fieldsAsRaw[documentsReturnedIn] = true; + // Set up the options + var _options = {promoteLongs: this.opts.promoteLongs, fieldsAsRaw: fieldsAsRaw}; + + // Deserialize but keep the array of documents in non-parsed form + var doc = this.bson.deserialize(document, _options); + + // Get the documents + this.documents = doc.cursor[documentsReturnedIn]; + this.numberReturned = this.documents.length; + // Ensure we have a Long valie cursor id + this.cursorId = typeof doc.cursor.id == 'number' + ? Long.fromNumber(doc.cursor.id) + : doc.cursor.id; + + // Adjust the index + this.index = this.index + bsonSize; + + // Set as parsed + this.parsed = true + return; + } + + // + // Parse Body + // + for(var i = 0; i < this.numberReturned; i++) { + var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Parse options + var _options = {promoteLongs: this.opts.promoteLongs}; + + // If we have raw results specified slice the return document + if(raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + // Set parsed + this.parsed = true; +} + +module.exports = { + Query: Query + , GetMore: GetMore + , Response: Response + , KillCursor: KillCursor +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js new file mode 100644 index 0000000..217e58a --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js @@ -0,0 +1,462 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , net = require('net') + , tls = require('tls') + , f = require('util').format + , getSingleProperty = require('./utils').getSingleProperty + , debugOptions = require('./utils').debugOptions + , Response = require('./commands').Response + , MongoError = require('../error') + , Logger = require('./logger'); + +var _id = 0; +var debugFields = ['host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay' + , 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert' + , 'rejectUnauthorized', 'promoteLongs']; + +/** + * Creates a new Connection instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @return {Connection} A cursor instance + */ +var Connection = function(options) { + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + // Identification information + this.id = _id++; + // Logger instance + this.logger = Logger('Connection', options); + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Get bson parser + this.bson = options.bson; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Message handler + this.messageHandler = options.messageHandler; + + // Max BSON message size + this.maxBsonMessageSize = options.maxBsonMessageSize || (1024 * 1024 * 16 * 4); + // Debug information + if(this.logger.isDebug()) this.logger.debug(f('creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)))); + + // Default options + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0; + this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; + this.connectionTimeout = options.connectionTimeout || 0; + this.socketTimeout = options.socketTimeout || 0; + + // If connection was destroyed + this.destroyed = false; + + // Check if we have a domain socket + this.domainSocket = this.host.indexOf('\/') != -1; + + // Serialize commands using function + this.singleBufferSerializtion = typeof options.singleBufferSerializtion == 'boolean' ? options.singleBufferSerializtion : true; + this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; + + // SSL options + this.ca = options.ca || null; + this.cert = options.cert || null; + this.key = options.key || null; + this.passphrase = options.passphrase || null; + this.ssl = typeof options.ssl == 'boolean' ? options.ssl : false; + this.rejectUnauthorized = typeof options.rejectUnauthorized == 'boolean' ? options.rejectUnauthorized : true + + // If ssl not enabled + if(!this.ssl) this.rejectUnauthorized = false; + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true + } + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.connection = null; + this.writeStream = null; +} + +inherits(Connection, EventEmitter); + +// +// Connection handlers +var errorHandler = function(self) { + return function(err) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err))); + // Emit the error + if(self.listeners('error').length > 0) self.emit("error", MongoError.create(err), self); + } +} + +var timeoutHandler = function(self) { + return function() { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); + // Emit timeout error + self.emit("timeout" + , MongoError.create(f("connection %s to %s:%s timed out", self.id, self.host, self.port)) + , self); + } +} + +var closeHandler = function(self) { + return function(hadError) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); + // Emit close event + if(!hadError) { + self.emit("close" + , MongoError.create(f("connection %s to %s:%s closed", self.id, self.host, self.port)) + , self); + } + } +} + +var dataHandler = function(self) { + return function(data) { + // Parse until we are done with the data + while(data.length > 0) { + // If we still have bytes to read on the current message + if(self.bytesRead > 0 && self.sizeOfMessage > 0) { + // Calculate the amount of remaining bytes + var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; + // Check if the current chunk contains the rest of the message + if(remainingBytesToRead > data.length) { + // Copy the new data into the exiting buffer (should have been allocated when we know the message size) + data.copy(self.buffer, self.bytesRead); + // Adjust the number of bytes read so it point to the correct index in the buffer + self.bytesRead = self.bytesRead + data.length; + + // Reset state of buffer + data = new Buffer(0); + } else { + // Copy the missing part of the data into our current buffer + data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); + // Slice the overflow into a new buffer that we will then re-parse + data = data.slice(remainingBytesToRead); + + // Emit current complete message + try { + var emitBuffer = self.buffer; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Emit the buffer + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } catch(err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + } + } + } else { + // Stub buffer is kept in case we don't get enough bytes to determine the + // size of the message (< 4 bytes) + if(self.stubBuffer != null && self.stubBuffer.length > 0) { + // If we have enough bytes to determine the message size let's do it + if(self.stubBuffer.length + data.length > 4) { + // Prepad the data + var newData = new Buffer(self.stubBuffer.length + data.length); + self.stubBuffer.copy(newData, 0); + data.copy(newData, self.stubBuffer.length); + // Reassign for parsing + data = newData; + + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + + } else { + + // Add the the bytes to the stub buffer + var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); + // Copy existing stub buffer + self.stubBuffer.copy(newStubBuffer, 0); + // Copy missing part of the data + data.copy(newStubBuffer, self.stubBuffer.length); + // Exit parsing loop + data = new Buffer(0); + } + } else { + if(data.length > 4) { + // Retrieve the message size + // var sizeOfMessage = data.readUInt32LE(0); + var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; + // If we have a negative sizeOfMessage emit error and return + if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ + sizeOfMessage: sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + return; + } + + // Ensure that the size of message is larger than 0 and less than the max allowed + if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage > data.length) { + self.buffer = new Buffer(sizeOfMessage); + // Copy all the data into the buffer + data.copy(self.buffer, 0); + // Update bytes read + self.bytesRead = data.length; + // Update sizeOfMessage + self.sizeOfMessage = sizeOfMessage; + // Ensure stub buffer is null + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + + } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage == data.length) { + try { + var emitBuffer = data; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + // Emit the message + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } catch (err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + } + } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ + sizeOfMessage:sizeOfMessage, + bytesRead:0, + buffer:null, + stubBuffer:null}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + + // Clear out the state of the parser + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + } else { + var emitBuffer = data.slice(0, sizeOfMessage); + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Copy rest of message + data = data.slice(sizeOfMessage); + // Emit the message + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } + } else { + // Create a buffer that contains the space for the non-complete message + self.stubBuffer = new Buffer(data.length) + // Copy the data to the stub buffer + data.copy(self.stubBuffer, 0); + // Exit parsing loop + data = new Buffer(0); + } + } + } + } + } +} + +/** + * Connect + * @method + */ +Connection.prototype.connect = function(_options) { + var self = this; + _options = _options || {}; + // Check if we are overriding the promoteLongs + if(typeof _options.promoteLongs == 'boolean') { + self.responseOptions.promoteLongs = _options.promoteLongs; + } + + // Create new connection instance + self.connection = self.domainSocket + ? net.createConnection(self.host) + : net.createConnection(self.port, self.host); + + // Set the options for the connection + self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + self.connection.setTimeout(self.connectionTimeout); + self.connection.setNoDelay(self.noDelay); + + // If we have ssl enabled + if(self.ssl) { + var sslOptions = { + socket: self.connection + , rejectUnauthorized: self.rejectUnauthorized + } + + if(self.ca) sslOptions.ca = self.ca; + if(self.cert) sslOptions.cert = self.cert; + if(self.key) sslOptions.key = self.key; + if(self.passphrase) sslOptions.passphrase = self.passphrase; + + // Attempt SSL connection + self.connection = tls.connect(self.port, self.host, sslOptions, function() { + // Error on auth or skip + if(self.connection.authorizationError && self.rejectUnauthorized) { + return self.emit("error", self.connection.authorizationError, self, {ssl:true}); + } + + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // We are done emit connect + self.emit('connect', self); + }); + self.connection.setTimeout(self.connectionTimeout); + } else { + self.connection.on('connect', function() { + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // Emit connect event + self.emit('connect', self); + }); + } + + // Add handlers for events + self.connection.once('error', errorHandler(self)); + self.connection.once('timeout', timeoutHandler(self)); + self.connection.once('close', closeHandler(self)); + self.connection.on('data', dataHandler(self)); +} + +/** + * Destroy connection + * @method + */ +Connection.prototype.destroy = function() { + if(this.connection) this.connection.destroy(); + this.destroyed = true; +} + +/** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ +Connection.prototype.write = function(buffer) { + // Debug log + if(this.logger.isDebug()) this.logger.debug(f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port)); + // Write out the command + if(!Array.isArray(buffer)) return this.connection.write(buffer, 'binary'); + // Iterate over all buffers and write them in order to the socket + for(var i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); +} + +/** + * Return id of connection as a string + * @method + * @return {string} + */ +Connection.prototype.toString = function() { + return "" + this.id; +} + +/** + * Return json object of connection + * @method + * @return {object} + */ +Connection.prototype.toJSON = function() { + return {id: this.id, host: this.host, port: this.port}; +} + +/** + * Is the connection connected + * @method + * @return {boolean} + */ +Connection.prototype.isConnected = function() { + if(this.destroyed) return false; + return !this.connection.destroyed && this.connection.writable; +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +module.exports = Connection; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js new file mode 100644 index 0000000..69c6f93 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js @@ -0,0 +1,196 @@ +"use strict"; + +var f = require('util').format + , MongoError = require('../error'); + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if(!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + var self = this; + this.className = className; + + // Current logger + if(currentLogger == null && options.logger) { + currentLogger = options.logger; + } else if(currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if(level == null) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if(filteredClasses[this.className] == null) classFilters[this.className] = true; +} + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if(this.isDebug() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +} + +/** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.info = function(message, object) { + if(this.isInfo() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.error = function(message, object) { + if(this.isError() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Is the logger set at info level + * @method + * @return {boolean} + */ +Logger.prototype.isInfo = function() { + return level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at error level + * @method + * @return {boolean} + */ +Logger.prototype.isError = function() { + return level == 'error' || level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at debug level + * @method + * @return {boolean} + */ +Logger.prototype.isDebug = function() { + return level == 'debug'; +} + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +} + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +} + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if(typeof logger != 'function') throw new MongoError("current logger must be a function"); + currentLogger = logger; +} + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if(type == 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +} + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if(_level != 'info' && _level != 'error' && _level != 'debug') throw new Error(f("%s is an illegal logging level", _level)); + level = _level; +} + +module.exports = Logger; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js new file mode 100644 index 0000000..dd13707 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js @@ -0,0 +1,275 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , Connection = require('./connection') + , Query = require('./commands').Query + , Logger = require('./logger') + , f = require('util').format; + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +var _id = 0; + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passPhrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(options) { + var self = this; + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + this.size = typeof options.size == 'number' ? options.size : 5; + // Message handler + this.messageHandler = options.messageHandler; + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Contains all connections + this.connections = []; + this.state = DISCONNECTED; + // Round robin index + this.index = 0; + this.dead = false; + // Logger instance + this.logger = Logger('Pool', options); + // Pool id + this.id = _id++; + // Grouping tag used for debugging purposes + this.tag = options.tag; +} + +inherits(Pool, EventEmitter); + +var errorHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('error', err, self); + } + } +} + +var timeoutHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] timed out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('timeout', err, self); + } + } +} + +var closeHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] closed [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('close', err, self); + } + } +} + +var parseErrorHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('parseError', err, self); + } + } +} + +var connectHandler = function(self) { + return function(connection) { + self.connections.push(connection); + // We have connected to all servers + if(self.connections.length == self.size) { + self.state = CONNECTED; + // Done connecting + self.emit("connect", self); + } + } +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function() { + this.state = DESTROYED; + // Set dead + this.dead = true; + // Destroy all the connections + this.connections.forEach(function(c) { + // Destroy all event emitters + ["close", "message", "error", "timeout", "parseError", "connect"].forEach(function(e) { + c.removeAllListeners(e); + }); + + // Destroy the connection + c.destroy(); + }); +} + +var execute = null; + +try { + execute = setImmediate; +} catch(err) { + execute = process.nextTick; +} + +/** + * Connect pool + * @method + */ +Pool.prototype.connect = function(_options) { + var self = this; + // Set to connecting + this.state = CONNECTING + // No dead + this.dead = false; + + // Ensure we allow for a little time to setup connections + var wait = 1; + + // Connect all sockets + for(var i = 0; i < this.size; i++) { + setTimeout(function() { + execute(function() { + self.options.messageHandler = self.messageHandler; + var connection = new Connection(self.options); + + // Add all handlers + connection.once('close', closeHandler(self)); + connection.once('error', errorHandler(self)); + connection.once('timeout', timeoutHandler(self)); + connection.once('parseError', parseErrorHandler(self)); + connection.on('connect', connectHandler(self)); + + // Start connection + connection.connect(_options); + }); + }, wait); + + // wait for 1 miliseconds before attempting to connect, spacing out connections + wait = wait + 1; + } +} + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function() { + // if(this.dead) return null; + var connection = this.connections[this.index++]; + this.index = this.index % this.connections.length; + return connection; +} + +/** + * Get all pool connections + * @method + * @return {array} + */ +Pool.prototype.getAll = function() { + return this.connections.slice(0); +} + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + for(var i = 0; i < this.connections.length; i++) { + if(!this.connections[i].isConnected()) return false; + } + + return this.state == CONNECTED; +} + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state == DESTROYED; +} + + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +module.exports = Pool; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js new file mode 100644 index 0000000..7f0b89d --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js @@ -0,0 +1,77 @@ +"use strict"; + +// Set property function +var setProperty = function(obj, prop, flag, values) { + Object.defineProperty(obj, prop.name, { + enumerable:true, + set: function(value) { + if(typeof value != 'boolean') throw new Error(f("%s required a boolean", prop.name)); + // Flip the bit to 1 + if(value == true) values.flags |= flag; + // Flip the bit to 0 if it's set, otherwise ignore + if(value == false && (values.flags & flag) == flag) values.flags ^= flag; + prop.value = value; + } + , get: function() { return prop.value; } + }); +} + +// Set property function +var getProperty = function(obj, propName, fieldName, values, func) { + Object.defineProperty(obj, propName, { + enumerable:true, + get: function() { + // Not parsed yet, parse it + if(values[fieldName] == null && obj.isParsed && !obj.isParsed()) { + obj.parse(); + } + + // Do we have a post processing function + if(typeof func == 'function') return func(values[fieldName]); + // Return raw value + return values[fieldName]; + } + }); +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +// Shallow copy +var copy = function(fObj, tObj) { + tObj = tObj || {}; + for(var name in fObj) tObj[name] = fObj[name]; + return tObj; +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) return callback; + return domain.bind(callback); +} + +exports.setProperty = setProperty; +exports.getProperty = getProperty; +exports.getSingleProperty = getSingleProperty; +exports.copy = copy; +exports.bindToCurrentDomain = bindToCurrentDomain; +exports.debugOptions = debugOptions; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js new file mode 100644 index 0000000..ab82818 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js @@ -0,0 +1,756 @@ +"use strict"; + +var Long = require('bson').Long + , Logger = require('./connection/logger') + , MongoError = require('./error') + , f = require('util').format; + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * assert.equal(null, err); + * + * // Execute the write + * var cursor = _server.cursor('integration_tests.inserts_example4', { + * find: 'integration_tests.example4' + * , query: {a:1} + * }, { + * readPreference: new ReadPreference('secondary'); + * }); + * + * // Get the first document + * cursor.next(function(err, doc) { + * assert.equal(null, err); + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Cursor, not to be used directly + * @class + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + * @return {Cursor} A cursor instance + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + // Cursor reference + var self = this; + // Initial query + var query = null; + + // Cursor connection + this.connection = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null + , cmd: cmd + , documents: options.documents || [] + , cursorIndex: 0 + , dead: false + , killed: false + , init: false + , notified: false + , limit: options.limit || cmd.limit || 0 + , skip: options.skip || cmd.skip || 0 + , batchSize: options.batchSize || cmd.batchSize || 1000 + , currentLimit: 0 + // Result field name if not a cursor (contains the array of results) + , transforms: options.transforms + } + + // Callback controller + this.callbacks = null; + + // Logger + this.logger = Logger('Cursor', options); + + // + // Did we pass in a cursor id + if(typeof cmd == 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + } else if(cmd instanceof Long) { + this.cursorState.cursorId = cmd; + } +} + +Cursor.prototype.setCursorBatchSize = function(value) { + this.cursorState.batchSize = value; +} + +Cursor.prototype.cursorBatchSize = function() { + return this.cursorState.batchSize; +} + +Cursor.prototype.setCursorLimit = function(value) { + this.cursorState.limit = value; +} + +Cursor.prototype.cursorLimit = function() { + return this.cursorState.limit; +} + +Cursor.prototype.setCursorSkip = function(value) { + this.cursorState.skip = value; +} + +Cursor.prototype.cursorSkip = function() { + return this.cursorState.skip; +} + +// // +// // Execute getMore command +// var execGetMore = function(self, callback) { +// } + +// +// Execute the first query +var execInitialQuery = function(self, query, cmd, options, cursorState, connection, logger, callbacks, callback) { + if(logger.isDebug()) { + logger.debug(f("issue initial query [%s] with flags [%s]" + , JSON.stringify(cmd) + , JSON.stringify(query))); + } + + var queryCallback = function(err, result) { + if(err) return callback(err); + + if(result.queryFailure) { + return callback(MongoError.create(result.documents[0]), null); + } + + // Check if we have a command cursor + if(Array.isArray(result.documents) && result.documents.length == 1 + && (!cmd.find || (cmd.find && cmd.virtual == false)) + && (result.documents[0].cursor != 'string' + || result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || Array.isArray(result.documents[0].result)) + ) { + + // We have a an error document return the error + if(result.documents[0]['$err'] + || result.documents[0]['errmsg']) { + return callback(MongoError.create(result.documents[0]), null); + } + + // We have a cursor document + if(result.documents[0].cursor != null + && typeof result.documents[0].cursor != 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if(result.documents[0].cursor.ns) { + self.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; + // If we have a firstBatch set it + if(Array.isArray(result.documents[0].cursor.firstBatch)) { + cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); + } + + // Return after processing command cursor + return callback(null, null); + } + + if(Array.isArray(result.documents[0].result)) { + cursorState.documents = result.documents[0].result; + cursorState.cursorId = Long.ZERO; + return callback(null, null); + } + } + + // Otherwise fall back to regular find path + cursorState.cursorId = result.cursorId; + cursorState.documents = result.documents; + + // Transform the results with passed in transformation method if provided + if(cursorState.transforms && typeof cursorState.transforms.query == 'function') { + cursorState.documents = cursorState.transforms.query(result); + } + + // Return callback + callback(null, null); + } + + // If we have a raw query decorate the function + if(options.raw || cmd.raw) { + queryCallback.raw = options.raw || cmd.raw; + } + + // Do we have documentsReturnedIn set on the query + if(typeof query.documentsReturnedIn == 'string') { + queryCallback.documentsReturnedIn = query.documentsReturnedIn; + } + + // Set up callback + callbacks.register(query.requestId, queryCallback); + + // Write the initial command out + connection.write(query.toBin()); +} + +// +// Handle callback (including any exceptions thrown) +var handleCallback = function(callback, err, result) { + try { + callback(err, result); + } catch(err) { + process.nextTick(function() { + throw err; + }); + } +} + + +// Internal methods +Cursor.prototype._find = function(callback) { + var self = this; + // execInitialQuery(self, self.query, self.cmd, self.options, self.cursorState, self.connection, self.logger, self.callbacks, function(err, r) { + if(self.logger.isDebug()) { + self.logger.debug(f("issue initial query [%s] with flags [%s]" + , JSON.stringify(self.cmd) + , JSON.stringify(self.query))); + } + + var queryCallback = function(err, result) { + if(err) return callback(err); + + if(result.queryFailure) { + return callback(MongoError.create(result.documents[0]), null); + } + + // Check if we have a command cursor + if(Array.isArray(result.documents) && result.documents.length == 1 + && (!self.cmd.find || (self.cmd.find && self.cmd.virtual == false)) + && (result.documents[0].cursor != 'string' + || result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || Array.isArray(result.documents[0].result)) + ) { + + // We have a an error document return the error + if(result.documents[0]['$err'] + || result.documents[0]['errmsg']) { + return callback(MongoError.create(result.documents[0]), null); + } + + // We have a cursor document + if(result.documents[0].cursor != null + && typeof result.documents[0].cursor != 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if(result.documents[0].cursor.ns) { + self.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + self.cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; + // If we have a firstBatch set it + if(Array.isArray(result.documents[0].cursor.firstBatch)) { + self.cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); + } + + // Return after processing command cursor + return callback(null, null); + } + + if(Array.isArray(result.documents[0].result)) { + self.cursorState.documents = result.documents[0].result; + self.cursorState.cursorId = Long.ZERO; + return callback(null, null); + } + } + + // Otherwise fall back to regular find path + self.cursorState.cursorId = result.cursorId; + self.cursorState.documents = result.documents; + + // Transform the results with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.query == 'function') { + self.cursorState.documents = self.cursorState.transforms.query(result); + } + + // Return callback + callback(null, null); + } + // console.log("------------------------- 2") + + // If we have a raw query decorate the function + if(self.options.raw || self.cmd.raw) { + queryCallback.raw = self.options.raw || self.cmd.raw; + } + // console.log("------------------------- 3") + + // Do we have documentsReturnedIn set on the query + if(typeof self.query.documentsReturnedIn == 'string') { + queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; + } + // console.log("------------------------- 4") + + // Set up callback + self.callbacks.register(self.query.requestId, queryCallback); + + // Write the initial command out + self.connection.write(self.query.toBin()); +// console.log("------------------------- 5") +} + +Cursor.prototype._getmore = function(callback) { + if(this.logger.isDebug()) this.logger.debug(f("schedule getMore call for query [%s]", JSON.stringify(this.query))) + // Determine if it's a raw query + var raw = this.options.raw || this.cmd.raw; + // We have a wire protocol handler + this.server.wireProtocolHandler.getMore(this.bson, this.ns, this.cursorState, this.cursorState.batchSize, raw, this.connection, this.callbacks, this.options, callback); +} + +Cursor.prototype._killcursor = function(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) { + if(callback) callback(null, null); + return; + } + + // Execute command + this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState.cursorId, this.connection, this.callbacks, callback); +} + +/** + * Clone the cursor + * @method + * @return {Cursor} + */ +Cursor.prototype.clone = function() { + return this.topology.cursor(this.ns, this.cmd, this.options); +} + +/** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ +Cursor.prototype.isDead = function() { + return this.cursorState.dead == true; +} + +/** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ +Cursor.prototype.isKilled = function() { + return this.cursorState.killed == true; +} + +/** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ +Cursor.prototype.isNotified = function() { + return this.cursorState.notified == true; +} + +/** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ +Cursor.prototype.bufferedCount = function() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; +} + +/** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ +Cursor.prototype.readBufferedDocuments = function(number) { + var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length); + + // Transform the doc with passed in transformation method if provided + if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') { + // Transform all the elements + for(var i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if(this.cursorState.limit > 0 && (this.cursorState.currentLimit + elements.length) > this.cursorState.limit) { + elements = elements.slice(0, (this.cursorState.limit - this.cursorState.currentLimit)); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; +} + +/** + * Kill the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.kill = function(callback) { + this._killcursor(callback); +} + +/** + * Resets the cursor + * @method + * @return {null} + */ +Cursor.prototype.rewind = function() { + if(this.cursorState.init) { + if(!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } +} + +/** + * Validate if the connection is dead and return error + */ +var isConnectionDead = function(self, callback) { + if(self.connection + && !self.connection.isConnected()) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + callback(MongoError.create(f('connection to host %s:%s was destroyed', self.connection.host, self.connection.port))) + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +var isCursorDeadButNotkilled = function(self, callback) { + // Cursor is dead but not marked killed, return null + if(self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +var isCursorDeadAndKilled = function(self, callback) { + if(self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, MongoError.create("cursor is dead")); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +var isCursorKilled = function(self, callback) { + if(self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +var setCursorDeadAndNotified = function(self, callback) { + self.cursorState.dead = true; + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +/** + * Mark cursor as being notified + */ +var setCursorNotified = function(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +var nextFunction = function(self, callback) { + // We have notified about it + if(self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if(isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if(isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if(isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if(!self.cursorState.init) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.topology.isConnected(self.options) && self.disconnectHandler != null) { + return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + } + + try { + // Get a server + self.server = self.topology.getServer(self.options); + // Get a connection + self.connection = self.server.getConnection(); + // Get the callbacks + self.callbacks = self.server.getCallbacks(); + } catch(err) { + return callback(err); + } + + // Set as init + self.cursorState.init = true; + + try { + // Get the right wire protocol command + self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options); + } catch(err) { + return callback(err); + } + } + + // Process exhaust messages + var processExhaustMessages = function(err, result) { + if(err) { + self.cursorState.dead = true; + self.callbacks.unregister(self.query.requestId); + return callback(err); + } + + // Concatenate all the documents + self.cursorState.documents = self.cursorState.documents.concat(result.documents); + + // If we have no documents left + if(Long.ZERO.equals(result.cursorId)) { + self.cursorState.cursorId = Long.ZERO; + self.callbacks.unregister(self.query.requestId); + return nextFunction(self, callback); + } + + // Set up next listener + self.callbacks.register(result.requestId, processExhaustMessages) + + // Initial result + if(self.cursorState.cursorId == null) { + self.cursorState.cursorId = result.cursorId; + nextFunction(self, callback); + } + } + + // If we have exhaust + if(self.cmd.exhaust && self.cursorState.cursorId == null) { + // Handle all the exhaust responses + self.callbacks.register(self.query.requestId, processExhaustMessages); + // Write the initial command out + return self.connection.write(self.query.toBin()); + } else if(self.cmd.exhaust && self.cursorState.cursorIndex < self.cursorState.documents.length) { + return handleCallback(callback, null, self.cursorState.documents[self.cursorState.cursorIndex++]); + } else if(self.cmd.exhaust && Long.ZERO.equals(self.cursorState.cursorId)) { + self.callbacks.unregister(self.query.requestId); + return setCursorNotified(self, callback); + } else if(self.cmd.exhaust) { + return setTimeout(function() { + if(Long.ZERO.equals(self.cursorState.cursorId)) return; + nextFunction(self, callback); + }, 1); + } + + // If we don't have a cursorId execute the first query + if(self.cursorState.cursorId == null) { + // Check if connection is dead and return if not possible to + // execute the query against the db + if(isConnectionDead(self, callback)) return; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // query, cmd, options, cursorState, callback + self._find(function(err, r) { + if(err) return handleCallback(callback, err, null); + if(self.cursorState.documents.length == 0 && !self.cmd.tailable && !self.cmd.awaitData) { + return setCursorNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } else if(self.cursorState.cursorIndex == self.cursorState.documents.length + && !Long.ZERO.equals(self.cursorState.cursorId)) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // Check if connection is dead and return if not possible to + // execute a getmore on this connection + if(isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getmore(function(err, doc) { + if(err) return handleCallback(callback, err); + if(self.cursorState.documents.length == 0 + && Long.ZERO.equals(self.cursorState.cursorId)) { + self.cursorState.dead = true; + } + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if(self.cursorState.documents.length == 0 && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } + + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && Long.ZERO.equals(self.cursorState.cursorId)) { + setCursorDeadAndNotified(self, callback); + } else { + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Transform the doc with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +} + +/** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.next = function(callback) { + nextFunction(this, callback); +} + +module.exports = Cursor; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js new file mode 100644 index 0000000..4e17ef3 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js @@ -0,0 +1,44 @@ +"use strict"; + +/** + * Creates a new MongoError + * @class + * @augments Error + * @param {string} message The error message + * @return {MongoError} A MongoError instance + */ +function MongoError(message) { + this.name = 'MongoError'; + this.message = message; + Error.captureStackTrace(this, MongoError); +} + +/** + * Creates a new MongoError object + * @method + * @param {object} options The error options + * @return {MongoError} A MongoError instance + */ +MongoError.create = function(options) { + var err = null; + + if(options instanceof Error) { + err = new MongoError(options.message); + err.stack = options.stack; + } else if(typeof options == 'string') { + err = new MongoError(options); + } else { + err = new MongoError(options.message || options.errmsg || options.$err || "n/a"); + // Other options + for(var name in options) { + err[name] = options[name]; + } + } + + return err; +} + +// Extend JavaScript error +MongoError.prototype = new Error; + +module.exports = MongoError; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js new file mode 100644 index 0000000..dcceda4 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js @@ -0,0 +1,59 @@ +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results : [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: "" + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: "fail", + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: "" + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js new file mode 100644 index 0000000..ff7bf1b --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js @@ -0,0 +1,37 @@ +"use strict"; + +var setProperty = require('../connection/utils').setProperty + , getProperty = require('../connection/utils').getProperty + , getSingleProperty = require('../connection/utils').getSingleProperty; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection) { + this.result = result; + this.connection = connection; +} + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + return this.result; +} + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +} + +module.exports = CommandResult; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js new file mode 100644 index 0000000..c54514a --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js @@ -0,0 +1,1000 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , BasicCursor = require('../cursor') + , Server = require('./server') + , Logger = require('../connection/logger') + , ReadPreference = require('./read_preference') + , Session = require('./session') + , MongoError = require('../error'); + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * @example + * var Mongos = require('mongodb-core').Mongos + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Mongos([{host: 'localhost', port: 30000}]); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +// Instance id +var mongosId = 0; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +var State = function(readPreferenceStrategies) { + // Internal state + this.s = { + connectedServers: [] + , disconnectedServers: [] + , readPreferenceStrategies: readPreferenceStrategies + } +} + +// +// A Mongos connected +State.prototype.connected = function(server) { + // Locate in disconnected servers and remove + this.s.disconnectedServers = this.s.disconnectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.connectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.connectedServers.push(server); +} + +// +// A Mongos disconnected +State.prototype.disconnected = function(server) { + // Locate in disconnected servers and remove + this.s.connectedServers = this.s.connectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.disconnectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.disconnectedServers.push(server); +} + +// +// Return the list of disconnected servers +State.prototype.disconnectedServers = function() { + return this.s.disconnectedServers.slice(0); +} + +// +// Get connectedServers +State.prototype.connectedServers = function() { + return this.s.connectedServers.slice(0) +} + +// +// Get all servers +State.prototype.getAll = function() { + return this.s.connectedServers.slice(0).concat(this.s.disconnectedServers); +} + +// +// Get all connections +State.prototype.getAllConnections = function() { + var connections = []; + this.s.connectedServers.forEach(function(e) { + connections = connections.concat(e.connections()); + }); + return connections; +} + +// +// Destroy the state +State.prototype.destroy = function() { + // Destroy any connected servers + while(this.s.connectedServers.length > 0) { + var server = this.s.connectedServers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Server destroy + server.destroy(); + // Add to list of disconnected servers + this.s.disconnectedServers.push(server); + } +} + +// +// Are we connected +State.prototype.isConnected = function() { + return this.s.connectedServers.length > 0; +} + +// +// Pick a server +State.prototype.pickServer = function(readPreference) { + readPreference = readPreference || ReadPreference.primary; + + // Do we have a custom readPreference strategy, use it + if(this.s.readPreferenceStrategies != null && this.s.readPreferenceStrategies[readPreference] != null) { + return this.s.readPreferenceStrategies[readPreference].pickServer(connectedServers, readPreference); + } + + // No valid connections + if(this.s.connectedServers.length == 0) throw new MongoError("no mongos proxy available"); + // Pick first one + return this.s.connectedServers[0]; +} + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.reconnectTries=30] Reconnect retries for HA if no servers available + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#joined + * @fires Mongos#left + */ +var Mongos = function(seedlist, options) { + var self = this; + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // BSON Parser, ensure we have a single instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + // Pick the right bson parser + var bson = options.bson ? options.bson : bsonInstance; + // Add bson parser to options + options.bson = bson; + + // The Mongos state + this.s = { + // Seed list for sharding passed in + seedlist: seedlist + // Passed in options + , options: options + // Logger + , logger: Logger('Mongos', options) + // Reconnect tries + , reconnectTries: options.reconnectTries || 30 + // Ha interval + , haInterval: options.haInterval || 5000 + // Have omitted fullsetup + , fullsetup: false + // Cursor factory + , Cursor: options.cursorFactory || BasicCursor + // Current credentials used for auth + , credentials: [] + // BSON Parser + , bsonInstance: bsonInstance + , bson: bson + // Default state + , state: DISCONNECTED + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // Unique instance id + , id: mongosId++ + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Current retries left + , retriesLeft: options.reconnectTries || 30 + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + } + + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 1000; + + // Create a new state for the mongos + this.s.mongosState = new State(this.s.readPreferenceStrategies); + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.mongosState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'mongos'; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.mongosState; } + }); +} + +inherits(Mongos, EventEmitter); + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +Mongos.prototype.parserType = function() { + if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Mongos.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + var connectedServers = this.s.mongosState.connectedServers(); + if(connectedServers.length > 0) return connectedServers[0].lastIsMaster(); + return null; +} + +/** + * Initiate server connect + * @method + */ +Mongos.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setTimeout(mongosInquirer(self, self.s), self.s.haInterval); + // Additional options + if(_options) for(var name in _options) self.s.options[name] = _options[name]; + // For all entries in the seedlist build a server instance + self.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Don't emit errors + opts.emitError = true; + // Create a new Server + self.s.mongosState.disconnected(new Server(opts)); + }); + + // Get the disconnected servers + var servers = self.s.mongosState.disconnectedServers(); + + // Attempt to connect to all the servers + while(servers.length > 0) { + // Get the server + var server = servers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, self.s, server)); + server.once('close', errorHandlerTemp(self, self.s, server)); + server.once('timeout', errorHandlerTemp(self, self.s, server)); + server.once('parseError', errorHandlerTemp(self, self.s, server)); + server.once('connect', connectHandler(self, self.s, 'connect')); + + if(self.s.logger.isInfo()) self.s.logger.info(f('connecting to server %s', server.name)); + // Attempt to connect + server.connect(); + } +} + +/** + * Destroy the server connection + * @method + */ +Mongos.prototype.destroy = function(emitClose) { + this.s.state = DESTROYED; + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + // Destroy the state + this.s.mongosState.destroy(); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.s.mongosState.isConnected(); +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +// +// Operations +// + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'update', ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'remove', ns, ops, options, callback); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + var server = null; + // Ensure we have no options + options = options || {}; + + // We need to execute the command on all servers + if(options.onAll) { + var servers = self.s.mongosState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(state, ns); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + + try { + // Get a primary + server = self.s.mongosState.pickServer(options.writeConcern ? ReadPreference.primary : options.readPreference); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // Authenticate against all the servers + var servers = this.s.mongosState.connectedServers().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Mongos.prototype.addReadPreferenceStrategy = function(name, strategy) { + if(this.s.readPreferenceStrategies == null) this.s.readPreferenceStrategies = {}; + this.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Mongos.prototype.addAuthProvider = function(name, provider) { + this.s.authProviders[name] = provider; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Mongos.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = this.s.mongosState.pickServer(options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Mongos.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return this.s.mongosState.pickServer(options.readPreference); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + return this.s.mongosState.getAllConnections(); +} + +// +// Inquires about state changes +// +var mongosInquirer = function(self, state) { + return function() { + if(state.state == DESTROYED) return + if(state.state == CONNECTED) state.retriesLeft = state.reconnectTries; + + // If we have a disconnected site + if(state.state == DISCONNECTED && state.retriesLeft == 0) { + self.destroy(); + return self.emit('error', new MongoError(f('failed to reconnect after %s', state.reconnectTries))); + } else if(state == DISCONNECTED) { + state.retriesLeft = state.retriesLeft - 1; + } + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.mongosState.isConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // Log the information + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess running')); + + // Let's query any disconnected proxies + var disconnectedServers = state.mongosState.disconnectedServers(); + if(disconnectedServers.length == 0) return setTimeout(mongosInquirer(self, state), state.haInterval); + + // Count of connections waiting to be connected + var connectionCount = disconnectedServers.length; + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess found %d disconnected proxies', connectionCount)); + + // Let's attempt to reconnect + while(disconnectedServers.length > 0) { + var server = disconnectedServers.shift(); + if(state.logger.isDebug()) state.logger.debug(f('attempting to connect to server %s', server.name)); + + // Remove any listeners + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, server)); + server.once('close', errorHandlerTemp(self, state, server)); + server.once('timeout', errorHandlerTemp(self, state, server)); + server.once('connect', connectHandler(self, state, 'ha')); + // Start connect + server.connect(); + } + + // Let's keep monitoring but wait for possible timeout to happen + return setTimeout(mongosInquirer(self, state), state.options.connectionTimeout + state.haInterval); + } +} + +// +// Error handler for initial connect +var errorHandlerTemp = function(self, state, server) { + return function(err, server) { + // Log the information + if(state.logger.isInfo()) state.logger.info(f('server %s disconnected with error %s', server.name, JSON.stringify(err))); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Signal disconnect of server + state.mongosState.disconnected(server); + } +} + +// +// Handlers +var errorHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', server.name, JSON.stringify(err))); + state.mongosState.disconnected(server); + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + if(state.emitError) self.emit('error', err, server); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', server.name)); + state.mongosState.disconnected(server); + + // No more servers emit close event if no entries left + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s closed', server.name)); + state.mongosState.disconnected(server); + + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +// Connect handler +var connectHandler = function(self, state, e) { + return function(server) { + if(state.logger.isInfo()) state.logger.info(f('connected to %s', server.name)); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // finish processing the server + var processNewServer = function(_server) { + // Add the server handling code + if(_server.isConnected()) { + _server.once('error', errorHandler(self, state)); + _server.once('close', closeHandler(self, state)); + _server.once('timeout', timeoutHandler(self, state)); + _server.once('parseError', timeoutHandler(self, state)); + } + + // Emit joined event + self.emit('joined', 'mongos', _server); + + // Add to list connected servers + state.mongosState.connected(_server); + + // Do we have a reconnect event + if('ha' == e && state.mongosState.connectedServers().length == 1) { + self.emit('reconnect', _server); + } + + // Full setup + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length > 0 && + !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup'); + } + + // all connected + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length == state.seedlist.length && + !state.all) { + state.all = true; + self.emit('all'); + } + + // Set connected + if(state.state == DISCONNECTED) { + state.state = CONNECTED; + self.emit('connect', self); + } + } + + // Is there an authentication process ongoing + if(state.authInProgress) { + state.authInProgressServers.push(server); + } + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(server); + + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) processNewServer(server); + }])); + } + } +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } +} + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(state, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(state, db + ".dummy"); + // Add new credentials to list + state.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(state, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < state.credentials.length; i++) { + if(state.credentials[i][1] != db) filteredCredentials.push(state.credentials[i]); + } + + // Set new list of credentials + state.credentials = filteredCredentials; +} + +var processReadPreference = function(cmd, options) { + options = options || {} + // No read preference specified + if(options.readPreference == null) return cmd; +} + +// +// Execute write operation +var executeWriteOperation = function(state, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + try { + // Get a primary + server = state.mongosState.pickServer(); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + // Execute the command + server[op](ns, ops, options, callback); +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +module.exports = Mongos; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js new file mode 100644 index 0000000..913ca1b --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js @@ -0,0 +1,106 @@ +"use strict"; + +var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * var cursor = server.cursor('db.test' + * , {find: 'db.test', query: {}} + * , {readPreference: new ReadPreference('secondary')}); + * cursor.next(function(err, doc) { + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Pool instance + * @class + * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {object} tags The tags object + * @param {object} [options] Additional read preference options + * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @property {object} tags The tags object + * @property {object} options Additional read preference options + * @return {ReadPreference} + */ +var ReadPreference = function(preference, tags, options) { + this.preference = preference; + this.tags = tags; + this.options = options; +} + +/** + * This needs slaveOk bit set + * @method + * @return {boolean} + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.preference) != -1; +} + +/** + * Are the two read preference equal + * @method + * @return {boolean} + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.preference == this.preference; +} + +/** + * Return JSON representation + * @method + * @return {Object} + */ +ReadPreference.prototype.toJSON = function() { + var readPreference = {mode: this.preference}; + if(Array.isArray(this.tags)) readPreference.tags = this.tags; + return readPreference; +} + +/** + * Primary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js new file mode 100644 index 0000000..011c8fe --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js @@ -0,0 +1,1333 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , debugOptions = require('../connection/utils').debugOptions + , EventEmitter = require('events').EventEmitter + , Server = require('./server') + , ReadPreference = require('./read_preference') + , MongoError = require('../error') + , Ping = require('./strategies/ping') + , Session = require('./session') + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , State = require('./replset_state') + , Logger = require('../connection/logger'); + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connecctions. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// +// ReplSet instance id +var replSetId = 1; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // Add event listener + EventEmitter.call(this); + + // Set the bson instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + + // Internal state hash for the object + this.s = { + options: options + // Logger instance + , logger: Logger('ReplSet', options) + // Uniquely identify the replicaset instance + , id: replSetId++ + // Index + , index: 0 + // Ha Index + , haId: 0 + // Current credentials used for auth + , credentials: [] + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Special replicaset options + , secondaryOnlyConnectionAllowed: typeof options.secondaryOnlyConnectionAllowed == 'boolean' + ? options.secondaryOnlyConnectionAllowed : false + , haInterval: options.haInterval || 10000 + // Are we running in debug mode + , debug: typeof options.debug == 'boolean' ? options.debug : false + // The replicaset name + , setName: options.setName + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // Currently connecting servers + , connectingServers: {} + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // All the servers + , disconnectedServers: [] + // Initial connection servers + , initialConnectionServers: [] + // High availability process running + , highAvailabilityProcessRunning: false + // Full setup + , fullsetup: false + // All servers accounted for (used for testing) + , all: false + // Seedlist + , seedlist: seedlist + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Minimum heartbeat frequency used if we detect a server close + , minHeartbeatFrequencyMS: 500 + } + + // Add bson parser to options + options.bson = this.s.bson; + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 10000; + + // Replicaset state + var replState = new State(this, { + id: this.s.id, setName: this.s.setName + , connectingServers: this.s.connectingServers + , secondaryOnlyConnectionAllowed: this.s.secondaryOnlyConnectionAllowed + }); + + // Add Replicaset state to our internal state + this.s.replState = replState; + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.replState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.replState; } + }); + + // + // Debug options + if(self.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'readPreferenceStrategies', { + enumerable: true, get: function() { return self.s.readPreferenceStrategies; } + }); + } + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'replset'; } + }); + + // Add the ping strategy for nearest + this.addReadPreferenceStrategy('nearest', new Ping(options)); +} + +inherits(ReplSet, EventEmitter); + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +ReplSet.prototype.addReadPreferenceStrategy = function(name, func) { + this.s.readPreferenceStrategies[name] = func; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +ReplSet.prototype.addAuthProvider = function(name, provider) { + if(this.s.authProviders == null) this.s.authProviders = {}; + this.s.authProviders[name] = provider; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +ReplSet.prototype.parserType = function() { + if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +ReplSet.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + return this.s.replState.lastIsMaster(); +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +ReplSet.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = pickServer(this, this.s, options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + return this.s.replState.getAllConnections(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +ReplSet.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return pickServer(this, this.s, options.readPreference); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +// +// Execute write operation +var executeWriteOperation = function(self, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + // Get a primary + try { + server = pickServer(self, self.s, ReadPreference.primary); + if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + + // Handler + var handler = function(err, r) { + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the result + callback(err, r); + } + + // Add operationId if existing + if(callback.operationId) handler.operationId = callback.operationId; + // Execute the command + server[op](ns, ops, options, handler); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + var server = null; + var self = this; + // Ensure we have no options + options = options || {}; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected(options) && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // We need to execute the command on all servers + if(options.onAll) { + var servers = this.s.replState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + // Pick the right server based on readPreference + try { + server = pickServer(self, self.s, options.writeConcern ? ReadPreference.primary : options.readPreference); + if(self.s.debug) self.emit('pickedServer', options.writeConcern ? ReadPreference.primary : options.readPreference, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + // Execute the command + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) { + replicasetInquirer(self, self.s, true)(); + } + // Return the error + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this, 'remove', ns, ops, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this, 'update', ns, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // Authenticate against all the servers + var servers = this.s.replState.getAll().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +ReplSet.prototype.state = function() { + return this.s.replState.state; +} + +/** + * Ensure single socket connections to arbiters and hidden servers + * @method + */ +var handleIsmaster = function(self) { + return function(ismaster, _server) { + if(ismaster.arbiterOnly) { + _server.s.options.size = 1; + } else if(ismaster.hidden) { + _server.s.options.size = 1; + } + } +} + +/** + * Initiate server connect + * @method + */ +ReplSet.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setTimeout(replicasetInquirer(this, this.s, false), this.s.haInterval); + // Additional options + if(_options) for(var name in _options) this.s.options[name] = _options[name]; + + // Set the state as connecting + this.s.replState.state = CONNECTING; + + // No fullsetup reached + this.s.fullsetup = false; + + // For all entries in the seedlist build a server instance + this.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + opts.emitError = true; + if(self.s.tag) opts.tag = self.s.tag; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Create a new Server + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Add to list of disconnected servers + self.s.disconnectedServers.push(server); + // Add to list of inflight Connections + self.s.initialConnectionServers.push(server); + }); + + // Attempt to connect to all the servers + while(this.s.disconnectedServers.length > 0) { + // Get the server + var server = this.s.disconnectedServers.shift(); + + // Set up the event handlers + server.once('error', errorHandlerTemp(this, this.s, 'error')); + server.once('close', errorHandlerTemp(this, this.s, 'close')); + server.once('timeout', errorHandlerTemp(this, this.s, 'timeout')); + server.once('connect', connectHandler(this, this.s)); + + // Attempt to connect + server.connect(); + } +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + // If we specified a read preference check if we are connected to something + // than can satisfy this + if(options.readPreference + && options.readPreference.equals(ReadPreference.secondary)) + return this.s.replState.isSecondaryConnected(); + + if(options.readPreference + && options.readPreference.equals(ReadPreference.primary)) + return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); + + if(this.s.secondaryOnlyConnectionAllowed + && this.s.replState.isSecondaryConnected()) return true; + return this.s.replState.isPrimaryConnected(); +} + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.s.replState.state == DESTROYED; +} + +/** + * Destroy the server connection + * @method + */ +ReplSet.prototype.destroy = function(emitClose) { + var self = this; + if(this.s.logger.isInfo()) this.s.logger.info(f('[%s] destroyed', this.s.id)); + this.s.replState.state = DESTROYED; + + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + + // Destroy state + this.s.replState.destroy(); + + // Clear out any listeners + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); +} + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +// +// Inquires about state changes +// + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(s, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(s, db + ".dummy"); + // Add new credentials to list + s.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(s, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < s.credentials.length; i++) { + if(s.credentials[i][1] != db) filteredCredentials.push(s.credentials[i]); + } + + // Set new list of credentials + s.credentials = filteredCredentials; +} + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tags = readPreference.tags; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) filteredServers.push(servers[i]); + } + + // Returned filtered servers + return filteredServers; +} + +// +// Pick a server based on readPreference +var pickServer = function(self, s, readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // Do we have a custom readPreference strategy, use it + if(s.readPreferenceStrategies != null && s.readPreferenceStrategies[readPreference.preference] != null) { + if(s.readPreferenceStrategies[readPreference.preference] == null) throw new MongoError(f("cannot locate read preference handler for %s", readPreference.preference)); + var server = s.readPreferenceStrategies[readPreference.preference].pickServer(s.replState, readPreference); + if(s.debug) self.emit('pickedServer', readPreference, server); + return server; + } + + // Filter out any hidden secondaries + var secondaries = s.replState.secondaries.filter(function(server) { + if(server.lastIsMaster().hidden) return false; + return true; + }); + + // Check if we can satisfy and of the basic read Preferences + if(readPreference.equals(ReadPreference.secondary) + && secondaries.length == 0) + throw new MongoError("no secondary server available"); + + if(readPreference.equals(ReadPreference.secondaryPreferred) + && secondaries.length == 0 + && s.replState.primary == null) + throw new MongoError("no secondary or primary server available"); + + if(readPreference.equals(ReadPreference.primary) + && s.replState.primary == null) + throw new MongoError("no primary server available"); + + // Secondary + if(readPreference.equals(ReadPreference.secondary)) { + s.index = (s.index + 1) % secondaries.length; + return secondaries[s.index]; + } + + // Secondary preferred + if(readPreference.equals(ReadPreference.secondaryPreferred)) { + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + } + + return s.replState.primary; + } + + // Primary preferred + if(readPreference.equals(ReadPreference.primaryPreferred)) { + if(s.replState.primary) return s.replState.primary; + + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + + // Throw error a we have not valid secondary or primary servers + throw new MongoError("no secondary or primary server available"); + } + } + + // Return the primary + return s.replState.primary; +} + +var replicasetInquirer = function(self, state, norepeat) { + return function() { + if(state.replState.state == DESTROYED) return + // Process already running don't rerun + if(state.highAvailabilityProcessRunning) return; + // Started processes + state.highAvailabilityProcessRunning = true; + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring process running %s', state.id, JSON.stringify(state.replState))); + + // Unique HA id to identify the current look running + var localHaId = state.haId++; + + // Clean out any failed connection attempts + state.connectingServers = {}; + + // Controls if we are doing a single inquiry or repeating + norepeat = typeof norepeat == 'boolean' ? norepeat : false; + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.replState.isPrimaryConnected() && state.replState.isSecondaryConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // Emit replicasetInquirer + self.emit('ha', 'start', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + + // Let's process all the disconnected servers + while(state.disconnectedServers.length > 0) { + // Get the first disconnected server + var server = state.disconnectedServers.shift(); + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring attempting to connect to %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + // Attempt to connect + server.connect(); + } + + // Cleanup state (removed disconnected servers) + state.replState.clean(); + + // We need to query all servers + var servers = state.replState.getAll(); + var serversLeft = servers.length; + + // If no servers and we are not destroyed keep pinging + if(servers.length == 0 && state.replState.state == CONNECTED) { + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Restart ha process + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + + // + // ismaster for Master server + var primaryIsMaster = null; + + // Kill the server connection if it hangs + var timeoutServer = function(_server) { + return setTimeout(function() { + if(_server.isConnected()) { + _server.connections()[0].connection.destroy(); + } + }, self.s.options.connectionTimeout); + } + + // + // Inspect a specific servers ismaster + var inspectServer = function(server) { + if(state.replState.state == DESTROYED) return; + // Did we get a server + if(server && server.isConnected()) { + // Get the timeout id + var timeoutId = timeoutServer(server); + // Execute ismaster + server.command('system.$cmd', {ismaster:true}, function(err, r) { + // Clear out the timeoutServer + clearTimeout(timeoutId); + // If the state was destroyed + if(state.replState.state == DESTROYED) return; + // Count down the number of servers left + serversLeft = serversLeft - 1; + // If we have an error but still outstanding server request return + if(err && serversLeft > 0) return; + // We had an error and have no more servers to inspect, schedule a new check + if(err && serversLeft == 0) { + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunnfing + state.highAvailabilityProcessRunning = false; + // Return the replicasetInquirer + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + + // Let all the read Preferences do things to the servers + var rPreferencesCount = Object.keys(state.readPreferenceStrategies).length; + + // Handle the primary + var ismaster = r.result; + if(state.logger.isDebug()) state.logger.debug(f('[%s] monitoring process ismaster %s', state.id, JSON.stringify(ismaster))); + + // Update the replicaset state + state.replState.update(ismaster, server); + + // Add any new servers + if(err == null && ismaster.ismaster && Array.isArray(ismaster.hosts)) { + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + // Process all the hsots + processHosts(self, state, hosts); + } + + // No read Preferences strategies + if(rPreferencesCount == 0) { + // Don't schedule a new inquiry + if(serversLeft > 0) return; + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + + // No servers left to query, execute read preference strategies + if(serversLeft == 0) { + // Go over all the read preferences + for(var name in state.readPreferenceStrategies) { + state.readPreferenceStrategies[name].ha(self, state.replState, function() { + rPreferencesCount = rPreferencesCount - 1; + + if(rPreferencesCount == 0) { + // Add any new servers in primary ismaster + if(err == null + && ismaster.ismaster + && Array.isArray(ismaster.hosts)) { + processHosts(self, state, ismaster.hosts); + } + + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + }); + } + } + }); + } + } + + // Call ismaster on all servers + for(var i = 0; i < servers.length; i++) { + inspectServer(servers[i]); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + + // If all servers are accounted for and we have not sent the all event + if(state.replState.primary != null && self.lastIsMaster() + && Array.isArray(self.lastIsMaster().hosts) && !state.all) { + var length = 1 + state.replState.secondaries.length; + // If we have all secondaries + primary + if(length == self.lastIsMaster().hosts.length + 1) { + state.all = true; + self.emit('all', self); + } + } + } +} + +// Error handler for initial connect +var errorHandlerTemp = function(self, state, event) { + return function(err, server) { + // Log the information + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s disconnected', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + + // Connection is destroyed, ignore + if(state.replState.state == DESTROYED) return; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Push to list of disconnected servers + addToListIfNotExist(state.disconnectedServers, server); + + // End connection operation if we have no legal replicaset state + if(state.initialConnectionServers == 0 && state.replState.state == CONNECTING) { + if((state.secondaryOnlyConnectionAllowed && !state.replState.isSecondaryConnected() && !state.replState.isPrimaryConnected()) + || (!state.secondaryOnlyConnectionAllowed && !state.replState.isPrimaryConnected())) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) + return self.emit('error', new MongoError('no valid seed servers in list')); + } + } + + // If the number of disconnected servers is equal to + // the number of seed servers we cannot connect + if(state.disconnectedServers.length == state.seedlist.length && state.replState.state == CONNECTING) { + if(state.emitError && self.listeners('error').length > 0) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) + self.emit('error', new MongoError('no valid seed servers in list')); + } + } + } +} + +// Connect handler +var connectHandler = function(self, state) { + return function(server) { + if(state.logger.isInfo()) state.logger.info(f('[%s] connected to %s', state.id, server.name)); + // Destroyed connection + if(state.replState.state == DESTROYED) { + server.destroy(false, false); + return; + } + + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + + // Process the new server + var processNewServer = function() { + // Discover any additional servers + var ismaster = server.lastIsMaster(); + + var events = ['error', 'close', 'timeout', 'connect', 'message']; + // Remove any non used handlers + events.forEach(function(e) { + server.removeAllListeners(e); + }) + + // Clean up + delete state.connectingServers[server.name]; + // Update the replicaset state, destroy if not added + if(!state.replState.update(ismaster, server)) { + return server.destroy(); + } + + // Add the server handling code + if(server.isConnected()) { + server.on('error', errorHandler(self, state)); + server.on('close', closeHandler(self, state)); + server.on('timeout', timeoutHandler(self, state)); + } + + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + + // Add any new servers + processHosts(self, state, hosts); + + // If have the server instance already destroy it + if(state.initialConnectionServers.length == 0 && Object.keys(state.connectingServers).length == 0 + && !state.replState.isPrimaryConnected() && !state.secondaryOnlyConnectionAllowed && state.replState.state == CONNECTING) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no primary found in replicaset', state.id)); + self.emit('error', new MongoError("no primary found in replicaset")); + return self.destroy(); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + } + + // Save up new members to be authenticated against + if(self.s.authInProgress) { + self.s.authInProgressServers.push(server); + } + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(); + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) processNewServer(); + }])); + } + } +} + +// +// Detect if we need to add new servers +var processHosts = function(self, state, hosts) { + if(state.replState.state == DESTROYED) return; + if(Array.isArray(hosts)) { + // Check any hosts exposed by ismaster + for(var i = 0; i < hosts.length; i++) { + // If not found we need to create a new connection + if(!state.replState.contains(hosts[i])) { + if(state.connectingServers[hosts[i]] == null && !inInitialConnectingServers(self, state, hosts[i])) { + if(state.logger.isInfo()) state.logger.info(f('[%s] scheduled server %s for connection', state.id, hosts[i])); + // Make sure we know what is trying to connect + state.connectingServers[hosts[i]] = hosts[i]; + // Connect the server + connectToServer(self, state, hosts[i].split(':')[0], parseInt(hosts[i].split(':')[1], 10)); + } + } + } + } +} + +var inInitialConnectingServers = function(self, state, address) { + for(var i = 0; i < state.initialConnectionServers.length; i++) { + if(state.initialConnectionServers[i].name == address) return true; + } + return false; +} + +// Connect to a new server +var connectToServer = function(self, state, host, port) { + var opts = cloneOptions(state.options); + opts.host = host; + opts.port = port; + opts.reconnect = false; + opts.readPreferenceStrategies = state.readPreferenceStrategies; + if(state.tag) opts.tag = state.tag; + // Share the auth store + opts.authProviders = state.authProviders; + opts.emitError = true; + // Create a new server instance + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + // Attempt to connect + server.connect(); +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } + + return found; +} + +var errorHandler = function(self, state) { + return function(err, server) { + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s errored out with %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name, JSON.stringify(err))); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + if(found && state.emitError && self.listeners('error').length > 0) self.emit('error', err, server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + replicasetInquirer(self, self.s, true)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s timed out', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + replicasetInquirer(self, self.s, true)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s closed', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + replicasetInquirer(self, self.s, true)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +// +// Validate if a non-master or recovering error +var notMasterError = function(r) { + // Get result of any + var result = r && r.result ? r.result : r; + + // Explore if we have a not master error + if(result && (result.err == 'not master' + || result.errmsg == 'not master' || (result['$err'] && result['$err'].indexOf('not master or secondary') != -1) + || (result['$err'] && result['$err'].indexOf("not master and slaveOk=false") != -1) + || result.errmsg == 'node is recovering')) { + return true; + } + + return false; +} + +module.exports = ReplSet; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js new file mode 100644 index 0000000..951a043 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js @@ -0,0 +1,483 @@ +"use strict"; + +var Logger = require('../connection/logger') + , f = require('util').format + , ObjectId = require('bson').ObjectId + , MongoError = require('../error'); + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +/** + * Creates a new Replicaset State object + * @class + * @property {object} primary Primary property + * @property {array} secondaries List of secondaries + * @property {array} arbiters List of arbiters + * @return {State} A cursor instance + */ +var State = function(replSet, options) { + this.replSet = replSet; + this.options = options; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.primary = null; + // Initial state is disconnected + this.state = DISCONNECTED; + // Current electionId + this.electionId = null; + // Get a logger instance + this.logger = Logger('ReplSet', options); + // Unpacked options + this.id = options.id; + this.setName = options.setName; + this.connectingServers = options.connectingServers; + this.secondaryOnlyConnectionAllowed = options.secondaryOnlyConnectionAllowed; +} + +/** + * Is there a secondary connected + * @method + * @return {boolean} + */ +State.prototype.isSecondaryConnected = function() { + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].isConnected()) return true; + } + + return false; +} + +/** + * Is there a primary connection + * @method + * @return {boolean} + */ +State.prototype.isPrimaryConnected = function() { + return this.primary != null && this.primary.isConnected(); +} + +/** + * Is the given address the primary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPrimary = function(address) { + if(this.primary == null) return false; + return this.primary && this.primary.equals(address); +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isSecondary = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPassive = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Does the replicaset contain this server + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.contains = function(address) { + if(this.primary && this.primary.equals(address)) return true; + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) return true; + } + + for(var i = 0; i < this.arbiters.length; i++) { + if(this.arbiters[i].equals(address)) return true; + } + + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) return true; + } + + return false; +} + +/** + * Clean out all dead connections + * @method + */ +State.prototype.clean = function() { + if(this.primary != null && !this.primary.isConnected()) { + this.primary = null; + } + + // Filter out disconnected servers + this.secondaries = this.secondaries.filter(function(s) { + return s.isConnected(); + }); + + // Filter out disconnected servers + this.arbiters = this.arbiters.filter(function(s) { + return s.isConnected(); + }); +} + +/** + * Destroy state + * @method + */ +State.prototype.destroy = function() { + this.state = DESTROYED; + if(this.primary) this.primary.destroy(); + this.secondaries.forEach(function(s) { + s.destroy(); + }); +} + +/** + * Remove server from state + * @method + * @param {Server} Server to remove + * @return {string} Returns type of server removed (primary|secondary) + */ +State.prototype.remove = function(server) { + if(this.primary && this.primary.equals(server)) { + this.primary = null; + } + + var length = this.arbiters.length; + // Filter out the server from the arbiters + this.arbiters = this.arbiters.filter(function(s) { + return !s.equals(server); + }); + if(this.arbiters.length < length) return 'arbiter'; + + var length = this.passives.length; + // Filter out the server from the passives + this.passives = this.passives.filter(function(s) { + return !s.equals(server); + }); + + // We have removed a passive + if(this.passives.length < length) { + // Ensure we removed it from the list of secondaries as well if it exists + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + } + + // Filter out the server from the secondaries + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + + // Get the isMaster + var isMaster = server.lastIsMaster(); + // Return primary if the server was primary + if(isMaster.ismaster) return 'primary'; + if(isMaster.secondary) return 'secondary'; + if(isMaster.passive) return 'passive'; + return 'arbiter'; +} + +/** + * Get the server by name + * @method + * @param {string} address Server address + * @return {Server} + */ +State.prototype.get = function(server) { + var found = false; + // All servers to search + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + // Locate the server + for(var i = 0; i < servers.length; i++) { + if(servers[i].equals(server)) { + return servers[i]; + } + } +} + +/** + * Get all the servers in the set + * @method + * @return {array} + */ +State.prototype.getAll = function() { + var servers = []; + if(this.primary) servers.push(this.primary); + return servers.concat(this.secondaries); +} + +/** + * All raw connections + * @method + * @return {array} + */ +State.prototype.getAllConnections = function() { + var connections = []; + if(this.primary) connections = connections.concat(this.primary.connections()); + this.secondaries.forEach(function(s) { + connections = connections.concat(s.connections()); + }) + + return connections; +} + +/** + * Return JSON object + * @method + * @return {object} + */ +State.prototype.toJSON = function() { + return { + primary: this.primary ? this.primary.lastIsMaster().me : null + , secondaries: this.secondaries.map(function(s) { + return s.lastIsMaster().me + }) + } +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +State.prototype.lastIsMaster = function() { + if(this.primary) return this.primary.lastIsMaster(); + if(this.secondaries.length > 0) return this.secondaries[0].lastIsMaster(); + return {}; +} + +/** + * Promote server to primary + * @method + * @param {Server} server Server we wish to promote + */ +State.prototype.promotePrimary = function(server) { + var currentServer = this.get(server); + // Server does not exist in the state, add it as new primary + if(currentServer == null) { + this.primary = server; + return; + } + + // We found a server, make it primary and remove it from the secondaries + // Remove the server first + this.remove(currentServer); + // Set as primary + this.primary = currentServer; +} + +var add = function(list, server) { + // Check if the server is a secondary at the moment + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) return false; + } + + list.push(server); + return true; +} + +/** + * Add server to list of secondaries + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addSecondary = function(server) { + return add(this.secondaries, server); +} + +/** + * Add server to list of arbiters + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addArbiter = function(server) { + return add(this.arbiters, server); +} + +/** + * Add server to list of passives + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addPassive = function(server) { + return add(this.passives, server); +} + +var compareObjectIds = function(id1, id2) { + var a = new Buffer(id1.toHexString(), 'hex'); + var b = new Buffer(id2.toHexString(), 'hex'); + + if(a === b) { + return 0; + } + + if(typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +/** + * Update the state given a specific ismaster result + * @method + * @param {object} ismaster IsMaster result + * @param {Server} server IsMaster Server source + */ +State.prototype.update = function(ismaster, server) { + var self = this; + // Not in a known connection valid state + if(!ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { + // Remove the state + var result = self.remove(server); + if(self.state == CONNECTED) { + if(self.logger.isInfo()) self.logger.info(f('[%s] removing %s from set', self.id, ismaster.me)); + self.replSet.emit('left', self.remove(server), server); + } + + return false; + } + + // Set the setName if it's not set from the first server + if(self.setName == null && ismaster.setName) { + if(self.logger.isInfo()) self.logger.info(f('[%s] setting setName to %s', self.id, ismaster.setName)); + self.setName = ismaster.setName; + } + + // Check if the replicaset name matches the provided one + if(ismaster.setName && self.setName != ismaster.setName) { + if(self.logger.isError()) self.logger.error(f('[%s] server in replset %s is not part of the specified setName %s', self.id, ismaster.setName, self.setName)); + self.remove(server); + self.replSet.emit('error', new MongoError("provided setName for Replicaset Connection does not match setName found in server seedlist")); + return false; + } + + // Log information + if(self.logger.isInfo()) self.logger.info(f('[%s] updating replicaset state %s', self.id, JSON.stringify(this))); + + // It's a master set it + if(ismaster.ismaster && self.setName == ismaster.setName && !self.isPrimary(ismaster.me)) { + // Check if the electionId is not null + if(ismaster.electionId instanceof ObjectId && self.electionId instanceof ObjectId) { + if(compareObjectIds(self.electionId, ismaster.electionId) == -1) { + self.electionId = ismaster.electionId; + } else if(compareObjectIds(self.electionId, ismaster.electionId) == 0) { + self.electionId = ismaster.electionId; + } else { + return false; + } + } + + // Initial electionId + if(ismaster.electionId instanceof ObjectId && self.electionId == null) { + self.electionId = ismaster.electionId; + } + + // Promote to primary + self.promotePrimary(server); + // Log change of primary + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to primary', self.id, ismaster.me)); + // Emit primary + self.replSet.emit('joined', 'primary', this.primary); + + // We are connected + if(self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } else { + self.state = CONNECTED; + self.replSet.emit('reconnect', server); + } + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.arbiterOnly) { + if(self.addArbiter(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to arbiter', self.id, ismaster.me)); + self.replSet.emit('joined', 'arbiter', server); + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary && ismaster.passive) { + if(self.addPassive(server) && self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to passive', self.id, ismaster.me)); + self.replSet.emit('joined', 'passive', server); + + // If we have secondaryOnlyConnectionAllowed and just a passive it's + // still a valid connection + if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } + + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary) { + if(self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to secondary', self.id, ismaster.me)); + self.replSet.emit('joined', 'secondary', server); + + if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } + + return true; + }; + + return false; + } + + // Return update applied + return true; +} + +module.exports = State; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js new file mode 100644 index 0000000..0fae9ea --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js @@ -0,0 +1,1230 @@ + "use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , Pool = require('../connection/pool') + , b = require('bson') + , Query = require('../connection/commands').Query + , MongoError = require('../error') + , ReadPreference = require('./read_preference') + , BasicCursor = require('../cursor') + , CommandResult = require('./command_result') + , getSingleProperty = require('../connection/utils').getSingleProperty + , getProperty = require('../connection/utils').getProperty + , debugOptions = require('../connection/utils').debugOptions + , BSON = require('bson').native().BSON + , PreTwoSixWireProtocolSupport = require('../wireprotocol/2_4_support') + , TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support') + , ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support') + , Session = require('./session') + , Logger = require('../connection/logger') + , MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram'); + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; +// Server instance id +var serverId = 0; +// Callbacks instance id +var callbackId = 0; + +// Single store for all callbacks +var Callbacks = function() { + // EventEmitter.call(this); + var self = this; + // Callbacks + this.callbacks = {}; + // Set the callbacks id + this.id = callbackId++; + // Set the type to server + this.type = 'server'; +} + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// +// Flush all callbacks +Callbacks.prototype.flush = function(err) { + for(var id in this.callbacks) { + if(!isNaN(parseInt(id, 10))) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, null); + } + } +} + +Callbacks.prototype.emit = function(id, err, value) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, value); +} + +Callbacks.prototype.raw = function(id) { + if(this.callbacks[id] == null) return false; + return this.callbacks[id].raw == true ? true : false +} + +Callbacks.prototype.documentsReturnedIn = function(id) { + if(this.callbacks[id] == null) return false; + return typeof this.callbacks[id].documentsReturnedIn == 'string' ? this.callbacks[id].documentsReturnedIn : null; +} + +Callbacks.prototype.unregister = function(id) { + delete this.callbacks[id]; +} + +Callbacks.prototype.register = function(id, callback) { + this.callbacks[id] = bindToCurrentDomain(callback); +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) return callback; + return domain.bind(callback); +} + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// Supports server +var supportsServer = function(_s) { + return _s.ismaster && typeof _s.ismaster.minWireVersion == 'number'; +} + +// +// createWireProtocolHandler +var createWireProtocolHandler = function(result) { + // 3.2 wire protocol handler + if(result && result.maxWireVersion >= 4) { + return new ThreeTwoWireProtocolSupport(new TwoSixWireProtocolSupport()); + } + + // 2.6 wire protocol handler + if(result && result.maxWireVersion >= 2) { + return new TwoSixWireProtocolSupport(); + } + + // 2.4 or earlier wire protocol handler + return new PreTwoSixWireProtocolSupport(); +} + +// +// Reconnect server +var reconnectServer = function(self, state) { + // If the current reconnect retries is 0 stop attempting to reconnect + if(state.currentReconnectRetry == 0) { + return self.destroy(true, true); + } + + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + + // Set status to connecting + state.state = CONNECTING; + // Create a new Pool + state.pool = new Pool(state.options); + // error handler + var reconnectErrorHandler = function(err) { + state.state = DISCONNECTED; + // Destroy the pool + state.pool.destroy(); + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + // No more retries + if(state.currentReconnectRetry <= 0) { + self.state = DESTROYED; + self.emit('error', f('failed to connect to %s:%s after %s retries', state.options.host, state.options.port, state.reconnectTries)); + } else { + setTimeout(function() { + reconnectServer(self, state); + }, state.reconnectInterval); + } + } + + // + // Attempt to connect + state.pool.once('connect', function() { + // Reset retries + state.currentReconnectRetry = state.reconnectTries; + + // Remove any non used handlers + var events = ['error', 'close', 'timeout', 'parseError']; + events.forEach(function(e) { + state.pool.removeAllListeners(e); + }); + + // Set connected state + state.state = CONNECTED; + + // Add proper handlers + state.pool.once('error', reconnectErrorHandler); + state.pool.once('close', closeHandler(self, state)); + state.pool.once('timeout', timeoutHandler(self, state)); + state.pool.once('parseError', fatalErrorHandler(self, state)); + + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return self.emit('reconnect', self); + + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return self.emit('reconnect', self); + } + }); + } + }); + + // + // Handle connection failure + state.pool.once('error', errorHandler(self, state)); + state.pool.once('close', errorHandler(self, state)); + state.pool.once('timeout', errorHandler(self, state)); + state.pool.once('parseError', errorHandler(self, state)); + + // Connect pool + state.pool.connect(); +} + +// +// Handlers +var messageHandler = function(self, state) { + return function(response, connection) { + try { + // Parse the message + response.parse({raw: state.callbacks.raw(response.responseTo), documentsReturnedIn: state.callbacks.documentsReturnedIn(response.responseTo)}); + if(state.logger.isDebug()) state.logger.debug(f('message [%s] received from %s', response.raw.toString('hex'), self.name)); + state.callbacks.emit(response.responseTo, null, response); + } catch (err) { + state.callbacks.flush(new MongoError(err)); + self.destroy(); + } + } +} + +var errorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Destroy all connections + self.destroy(); + // Emit error event + if(state.emitError && self.listeners('error').length > 0) self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + } +} + +var fatalErrorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Emit error event + if(self.listeners('error').length > 0) self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } +} + +var timeoutHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'timeout', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', self.name)); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s timed out", self.name))); + // Emit error event + self.emit('timeout', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } +} + +var closeHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'close', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s closed', self.name)); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); + // Emit error event + self.emit('close', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } +} + +var connectHandler = function(self, state) { + // Apply all stored authentications + var applyAuthentications = function(callback) { + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return callback(null, null); + + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return callback(null, null); + } + }); + } + } + + return function(connection) { + // Apply any applyAuthentications + applyAuthentications(function() { + + // Execute an ismaster + self.command('system.$cmd', {ismaster:true}, function(err, r) { + if(err) { + state.state = DISCONNECTED; + return self.emit('close', err, self); + } + + // Set the current ismaster + if(!err) { + state.ismaster = r.result; + } + + // Emit the ismaster + self.emit('ismaster', r.result, self); + + // Determine the wire protocol handler + state.wireProtocolHandler = createWireProtocolHandler(state.ismaster); + + // Set the wireProtocolHandler + state.options.wireProtocolHandler = state.wireProtocolHandler; + + // Log the ismaster if available + if(state.logger.isInfo()) state.logger.info(f('server %s connected with ismaster [%s]', self.name, JSON.stringify(r.result))); + + // Validate if we it's a server we can connect to + if(!supportsServer(state) && state.wireProtocolHandler == null) { + state.state = DISCONNECTED + return self.emit('error', new MongoError("non supported server version"), self); + } + + // Set the details + if(state.ismaster && state.ismaster.me) state.serverDetails.name = state.ismaster.me; + + // No read preference strategies just emit connect + if(state.readPreferenceStrategies == null) { + state.state = CONNECTED; + return self.emit('connect', self); + } + + // Signal connect to all readPreferences + notifyStrategies(self, self.s, 'connect', [self], function(err, result) { + state.state = CONNECTED; + return self.emit('connect', self); + }); + }); + }); + } +} + +var slaveOk = function(r) { + if(r) return r.slaveOk() + return false; +} + +// +// Execute readPreference Strategies +var notifyStrategies = function(self, state, op, params, callback) { + if(typeof callback != 'function') { + // Notify query start to any read Preference strategies + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + strat[op].apply(strat, params); + } + } + // Finish up + return; + } + + // Execute the async callbacks + var nPreferences = Object.keys(state.readPreferenceStrategies).length; + if(nPreferences == 0) return callback(null, null); + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + // Add a callback to params + var cParams = params.slice(0); + cParams.push(function(err, r) { + nPreferences = nPreferences - 1; + if(nPreferences == 0) { + callback(null, null); + } + }) + // Execute the readPreference + strat[op].apply(strat, cParams); + } + } +} + +var debugFields = ['reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host' + , 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout' + , 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs']; + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + */ +var Server = function(options) { + var self = this; + + // Add event listener + EventEmitter.call(this); + + // BSON Parser, ensure we have a single instance + if(bsonInstance == null) { + bsonInstance = new BSON(bsonTypes); + } + + // Reconnect retries + var reconnectTries = options.reconnectTries || 30; + + // Keeps all the internal state of the server + this.s = { + // Options + options: options + // Contains all the callbacks + , callbacks: new Callbacks() + // Logger + , logger: Logger('Server', options) + // Server state + , state: DISCONNECTED + // Reconnect option + , reconnect: typeof options.reconnect == 'boolean' ? options.reconnect : true + , reconnectTries: reconnectTries + , reconnectInterval: options.reconnectInterval || 1000 + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Current state + , currentReconnectRetry: reconnectTries + // Contains the ismaster + , ismaster: null + // Contains any alternate strategies for picking + , readPreferenceStrategies: options.readPreferenceStrategies + // Auth providers + , authProviders: options.authProviders || {} + // Server instance id + , id: serverId++ + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // wireProtocolHandler methods + , wireProtocolHandler: options.wireProtocolHandler || new PreTwoSixWireProtocolSupport() + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Internal connection pool + , pool: null + // Server details + , serverDetails: { + host: options.host + , port: options.port + , name: options.port ? f("%s:%s", options.host, options.port) : options.host + } + } + + // Reference state + var s = this.s; + + // Add bson parser to options + options.bson = s.bson; + + // Set error properties + getProperty(this, 'name', 'name', s.serverDetails, {}); + getProperty(this, 'bson', 'bson', s.options, {}); + getProperty(this, 'wireProtocolHandler', 'wireProtocolHandler', s.options, {}); + getSingleProperty(this, 'id', s.id); + + // Add auth providers + this.addAuthProvider('mongocr', new MongoCR()); + this.addAuthProvider('x509', new X509()); + this.addAuthProvider('plain', new Plain()); + this.addAuthProvider('gssapi', new GSSAPI()); + this.addAuthProvider('sspi', new SSPI()); + this.addAuthProvider('scram-sha-1', new ScramSHA1()); +} + +inherits(Server, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Server.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.s.ismaster; +} + +/** + * Initiate server connect + * @method + */ +Server.prototype.connect = function(_options) { + var self = this; + // Set server specific settings + _options = _options || {} + // Set the promotion + if(typeof _options.promoteLongs == 'boolean') { + self.s.options.promoteLongs = _options.promoteLongs; + } + + // Destroy existing pool + if(self.s.pool) { + self.s.pool.destroy(); + self.s.pool = null; + } + + // Set the state to connection + self.s.state = CONNECTING; + // Create a new connection pool + if(!self.s.pool) { + self.s.options.messageHandler = messageHandler(self, self.s); + self.s.pool = new Pool(self.s.options); + } + + // Add all the event handlers + self.s.pool.once('timeout', timeoutHandler(self, self.s)); + self.s.pool.once('close', closeHandler(self, self.s)); + self.s.pool.once('error', errorHandler(self, self.s)); + self.s.pool.once('connect', connectHandler(self, self.s)); + self.s.pool.once('parseError', fatalErrorHandler(self, self.s)); + + // Connect the pool + self.s.pool.connect(); +} + +/** + * Destroy the server connection + * @method + */ +Server.prototype.destroy = function(emitClose, emitDestroy) { + var self = this; + if(self.s.logger.isDebug()) self.s.logger.debug(f('destroy called on server %s', self.name)); + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + + // Emit destroy event + if(emitDestroy) self.emit('destroy', self); + // Set state as destroyed + self.s.state = DESTROYED; + // Close the pool + self.s.pool.destroy(); + // Flush out all the callbacks + if(self.s.callbacks) self.s.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + var self = this; + if(self.s.pool) return self.s.pool.isConnected(); + return false; +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +var executeSingleOperation = function(self, ns, cmd, queryOptions, options, onAll, callback) { + // Create a query instance + var query = new Query(self.s.bson, ns, cmd, queryOptions); + + // Set slave OK + query.slaveOk = slaveOk(options.readPreference); + + // Notify query start to any read Preference strategies + if(self.s.readPreferenceStrategies != null) + notifyStrategies(self, self.s, 'startOperation', [self, query, new Date()]); + + // Get a connection (either passed or from the pool) + var connection = options.connection || self.s.pool.get(); + + // Double check if we have a valid connection + if(!connection.isConnected()) { + return callback(new MongoError(f("no connection available to server %s", self.name))); + } + + // Print cmd and execution connection if in debug mode for logging + if(self.s.logger.isDebug()) { + var json = connection.toJSON(); + self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(cmd), json.id, json.host, json.port)); + } + + // Execute multiple queries + if(onAll) { + var connections = self.s.pool.getAll(); + var total = connections.length; + // We have an error + var error = null; + // Execute on all connections + for(var i = 0; i < connections.length; i++) { + try { + query.incRequestId(); + connections[i].write(query.toBin()); + } catch(err) { + total = total - 1; + if(total == 0) return callback(MongoError.create(err)); + } + + // Register the callback + self.s.callbacks.register(query.requestId, function(err, result) { + if(err) error = err; + total = total - 1; + + // Done + if(total == 0) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, error, result, new Date()]); + if(error) return callback(MongoError.create(error)); + // Execute callback, catch and rethrow if needed + try { callback(null, new CommandResult(result.documents[0], connections)); } + catch(err) { process.nextTick(function() { throw err}); } + } + }); + } + + return; + } + + // Execute a single command query + try { + connection.write(query.toBin()); + } catch(err) { + return callback(MongoError.create(err)); + } + + // Register the callback + self.s.callbacks.register(query.requestId, function(err, result) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); + if(err) return callback(err); + if(result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || result.documents[0]['err'] + || result.documents[0]['code']) return callback(MongoError.create(result.documents[0])); + // Execute callback, catch and rethrow if needed + try { callback(null, new CommandResult(result.documents[0], connection)); } + catch(err) { process.nextTick(function() { throw err}); } + }); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Ensure we have no options + options = options || {}; + // Do we have a read Preference it need to be of type ReadPreference + if(options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error("readPreference must be an instance of ReadPreference"); + } + + // Debug log + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command [%s] against %s', JSON.stringify({ + ns: ns, cmd: cmd, options: debugOptions(debugFields, options) + }), self.name)); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // If we have no connection error + if(!self.s.pool.isConnected()) return callback(new MongoError(f("no connection available to server %s", self.name))); + + // Execute on all connections + var onAll = typeof options.onAll == 'boolean' ? options.onAll : false; + + // Check keys + var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys: false; + + // Serialize function + var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + + // Ignore undefined values + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + + // Query options + var queryOptions = { + numberToSkip: 0, numberToReturn: -1, checkKeys: checkKeys + }; + + // Set up the serialize functions and ignore undefined + if(serializeFunctions) queryOptions.serializeFunctions = serializeFunctions; + if(ignoreUndefined) queryOptions.ignoreUndefined = ignoreUndefined; + + // Single operation execution + if(!Array.isArray(cmd)) { + return executeSingleOperation(self, ns, cmd, queryOptions, options, onAll, callback); + } + + // Build commands for each of the instances + var queries = new Array(cmd.length); + for(var i = 0; i < cmd.length; i++) { + queries[i] = new Query(self.s.bson, ns, cmd[i], queryOptions); + queries[i].slaveOk = slaveOk(options.readPreference); + } + + // Notify query start to any read Preference strategies + if(self.s.readPreferenceStrategies != null) + notifyStrategies(self, self.s, 'startOperation', [self, queries, new Date()]); + + // Get a connection (either passed or from the pool) + var connection = options.connection || self.s.pool.get(); + + // Double check if we have a valid connection + if(!connection.isConnected()) { + return callback(new MongoError(f("no connection available to server %s", self.name))); + } + + // Print cmd and execution connection if in debug mode for logging + if(self.s.logger.isDebug()) { + var json = connection.toJSON(); + self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(queries), json.id, json.host, json.port)); + } + + // Canceled operations + var canceled = false; + // Number of operations left + var operationsLeft = queries.length; + // Results + var results = []; + + // We need to nest the callbacks + for(var i = 0; i < queries.length; i++) { + // Get the query object + var query = queries[i]; + + // Execute a single command query + try { + connection.write(query.toBin()); + } catch(err) { + return callback(MongoError.create(err)); + } + + // Register the callback + self.s.callbacks.register(query.requestId, function(err, result) { + // If it's canceled ignore the operation + if(canceled) return; + // Update the current index + operationsLeft = operationsLeft - 1; + + // If we have an error cancel the operation + if(err) { + canceled = true; + return callback(err); + } + + // Return the result + if(result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || result.documents[0]['err'] + || result.documents[0]['code']) { + + // Set to canceled + canceled = true; + // Return the error + return callback(MongoError.create(result.documents[0])); + } + + // Push results + results.push(result.documents[0]); + + // We are done, return the result + if(operationsLeft == 0) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); + + // Turn into command results + var commandResults = new Array(results.length); + for(var i = 0; i < results.length; i++) { + commandResults[i] = new CommandResult(results[i], connection); + } + + // Execute callback, catch and rethrow if needed + try { callback(null, commandResults); } + catch(err) { process.nextTick(function() { throw err}); } + } + }); + } +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.insert(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.update(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.remove(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(mechanism, db) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(self.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // If we have the default mechanism we pick mechanism based on the wire + // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr + if(mechanism == 'default' && self.s.ismaster && self.s.ismaster.maxWireVersion >= 3) { + mechanism = 'scram-sha-1'; + } else if(mechanism == 'default') { + mechanism = 'mongocr'; + } + + // Actual arguments + var finalArguments = [self, self.s.pool, db].concat(args.slice(0)).concat([function(err, r) { + if(err) return callback(err); + if(!r) return callback(new MongoError('could not authenticate')); + callback(null, new Session({}, self)); + }]); + + // Let's invoke the auth mechanism + self.s.authProviders[mechanism].auth.apply(self.s.authProviders[mechanism], finalArguments); +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Server.prototype.addReadPreferenceStrategy = function(name, strategy) { + var self = this; + if(self.s.readPreferenceStrategies == null) self.s.readPreferenceStrategies = {}; + self.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Server.prototype.addAuthProvider = function(name, provider) { + var self = this; + self.s.authProviders[name] = provider; +} + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if(typeof server == 'string') return server == this.name; + return server.name == this.name; +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.getAll(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Server.prototype.getServer = function(options) { + return this; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Server.prototype.getConnection = function(options) { + return this.s.pool.get(); +} + +/** + * Get callbacks object + * @method + * @return {Callbacks} + */ +Server.prototype.getCallbacks = function() { + return this.s.callbacks; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +Server.prototype.parserType = function() { + var s = this.s; + if(s.options.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.cursor = function(ns, cmd, cursorOptions) { + var s = this.s; + cursorOptions = cursorOptions || {}; + // Set up final cursor type + var FinalCursor = cursorOptions.cursorFactory || s.Cursor; + // Return the cursor + return new FinalCursor(s.bson, ns, cmd, cursorOptions, this, s.options); +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Server#close + * @type {Server} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Server#error + * @type {Server} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Server#timeout + * @type {Server} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Server#parseError + * @type {Server} + */ + +/** + * The server reestablished the connection + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * This is an insert result callback + * + * @callback opResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {CommandResult} command result + */ + +/** + * This is an authentication result callback + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Session} an authenticated session + */ + +module.exports = Server; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js new file mode 100644 index 0000000..032c3c5 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js @@ -0,0 +1,93 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , EventEmitter = require('events').EventEmitter; + +/** + * Creates a new Authentication Session + * @class + * @param {object} [options] Options for the session + * @param {{Server}|{ReplSet}|{Mongos}} topology The topology instance underpinning the session + */ +var Session = function(options, topology) { + this.options = options; + this.topology = topology; + + // Add event listener + EventEmitter.call(this); +} + +inherits(Session, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {object} [options.readPreference] Specify read preference if command supports it + * @param {object} [options.connection] Specify connection object to execute command against + * @param {opResultCallback} callback A callback function + */ +Session.prototype.command = function(ns, cmd, options, callback) { + this.topology.command(ns, cmd, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.insert = function(ns, ops, options, callback) { + this.topology.insert(ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.update = function(ns, ops, options, callback) { + this.topology.update(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.remove = function(ns, ops, options, callback) { + this.topology.remove(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {boolean} [options.tailable=false] Tailable flag set + * @param {boolean} [options.oplogReply=false] oplogReply flag set + * @param {boolean} [options.awaitdata=false] awaitdata flag set + * @param {boolean} [options.exhaust=false] exhaust flag set + * @param {boolean} [options.partial=false] partial flag set + * @param {opResultCallback} callback A callback function + */ +Session.prototype.cursor = function(ns, cmd, options) { + return this.topology.cursor(ns, cmd, options); +} + +module.exports = Session; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js new file mode 100644 index 0000000..3a7b460 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js @@ -0,0 +1,276 @@ +"use strict"; + +var Logger = require('../../connection/logger') + , EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format; + +/** + * Creates a new Ping read preference strategy instance + * @class + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {Ping} A cursor instance + */ +var Ping = function(options) { + // Add event listener + EventEmitter.call(this); + + // Contains the ping state + this.s = { + // Contains all the ping data + pings: {} + // Set no options if none provided + , options: options || {} + // Logger + , logger: Logger('Ping', options) + // Ping interval + , pingInterval: options.pingInterval || 10000 + , acceptableLatency: options.acceptableLatency || 15 + // Debug options + , debug: typeof options.debug == 'boolean' ? options.debug : false + // Index + , index: 0 + // Current ping time + , lastPing: null + + } + + // Log the options set + if(this.s.logger.isDebug()) this.s.logger.debug(f('ping strategy interval [%s], acceptableLatency [%s]', this.s.pingInterval, this.s.acceptableLatency)); + + // If we have enabled debug + if(this.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'data', { + enumerable: true, get: function() { return this.s.pings; } + }); + } +} + +inherits(Ping, EventEmitter); + +/** + * @ignore + */ +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tags = readPreference.tags; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) filteredServers.push(servers[i]); + } + + // Returned filtered servers + return filteredServers; +} + +/** + * Pick a server + * @method + * @param {State} set The current replicaset state object + * @param {ReadPreference} readPreference The current readPreference object + * @param {readPreferenceResultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.pickServer = function(set, readPreference) { + var self = this; + // Only get primary and secondaries as seeds + var seeds = {}; + var servers = []; + if(set.primary) { + servers.push(set.primary); + } + + for(var i = 0; i < set.secondaries.length; i++) { + servers.push(set.secondaries[i]); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Transform the list + var serverList = []; + // for(var name in seeds) { + for(var i = 0; i < servers.length; i++) { + serverList.push({name: servers[i].name, time: self.s.pings[servers[i].name] || 0}); + } + + // Sort by time + serverList.sort(function(a, b) { + return a.time > b.time; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = serverList.length > 0 ? serverList[0].time : 0; + + // Filter by latency + serverList = serverList.filter(function(s) { + return s.time <= lowest + self.s.acceptableLatency; + }); + + // No servers, default to primary + if(serverList.length == 0 && set.primary) { + if(self.s.logger.isInfo()) self.s.logger.info(f('picked primary server [%s]', set.primary.name)); + return set.primary; + } else if(serverList.length == 0) { + return null + } + + // We picked first server + if(self.s.logger.isInfo()) self.s.logger.info(f('picked server [%s] with ping latency [%s]', serverList[0].name, serverList[0].time)); + + // Add to the index + self.s.index = self.s.index + 1; + // Select the index + self.s.index = self.s.index % serverList.length; + // Return the first server of the sorted and filtered list + return set.get(serverList[self.s.index].name); +} + +/** + * Start of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {object} query The operation running + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.startOperation = function(server, query, date) { +} + +/** + * End of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {error} err An error from the operation + * @param {object} result The result from the operation + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.endOperation = function(server, err, result, date) { +} + +/** + * High availability process running + * @method + * @param {State} set The current replicaset state object + * @param {resultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.ha = function(topology, state, callback) { + var self = this; + var servers = state.getAll(); + var count = servers.length; + + // No servers return + if(servers.length == 0) return callback(null, null); + + // Return if we have not yet reached the ping interval + if(self.s.lastPing != null) { + var diff = new Date().getTime() - self.s.lastPing.getTime(); + if(diff < self.s.pingInterval) return callback(null, null); + } + + // Execute operation + var operation = function(_server) { + var start = new Date(); + // Execute ping against server + _server.command('system.$cmd', {ismaster:1}, function(err, r) { + count = count - 1; + var time = new Date().getTime() - start.getTime(); + self.s.pings[_server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('ha latency for server [%s] is [%s] ms', _server.name, time)); + // We are done with all the servers + if(count == 0) { + // Emit ping event + topology.emit('ping', err, r ? r.result : null); + // Update the last ping time + self.s.lastPing = new Date(); + // Return + callback(null, null); + } + }); + } + + // Let's ping all servers + while(servers.length > 0) { + operation(servers.shift()); + } +} + +var removeServer = function(self, server) { + delete self.s.pings[server.name]; +} + +/** + * Server connection closed + * @method + * @param {Server} server The server that closed + */ +Ping.prototype.close = function(server) { + removeServer(this, server); +} + +/** + * Server connection errored out + * @method + * @param {Server} server The server that errored out + */ +Ping.prototype.error = function(server) { + removeServer(this, server); +} + +/** + * Server connection timeout + * @method + * @param {Server} server The server that timed out + */ +Ping.prototype.timeout = function(server) { + removeServer(this, server); +} + +/** + * Server connection happened + * @method + * @param {Server} server The server that connected + * @param {resultCallback} callback The callback to return the result from the function + */ +Ping.prototype.connect = function(server, callback) { + var self = this; + // Get the command start date + var start = new Date(); + // Execute ping against server + server.command('system.$cmd', {ismaster:1}, function(err, r) { + var time = new Date().getTime() - start.getTime(); + self.s.pings[server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('connect latency for server [%s] is [%s] ms', server.name, time)); + // Set last ping + self.s.lastPing = new Date(); + // Done, return + callback(null, null); + }); +} + +/** + * This is a result from a readPreference strategy + * + * @callback readPreferenceResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Server} server The server picked by the strategy + */ + +module.exports = Ping; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js new file mode 100644 index 0000000..e2e6a67 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js @@ -0,0 +1,559 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +// Write concern fields +var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync']; + +var WireProtocol = function() {} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var legacy = typeof options.legacy == 'boolean' ? options.legacy : false; + ops = Array.isArray(ops) ? ops :[ops]; + + // If we have more than a 1000 ops fails + if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000")); + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(connection && connection.isConnected()) connection.write(killCursor.toBin()); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + connection.write(getMore.toBin()); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + // If we have explain, return a single document and close cursor + if(cmd.explain) { + numberToReturn = -1; + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; + if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; + if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + finalCmd['$readPreference'] = readPreference.toJSON(); + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +var hasWriteConcern = function(writeConcern) { + if(writeConcern.w + || writeConcern.wtimeout + || writeConcern.j == true + || writeConcern.fsync == true + || Object.keys(writeConcern).length == 0) { + return true; + } + return false; +} + +var cloneWriteConcern = function(writeConcern) { + var wc = {}; + if(writeConcern.w != null) wc.w = writeConcern.w; + if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout; + if(writeConcern.j != null) wc.j = writeConcern.j; + if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync; + return wc; +} + +// +// Aggregate up all the results +// +var aggregateWriteOperationResults = function(opType, ops, results, connection) { + var finalResult = { ok: 1, n: 0 } + + // Map all the results coming back + for(var i = 0; i < results.length; i++) { + var result = results[i]; + var op = ops[i]; + + if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) { + finalResult.upserted = []; + } + + // Push the upserted document to the list of upserted values + if(result.upserted) { + finalResult.upserted.push({index: i, _id: result.upserted}); + } + + // We have an upsert where we passed in a _id + if(result.updatedExisting == false && result.n == 1 && result.upserted == null) { + finalResult.upserted.push({index: i, _id: op.q._id}); + } + + // We have an insert command + if(result.ok == 1 && opType == 'insert' && result.err == null) { + finalResult.n = finalResult.n + 1; + } + + // We have a command error + if(result != null && result.ok == 0 || result.err || result.errmsg) { + if(result.ok == 0) finalResult.ok = 0; + finalResult.code = result.code; + finalResult.errmsg = result.errmsg || result.err || result.errMsg; + + // Check if we have a write error + if(result.code == 11000 + || result.code == 11001 + || result.code == 12582 + || result.code == 16544 + || result.code == 16538 + || result.code == 16542 + || result.code == 14 + || result.code == 13511) { + if(finalResult.writeErrors == null) finalResult.writeErrors = []; + finalResult.writeErrors.push({ + index: i + , code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + }); + } else { + finalResult.writeConcernError = { + code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + } + } + } else if(typeof result.n == 'number') { + finalResult.n += result.n; + } else { + finalResult.n += 1; + } + + // Result as expected + if(result != null && result.lastOp) finalResult.lastOp = result.lastOp; + } + + // Return finalResult aggregated results + return new CommandResult(finalResult, connection); +} + +// +// Execute all inserts in an ordered manner +// +var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + var _ops = ops.slice(0); + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Collect all the getLastErrors + var getLastErrors = []; + + // Execute an operation + var executeOp = function(list, _callback) { + // Get a pool connection + var connection = pool.get(); + // No more items in the list + if(list.length == 0) return _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + + // Get the first operation + var doc = list.shift(); + + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options); + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + + // Get the db name + var db = ns.split('.').shift(); + + // Error out if no connection available + if(connection == null) + return _callback(new MongoError("no connection available")); + + try { + // Execute the insert + connection.write(op.toBin()); + + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var i = 0; i < writeConcernFields.length; i++) { + if(writeConcern[writeConcernFields[i]] != null) + getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]]; + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Write the lastError message + connection.write(getLastErrorOp.toBin()); + // Register the callback + callbacks.register(getLastErrorOp.requestId, function(err, result) { + if(err) return callback(err); + // Get the document + var doc = result.documents[0]; + // Save the getLastError document + getLastErrors.push(doc); + // If we have an error terminate + if(doc.ok == 0 || doc.err || doc.errmsg) return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + // Execute the next op in the list + executeOp(list, callback); + }); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors.push({ ok: 1, errmsg: err.message, code: 14 }); + // Return due to an error + return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + } + } + + // Execute the operations + executeOp(_ops, callback); +} + +var executeUnordered = function(opType, command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Total operations to write + var totalOps = ops.length; + // Collect all the getLastErrors + var getLastErrors = []; + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + // Driver level error + var error; + + // Execute all the operations + for(var i = 0; i < ops.length; i++) { + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options); + // Get db name + var db = ns.split('.').shift(); + + // Get a pool connection + var connection = pool.get(); + + // Error out if no connection available + if(connection == null) + return _callback(new MongoError("no connection available")); + + try { + // Execute the insert + connection.write(op.toBin()); + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var j = 0; j < writeConcernFields.length; j++) { + if(writeConcern[writeConcernFields[j]] != null) + getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]]; + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Write the lastError message + connection.write(getLastErrorOp.toBin()); + + // Give the result from getLastError the right index + var callbackOp = function(_index) { + return function(err, result) { + if(err) error = err; + // Update the number of operations executed + totalOps = totalOps - 1; + // Save the getLastError document + if(!err) getLastErrors[_index] = result.documents[0]; + // Check if we are done + if(totalOps == 0) { + if(error) return callback(error); + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + } + } + } + + // Register the callback + callbacks.register(getLastErrorOp.requestId, callbackOp(i)); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // Update the number of operations executed + totalOps = totalOps - 1; + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors[i] = { ok: 1, errmsg: err.message, code: 14 }; + // Check if we are done + if(totalOps == 0) { + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + } + } + } + + // Empty w:0 return + if(writeConcern + && writeConcern.w == 0 && callback) { + callback(null, null); + } +} + +module.exports = WireProtocol; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js new file mode 100644 index 0000000..b1d1d46 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js @@ -0,0 +1,291 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +var WireProtocol = function() {} + +// +// Execute a write operation +var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern || {}; + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + writeCommand.writeConcern = writeConcern; + + // Options object + var opts = {}; + if(type == 'insert') opts.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; + if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; + // Execute command + topology.command(f("%s.$cmd", d), writeCommand, opts, callback); +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(connection && connection.isConnected()) connection.write(killCursor.toBin()); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + connection.write(getMore.toBin()); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + // If we have explain, return a single document and close cursor + if(cmd.explain) { + numberToReturn = -1; + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; + if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; + if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + finalCmd['$readPreference'] = readPreference.toJSON(); + } + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +module.exports = WireProtocol; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js new file mode 100644 index 0000000..c5e61aa --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js @@ -0,0 +1,494 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +var WireProtocol = function(legacyWireProtocol) { + this.legacyWireProtocol = legacyWireProtocol; +} + +// +// Execute a write operation +var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern || {}; + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + writeCommand.writeConcern = writeConcern; + + // Do we have bypassDocumentValidation set, then enable it on the write command + if(typeof options.bypassDocumentValidation == 'boolean') { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Options object + var opts = {}; + if(type == 'insert') opts.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; + if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; + // Execute command + topology.command(f("%s.$cmd", d), writeCommand, opts, callback); +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + // Create getMore command + var killcursorCmd = { + killCursors: parts.join('.'), + cursors: [cursorId] + } + + // Build Query object + var query = new Query(bson, commandns, killcursorCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = true; + + // Execute the kill cursor command + if(connection && connection.isConnected()) { + connection.write(query.toBin()); + } + + // Kill cursor callback + var killCursorCallback = function(err, r) { + if(err) { + if(typeof callback != 'function') return; + return callback(err); + } + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + if(typeof callback != 'function') return; + return callback(new MongoError("cursor killed or timed out"), null); + } + + if(!Array.isArray(r.documents) || r.documents.length == 0) { + if(typeof callback != 'function') return; + return callback(new MongoError(f('invalid getMore result returned for cursor id %s', cursorState.cursorId))); + } + + // Return the result + if(typeof callback == 'function') { + callback(null, r.documents[0]); + } + } + + // Register a callback + callbacks.register(query.requestId, killCursorCallback); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Check if we have an maxTimeMS set + var maxTimeMS = typeof cursorState.cmd.maxTimeMS == 'number' ? cursorState.cmd.maxTimeMS : 3000; + + // Create getMore command + var getMoreCmd = { + getMore: cursorState.cursorId, + collection: parts.join('.'), + batchSize: batchSize, + maxTimeMS: maxTimeMS + } + + // Build Query object + var query = new Query(bson, commandns, getMoreCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + if(!Array.isArray(r.documents) || r.documents.length == 0) + return callback(new MongoError(f('invalid getMore result returned for cursor id %s', cursorState.cursorId))); + + // Raw, return all the extracted documents + if(raw) { + cursorState.documents = r.documents; + cursorState.cursorId = r.cursorId; + return callback(null, r.documents); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.documents[0].cursor.id == 'number' + ? Long.fromNumber(r.documents[0].cursor.id) + : r.documents[0].cursor.id; + + // Set all the values + cursorState.documents = r.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + // Return the result + callback(null, r.documents[0]); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Add the result field needed + queryCallback.documentsReturnedIn = 'nextBatch'; + + // Register a callback + callbacks.register(query.requestId, queryCallback); + // Write out the getMore command + connection.write(query.toBin()); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + if(cmd.exhaust) { + return this.legacyWireProtocol.command(bson, ns, cmd, cursorState, topology, options); + } + + // Create the find command + var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options) + // Mark the cmd as virtual + cmd.virtual = false; + // Signal the documents are in the firstBatch value + query.documentsReturnedIn = 'firstBatch'; + // Return the query + return query; + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +// FIND/GETMORE SPEC +// { +// “find”: , +// “filter”: { ... }, +// “sort”: { ... }, +// “projection”: { ... }, +// “hint”: { ... }, +// “skip”: , +// “limit”: , +// “batchSize”: , +// “singleBatch”: , +// “comment”: , +// “maxScan”: , +// “maxTimeMS”: , +// “max”: { ... }, +// “min”: { ... }, +// “returnKey”: , +// “showRecordId”: , +// “snapshot”: , +// “tailable”: , +// “oplogReplay”: , +// “noCursorTimeout”: , +// “awaitData”: , +// “partial”: , +// “$readPreference”: { ... } +// } + +// +// Execute a find command +var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Build actual find command + var findCmd = { + find: parts.join('.') + }; + + // I we provided a filter + if(cmd.query) findCmd.filter = cmd.query; + + // Sort value + var sortValue = cmd.sort; + + // Handle issue of sort being an Array + if(Array.isArray(sortValue)) { + var sortObject = {}; + + if(sortValue.length > 0 && !Array.isArray(sortValue[0])) { + var sortDirection = sortValue[1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[0]] = sortDirection; + } else { + for(var i = 0; i < sortValue.length; i++) { + var sortDirection = sortValue[i][1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + }; + + // Add sort to command + if(cmd.sort) findCmd.sort = sortValue; + // Add a projection to the command + if(cmd.fields) findCmd.projection = cmd.fields; + // Add a hint to the command + if(cmd.hint) findCmd.hint = cmd.hint; + // Add a skip + if(cmd.skip) findCmd.skip = cmd.skip; + // Add a limit + if(cmd.limit) findCmd.limit = cmd.limit; + // Add a batchSize + if(cmd.batchSize) findCmd.batchSize = cmd.batchSize; + + // Check if we wish to have a singleBatch + if(cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + // If we have comment set + if(cmd.comment) findCmd.comment = cmd.comment; + + // If we have maxScan + if(cmd.maxScan) findCmd.maxScan = cmd.maxScan; + + // If we have maxTimeMS set + if(cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + + // If we have min + if(cmd.min) findCmd.min = cmd.min; + + // If we have max + if(cmd.max) findCmd.max = cmd.max; + + // If we have returnKey set + if(cmd.returnKey) findCmd.returnKey = cmd.returnKey; + + // If we have showDiskLoc set + if(cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; + + // If we have snapshot set + if(cmd.snapshot) findCmd.snapshot = cmd.snapshot; + + // If we have tailable set + if(cmd.tailable) findCmd.tailable = cmd.tailable; + + // If we have oplogReplay set + if(cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + + // If we have noCursorTimeout set + if(cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + + // If we have awaitData set + if(cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if(cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + + // If we have partial set + if(cmd.partial) findCmd.partial = cmd.partial; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + } + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if(cmd.explain) { + findCmd = { + explain: findCmd + } + } + + // Did we provide a readConcern + if(cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, commandns, findCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + finalCmd['$readPreference'] = readPreference.toJSON(); + } + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +module.exports = WireProtocol; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js new file mode 100644 index 0000000..9c665ee --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js @@ -0,0 +1,357 @@ +"use strict"; + +var MongoError = require('../error'); + +// Wire command operation ids +var OP_UPDATE = 2001; +var OP_INSERT = 2002; +var OP_DELETE = 2006; + +var Insert = function(requestId, ismaster, bson, ns, documents, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + if(!Array.isArray(documents) || documents.length == 0) throw new MongoError("documents array must contain at least one document to insert"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new MongoError("namespace cannot contain a null character"); + } + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.documents = documents; + this.ismaster = ismaster; + + // Ensure empty options + options = options || {}; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.continueOnError = typeof options.continueOnError == 'boolean' ? options.continueOnError : false; + // Set flags + this.flags = this.continueOnError ? 1 : 0; +} + +// To Binary +Insert.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(this.ns) + 1 // namespace + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize all the documents + for(var i = 0; i < this.documents.length; i++) { + var buffer = this.bson.serialize(this.documents[i] + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + + // Document is larger than maxBsonObjectSize, terminate serialization + if(buffer.length > this.ismaster.maxBsonObjectSize) { + throw new MongoError("Document exceeds maximum allowed bson size of " + this.ismaster.maxBsonObjectSize + " bytes"); + } + + // Add to total length of wire protocol message + totalLength = totalLength + buffer.length; + // Add to buffer + buffers.push(buffer); + } + + // Command is larger than maxMessageSizeBytes terminate serialization + if(totalLength > this.ismaster.maxMessageSizeBytes) { + throw new MongoError("Command exceeds maximum message size of " + this.ismaster.maxMessageSizeBytes + " bytes"); + } + + // Add all the metadata + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_INSERT >> 24) & 0xff; + header[index + 2] = (OP_INSERT >> 16) & 0xff; + header[index + 1] = (OP_INSERT >> 8) & 0xff; + header[index] = (OP_INSERT) & 0xff; + index = index + 4; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Return the buffers + return buffers; +} + +var Update = function(requestId, ismaster, bson, ns, update, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.upsert = typeof update[0].upsert == 'boolean' ? update[0].upsert : false; + this.multi = typeof update[0].multi == 'boolean' ? update[0].multi : false; + this.q = update[0].q; + this.u = update[0].u; + + // Create flag value + this.flags = this.upsert ? 1 : 0; + this.flags = this.multi ? this.flags | 2 : this.flags; +} + +// To Binary +Update.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Serialize the update + var update = this.bson.serialize(this.u + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(update); + totalLength = totalLength + update.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_UPDATE >> 24) & 0xff; + header[index + 2] = (OP_UPDATE >> 16) & 0xff; + header[index + 1] = (OP_UPDATE >> 8) & 0xff; + header[index] = (OP_UPDATE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +var Remove = function(requestId, ismaster, bson, ns, remove, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.limit = typeof remove[0].limit == 'number' ? remove[0].limit : 1; + this.q = remove[0].q; + + // Create flag value + this.flags = this.limit == 1 ? 1 : 0; +} + +// To Binary +Remove.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_DELETE >> 24) & 0xff; + header[index + 2] = (OP_DELETE >> 16) & 0xff; + header[index + 1] = (OP_DELETE >> 8) & 0xff; + header[index] = (OP_DELETE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write ZERO + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +module.exports = { + Insert: Insert + , Update: Update + , Remove: Remove +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY new file mode 100644 index 0000000..ecf5994 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY @@ -0,0 +1,113 @@ +0.4.16 2015-10-07 +----------------- +- Fixed issue with return statement in Map.js. + +0.4.15 2015-10-06 +----------------- +- Exposed Map correctly via index.js file. + +0.4.14 2015-10-06 +----------------- +- Exposed Map correctly via bson.js file. + +0.4.13 2015-10-06 +----------------- +- Added ES6 Map type serialization as well as a polyfill for ES5. + +0.4.12 2015-09-18 +----------------- +- Made ignore undefined an optional parameter. + +0.4.11 2015-08-06 +----------------- +- Minor fix for invalid key checking. + +0.4.10 2015-08-06 +----------------- +- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. +- Some performance improvements by in lining code. + +0.4.9 2015-08-06 +---------------- +- Undefined fields are omitted from serialization in objects. + +0.4.8 2015-07-14 +---------------- +- Fixed size validation to ensure we can deserialize from dumped files. + +0.4.7 2015-06-26 +---------------- +- Added ability to instruct deserializer to return raw BSON buffers for named array fields. +- Minor deserialization optimization by moving inlined function out. + +0.4.6 2015-06-17 +---------------- +- Fixed serializeWithBufferAndIndex bug. + +0.4.5 2015-06-17 +---------------- +- Removed any references to the shared buffer to avoid non GC collectible bson instances. + +0.4.4 2015-06-17 +---------------- +- Fixed rethrowing of error when not RangeError. + +0.4.3 2015-06-17 +---------------- +- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. + +0.4.2 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.1 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.0 2015-06-16 +---------------- +- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. +- Removed bson-ext extension dependency for now. + +0.3.2 2015-03-27 +---------------- +- Removed node-gyp from install script in package.json. + +0.3.1 2015-03-27 +---------------- +- Return pure js version on native() call if failed to initialize. + +0.3.0 2015-03-26 +---------------- +- Pulled out all C++ code into bson-ext and made it an optional dependency. + +0.2.21 2015-03-21 +----------------- +- Updated Nan to 1.7.0 to support io.js and node 0.12.0 + +0.2.19 2015-02-16 +----------------- +- Updated Nan to 1.6.2 to support io.js and node 0.12.0 + +0.2.18 2015-01-20 +----------------- +- Updated Nan to 1.5.1 to support io.js + +0.2.16 2014-12-17 +----------------- +- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's + +0.2.12 2014-08-24 +----------------- +- Fixes for fortify review of c++ extension +- toBSON correctly allows returns of non objects + +0.2.3 2013-10-01 +---------------- +- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) +- Fixed issue where corrupt CString's could cause endless loop +- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) + +0.1.4 2012-09-25 +---------------- +- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md new file mode 100644 index 0000000..56327c2 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md @@ -0,0 +1,69 @@ +Javascript + C++ BSON parser +============================ + +This BSON parser is primarily meant to be used with the `mongodb` node.js driver. +However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser. +The current build is located in the `browser_build/bson.js` file. + +A simple example of how to use BSON in the browser: + +```html + + + + + + + + +``` + +A simple example of how to use BSON in `node.js`: + +```javascript +var bson = require("bson"); +var BSON = new bson.BSONPure.BSON(); +var Long = bson.BSONPure.Long; + +var doc = {long: Long.fromNumber(100)} + +// Serialize a document +var data = BSON.serialize(doc, false, true, false); +console.log("data:", data); + +// Deserialize the resulting Buffer +var doc_2 = BSON.deserialize(data); +console.log("doc_2:", doc_2); +``` + +The API consists of two simple methods to serialize/deserialize objects to/from BSON format: + + * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** + * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports + + * BSON.deserialize(buffer, options, isArray) + * Options + * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * @param {TypedArray/Array} a TypedArray/Array containing the BSON data + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js new file mode 100644 index 0000000..555aa79 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js @@ -0,0 +1,1574 @@ +var Long = require('../lib/bson/long').Long + , Double = require('../lib/bson/double').Double + , Timestamp = require('../lib/bson/timestamp').Timestamp + , ObjectID = require('../lib/bson/objectid').ObjectID + , Symbol = require('../lib/bson/symbol').Symbol + , Code = require('../lib/bson/code').Code + , MinKey = require('../lib/bson/min_key').MinKey + , MaxKey = require('../lib/bson/max_key').MaxKey + , DBRef = require('../lib/bson/db_ref').DBRef + , Binary = require('../lib/bson/binary').Binary + , BinaryParser = require('../lib/bson/binary_parser').BinaryParser + , writeIEEE754 = require('../lib/bson/float_parser').writeIEEE754 + , readIEEE754 = require('../lib/bson/float_parser').readIEEE754 + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * Create a new BSON instance + * + * @class + * @return {BSON} instance of BSON Parser. + */ +function BSON () {}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions) { + var isBuffer = typeof Buffer !== 'undefined'; + + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + switch(typeof value) { + case 'string': + return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + case 'undefined': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + case 'boolean': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else if(serializeFunctions) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; + } + } + } + + return 0; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { + // Default setting false + serializeFunctions = serializeFunctions == null ? false : serializeFunctions; + // Write end information (length of the object) + var size = buffer.length; + // Write the size of the object + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; +} + +/** + * @ignore + * @api private + */ +var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { + if(object.toBSON) { + if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); + object = object.toBSON(); + if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); + } + + // Process the object + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Serialize the object + for(var key in object) { + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + // dollars and dots ok + BSON.checkKey(key, !checkKeys); + } + + // Pack the element + index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); + } + } + + // Write zero + buffer[index++] = 0; + return index; +} + +var stringToBytes = function(str) { + var ch, st, re = []; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re.concat( st.reverse() ); + } + // return an array of bytes + return re; +} + +var numberOfBytes = function(str) { + var ch, st, re = 0; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re + st.length; + } + // return an array of bytes + return re; +} + +/** + * @ignore + * @api private + */ +var writeToTypedArray = function(buffer, string, index) { + var bytes = stringToBytes(string); + for(var i = 0; i < bytes.length; i++) { + buffer[index + i] = bytes[i]; + } + return bytes.length; +} + +/** + * @ignore + * @api private + */ +var supportsBuffer = typeof Buffer != 'undefined'; + +/** + * @ignore + * @api private + */ +var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { + + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + var startIndex = index; + + switch(typeof value) { + case 'string': + // console.log("+++++++++++ index string:: " + index) + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; + // console.log("====== key :: " + name + " size ::" + size) + // Write the size of the string to buffer + buffer[index + 3] = (size >> 24) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index] = size & 0xff; + // Ajust the index + index = index + 4; + // Write the string + supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + // Return index + return index; + case 'number': + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + case 'undefined': + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + case 'boolean': + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + case 'object': + if(value === null || value instanceof MinKey || value instanceof MaxKey + || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + // console.log("+++++++++++ index OBJECTID:: " + index) + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write objectid + supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); + // Ajust index + index = index + 12; + return index; + } else if(value instanceof Date || isDate(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + // Write the type + buffer[index++] = value instanceof Long || value['_bsontype'] == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(value instanceof Double || value['_bsontype'] == 'Double') { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.code.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize + 4; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.code.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); + // Ajust index + index = index + value.position; + return index; + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(value.value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + // Message size + var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); + // Serialize the object + var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write zero for object + buffer[endIndex++] = 0x00; + // Return the end index + return endIndex; + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Adjust the index + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); + // Write size + var size = endIndex - index; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return endIndex; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + buffer.write(value.source, index, 'utf8'); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = new Buffer(scopeSize); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize - 4; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + scopeObjectBuffer.copy(buffer, index, 0, scopeSize); + + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else if(serializeFunctions) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } + } + + // If no value to serialize + return index; +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + // Throw error if we are trying serialize an illegal type + if(object == null || typeof object != 'object' || Array.isArray(object)) + throw new Error("Only javascript objects supported"); + + // Emoty target buffer + var buffer = null; + // Calculate the size of the object + var size = BSON.calculateObjectSize(object, serializeFunctions); + // Fetch the best available type for storing the binary data + if(buffer = typeof Buffer != 'undefined') { + buffer = new Buffer(size); + asBuffer = true; + } else if(typeof Uint8Array != 'undefined') { + buffer = new Uint8Array(new ArrayBuffer(size)); + } else { + buffer = new Array(size); + } + + // If asBuffer is false use typed arrays + BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); + // console.log("++++++++++++++++++++++++++++++++++++ OLDJS :: " + buffer.length) + // console.log(buffer.toString('hex')) + // console.log(buffer.toString('ascii')) + return buffer; +} + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Crc state variables shared by function + * + * @ignore + * @api private + */ +var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + +/** + * CRC32 hash method, Fast and enough versitility for our usage + * + * @ignore + * @api private + */ +var crc32 = function(string, start, end) { + var crc = 0 + var x = 0; + var y = 0; + crc = crc ^ (-1); + + for(var i = start, iTop = end; i < iTop;i++) { + y = (crc ^ string[i]) & 0xFF; + x = table[y]; + crc = (crc >>> 8) ^ x; + } + + return crc ^ (-1); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = BSON.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +/** + * Convert Uint8Array to String + * + * @ignore + * @api private + */ +var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { + return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); +} + +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + + return result; +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.deserialize = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + // Reads in a C style string + var readCStyleString = function() { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Grab utf8 encoded string + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); + // Update index position + index = i + 1; + // Return string + return string; + } + + // Create holding object + var object = isArray ? [] : {}; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var name = readCStyleString(); + // Switch on the type + switch(elementType) { + case BSON.BSON_DATA_OID: + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + break; + case BSON.BSON_DATA_STRING: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_INT: + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + break; + case BSON.BSON_DATA_NUMBER: + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + break; + case BSON.BSON_DATA_DATE: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + break; + case BSON.BSON_DATA_BOOLEAN: + // Parse the boolean value + object[name] = buffer[index++] == 1; + break; + case BSON.BSON_DATA_UNDEFINED: + case BSON.BSON_DATA_NULL: + // Parse the boolean value + object[name] = null; + break; + case BSON.BSON_DATA_BINARY: + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + break; + case BSON.BSON_DATA_ARRAY: + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, true); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_OBJECT: + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_REGEXP: + // Create the regexp + var source = readCStyleString(); + var regExpOptions = readCStyleString(); + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + break; + case BSON.BSON_DATA_LONG: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + break; + case BSON.BSON_DATA_SYMBOL: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_TIMESTAMP: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + break; + case BSON.BSON_DATA_MIN_KEY: + // Parse the object + object[name] = new MinKey(); + break; + case BSON.BSON_DATA_MAX_KEY: + // Parse the object + object[name] = new MaxKey(); + break; + case BSON.BSON_DATA_CODE: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Function string + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_CODE_W_SCOPE: + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Javascript function + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + + // Add string to object + break; + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Check if key name is valid. + * + * @ignore + * @api private + */ +BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { + if (!key.length) return; + // Check if we have a legal key for the object + if (!!~key.indexOf("\x00")) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + if (!dollarsAndDotsOk) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return BSON.deserialize(data, options); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { + return BSON.calculateObjectSize(object, serializeFunctions); +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { + return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); +} + +/** + * @ignore + * @api private + */ +module.exports = BSON; +module.exports.Code = Code; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js new file mode 100644 index 0000000..f19e44f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js @@ -0,0 +1,429 @@ +/// reduced to ~ 410 LOCs (parser only 300 vs. 1400+) with (some, needed) BSON classes "inlined". +/// Compare ~ 4,300 (22KB vs. 157KB) in browser build at: https://github.com/mongodb/js-bson/blob/master/browser_build/bson.js + +module.exports.calculateObjectSize = calculateObjectSize; + +function calculateObjectSize(object) { + var totalLength = (4 + 1); /// handles the obj.length prefix + terminating '0' ?! + for(var key in object) { /// looks like it handles arrays under the same for...in loop!? + totalLength += calculateElement(key, object[key]) + } + return totalLength; +} + +function calculateElement(name, value) { + var len = 1; /// always starting with 1 for the data type byte! + if (name) len += Buffer.byteLength(name, 'utf8') + 1; /// cstring: name + '0' termination + + if (value === undefined || value === null) return len; /// just the type byte plus name cstring + switch( value.constructor ) { /// removed all checks 'isBuffer' if Node.js Buffer class is present!? + + case ObjectID: /// we want these sorted from most common case to least common/deprecated; + return len + 12; + case String: + return len + 4 + Buffer.byteLength(value, 'utf8') +1; /// + case Number: + if (Math.floor(value) === value) { /// case: integer; pos.# more common, '&&' stops if 1st fails! + if ( value <= 2147483647 && value >= -2147483647 ) // 32 bit + return len + 4; + else return len + 8; /// covers Long-ish JS integers as Longs! + } else return len + 8; /// 8+1 --- covers Double & std. float + case Boolean: + return len + 1; + + case Array: + case Object: + return len + calculateObjectSize(value); + + case Buffer: /// replaces the entire Binary class! + return len + 4 + value.length + 1; + + case Regex: /// these are handled as strings by serializeFast() later, hence 'gim' opts = 3 + 1 chars + return len + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) +1; + case Date: + case Long: + case Timestamp: + case Double: + return len + 8; + + case MinKey: + case MaxKey: + return len; /// these two return the type byte and name cstring only! + } + return 0; +} + +module.exports.serializeFast = serializeFast; +module.exports.serialize = function(object, checkKeys, asBuffer, serializeFunctions, index) { + var buffer = new Buffer(calculateObjectSize(object)); + return serializeFast(object, checkKeys, buffer, 0); +} + +function serializeFast(object, checkKeys, buffer, i) { /// set checkKeys = false in query(..., options object to save performance IFF you're certain your keys are safe/system-set! + var size = buffer.length; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; /// these get overwritten later! + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + if (object.constructor === Array) { /// any need to checkKeys here?!? since we're doing for rather than for...in, should be safe from extra (non-numeric) keys added to the array?! + for(var j = 0; j < object.length; j++) { + i = packElement(j.toString(), object[j], checkKeys, buffer, i); + } + } else { /// checkKeys is needed if any suspicion of end-user key tampering/"injection" (a la SQL) + for(var key in object) { /// mostly there should never be direct access to them!? + if (checkKeys && (key.indexOf('\x00') >= 0 || key === '$where') ) { /// = "no script"?!; could add back key.indexOf('$') or maybe check for 'eval'?! +/// took out: || key.indexOf('.') >= 0... Don't we allow dot notation queries?! + console.log('checkKeys error: '); + return new Error('Illegal object key!'); + } + i = packElement(key, object[key], checkKeys, buffer, i); /// checkKeys pass needed for recursion! + } + } + buffer[i++] = 0; /// write terminating zero; !we do NOT -1 the index increase here as original does! + return i; +} + +function packElement(name, value, checkKeys, buffer, i) { /// serializeFunctions removed! checkKeys needed for Array & Object cases pass through (calling serializeFast recursively!) + if (value === undefined || value === null){ + buffer[i++] = 10; /// = BSON.BSON_DATA_NULL; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; /// buffer.write(...) returns bytesWritten! + return i; + } + switch(value.constructor) { + + case ObjectID: + buffer[i++] = 7; /// = BSON.BSON_DATA_OID; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// i += buffer.write(value.id, i, 'binary'); /// OLD: writes a String to a Buffer; 'binary' deprecated!! + value.id.copy(buffer, i); /// NEW ObjectID version has this.id = Buffer at the ready! + return i += 12; + + case String: + buffer[i++] = 2; /// = BSON.BSON_DATA_STRING; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + + var size = Buffer.byteLength(value) + 1; /// includes the terminating '0'!? + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + i += buffer.write(value, i, 'utf8'); buffer[i++] = 0; + return i; + + case Number: + if ( ~~(value) === value) { /// double-Tilde is equiv. to Math.floor(value) + if ( value <= 2147483647 && value >= -2147483647){ /// = BSON.BSON_INT32_MAX / MIN asf. + buffer[i++] = 16; /// = BSON.BSON_DATA_INT; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + buffer[i++] = value & 0xff; buffer[i++] = (value >> 8) & 0xff; + buffer[i++] = (value >> 16) & 0xff; buffer[i++] = (value >> 24) & 0xff; + +// Else large-ish JS int!? to Long!? + } else { /// if (value <= BSON.JS_INT_MAX && value >= BSON.JS_INT_MIN){ /// 9007199254740992 asf. + buffer[i++] = 18; /// = BSON.BSON_DATA_LONG; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var lowBits = ( value % 4294967296 ) | 0, highBits = ( value / 4294967296 ) | 0; + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + } + } else { /// we have a float / Double + buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); + buffer.writeDoubleLE(value, i); i += 8; + } + return i; + + case Boolean: + buffer[i++] = 8; /// = BSON.BSON_DATA_BOOLEAN; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + buffer[i++] = value ? 1 : 0; + return i; + + case Array: + case Object: + buffer[i++] = value.constructor === Array ? 4 : 3; /// = BSON.BSON_DATA_ARRAY / _OBJECT; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + + var endIndex = serializeFast(value, checkKeys, buffer, i); /// + 4); no longer needed b/c serializeFast writes a temp 4 bytes for length + var size = endIndex - i; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + return endIndex; + + /// case Binary: /// is basically identical unless special/deprecated options! + case Buffer: /// solves ALL of our Binary needs without the BSON.Binary class!? + buffer[i++] = 5; /// = BSON.BSON_DATA_BINARY; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var size = value.length; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + buffer[i++] = 0; /// write BSON.BSON_BINARY_SUBTYPE_DEFAULT; + value.copy(buffer, i); ///, 0, size); << defaults to sourceStart=0, sourceEnd=sourceBuffer.length); + i += size; + return i; + + case RegExp: + buffer[i++] = 11; /// = BSON.BSON_DATA_REGEXP; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + i += buffer.write(value.source, i, 'utf8'); buffer[i++] = 0x00; + + if (value.global) buffer[i++] = 0x73; // s = 'g' for JS Regex! + if (value.ignoreCase) buffer[i++] = 0x69; // i + if (value.multiline) buffer[i++] = 0x6d; // m + buffer[i++] = 0x00; + return i; + + case Date: + buffer[i++] = 9; /// = BSON.BSON_DATA_DATE; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var millis = value.getTime(); + var lowBits = ( millis % 4294967296 ) | 0, highBits = ( millis / 4294967296 ) | 0; + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + return i; + + case Long: + case Timestamp: + buffer[i++] = value.constructor === Long ? 18 : 17; /// = BSON.BSON_DATA_LONG / _TIMESTAMP + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var lowBits = value.getLowBits(), highBits = value.getHighBits(); + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + return i; + + case Double: + buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); i += 8; + buffer.writeDoubleLE(value, i); i += 8; + return i + + case MinKey: /// = BSON.BSON_DATA_MINKEY; + buffer[i++] = 127; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + return i; + case MaxKey: /// = BSON.BSON_DATA_MAXKEY; + buffer[i++] = 255; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + return i; + + } /// end of switch + return i; /// ?! If no value to serialize +} + + +module.exports.deserializeFast = deserializeFast; + +function deserializeFast(buffer, i, isArray){ //// , options, isArray) { //// no more options! + if (buffer.length < 5) return new Error('Corrupt bson message < 5 bytes long'); /// from 'throw' + var elementType, tempindex = 0, name; + var string, low, high; /// = lowBits / highBits + /// using 'i' as the index to keep the lines shorter: + i || ( i = 0 ); /// for parseResponse it's 0; set to running index in deserialize(object/array) recursion + var object = isArray ? [] : {}; /// needed for type ARRAY recursion later! + var size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + if(size < 5 || size > buffer.length) return new Error('Corrupt BSON message'); +/// 'size' var was not used by anything after this, so we can reuse it + + while(true) { // While we have more left data left keep parsing + elementType = buffer[i++]; // Read the type + if (elementType === 0) break; // If we get a zero it's the last byte, exit + + tempindex = i; /// inlined readCStyleString & removed extra i= buffer.length) return new Error('Corrupt BSON document: illegal CString') + name = buffer.toString('utf8', i, tempindex); + i = tempindex + 1; /// Update index position to after the string + '0' termination + + switch(elementType) { + + case 7: /// = BSON.BSON_DATA_OID: + var buf = new Buffer(12); + buffer.copy(buf, 0, i, i += 12 ); /// copy 12 bytes from the current 'i' offset into fresh Buffer + object[name] = new ObjectID(buf); ///... & attach to the new ObjectID instance + break; + + case 2: /// = BSON.BSON_DATA_STRING: + size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; + object[name] = buffer.toString('utf8', i, i += size -1 ); + i++; break; /// need to get the '0' index "tick-forward" back! + + case 16: /// = BSON.BSON_DATA_INT: // Decode the 32bit value + object[name] = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; break; + + case 1: /// = BSON.BSON_DATA_NUMBER: // Decode the double value + object[name] = buffer.readDoubleLE(i); /// slightly faster depending on dec.points; a LOT cleaner + /// OLD: object[name] = readIEEE754(buffer, i, 'little', 52, 8); + i += 8; break; + + case 8: /// = BSON.BSON_DATA_BOOLEAN: + object[name] = buffer[i++] == 1; break; + + case 6: /// = BSON.BSON_DATA_UNDEFINED: /// deprecated + case 10: /// = BSON.BSON_DATA_NULL: + object[name] = null; break; + + case 4: /// = BSON.BSON_DATA_ARRAY + size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; /// NO 'i' increment since the size bytes are reread during the recursion! + object[name] = deserializeFast(buffer, i, true ); /// pass current index & set isArray = true + i += size; break; + case 3: /// = BSON.BSON_DATA_OBJECT: + size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; + object[name] = deserializeFast(buffer, i, false ); /// isArray = false => Object + i += size; break; + + case 5: /// = BSON.BSON_DATA_BINARY: // Decode the size of the binary blob + size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + buffer[i++]; /// Skip, as we assume always default subtype, i.e. 0! + object[name] = buffer.slice(i, i += size); /// creates a new Buffer "slice" view of the same memory! + break; + + case 9: /// = BSON.BSON_DATA_DATE: /// SEE notes below on the Date type vs. other options... + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + object[name] = new Date( high * 4294967296 + (low < 0 ? low + 4294967296 : low) ); break; + + case 18: /// = BSON.BSON_DATA_LONG: /// usage should be somewhat rare beyond parseResponse() -> cursorId, where it is handled inline, NOT as part of deserializeFast(returnedObjects); get lowBits, highBits: + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + + size = high * 4294967296 + (low < 0 ? low + 4294967296 : low); /// from long.toNumber() + if (size < JS_INT_MAX && size > JS_INT_MIN) object[name] = size; /// positive # more likely! + else object[name] = new Long(low, high); break; + + case 127: /// = BSON.BSON_DATA_MIN_KEY: /// do we EVER actually get these BACK from MongoDB server?! + object[name] = new MinKey(); break; + case 255: /// = BSON.BSON_DATA_MAX_KEY: + object[name] = new MaxKey(); break; + + case 17: /// = BSON.BSON_DATA_TIMESTAMP: /// somewhat obscure internal BSON type; MongoDB uses it for (pseudo) high-res time timestamp (past millisecs precision is just a counter!) in the Oplog ts: field, etc. + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + object[name] = new Timestamp(low, high); break; + +/// case 11: /// = RegExp is skipped; we should NEVER be getting any from the MongoDB server!? + } /// end of switch(elementType) + } /// end of while(1) + return object; // Return the finalized object +} + + +function MinKey() { this._bsontype = 'MinKey'; } /// these are merely placeholders/stubs to signify the type!? + +function MaxKey() { this._bsontype = 'MaxKey'; } + +function Long(low, high) { + this._bsontype = 'Long'; + this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. +} +Long.prototype.getLowBits = function(){ return this.low_; } +Long.prototype.getHighBits = function(){ return this.high_; } + +Long.prototype.toNumber = function(){ + return this.high_ * 4294967296 + (this.low_ < 0 ? this.low_ + 4294967296 : this.low_); +} +Long.fromNumber = function(num){ + return new Long(num % 4294967296, num / 4294967296); /// |0 is forced in the constructor! +} +function Double(value) { + this._bsontype = 'Double'; + this.value = value; +} +function Timestamp(low, high) { + this._bsontype = 'Timestamp'; + this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. +} +Timestamp.prototype.getLowBits = function(){ return this.low_; } +Timestamp.prototype.getHighBits = function(){ return this.high_; } + +/////////////////////////////// ObjectID ///////////////////////////////// +/// machine & proc IDs stored as 1 string, b/c Buffer shouldn't be held for long periods (could use SlowBuffer?!) + +var MACHINE = parseInt(Math.random() * 0xFFFFFF, 10); +var PROCESS = process.pid % 0xFFFF; +var MACHINE_AND_PROC = encodeIntBE(MACHINE, 3) + encodeIntBE(PROCESS, 2); /// keep as ONE string, ready to go. + +function encodeIntBE(data, bytes){ /// encode the bytes to a string + var result = ''; + if (bytes >= 4){ result += String.fromCharCode(Math.floor(data / 0x1000000)); data %= 0x1000000; } + if (bytes >= 3){ result += String.fromCharCode(Math.floor(data / 0x10000)); data %= 0x10000; } + if (bytes >= 2){ result += String.fromCharCode(Math.floor(data / 0x100)); data %= 0x100; } + result += String.fromCharCode(Math.floor(data)); + return result; +} +var _counter = ~~(Math.random() * 0xFFFFFF); /// double-tilde is equivalent to Math.floor() +var checkForHex = new RegExp('^[0-9a-fA-F]{24}$'); + +function ObjectID(id) { + this._bsontype = 'ObjectID'; + if (!id){ this.id = createFromScratch(); /// base case, DONE. + } else { + if (id.constructor === Buffer){ + this.id = id; /// case of + } else if (id.constructor === String) { + if ( id.length === 24 && checkForHex.test(id) ) { + this.id = new Buffer(id, 'hex'); + } else { + this.id = new Error('Illegal/faulty Hexadecimal string supplied!'); /// changed from 'throw' + } + } else if (id.constructor === Number) { + this.id = createFromTime(id); /// this is what should be the only interface for this!? + } + } +} +function createFromScratch() { + var buf = new Buffer(12), i = 0; + var ts = ~~(Date.now()/1000); /// 4 bytes timestamp in seconds, BigEndian notation! + buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; + buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; + + buf.write(MACHINE_AND_PROC, i, 5, 'utf8'); i += 5; /// write 3 bytes + 2 bytes MACHINE_ID and PROCESS_ID + _counter = ++_counter % 0xFFFFFF; /// 3 bytes internal _counter for subsecond resolution; BigEndian + buf[i++] = (_counter >> 16) & 0xFF; + buf[i++] = (_counter >> 8) & 0xFF; + buf[i++] = (_counter) & 0xFF; + return buf; +} +function createFromTime(ts) { + ts || ( ts = ~~(Date.now()/1000) ); /// 4 bytes timestamp in seconds only + var buf = new Buffer(12), i = 0; + buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; + buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; + + for (;i < 12; ++i) buf[i] = 0x00; /// indeces 4 through 11 (8 bytes) get filled up with nulls + return buf; +} +ObjectID.prototype.toHexString = function toHexString() { + return this.id.toString('hex'); +} +ObjectID.prototype.getTimestamp = function getTimestamp() { + return this.id.readUIntBE(0, 4); +} +ObjectID.prototype.getTimestampDate = function getTimestampDate() { + var ts = new Date(); + ts.setTime(this.id.readUIntBE(0, 4) * 1000); + return ts; +} +ObjectID.createPk = function createPk () { ///?override if a PrivateKey factory w/ unique factors is warranted?! + return new ObjectID(); +} +ObjectID.prototype.toJSON = function toJSON() { + return "ObjectID('" +this.id.toString('hex')+ "')"; +} + +/// module.exports.BSON = BSON; /// not needed anymore!? exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.Long = Long; /// ?! we really don't want to do the complicated Long math anywhere for now!? + +//module.exports.Double = Double; +//module.exports.Timestamp = Timestamp; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js new file mode 100644 index 0000000..8e942dd --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js @@ -0,0 +1,4843 @@ +var bson = (function(){ + + var pkgmap = {}, + global = {}, + nativeRequire = typeof require != 'undefined' && require, + lib, ties, main, async; + + function exports(){ return main(); }; + + exports.main = exports; + exports.module = module; + exports.packages = pkgmap; + exports.pkg = pkg; + exports.require = function require(uri){ + return pkgmap.main.index.require(uri); + }; + + + ties = {}; + + aliases = {}; + + + return exports; + +function join() { + return normalize(Array.prototype.join.call(arguments, "/")); +}; + +function normalize(path) { + var ret = [], parts = path.split('/'), cur, prev; + + var i = 0, l = parts.length-1; + for (; i <= l; i++) { + cur = parts[i]; + + if (cur === "." && prev !== undefined) continue; + + if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { + ret.pop(); + prev = ret.slice(-1)[0]; + } else { + if (prev === ".") ret.pop(); + ret.push(cur); + prev = cur; + } + } + + return ret.join("/"); +}; + +function dirname(path) { + return path && path.substr(0, path.lastIndexOf("/")) || "."; +}; + +function findModule(workingModule, uri){ + var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), + moduleIndexId = join(moduleId, 'index'), + pkg = workingModule.pkg, + module; + + var i = pkg.modules.length, + id; + + while(i-->0){ + id = pkg.modules[i].id; + + if(id==moduleId || id == moduleIndexId){ + module = pkg.modules[i]; + break; + } + } + + return module; +} + +function newRequire(callingModule){ + function require(uri){ + var module, pkg; + + if(/^\./.test(uri)){ + module = findModule(callingModule, uri); + } else if ( ties && ties.hasOwnProperty( uri ) ) { + return ties[uri]; + } else if ( aliases && aliases.hasOwnProperty( uri ) ) { + return require(aliases[uri]); + } else { + pkg = pkgmap[uri]; + + if(!pkg && nativeRequire){ + try { + pkg = nativeRequire(uri); + } catch (nativeRequireError) {} + + if(pkg) return pkg; + } + + if(!pkg){ + throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); + } + + module = pkg.index; + } + + if(!module){ + throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); + } + + module.parent = callingModule; + return module.call(); + }; + + + return require; +} + + +function module(parent, id, wrapper){ + var mod = { pkg: parent, id: id, wrapper: wrapper }, + cached = false; + + mod.exports = {}; + mod.require = newRequire(mod); + + mod.call = function(){ + if(cached) { + return mod.exports; + } + + cached = true; + + global.require = mod.require; + + mod.wrapper(mod, mod.exports, global, global.require); + return mod.exports; + }; + + if(parent.mainModuleId == mod.id){ + parent.index = mod; + parent.parents.length === 0 && ( main = mod.call ); + } + + parent.modules.push(mod); +} + +function pkg(/* [ parentId ...], wrapper */){ + var wrapper = arguments[ arguments.length - 1 ], + parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), + ctx = wrapper(parents); + + + pkgmap[ctx.name] = ctx; + + arguments.length == 1 && ( pkgmap.main = ctx ); + + return function(modules){ + var id; + for(id in modules){ + module(ctx, id, modules[id]); + } + }; +} + + +}(this)); + +bson.pkg(function(parents){ + + return { + 'name' : 'bson', + 'mainModuleId' : 'bson', + 'modules' : [], + 'parents' : parents + }; + +})({ 'binary': function(module, exports, global, require, undefined){ + /** + * Module dependencies. + */ +if(typeof window === 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +// Binary default subtype +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + * @api private + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for(var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +} + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + * @api private + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class Represents the Binary BSON type. + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Grid} + */ +function Binary(buffer, subType) { + if(!(this instanceof Binary)) return new Binary(buffer, subType); + + this._bsontype = 'Binary'; + + if(buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if(buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if(typeof buffer == 'string') { + // Different ways of writing the length of the string for the different types + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(buffer); + } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error("only String, Buffer, Uint8Array or Array accepted"); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if(typeof Uint8Array != 'undefined'){ + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +}; + +/** + * Updates this binary with byte_value. + * + * @param {Character} byte_value a single byte we wish to write. + * @api public + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); + if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); + + // Decode the byte value once + var decoded_byte = null; + if(typeof byte_value == 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if(byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if(this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + var buffer = null; + // Create a new buffer (typed or normal array) + if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for(var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. + * @param {Number} offset specify the binary of where to write the content. + * @api public + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset == 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if(this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) + // Copy the content + for(var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length + } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, 'binary', offset); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length; + } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' + || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if(typeof string == 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @param {Number} position read from the given position in the Binary. + * @param {Number} length the number of bytes to read. + * @return {Buffer} + * @api public + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 + ? length + : this.position; + + // Let's return the data based on the type we have + if(this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for(var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @return {String} + * @api public + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // If it's a node.js buffer object + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if(asRaw) { + // we support the slice command use it + if(this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for(var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @return {Number} the length of the binary. + * @api public + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + * @api private + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +} + +/** + * @ignore + * @api private + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +} + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +exports.Binary = Binary; + + +}, + + + +'binary_parser': function(module, exports, global, require, undefined){ + /** + * Binary Parser. + * Jonas Raoni Soares Silva + * http://jsfromhell.com/classes/binary-parser [v1.0] + */ +var chr = String.fromCharCode; + +var maxBits = []; +for (var i = 0; i < 64; i++) { + maxBits[i] = Math.pow(2, i); +} + +function BinaryParser (bigEndian, allowExceptions) { + if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); + + this.bigEndian = bigEndian; + this.allowExceptions = allowExceptions; +}; + +BinaryParser.warn = function warn (msg) { + if (this.allowExceptions) { + throw new Error(msg); + } + + return 1; +}; + +BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { + var b = new this.Buffer(this.bigEndian, data); + + b.checkBuffer(precisionBits + exponentBits + 1); + + var bias = maxBits[exponentBits - 1] - 1 + , signal = b.readBits(precisionBits + exponentBits, 1) + , exponent = b.readBits(precisionBits, exponentBits) + , significand = 0 + , divisor = 2 + , curByte = b.buffer.length + (-precisionBits >> 3) - 1; + + do { + for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); + } while (precisionBits -= startBit); + + return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); +}; + +BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { + var b = new this.Buffer(this.bigEndian || forceBigEndian, data) + , x = b.readBits(0, bits) + , max = maxBits[bits]; //max = Math.pow( 2, bits ); + + return signed && x >= max / 2 + ? x - max + : x; +}; + +BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { + var bias = maxBits[exponentBits - 1] - 1 + , minExp = -bias + 1 + , maxExp = bias + , minUnnormExp = minExp - precisionBits + , n = parseFloat(data) + , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 + , exp = 0 + , len = 2 * bias + 1 + precisionBits + 3 + , bin = new Array(len) + , signal = (n = status !== 0 ? 0 : n) < 0 + , intPart = Math.floor(n = Math.abs(n)) + , floatPart = n - intPart + , lastBit + , rounded + , result + , i + , j; + + for (i = len; i; bin[--i] = 0); + + for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); + + for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); + + for (i = -1; ++i < len && !bin[i];); + + if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { + if (!(rounded = bin[lastBit])) { + for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); + } + + for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); + } + + for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); + + if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { + ++i; + } else if (exp < minExp) { + exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); + i = bias + 1 - (exp = minExp - 1); + } + + if (intPart || status !== 0) { + this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); + exp = maxExp + 1; + i = bias + 2; + + if (status == -Infinity) { + signal = 1; + } else if (isNaN(status)) { + bin[i] = 1; + } + } + + for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); + + for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { + n += (1 << j) * result.charAt(--i); + if (j == 7) { + r[r.length] = String.fromCharCode(n); + n = 0; + } + } + + r[r.length] = n + ? String.fromCharCode(n) + : ""; + + return (this.bigEndian ? r.reverse() : r).join(""); +}; + +BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { + var max = maxBits[bits]; + + if (data >= max || data < -(max / 2)) { + this.warn("encodeInt::overflow"); + data = 0; + } + + if (data < 0) { + data += max; + } + + for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); + + for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); + + return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); +}; + +BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; +BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; +BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; +BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; +BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; +BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; +BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; +BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; +BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; +BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; +BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; +BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; +BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; +BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; +BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; +BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; + +// Factor out the encode so it can be shared by add_header and push_int32 +BinaryParser.encode_int32 = function encode_int32 (number, asArray) { + var a, b, c, d, unsigned; + unsigned = (number < 0) ? (number + 0x100000000) : number; + a = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + b = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + c = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + d = Math.floor(unsigned); + return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); +}; + +BinaryParser.encode_int64 = function encode_int64 (number) { + var a, b, c, d, e, f, g, h, unsigned; + unsigned = (number < 0) ? (number + 0x10000000000000000) : number; + a = Math.floor(unsigned / 0xffffffffffffff); + unsigned &= 0xffffffffffffff; + b = Math.floor(unsigned / 0xffffffffffff); + unsigned &= 0xffffffffffff; + c = Math.floor(unsigned / 0xffffffffff); + unsigned &= 0xffffffffff; + d = Math.floor(unsigned / 0xffffffff); + unsigned &= 0xffffffff; + e = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + f = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + g = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + h = Math.floor(unsigned); + return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); +}; + +/** + * UTF8 methods + */ + +// Take a raw binary string and return a utf8 string +BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { + var len = binaryStr.length + , decoded = '' + , i = 0 + , c = 0 + , c1 = 0 + , c2 = 0 + , c3; + + while (i < len) { + c = binaryStr.charCodeAt(i); + if (c < 128) { + decoded += String.fromCharCode(c); + i++; + } else if ((c > 191) && (c < 224)) { + c2 = binaryStr.charCodeAt(i+1); + decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = binaryStr.charCodeAt(i+1); + c3 = binaryStr.charCodeAt(i+2); + decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; + } + } + + return decoded; +}; + +// Encode a cstring +BinaryParser.encode_cstring = function encode_cstring (s) { + return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); +}; + +// Take a utf8 string and return a binary string +BinaryParser.encode_utf8 = function encode_utf8 (s) { + var a = "" + , c; + + for (var n = 0, len = s.length; n < len; n++) { + c = s.charCodeAt(n); + + if (c < 128) { + a += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + a += String.fromCharCode((c>>6) | 192) ; + a += String.fromCharCode((c&63) | 128); + } else { + a += String.fromCharCode((c>>12) | 224); + a += String.fromCharCode(((c>>6) & 63) | 128); + a += String.fromCharCode((c&63) | 128); + } + } + + return a; +}; + +BinaryParser.hprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } + } + + process.stdout.write("\n\n"); +}; + +BinaryParser.ilprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +BinaryParser.hlprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +/** + * BinaryParser buffer constructor. + */ +function BinaryParserBuffer (bigEndian, buffer) { + this.bigEndian = bigEndian || 0; + this.buffer = []; + this.setBuffer(buffer); +}; + +BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { + var l, i, b; + + if (data) { + i = l = data.length; + b = this.buffer = new Array(l); + for (; i; b[l - i] = data.charCodeAt(--i)); + this.bigEndian && b.reverse(); + } +}; + +BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { + return this.buffer.length >= -(-neededBits >> 3); +}; + +BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { + if (!this.hasNeededBits(neededBits)) { + throw new Error("checkBuffer::missing bytes"); + } +}; + +BinaryParserBuffer.prototype.readBits = function readBits (start, length) { + //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) + + function shl (a, b) { + for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); + return a; + } + + if (start < 0 || length <= 0) { + return 0; + } + + this.checkBuffer(start + length); + + var offsetLeft + , offsetRight = start % 8 + , curByte = this.buffer.length - ( start >> 3 ) - 1 + , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) + , diff = curByte - lastByte + , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); + + for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); + + return sum; +}; + +/** + * Expose. + */ +BinaryParser.Buffer = BinaryParserBuffer; + +exports.BinaryParser = BinaryParser; + +}, + + + +'bson': function(module, exports, global, require, undefined){ + var Long = require('./long').Long + , Double = require('./double').Double + , Timestamp = require('./timestamp').Timestamp + , ObjectID = require('./objectid').ObjectID + , Symbol = require('./symbol').Symbol + , Code = require('./code').Code + , MinKey = require('./min_key').MinKey + , MaxKey = require('./max_key').MaxKey + , DBRef = require('./db_ref').DBRef + , Binary = require('./binary').Binary + , BinaryParser = require('./binary_parser').BinaryParser + , writeIEEE754 = require('./float_parser').writeIEEE754 + , readIEEE754 = require('./float_parser').readIEEE754 + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * Create a new BSON instance + * + * @class Represents the BSON Parser + * @return {BSON} instance of BSON Parser. + */ +function BSON () {}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions) { + var isBuffer = typeof Buffer !== 'undefined'; + + switch(typeof value) { + case 'string': + return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + case 'undefined': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + case 'boolean': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else if(serializeFunctions) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; + } + } + } + + return 0; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { + // Default setting false + serializeFunctions = serializeFunctions == null ? false : serializeFunctions; + // Write end information (length of the object) + var size = buffer.length; + // Write the size of the object + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; +} + +/** + * @ignore + * @api private + */ +var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { + // Process the object + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Serialize the object + for(var key in object) { + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + // dollars and dots ok + BSON.checkKey(key, !checkKeys); + } + + // Pack the element + index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); + } + } + + // Write zero + buffer[index++] = 0; + return index; +} + +var stringToBytes = function(str) { + var ch, st, re = []; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re.concat( st.reverse() ); + } + // return an array of bytes + return re; +} + +var numberOfBytes = function(str) { + var ch, st, re = 0; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re + st.length; + } + // return an array of bytes + return re; +} + +/** + * @ignore + * @api private + */ +var writeToTypedArray = function(buffer, string, index) { + var bytes = stringToBytes(string); + for(var i = 0; i < bytes.length; i++) { + buffer[index + i] = bytes[i]; + } + return bytes.length; +} + +/** + * @ignore + * @api private + */ +var supportsBuffer = typeof Buffer != 'undefined'; + +/** + * @ignore + * @api private + */ +var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { + var startIndex = index; + + switch(typeof value) { + case 'string': + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; + // Write the size of the string to buffer + buffer[index + 3] = (size >> 24) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index] = size & 0xff; + // Ajust the index + index = index + 4; + // Write the string + supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + // Return index + return index; + case 'number': + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + case 'undefined': + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + case 'boolean': + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + case 'object': + if(value === null || value instanceof MinKey || value instanceof MaxKey + || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write objectid + supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); + // Ajust index + index = index + 12; + return index; + } else if(value instanceof Date || isDate(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + // Write the type + buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(value instanceof Double || value['_bsontype'] == 'Double') { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.code.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize + 4; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.code.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); + // Ajust index + index = index + value.position; + return index; + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(value.value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + // Message size + var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); + // Serialize the object + var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write zero for object + buffer[endIndex++] = 0x00; + // Return the end index + return endIndex; + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Adjust the index + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); + // Write size + var size = endIndex - index; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return endIndex; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + buffer.write(value.source, index, 'utf8'); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = new Buffer(scopeSize); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize - 4; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + scopeObjectBuffer.copy(buffer, index, 0, scopeSize); + + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else if(serializeFunctions) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } + } + + // If no value to serialize + return index; +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + // Throw error if we are trying serialize an illegal type + if(object == null || typeof object != 'object' || Array.isArray(object)) + throw new Error("Only javascript objects supported"); + + // Emoty target buffer + var buffer = null; + // Calculate the size of the object + var size = BSON.calculateObjectSize(object, serializeFunctions); + // Fetch the best available type for storing the binary data + if(buffer = typeof Buffer != 'undefined') { + buffer = new Buffer(size); + asBuffer = true; + } else if(typeof Uint8Array != 'undefined') { + buffer = new Uint8Array(new ArrayBuffer(size)); + } else { + buffer = new Array(size); + } + + // If asBuffer is false use typed arrays + BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); + return buffer; +} + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Crc state variables shared by function + * + * @ignore + * @api private + */ +var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + +/** + * CRC32 hash method, Fast and enough versitility for our usage + * + * @ignore + * @api private + */ +var crc32 = function(string, start, end) { + var crc = 0 + var x = 0; + var y = 0; + crc = crc ^ (-1); + + for(var i = start, iTop = end; i < iTop;i++) { + y = (crc ^ string[i]) & 0xFF; + x = table[y]; + crc = (crc >>> 8) ^ x; + } + + return crc ^ (-1); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = BSON.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +/** + * Convert Uint8Array to String + * + * @ignore + * @api private + */ +var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { + return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); +} + +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + + return result; +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.deserialize = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] || true; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + // Reads in a C style string + var readCStyleString = function() { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00) { i++ } + // Grab utf8 encoded string + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); + // Update index position + index = i + 1; + // Return string + return string; + } + + // Create holding object + var object = isArray ? [] : {}; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var name = readCStyleString(); + // Switch on the type + switch(elementType) { + case BSON.BSON_DATA_OID: + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + break; + case BSON.BSON_DATA_STRING: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_INT: + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + break; + case BSON.BSON_DATA_NUMBER: + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + break; + case BSON.BSON_DATA_DATE: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + break; + case BSON.BSON_DATA_BOOLEAN: + // Parse the boolean value + object[name] = buffer[index++] == 1; + break; + case BSON.BSON_DATA_NULL: + // Parse the boolean value + object[name] = null; + break; + case BSON.BSON_DATA_BINARY: + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + break; + case BSON.BSON_DATA_ARRAY: + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, true); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_OBJECT: + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_REGEXP: + // Create the regexp + var source = readCStyleString(); + var regExpOptions = readCStyleString(); + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + break; + case BSON.BSON_DATA_LONG: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + break; + case BSON.BSON_DATA_SYMBOL: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_TIMESTAMP: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + break; + case BSON.BSON_DATA_MIN_KEY: + // Parse the object + object[name] = new MinKey(); + break; + case BSON.BSON_DATA_MAX_KEY: + // Parse the object + object[name] = new MaxKey(); + break; + case BSON.BSON_DATA_CODE: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Function string + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_CODE_W_SCOPE: + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Javascript function + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + + // Add string to object + break; + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Check if key name is valid. + * + * @ignore + * @api private + */ +BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { + if (!key.length) return; + // Check if we have a legal key for the object + if (!!~key.indexOf("\x00")) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + if (!dollarsAndDotsOk) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return BSON.deserialize(data, options); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { + return BSON.calculateObjectSize(object, serializeFunctions); +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { + return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); +} + +/** + * @ignore + * @api private + */ +exports.Code = Code; +exports.Symbol = Symbol; +exports.BSON = BSON; +exports.DBRef = DBRef; +exports.Binary = Binary; +exports.ObjectID = ObjectID; +exports.Long = Long; +exports.Timestamp = Timestamp; +exports.Double = Double; +exports.MinKey = MinKey; +exports.MaxKey = MaxKey; + +}, + + + +'code': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON Code type. + * + * @class Represents the BSON Code type. + * @param {String|Function} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +function Code(code, scope) { + if(!(this instanceof Code)) return new Code(code, scope); + + this._bsontype = 'Code'; + this.code = code; + this.scope = scope == null ? {} : scope; +}; + +/** + * @ignore + * @api private + */ +Code.prototype.toJSON = function() { + return {scope:this.scope, code:this.code}; +} + +exports.Code = Code; +}, + + + +'db_ref': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON DBRef type. + * + * @class Represents the BSON DBRef type. + * @param {String} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {String} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +}; + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + '$ref':this.namespace, + '$id':this.oid, + '$db':this.db == null ? '' : this.db + }; +} + +exports.DBRef = DBRef; +}, + + + +'double': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON Double type. + * + * @class Represents the BSON Double type. + * @param {Number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if(!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @return {Number} returns the wrapped double number. + * @api public + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + * @api private + */ +Double.prototype.toJSON = function() { + return this.value; +} + +exports.Double = Double; +}, + + + +'float_parser': function(module, exports, global, require, undefined){ + // Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, m, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : (nBytes - 1), + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, m, c, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = bBE ? (nBytes-1) : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e+eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754; +}, + + + +'index': function(module, exports, global, require, undefined){ + try { + exports.BSONPure = require('./bson'); + exports.BSONNative = require('../../ext'); +} catch(err) { + // do nothing +} + +[ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + exports[i] = module[i]; + } +}); + +// Exports all the classes for the NATIVE JS BSON Parser +exports.native = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long' + , '../../ext' +].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + // Return classes list + return classes; +} + +// Exports all the classes for the PURE JS BSON Parser +exports.pure = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long' + , '././bson'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + // Return classes list + return classes; +} + +}, + + + +'long': function(module, exports, global, require, undefined){ + // 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class Represents the BSON Long type. + * @param {Number} low the low (signed) 32 bits of the Long. + * @param {Number} high the high (signed) 32 bits of the Long. + */ +function Long(low, high) { + if(!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @api private + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @api private + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {Number} the value, assuming it is a 32-bit integer. + * @api public + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @return {Number} the closest floating-point representation to this value. + * @api public + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @return {String} the JSON representation. + * @api public + */ +Long.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @param {Number} [opt_radix] the radix in which the text should be written. + * @return {String} the textual representation of this value. + * @api public + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @return {Number} the high 32-bits as a signed value. + * @api public + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @return {Number} the low 32-bits as a signed value. + * @api public + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @return {Number} the low 32-bits as an unsigned value. + * @api public + */ +Long.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. + * @api public + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @return {Boolean} whether this value is zero. + * @api public + */ +Long.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @return {Boolean} whether this value is negative. + * @api public + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @return {Boolean} whether this value is odd. + * @api public + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Long equals the other + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long equals the other + * @api public + */ +Long.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Long does not equal the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long does not equal the other. + * @api public + */ +Long.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Long is less than the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is less than the other. + * @api public + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is less than or equal to the other. + * @api public + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is greater than the other. + * @api public + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is greater than or equal to the other. + * @api public + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @param {Long} other Long to compare against. + * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + * @api public + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @return {Long} the negation of this value. + * @api public + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + * @api public + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + * @api public + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + * @api public + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && + other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + * @api public + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || + other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + * @api public + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @return {Long} the bitwise-NOT of this value. + * @api public + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + * @api public + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + * @api public + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + * @api public + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + * @api public + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + * @api public + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Long.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + * @api public + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @param {Number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @param {Number} value the number in question. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long( + (value % Long.TWO_PWR_32_DBL_) | 0, + (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @param {Number} lowBits the low 32-bits. + * @param {Number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @param {String} str the textual representation of the Long. + * @param {Number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @api private + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @api private + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = + Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @api private + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +exports.Long = Long; +}, + + + +'max_key': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON MaxKey type. + * + * @class Represents the BSON MaxKey type. + * @return {MaxKey} + */ +function MaxKey() { + if(!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +exports.MaxKey = MaxKey; +}, + + + +'min_key': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON MinKey type. + * + * @class Represents the BSON MinKey type. + * @return {MinKey} + */ +function MinKey() { + if(!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +exports.MinKey = MinKey; +}, + + + +'objectid': function(module, exports, global, require, undefined){ + /** + * Module dependencies. + */ +var BinaryParser = require('./binary_parser').BinaryParser; + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + */ +var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); + +/** +* Create a new ObjectID instance +* +* @class Represents the BSON ObjectID type +* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @return {Object} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id, _hex) { + if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); + + this._bsontype = 'ObjectID'; + var __id = null; + + // Throw an error if it's not a valid setup + if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + // Generate id based on the input + if(id == null || typeof id == 'number') { + // convert to 12 byte binary string + this.id = this.generate(id); + } else if(id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if(checkForHexRegExp.test(id)) { + return ObjectID.createFromHexString(id); + } else { + throw new Error("Value passed in is not a valid 24 character hex string"); + } + + if(ObjectID.cacheHexString) this.__id = this.toHexString(); +}; + +// Allow usage of ObjectId as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @return {String} return the 24 byte hex string representation. +* @api public +*/ +ObjectID.prototype.toHexString = function() { + if(ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @return {Number} returns next index value. +* @api private +*/ +ObjectID.prototype.get_inc = function() { + return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @return {Number} returns next index value. +* @api private +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id string used in ObjectID's +* +* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {String} return the 12 byte id binary string. +* @api private +*/ +ObjectID.prototype.generate = function(time) { + if ('number' == typeof time) { + var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); + /* for time-based ObjectID the bytes following the time will be zeroed */ + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + } else { + var unixTime = parseInt(Date.now()/1000,10); + var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + } + + return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @return {String} return the 24 byte hex string representation. +* @api private +*/ +ObjectID.prototype.toString = function() { + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @api private +*/ +ObjectID.prototype.inspect = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @api private +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @param {Object} otherID ObjectID instance to compare against. +* @return {Bool} the result of comparing two ObjectID's +* @api public +*/ +ObjectID.prototype.equals = function equals (otherID) { + var id = (otherID instanceof ObjectID || otherID.toHexString) + ? otherID.id + : ObjectID.createFromHexString(otherID).id; + + return this.id === id; +} + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @return {Date} the generation date +* @api public +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); + return timestamp; +} + +/** +* @ignore +* @api private +*/ +ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); + +ObjectID.createPk = function createPk () { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @param {Number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +* @api public +*/ +ObjectID.createFromTime = function createFromTime (time) { + var id = BinaryParser.encodeInt(time, 32, true, true) + + BinaryParser.encodeInt(0, 64, true, true); + return new ObjectID(id); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +* @api public +*/ +ObjectID.createFromHexString = function createFromHexString (hexString) { + // Throw an error if it's not a valid setup + if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + var len = hexString.length; + + if(len > 12*2) { + throw new Error('Id cannot be longer than 12 bytes'); + } + + var result = '' + , string + , number; + + for (var index = 0; index < len; index += 2) { + string = hexString.substr(index, 2); + number = parseInt(string, 16); + result += BinaryParser.fromByte(number); + } + + return new ObjectID(result, hexString); +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, "generationTime", { + enumerable: true + , get: function () { + return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); + } + , set: function (value) { + var value = BinaryParser.encodeInt(value, 32, true, true); + this.id = value + this.id.substr(4); + // delete this.__id; + this.toHexString(); + } +}); + +/** + * Expose. + */ +exports.ObjectID = ObjectID; +exports.ObjectId = ObjectID; + +}, + + + +'symbol': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON Symbol type. + * + * @class Represents the BSON Symbol type. + * @param {String} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if(!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @return {String} returns the wrapped string. + * @api public + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + * @api private + */ +Symbol.prototype.toString = function() { + return this.value; +} + +/** + * @ignore + * @api private + */ +Symbol.prototype.inspect = function() { + return this.value; +} + +/** + * @ignore + * @api private + */ +Symbol.prototype.toJSON = function() { + return this.value; +} + +exports.Symbol = Symbol; +}, + + + +'timestamp': function(module, exports, global, require, undefined){ + // 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class Represents the BSON Timestamp type. + * @param {Number} low the low (signed) 32 bits of the Timestamp. + * @param {Number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if(!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @api private + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @api private + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {Number} the value, assuming it is a 32-bit integer. + * @api public + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @return {Number} the closest floating-point representation to this value. + * @api public + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @return {String} the JSON representation. + * @api public + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @param {Number} [opt_radix] the radix in which the text should be written. + * @return {String} the textual representation of this value. + * @api public + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @return {Number} the high 32-bits as a signed value. + * @api public + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @return {Number} the low 32-bits as a signed value. + * @api public + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @return {Number} the low 32-bits as an unsigned value. + * @api public + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. + * @api public + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @return {Boolean} whether this value is zero. + * @api public + */ +Timestamp.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @return {Boolean} whether this value is negative. + * @api public + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @return {Boolean} whether this value is odd. + * @api public + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp equals the other + * @api public + */ +Timestamp.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp does not equal the other. + * @api public + */ +Timestamp.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is less than the other. + * @api public + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is less than or equal to the other. + * @api public + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is greater than the other. + * @api public + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is greater than or equal to the other. + * @api public + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + * @api public + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @return {Timestamp} the negation of this value. + * @api public + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + * @api public + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + * @api public + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + * @api public + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && + other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + * @api public + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || + other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + * @api public + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @return {Timestamp} the bitwise-NOT of this value. + * @api public + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + * @api public + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + * @api public + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + * @api public + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + * @api public + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + * @api public + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Timestamp.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + * @api public + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @param {Number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @param {Number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @param {Number} lowBits the low 32-bits. + * @param {Number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @param {String} str the textual representation of the Timestamp. + * @param {Number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @api private + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = + Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @api private + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +exports.Timestamp = Timestamp; +}, + + }); + + +if(typeof module != 'undefined' && module.exports ){ + module.exports = bson; + + if( !module.parent ){ + bson(); + } +} + +if(typeof window != 'undefined' && typeof require == 'undefined'){ + window.require = bson.require; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json new file mode 100644 index 0000000..3ebb587 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json @@ -0,0 +1,8 @@ +{ "name" : "bson" +, "description" : "A bson parser for node.js and the browser" +, "main": "../lib/bson/bson" +, "directories" : { "lib" : "../lib/bson" } +, "engines" : { "node" : ">=0.6.0" } +, "licenses" : [ { "type" : "Apache License, Version 2.0" + , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js new file mode 100644 index 0000000..ef74b16 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,344 @@ +/** + * Module dependencies. + * @ignore + */ +if(typeof window === 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +function Binary(buffer, subType) { + if(!(this instanceof Binary)) return new Binary(buffer, subType); + + this._bsontype = 'Binary'; + + if(buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if(buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if(typeof buffer == 'string') { + // Different ways of writing the length of the string for the different types + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(buffer); + } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error("only String, Buffer, Uint8Array or Array accepted"); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if(typeof Uint8Array != 'undefined'){ + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +}; + +/** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); + if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); + + // Decode the byte value once + var decoded_byte = null; + if(typeof byte_value == 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if(byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if(this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + var buffer = null; + // Create a new buffer (typed or normal array) + if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for(var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset == 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if(this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) + // Copy the content + for(var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length + } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, offset, 'binary'); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length; + } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' + || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if(typeof string == 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 + ? length + : this.position; + + // Let's return the data based on the type we have + if(this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for(var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) + return this.buffer; + + // If it's a node.js buffer object + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if(asRaw) { + // we support the slice command use it + if(this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for(var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +} + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +} + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for(var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +} + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +module.exports = Binary; +module.exports.Binary = Binary; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js new file mode 100644 index 0000000..d2fc811 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js @@ -0,0 +1,385 @@ +/** + * Binary Parser. + * Jonas Raoni Soares Silva + * http://jsfromhell.com/classes/binary-parser [v1.0] + */ +var chr = String.fromCharCode; + +var maxBits = []; +for (var i = 0; i < 64; i++) { + maxBits[i] = Math.pow(2, i); +} + +function BinaryParser (bigEndian, allowExceptions) { + if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); + + this.bigEndian = bigEndian; + this.allowExceptions = allowExceptions; +}; + +BinaryParser.warn = function warn (msg) { + if (this.allowExceptions) { + throw new Error(msg); + } + + return 1; +}; + +BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { + var b = new this.Buffer(this.bigEndian, data); + + b.checkBuffer(precisionBits + exponentBits + 1); + + var bias = maxBits[exponentBits - 1] - 1 + , signal = b.readBits(precisionBits + exponentBits, 1) + , exponent = b.readBits(precisionBits, exponentBits) + , significand = 0 + , divisor = 2 + , curByte = b.buffer.length + (-precisionBits >> 3) - 1; + + do { + for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); + } while (precisionBits -= startBit); + + return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); +}; + +BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { + var b = new this.Buffer(this.bigEndian || forceBigEndian, data) + , x = b.readBits(0, bits) + , max = maxBits[bits]; //max = Math.pow( 2, bits ); + + return signed && x >= max / 2 + ? x - max + : x; +}; + +BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { + var bias = maxBits[exponentBits - 1] - 1 + , minExp = -bias + 1 + , maxExp = bias + , minUnnormExp = minExp - precisionBits + , n = parseFloat(data) + , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 + , exp = 0 + , len = 2 * bias + 1 + precisionBits + 3 + , bin = new Array(len) + , signal = (n = status !== 0 ? 0 : n) < 0 + , intPart = Math.floor(n = Math.abs(n)) + , floatPart = n - intPart + , lastBit + , rounded + , result + , i + , j; + + for (i = len; i; bin[--i] = 0); + + for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); + + for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); + + for (i = -1; ++i < len && !bin[i];); + + if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { + if (!(rounded = bin[lastBit])) { + for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); + } + + for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); + } + + for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); + + if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { + ++i; + } else if (exp < minExp) { + exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); + i = bias + 1 - (exp = minExp - 1); + } + + if (intPart || status !== 0) { + this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); + exp = maxExp + 1; + i = bias + 2; + + if (status == -Infinity) { + signal = 1; + } else if (isNaN(status)) { + bin[i] = 1; + } + } + + for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); + + for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { + n += (1 << j) * result.charAt(--i); + if (j == 7) { + r[r.length] = String.fromCharCode(n); + n = 0; + } + } + + r[r.length] = n + ? String.fromCharCode(n) + : ""; + + return (this.bigEndian ? r.reverse() : r).join(""); +}; + +BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { + var max = maxBits[bits]; + + if (data >= max || data < -(max / 2)) { + this.warn("encodeInt::overflow"); + data = 0; + } + + if (data < 0) { + data += max; + } + + for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); + + for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); + + return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); +}; + +BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; +BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; +BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; +BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; +BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; +BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; +BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; +BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; +BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; +BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; +BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; +BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; +BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; +BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; +BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; +BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; + +// Factor out the encode so it can be shared by add_header and push_int32 +BinaryParser.encode_int32 = function encode_int32 (number, asArray) { + var a, b, c, d, unsigned; + unsigned = (number < 0) ? (number + 0x100000000) : number; + a = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + b = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + c = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + d = Math.floor(unsigned); + return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); +}; + +BinaryParser.encode_int64 = function encode_int64 (number) { + var a, b, c, d, e, f, g, h, unsigned; + unsigned = (number < 0) ? (number + 0x10000000000000000) : number; + a = Math.floor(unsigned / 0xffffffffffffff); + unsigned &= 0xffffffffffffff; + b = Math.floor(unsigned / 0xffffffffffff); + unsigned &= 0xffffffffffff; + c = Math.floor(unsigned / 0xffffffffff); + unsigned &= 0xffffffffff; + d = Math.floor(unsigned / 0xffffffff); + unsigned &= 0xffffffff; + e = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + f = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + g = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + h = Math.floor(unsigned); + return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); +}; + +/** + * UTF8 methods + */ + +// Take a raw binary string and return a utf8 string +BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { + var len = binaryStr.length + , decoded = '' + , i = 0 + , c = 0 + , c1 = 0 + , c2 = 0 + , c3; + + while (i < len) { + c = binaryStr.charCodeAt(i); + if (c < 128) { + decoded += String.fromCharCode(c); + i++; + } else if ((c > 191) && (c < 224)) { + c2 = binaryStr.charCodeAt(i+1); + decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = binaryStr.charCodeAt(i+1); + c3 = binaryStr.charCodeAt(i+2); + decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; + } + } + + return decoded; +}; + +// Encode a cstring +BinaryParser.encode_cstring = function encode_cstring (s) { + return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); +}; + +// Take a utf8 string and return a binary string +BinaryParser.encode_utf8 = function encode_utf8 (s) { + var a = "" + , c; + + for (var n = 0, len = s.length; n < len; n++) { + c = s.charCodeAt(n); + + if (c < 128) { + a += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + a += String.fromCharCode((c>>6) | 192) ; + a += String.fromCharCode((c&63) | 128); + } else { + a += String.fromCharCode((c>>12) | 224); + a += String.fromCharCode(((c>>6) & 63) | 128); + a += String.fromCharCode((c&63) | 128); + } + } + + return a; +}; + +BinaryParser.hprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } + } + + process.stdout.write("\n\n"); +}; + +BinaryParser.ilprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +BinaryParser.hlprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +/** + * BinaryParser buffer constructor. + */ +function BinaryParserBuffer (bigEndian, buffer) { + this.bigEndian = bigEndian || 0; + this.buffer = []; + this.setBuffer(buffer); +}; + +BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { + var l, i, b; + + if (data) { + i = l = data.length; + b = this.buffer = new Array(l); + for (; i; b[l - i] = data.charCodeAt(--i)); + this.bigEndian && b.reverse(); + } +}; + +BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { + return this.buffer.length >= -(-neededBits >> 3); +}; + +BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { + if (!this.hasNeededBits(neededBits)) { + throw new Error("checkBuffer::missing bytes"); + } +}; + +BinaryParserBuffer.prototype.readBits = function readBits (start, length) { + //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) + + function shl (a, b) { + for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); + return a; + } + + if (start < 0 || length <= 0) { + return 0; + } + + this.checkBuffer(start + length); + + var offsetLeft + , offsetRight = start % 8 + , curByte = this.buffer.length - ( start >> 3 ) - 1 + , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) + , diff = curByte - lastByte + , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); + + for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); + + return sum; +}; + +/** + * Expose. + */ +BinaryParser.Buffer = BinaryParserBuffer; + +exports.BinaryParser = BinaryParser; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js new file mode 100644 index 0000000..36f0057 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,323 @@ +// "use strict" + +var writeIEEE754 = require('./float_parser').writeIEEE754, + readIEEE754 = require('./float_parser').readIEEE754, + Map = require('./map'), + Long = require('./long').Long, + Double = require('./double').Double, + Timestamp = require('./timestamp').Timestamp, + ObjectID = require('./objectid').ObjectID, + BSONRegExp = require('./regexp').BSONRegExp, + Symbol = require('./symbol').Symbol, + Code = require('./code').Code, + MinKey = require('./min_key').MinKey, + MaxKey = require('./max_key').MaxKey, + DBRef = require('./db_ref').DBRef, + Binary = require('./binary').Binary; + +// Parts of the parser +var deserialize = require('./parser/deserializer'), + serializer = require('./parser/serializer'), + calculateObjectSize = require('./parser/calculate_size'); + +/** + * @ignore + * @api private + */ +// Max Size +var MAXSIZE = (1024*1024*17); +// Max Document Buffer size +var buffer = new Buffer(MAXSIZE); + +var BSON = function() { +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function serialize(object, checkKeys, asBuffer, serializeFunctions, index, ignoreUndefined) { + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, index || 0, 0, serializeFunctions, ignoreUndefined); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, finalBuffer, startIndex, serializeFunctions, ignoreUndefined) { + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; +} + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return deserialize(data, options); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions, ignoreUndefined) { + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// Return BSON +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js new file mode 100644 index 0000000..83a42c9 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var Code = function Code(code, scope) { + if(!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope == null ? {} : scope; +}; + +/** + * @ignore + */ +Code.prototype.toJSON = function() { + return {scope:this.scope, code:this.code}; +} + +module.exports = Code; +module.exports.Code = Code; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 0000000..06789a6 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +}; + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + '$ref':this.namespace, + '$id':this.oid, + '$db':this.db == null ? '' : this.db + }; +} + +module.exports = DBRef; +module.exports.DBRef = DBRef; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js new file mode 100644 index 0000000..09ed222 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if(!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +} + +module.exports = Double; +module.exports.Double = Double; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 0000000..6fca392 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js @@ -0,0 +1,121 @@ +// Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, m, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : (nBytes - 1), + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, m, c, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = bBE ? (nBytes-1) : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e+eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js new file mode 100644 index 0000000..f4147b2 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js @@ -0,0 +1,86 @@ +try { + exports.BSONPure = require('./bson'); + exports.BSONNative = require('bson-ext'); +} catch(err) { +} + +[ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './symbol' + , './timestamp' + , './long'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + exports[i] = module[i]; + } +}); + +// Exports all the classes for the PURE JS BSON Parser +exports.pure = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './symbol' + , './timestamp' + , './long' + , '././bson'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + // Return classes list + return classes; +} + +// Exports all the classes for the NATIVE JS BSON Parser +exports.native = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './symbol' + , './timestamp' + , './long' + ].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + + // Catch error and return no classes found + try { + classes['BSON'] = require('bson-ext') + } catch(err) { + return exports.pure(); + } + + // Return classes list + return classes; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js new file mode 100644 index 0000000..6f18885 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js @@ -0,0 +1,856 @@ +// 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if(!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Long.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && + other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || + other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Long.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long( + (value % Long.TWO_PWR_32_DBL_) | 0, + (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ +Long.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = + Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js new file mode 100644 index 0000000..f53c8c1 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js @@ -0,0 +1,126 @@ +"use strict" + +// We have an ES6 Map available, return the native instance +if(typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for(var i = 0; i < array.length; i++) { + if(array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + } + } + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + } + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if(value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + } + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for(var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + } + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + } + + Map.prototype.has = function(key) { + return this._values[key] != null; + } + + Map.prototype.keys = function(key) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.set = function(key, value) { + if(this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + return this; + } + + Map.prototype.values = function(key, value) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable:true, + get: function() { return this._keys.length; } + }); + + module.exports = Map; + module.exports.Map = Map; +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 0000000..03ee9cd --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if(!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 0000000..5e120fb --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if(!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 0000000..3ddcb14 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,273 @@ +/** + * Module dependencies. + * @ignore + */ +var BinaryParser = require('./binary_parser').BinaryParser; + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ +var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); + +/** +* Create a new ObjectID instance +* +* @class +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + if(!(this instanceof ObjectID)) return new ObjectID(id); + if((id instanceof ObjectID)) return id; + + this._bsontype = 'ObjectID'; + var __id = null; + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if(!valid && id != null){ + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } else if(valid && typeof id == 'string' && id.length == 24) { + return ObjectID.createFromHexString(id); + } else if(id == null || typeof id == 'number') { + // convert to 12 byte binary string + this.id = this.generate(id); + } else if(id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } + + if(ObjectID.cacheHexString) this.__id = this.toHexString(); +}; + +// Allow usage of ObjectId as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if(ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.get_inc = function() { + return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id string used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {string} return the 12 byte id binary string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' != typeof time) { + time = parseInt(Date.now()/1000,10); + } + + var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); + /* for time-based ObjectID the bytes following the time will be zeroed */ + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid % 0xFFFF); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + + return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toString = function() { + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.inspect = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals (otherID) { + if(otherID == null) return false; + var id = (otherID instanceof ObjectID || otherID.toHexString) + ? otherID.id + : ObjectID.createFromHexString(otherID).id; + + return this.id === id; +} + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); + return timestamp; +} + +/** +* @ignore +*/ +ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); + +/** +* @ignore +*/ +ObjectID.createPk = function createPk () { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromTime = function createFromTime (time) { + var id = BinaryParser.encodeInt(time, 32, true, true) + + BinaryParser.encodeInt(0, 64, true, true); + return new ObjectID(id); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromHexString = function createFromHexString (hexString) { + // Throw an error if it's not a valid setup + if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + var len = hexString.length; + + if(len > 12*2) { + throw new Error('Id cannot be longer than 12 bytes'); + } + + var result = '' + , string + , number; + + for (var index = 0; index < len; index += 2) { + string = hexString.substr(index, 2); + number = parseInt(string, 16); + result += BinaryParser.fromByte(number); + } + + return new ObjectID(result, hexString); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if(id == null) return false; + + if(typeof id == 'number') + return true; + if(typeof id == 'string') { + return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id)); + } + return false; +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, "generationTime", { + enumerable: true + , get: function () { + return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); + } + , set: function (value) { + var value = BinaryParser.encodeInt(value, 32, true, true); + this.id = value + this.id.substr(4); + // delete this.__id; + this.toHexString(); + } +}); + +/** + * Expose. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js new file mode 100644 index 0000000..03513f3 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js @@ -0,0 +1,310 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754 + , readIEEE754 = require('../float_parser').readIEEE754 + , Long = require('../long').Long + , Double = require('../double').Double + , Timestamp = require('../timestamp').Timestamp + , ObjectID = require('../objectid').ObjectID + , Symbol = require('../symbol').Symbol + , BSONRegExp = require('../regexp').BSONRegExp + , Code = require('../code').Code + , MinKey = require('../min_key').MinKey + , MaxKey = require('../max_key').MaxKey + , DBRef = require('../db_ref').DBRef + , Binary = require('../binary').Binary; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + switch(typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + case 'undefined': + if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + return 0; + case 'boolean': + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + + Buffer.byteLength(value.options, 'utf8') + 1 + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if(serializeFunctions) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; + } + } + } + + return 0; +} + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = calculateObjectSize; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js new file mode 100644 index 0000000..5f1cc10 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js @@ -0,0 +1,544 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754, + readIEEE754 = require('../float_parser').readIEEE754, + f = require('util').format, + Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var deserialize = function(buffer, options, isArray) { + var index = 0; + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || buffer.length < size) { + throw new Error("corrupt bson message"); + } + + // Illegal end value + if(buffer[size - 1] != 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, options, isArray); +} + +// Reads in a C style string +var readCStyleStringSpecial = function(buffer, index) { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Grab utf8 encoded string + var string = buffer.toString('utf8', index, i); + // Update index position + index = i + 1; + // Return string + return {s: string, i: index}; +} + +var deserializeObject = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? {} : options['fieldsAsRaw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // Create holding object + var object = isArray ? [] : {}; + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var r = readCStyleStringSpecial(buffer, index); + var name = r.s; + index = r.i; + + // Switch on the type + if(elementType == BSON.BSON_DATA_OID) { + var string = buffer.toString('binary', index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + } else if(elementType == BSON.BSON_DATA_STRING) { + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Validate if string Size is larger than the actual provided buffer + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Add string to object + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_INT) { + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if(elementType == BSON.BSON_DATA_NUMBER) { + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + } else if(elementType == BSON.BSON_DATA_DATE) { + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if(elementType == BSON.BSON_DATA_BOOLEAN) { + // Parse the boolean value + object[name] = buffer[index++] == 1; + } else if(elementType == BSON.BSON_DATA_UNDEFINED || elementType == BSON.BSON_DATA_NULL) { + // Parse the boolean value + object[name] = null; + } else if(elementType == BSON.BSON_DATA_BINARY) { + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + } else if(elementType == BSON.BSON_DATA_ARRAY) { + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // All elements of array to be returned as raw bson + if(fieldsAsRaw[name]) { + arrayOptions = {}; + for(var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + // Set the array to the object + object[name] = deserializeObject(buffer, arrayOptions, true); + // Adjust the index + index = index + objectSize; + } else if(elementType == BSON.BSON_DATA_OBJECT) { + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Validate if string Size is larger than the actual provided buffer + if(objectSize <= 0 || objectSize > (buffer.length - index)) throw new Error("bad embedded document length in bson"); + + // We have a raw value + if(options['raw']) { + // Set the array to the object + object[name] = buffer.slice(index, index + objectSize); + } else { + // Set the array to the object + object[name] = deserializeObject(buffer, options, false); + } + + // Adjust the index + index = index + objectSize; + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { + // Create the regexp + var r = readCStyleStringSpecial(buffer, index); + var source = r.s; + index = r.i; + + var r = readCStyleStringSpecial(buffer, index); + var regExpOptions = r.s; + index = r.i; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { + // Create the regexp + var r = readCStyleStringSpecial(buffer, index); + var source = r.s; + index = r.i; + + var r = readCStyleStringSpecial(buffer, index); + var regExpOptions = r.s; + index = r.i; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if(elementType == BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + } else if(elementType == BSON.BSON_DATA_SYMBOL) { + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Validate if string Size is larger than the actual provided buffer + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_TIMESTAMP) { + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + } else if(elementType == BSON.BSON_DATA_MIN_KEY) { + // Parse the object + object[name] = new MinKey(); + } else if(elementType == BSON.BSON_DATA_MAX_KEY) { + // Parse the object + object[name] = new MaxKey(); + } else if(elementType == BSON.BSON_DATA_CODE) { + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Validate if string Size is larger than the actual provided buffer + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Function string + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_CODE_W_SCOPE) { + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Validate if string Size is larger than the actual provided buffer + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Javascript function + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = deserializeObject(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = deserialize diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js new file mode 100644 index 0000000..285e45b --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js @@ -0,0 +1,909 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754, + readIEEE754 = require('../float_parser').readIEEE754, + Long = require('../long').Long, + Map = require('../map'), + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + BSONRegExp = require('../regexp').BSONRegExp, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + Binary = require('../binary').Binary; + +var regexp = /\x00/ + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} + +var serializeString = function(buffer, key, value, index) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = (size + 1 >> 24) & 0xff; + buffer[index + 2] = (size + 1 >> 16) & 0xff; + buffer[index + 1] = (size + 1 >> 8) & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeNumber = function(buffer, key, value, index) { + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; +} + +var serializeUndefined = function(buffer, key, value, index) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +var serializeBoolean = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} + +var serializeDate = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +var serializeRegExp = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +var serializeBSONRegExp = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options, index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +var serializeMinMax = function(buffer, key, value, index) { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +var serializeObjectId = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + buffer.write(value.id, index, 'binary') + + // Ajust index + return index + 12; +} + +var serializeBuffer = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; +} + +var serializeObject = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + // Write size + var size = endIndex - index; + return endIndex; +} + +var serializeLong = function(buffer, key, value, index) { + // Write the type + buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +var serializeDouble = function(buffer, key, value, index) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; +} + +var serializeFunction = function(buffer, key, value, index, checkKeys, depth) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeCode = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined) + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +} + +var serializeBinary = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; +} + +var serializeSymbol = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if(null != value.db) { + endIndex = serializeInto(buffer, { + '$ref': value.namespace + , '$id' : value.oid + , '$db' : value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + '$ref': value.namespace + , '$id' : value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} + +var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined) { + startingIndex = startingIndex || 0; + + // Start place to serialize into + var index = startingIndex + 4; + var self = this; + + // Special case isArray + if(Array.isArray(object)) { + // Get object keys + for(var i = 0; i < object.length; i++) { + var key = "" + i; + var value = object[i]; + + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + var type = typeof value; + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(type == 'undefined' || value == null) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else if(object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while(!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if(done) continue; + + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + + if (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + // console.log("---------------------------------------------------") + // console.dir("key = " + key) + // console.dir("value = " + value) + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if(object.toBSON) { + if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); + object = object.toBSON(); + if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); + } + + // Iterate over all the keys + for(var key in object) { + var value = object[key]; + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + + if (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = serializeInto; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js new file mode 100644 index 0000000..6b148b2 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js @@ -0,0 +1,30 @@ +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if(!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern; + this.options = options; + + // Validate options + for(var i = 0; i < options.length; i++) { + if(!(this.options[i] == 'i' + || this.options[i] == 'm' + || this.options[i] == 'x' + || this.options[i] == 'l' + || this.options[i] == 's' + || this.options[i] == 'u' + )) { + throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 0000000..7681a4d --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,47 @@ +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if(!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.inspect = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +} + +module.exports = Symbol; +module.exports.Symbol = Symbol; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 0000000..7718caf --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,856 @@ +// 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if(!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && + other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || + other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Timestamp.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = + Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json new file mode 100644 index 0000000..1eb5b0a --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json @@ -0,0 +1,70 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "version": "0.4.16", + "author": { + "name": "Christian Amor Kvalheim", + "email": "christkv@gmail.com" + }, + "contributors": [], + "repository": { + "type": "git", + "url": "git://github.com/mongodb/js-bson.git" + }, + "bugs": { + "url": "https://github.com/mongodb/js-bson/issues" + }, + "devDependencies": { + "nodeunit": "0.9.0", + "gleak": "0.2.3", + "one": "2.X.X", + "benchmark": "1.0.0", + "colors": "1.1.0" + }, + "config": { + "native": false + }, + "main": "./lib/bson/index", + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "scripts": { + "test": "nodeunit ./test/node" + }, + "browser": "lib/bson/bson.js", + "license": "Apache-2.0", + "gitHead": "4166146d0539a050946c1cae9188f274dd751ed9", + "homepage": "https://github.com/mongodb/js-bson", + "_id": "bson@0.4.16", + "_shasum": "e78fb993535123851f857fb83c7f68b1cd7e6caa", + "_from": "bson@>=0.4.0 <0.5.0", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "octave", + "email": "chinsay@gmail.com" + }, + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "e78fb993535123851f857fb83c7f68b1cd7e6caa", + "tarball": "http://registry.npmjs.org/bson/-/bson-0.4.16.tgz" + }, + "_resolved": "https://registry.npmjs.org/bson/-/bson-0.4.16.tgz" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js new file mode 100644 index 0000000..c707cfc --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js @@ -0,0 +1,21 @@ + +var gleak = require('gleak')(); +gleak.ignore('AssertionError'); +gleak.ignore('testFullSpec_param_found'); +gleak.ignore('events'); +gleak.ignore('Uint8Array'); +gleak.ignore('Uint8ClampedArray'); +gleak.ignore('TAP_Global_Harness'); +gleak.ignore('setImmediate'); +gleak.ignore('clearImmediate'); + +gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); +gleak.ignore('DTRACE_NET_STREAM_END'); +gleak.ignore('DTRACE_NET_SOCKET_READ'); +gleak.ignore('DTRACE_NET_SOCKET_WRITE'); +gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); +gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); +gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); +gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); + +module.exports = gleak; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml new file mode 100644 index 0000000..b0fb9f4 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml @@ -0,0 +1,20 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.12" + - "iojs-v1.8.4" + - "iojs-v2.5.0" + - "iojs-v3.3.0" + - "4" +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-4.8 +before_install: + - '[ "${TRAVIS_NODE_VERSION}" != "0.8" ] || npm install -g npm@1.4.28' + - if [[ $TRAVIS_OS_NAME == "linux" ]]; then export CXX=g++-4.8; fi + - $CXX --version + - npm explore npm -g -- npm install node-gyp@latest \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md new file mode 100644 index 0000000..7428b0d --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md @@ -0,0 +1,4 @@ +kerberos +======== + +Kerberos library for node.js \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp new file mode 100644 index 0000000..6655299 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp @@ -0,0 +1,46 @@ +{ + 'targets': [ + { + 'target_name': 'kerberos', + 'cflags!': [ '-fno-exceptions' ], + 'cflags_cc!': [ '-fno-exceptions' ], + 'include_dirs': [ '> $(depfile) +# Add extra rules as in (2). +# We remove slashes and replace spaces with new lines; +# remove blank lines; +# delete the first line and append a colon to the remaining lines. +sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ + grep -v '^$$' |\ + sed -e 1d -e 's|$$|:|' \ + >> $(depfile) +rm $(depfile).raw +endef + +# Command definitions: +# - cmd_foo is the actual command to run; +# - quiet_cmd_foo is the brief-output summary of the command. + +quiet_cmd_cc = CC($(TOOLSET)) $@ +cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_cxx = CXX($(TOOLSET)) $@ +cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_touch = TOUCH $@ +cmd_touch = touch $@ + +quiet_cmd_copy = COPY $@ +# send stderr to /dev/null to ignore messages when linking directories. +cmd_copy = rm -rf "$@" && cp -af "$<" "$@" + +quiet_cmd_alink = AR($(TOOLSET)) $@ +cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) + +quiet_cmd_alink_thin = AR($(TOOLSET)) $@ +cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) + +# Due to circular dependencies between libraries :(, we wrap the +# special "figure out circular dependencies" flags around the entire +# input list during linking. +quiet_cmd_link = LINK($(TOOLSET)) $@ +cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) + +# We support two kinds of shared objects (.so): +# 1) shared_library, which is just bundling together many dependent libraries +# into a link line. +# 2) loadable_module, which is generating a module intended for dlopen(). +# +# They differ only slightly: +# In the former case, we want to package all dependent code into the .so. +# In the latter case, we want to package just the API exposed by the +# outermost module. +# This means shared_library uses --whole-archive, while loadable_module doesn't. +# (Note that --whole-archive is incompatible with the --start-group used in +# normal linking.) + +# Other shared-object link notes: +# - Set SONAME to the library filename so our binaries don't reference +# the local, absolute paths used on the link command-line. +quiet_cmd_solink = SOLINK($(TOOLSET)) $@ +cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) + +quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) + + +# Define an escape_quotes function to escape single quotes. +# This allows us to handle quotes properly as long as we always use +# use single quotes and escape_quotes. +escape_quotes = $(subst ','\'',$(1)) +# This comment is here just to include a ' to unconfuse syntax highlighting. +# Define an escape_vars function to escape '$' variable syntax. +# This allows us to read/write command lines with shell variables (e.g. +# $LD_LIBRARY_PATH), without triggering make substitution. +escape_vars = $(subst $$,$$$$,$(1)) +# Helper that expands to a shell command to echo a string exactly as it is in +# make. This uses printf instead of echo because printf's behaviour with respect +# to escape sequences is more portable than echo's across different shells +# (e.g., dash, bash). +exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' + +# Helper to compare the command we're about to run against the command +# we logged the last time we ran the command. Produces an empty +# string (false) when the commands match. +# Tricky point: Make has no string-equality test function. +# The kernel uses the following, but it seems like it would have false +# positives, where one string reordered its arguments. +# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ +# $(filter-out $(cmd_$@), $(cmd_$(1)))) +# We instead substitute each for the empty string into the other, and +# say they're equal if both substitutions produce the empty string. +# .d files contain ? instead of spaces, take that into account. +command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ + $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) + +# Helper that is non-empty when a prerequisite changes. +# Normally make does this implicitly, but we force rules to always run +# so we can check their command lines. +# $? -- new prerequisites +# $| -- order-only dependencies +prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) + +# Helper that executes all postbuilds until one fails. +define do_postbuilds + @E=0;\ + for p in $(POSTBUILDS); do\ + eval $$p;\ + E=$$?;\ + if [ $$E -ne 0 ]; then\ + break;\ + fi;\ + done;\ + if [ $$E -ne 0 ]; then\ + rm -rf "$@";\ + exit $$E;\ + fi +endef + +# do_cmd: run a command via the above cmd_foo names, if necessary. +# Should always run for a given target to handle command-line changes. +# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. +# Third argument, if non-zero, makes it do POSTBUILDS processing. +# Note: We intentionally do NOT call dirx for depfile, since it contains ? for +# spaces already and dirx strips the ? characters. +define do_cmd +$(if $(or $(command_changed),$(prereq_changed)), + @$(call exact_echo, $($(quiet)cmd_$(1))) + @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" + $(if $(findstring flock,$(word 1,$(cmd_$1))), + @$(cmd_$(1)) + @echo " $(quiet_cmd_$(1)): Finished", + @$(cmd_$(1)) + ) + @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) + @$(if $(2),$(fixup_dep)) + $(if $(and $(3), $(POSTBUILDS)), + $(call do_postbuilds) + ) +) +endef + +# Declare the "all" target first so it is the default, +# even though we don't have the deps yet. +.PHONY: all +all: + +# make looks for ways to re-generate included makefiles, but in our case, we +# don't have a direct way. Explicitly telling make that it has nothing to do +# for them makes it go faster. +%.d: ; + +# Use FORCE_DO_CMD to force a target to run. Should be coupled with +# do_cmd. +.PHONY: FORCE_DO_CMD +FORCE_DO_CMD: + +TOOLSET := target +# Suffix rules, putting all outputs into $(obj). +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# Try building from generated source, too. +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + + +ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ + $(findstring $(join ^,$(prefix)),\ + $(join ^,kerberos.target.mk)))),) + include kerberos.target.mk +endif + +quiet_cmd_regen_makefile = ACTION Regenerating $@ +cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/fmason/hub/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/fmason/.node-gyp/0.12.7/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/fmason/.node-gyp/0.12.7" "-Dmodule_root_dir=/home/fmason/hub/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos" binding.gyp +Makefile: $(srcdir)/../../../../../../../../../.node-gyp/0.12.7/common.gypi $(srcdir)/../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp + $(call do_cmd,regen_makefile) + +# "all" is a concatenation of the "all" targets from all the included +# sub-makefiles. This is just here to clarify. +all: + +# Add in dependency-tracking rules. $(all_deps) is the list of every single +# target in our tree. Only consider the ones with .d (dependency) info: +d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) +ifneq ($(d_files),) + include $(d_files) +endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d new file mode 100644 index 0000000..0bc3206 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d @@ -0,0 +1 @@ +cmd_Release/kerberos.node := rm -rf "Release/kerberos.node" && cp -af "Release/obj.target/kerberos.node" "Release/kerberos.node" diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d new file mode 100644 index 0000000..2ec56f5 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d @@ -0,0 +1 @@ +cmd_Release/obj.target/kerberos.node := g++ -shared -pthread -rdynamic -m64 -Wl,-soname=kerberos.node -o Release/obj.target/kerberos.node -Wl,--start-group Release/obj.target/kerberos/lib/kerberos.o Release/obj.target/kerberos/lib/worker.o Release/obj.target/kerberos/lib/kerberosgss.o Release/obj.target/kerberos/lib/base64.o Release/obj.target/kerberos/lib/kerberos_context.o -Wl,--end-group -lkrb5 -lgssapi_krb5 diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d new file mode 100644 index 0000000..cfee5be --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d @@ -0,0 +1,4 @@ +cmd_Release/obj.target/kerberos/lib/base64.o := cc '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/base64.o.d.raw -c -o Release/obj.target/kerberos/lib/base64.o ../lib/base64.c +Release/obj.target/kerberos/lib/base64.o: ../lib/base64.c ../lib/base64.h +../lib/base64.c: +../lib/base64.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d new file mode 100644 index 0000000..a313cb5 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d @@ -0,0 +1,71 @@ +cmd_Release/obj.target/kerberos/lib/kerberos.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos.o ../lib/kerberos.cc +Release/obj.target/kerberos/lib/kerberos.o: ../lib/kerberos.cc \ + ../lib/kerberos.h /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /usr/include/mit-krb5/gssapi/gssapi.h \ + /usr/include/mit-krb5/gssapi/gssapi_generic.h \ + /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ + /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ + /usr/include/mit-krb5/krb5/krb5.h ../node_modules/nan/nan.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ + /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ + /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ + ../node_modules/nan/nan_callbacks.h \ + ../node_modules/nan/nan_callbacks_12_inl.h \ + ../node_modules/nan/nan_maybe_pre_43_inl.h \ + ../node_modules/nan/nan_converters.h \ + ../node_modules/nan/nan_converters_pre_43_inl.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h \ + ../node_modules/nan/nan_persistent_12_inl.h \ + ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h \ + ../lib/kerberosgss.h ../lib/worker.h ../lib/kerberos_context.h +../lib/kerberos.cc: +../lib/kerberos.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/usr/include/mit-krb5/gssapi/gssapi.h: +/usr/include/mit-krb5/gssapi/gssapi_generic.h: +/usr/include/mit-krb5/gssapi/gssapi_krb5.h: +/usr/include/mit-krb5/gssapi/gssapi_ext.h: +/usr/include/mit-krb5/krb5.h: +/usr/include/mit-krb5/krb5/krb5.h: +../node_modules/nan/nan.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: +/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/src/smalloc.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: +../node_modules/nan/nan_callbacks.h: +../node_modules/nan/nan_callbacks_12_inl.h: +../node_modules/nan/nan_maybe_pre_43_inl.h: +../node_modules/nan/nan_converters.h: +../node_modules/nan/nan_converters_pre_43_inl.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: +../node_modules/nan/nan_persistent_12_inl.h: +../node_modules/nan/nan_weak.h: +../node_modules/nan/nan_object_wrap.h: +../lib/kerberosgss.h: +../lib/worker.h: +../lib/kerberos_context.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d new file mode 100644 index 0000000..fcffab4 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d @@ -0,0 +1,70 @@ +cmd_Release/obj.target/kerberos/lib/kerberos_context.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos_context.o ../lib/kerberos_context.cc +Release/obj.target/kerberos/lib/kerberos_context.o: \ + ../lib/kerberos_context.cc ../lib/kerberos_context.h \ + /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /usr/include/mit-krb5/gssapi/gssapi.h \ + /usr/include/mit-krb5/gssapi/gssapi_generic.h \ + /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ + /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ + /usr/include/mit-krb5/krb5/krb5.h ../node_modules/nan/nan.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ + /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ + /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ + ../node_modules/nan/nan_callbacks.h \ + ../node_modules/nan/nan_callbacks_12_inl.h \ + ../node_modules/nan/nan_maybe_pre_43_inl.h \ + ../node_modules/nan/nan_converters.h \ + ../node_modules/nan/nan_converters_pre_43_inl.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h \ + ../node_modules/nan/nan_persistent_12_inl.h \ + ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h \ + ../lib/kerberosgss.h +../lib/kerberos_context.cc: +../lib/kerberos_context.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/usr/include/mit-krb5/gssapi/gssapi.h: +/usr/include/mit-krb5/gssapi/gssapi_generic.h: +/usr/include/mit-krb5/gssapi/gssapi_krb5.h: +/usr/include/mit-krb5/gssapi/gssapi_ext.h: +/usr/include/mit-krb5/krb5.h: +/usr/include/mit-krb5/krb5/krb5.h: +../node_modules/nan/nan.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: +/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/src/smalloc.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: +../node_modules/nan/nan_callbacks.h: +../node_modules/nan/nan_callbacks_12_inl.h: +../node_modules/nan/nan_maybe_pre_43_inl.h: +../node_modules/nan/nan_converters.h: +../node_modules/nan/nan_converters_pre_43_inl.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: +../node_modules/nan/nan_persistent_12_inl.h: +../node_modules/nan/nan_weak.h: +../node_modules/nan/nan_object_wrap.h: +../lib/kerberosgss.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d new file mode 100644 index 0000000..d4cefbf --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d @@ -0,0 +1,16 @@ +cmd_Release/obj.target/kerberos/lib/kerberosgss.o := cc '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberosgss.o ../lib/kerberosgss.c +Release/obj.target/kerberos/lib/kerberosgss.o: ../lib/kerberosgss.c \ + ../lib/kerberosgss.h /usr/include/mit-krb5/gssapi/gssapi.h \ + /usr/include/mit-krb5/gssapi/gssapi_generic.h \ + /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ + /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ + /usr/include/mit-krb5/krb5/krb5.h ../lib/base64.h +../lib/kerberosgss.c: +../lib/kerberosgss.h: +/usr/include/mit-krb5/gssapi/gssapi.h: +/usr/include/mit-krb5/gssapi/gssapi_generic.h: +/usr/include/mit-krb5/gssapi/gssapi_krb5.h: +/usr/include/mit-krb5/gssapi/gssapi_ext.h: +/usr/include/mit-krb5/krb5.h: +/usr/include/mit-krb5/krb5/krb5.h: +../lib/base64.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d new file mode 100644 index 0000000..02da394 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d @@ -0,0 +1,57 @@ +cmd_Release/obj.target/kerberos/lib/worker.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/worker.o.d.raw -c -o Release/obj.target/kerberos/lib/worker.o ../lib/worker.cc +Release/obj.target/kerberos/lib/worker.o: ../lib/worker.cc \ + ../lib/worker.h /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ + ../node_modules/nan/nan.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ + /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ + /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + ../node_modules/nan/nan_callbacks.h \ + ../node_modules/nan/nan_callbacks_12_inl.h \ + ../node_modules/nan/nan_maybe_pre_43_inl.h \ + ../node_modules/nan/nan_converters.h \ + ../node_modules/nan/nan_converters_pre_43_inl.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h \ + ../node_modules/nan/nan_persistent_12_inl.h \ + ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h +../lib/worker.cc: +../lib/worker.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: +../node_modules/nan/nan.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: +/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/src/smalloc.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +../node_modules/nan/nan_callbacks.h: +../node_modules/nan/nan_callbacks_12_inl.h: +../node_modules/nan/nan_maybe_pre_43_inl.h: +../node_modules/nan/nan_converters.h: +../node_modules/nan/nan_converters_pre_43_inl.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: +../node_modules/nan/nan_persistent_12_inl.h: +../node_modules/nan/nan_weak.h: +../node_modules/nan/nan_object_wrap.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node new file mode 100755 index 0000000000000000000000000000000000000000..2bcec8ec0121131fd8bf4a7bd02d25f4198f6fc3 GIT binary patch literal 85259 zcmeFad3=;b@;^R-fC0org$3~%6&3Ix0fGTU6T-km14IIX2ZoSLAQF<8OgKa|Y!YM~ zN8^33(bW}iyb(o%AVJpyT~}Ez@T7;hinwXJZiK~9=Me(vhjN{eyJC#w&!8p zTuG^}qg?}BgQmJy)+VK<4oFE{ol<)=N9xwiHPDqn+Mbv9Oz6`kA@%H(9&0lby5zXe zopV&r{rTATj-%APL=Q4eX`M1_U%gwdHTvwRu<+ujS=PPi%3cro`y#~M6 z;rDv{-iY6u@XMc@@p}t?Z^iE&_`MUqP5AvQe(%9Af9};6*L}FI!tebCegM~p%;!gN zebjvBWi@^u!|&txeGjk&JH^*Q{m!|%c8ZrPK0U)^UXZSvf7$LkrB zZt;$7$v$T8irc=vcIm#u-+JPK0T)iWzW<80w+?#Z9N(QKE0zyG;NzYD_~wAWFSu>^ zd0(#W+q3&gr@l7(vVXh!5Bu}7e{A*MKIxf%HXJ{9MR@*236-zBx#!u?w+Fm3_n|&1 zeLkPp`onF*XWh7R_YI4mS=m-GKPzYR!5=rCwPnwbzD2uQcJ=*uVgDgRavr&q za!%G>_dV&ot8N>9$Ii8V8^&~R+jzp<6}OzS^|;4g$GE3YT6)sn+lDuGJMyVzecyWG z$;T5*-uk@c&TP*=zj|x>mOXcLfBC}KXMA?=+Rv`Nr0}(mj%(A zto-S+eYXww{i*LWFCOyN6Cbwpo$;@WW*&CTZ6%ILjix$Yy21lzj*rD(d4S91tOdIz z1I~SrjWC~|KDcxISU7iQmdYIF5by#*y=9=&dumyp3en8GcTjal)`8RMg?;9u9$=o#~-V9RFl}+8O-=apqeRN6$yZ zi6^JW(evmy{=Y7c9+Kk3&((3}^=X_qd~FlB;6K9-5YsuAJD0yG&ieW*{Gqct;T;Iy8GaY^(3yT#K%Ymudbt{>YZskqJT)xy?d7U`K_mR| z8~!AL{vgoTZq)Gm`r`Tm>x<*eepw@qG5BSOKg7GHX~cMgFE-GL*d{6HgTmFOS%b2R<|$jzUR%=nE)&ese+!;F(+#u={3 zT_ePQdbyhZsu5orJau`HYk$}IuNs8841-@$o|GnyfP2f2!oSo*$`lP_S;@~bqlaBa z500MCmG$1s)oeD7>&?9OA>VO)*9E%2*NjtO_|_I{#5ab)56JJN-?BpE+su5=bnI*R zI{NfTJ>Sc<{Si&y!|;6=bsfj4yjJ6n(HGY|(ND*H*%avcK-VFz?TJSTCCKFGEa>?t zoIEs{bC^_v_sM$i<=WNG?#Fc1^saXFFDQvjUNt}KQ9=0nv8xNKddwJN^KG{ zmt(J!jQ(9_d`EfQT))v$!2MF zxrQSCQ~z78(}?%s2mEO@{#?0A!{x?L#>CNc1<1s&CTn^pNB9ii_Hp%2*q3(9Y`5;_ znfbQY=iE5)(^XI~cR@vYLAAfI%3o06Dkv!}FLf2TsR#jN)ug=LIR^ah?#t-u>B;)_%GI+b1w81 z`G=+EmsKp9==0~4Lu*jOgi>Ewu?PA*ck-Da%kV7L`1G?2%W8a)?rCY>!t&xWUw%eAM<2L_lV^Nu}u)Jf}YG2htUlm07wN{ZVVi!HB8IUAx*bHCc z{OrQAvN?rC^F33~)b_WL;|u+TIrjAPQ(rKQ5ZvumoV;9QZ$-|fK8DD9jV+#_MZS*}q;994}^75>F#d9u8t z^cpW-V=t`iG+9g$5sbT>!o@n*S0%HhpF{{E>sBl3lxY=pc0X+f-%v*q+nqxxkf}y&niJcXdeJE^vHaFRcZO$v^1DtLRH0r z>Hd<8Sn2c5ESe0jPovnHc-oRmpN=&cV3cQZk*|{RGTl>ERZ)d#Suj$E6fB$qGrqAr zW0Rg^#n1nUV5pX>Y~C*24gFt#ZmmQPKig#2)<>Sc$CHc zc#!~=M^AIOKu4*TqVd`2(}R}b1<-wJL57pcp#D;LoIywQNk)<`oY{=>7FK5$*36w} zR-Be%!~{gavWT7G9=04@_h97=;l!&5!UUk<#ic&D5?s|+RaIV5P*#Bi0u;xrk!aoL;EkPFQgHaZ{JKuRdnVZpV2A)`bz zV8m!}&yHNG036m%3V671R;JRgP0|G?lz#EB&K08*NjQ4ODl*-iWujt28 zWrnE;v&u^6mivnHDqvq<6+?QA{5oz&RW&MRZ6K?lF8ZU&ijEe$(pY2t&&SG$k&LBJ z`Tu+{N3eXU7yl839F_*jVkFUvT|y^TT3Wk-rDlq(QYVu~wq70i>S;ySY}&~73_Yd4zSuj4 zicYwgQaoO6vyzk@TJlF=V>3BFiG z(eSc8pIo@0eN>Ar6QQE01RZA>tD}ybq}s_(cWT9s1Ziogvtsiu?b~sFJUQ@J_)+h6 zm|%v3>7-zd&W5><3LU|XB;>-!G!BZQ$G;@YkJ@`q4Ne%0h9mXbDNxmKYALcHe?7gJ zb(b-rqN>P;ac!eRoJhV!br@f|5v;0Wm!4H{Qv41{@As}+7PG zr~rikcf2u7B6L)82ddKYi)u=%d@(&8iKXWp2s&~EilZWE(q$l2WP~7Sc~RvOVP}qC zI6XOPfhPPo_h7-T&m~YI7i1Sqo>nkD-!rvfa@Hh|^eZef0#x~m3otdk%fx&vxuX=W z$SB?^`P0T_<$J~#V7Rk$vOA6zqlF?2@0wpVC%r(_;3!Hkm4#I>hVWZ3AICWhDo2jc zv_(a*6%Gs*`XVs9>tvx(bA5j9IZ$~mz#(AaTyB@4m*SdA-Oe+sb_Bu{Ll^r%Sh2*S zqw5rvRu-07I7d`!wy=o1;TR*8 zi^@5(=&;(HW1fx;W+8NFNE0?+ zVAM{v?^JLds3o;VZ0jV%SliMibUCXJ?^x|d@>C}!5VzGFS2od+V#t%XP?Fzp#E(-Z z6mlQ5BxhQIC!@-TDx@0pew$=4m~EM%=LtgGtkUpZdF2_&t^!{$yI|PKBO;%MTc3xWobJk= zIWucqPC*)^6yljP(QyPrwj*xAu!2cB({vylE+6$RC07@Dnp^{k_{>{{`ZjAfJcHkz zk8lZ2Kao#5ebbixy5o00)5;d7jTGkAu6!b${X-s6oGn3=u8T|GB-FP|yJ7_PqHO$6 z_l}MsP134w*^zq>^yucotwH%=FPAIf|B?T+Oq6Dn+?#W`+(6|Ww*+?zd%7+Mjz0;I zd4_4v1l*^z6nFTNTvr>M|BzBV$+Dm876aD|Al%(`Z=`=0*AUajd-nf$bUvQ2=;3fgh(qr2^S)5IQT&p{wZtxd2#TYwFRD_&Z5?Q_eOtMz92r2pAt z;s0#mU2SfGNYC$~I6p}i9=F~jKPeVIIf8Y$`dj!LExg;pn@1<4b&!R>$)ZoS@NNsA zVc{RJ@R=6=Nel0_@cf>M^OI-cA9Ikn&b08yTlm=)-aJwvt@AAW9Tt71g|D;li!HqK ztPh)OE&Np${Yndeg@tdl@aY!*W(#i~g^<=J3*ThXud?uWS@_i!{#gsZ#=@_*@XZ$f zdJDhV!Urt;77K44<&f5`7CvOrZ@2J^EWEPti!J=kCeARP)LQsv3twsB`{U^j{zP-K zZggAtTQo}k9c1C7nbqY=weUL2>P{IJ9*H9IlWF0jdEJHQqN4KXysNw9S$HR=vt_1* zN1}@S%(n1OzGmY*3y(w+`Kh$~skjvI{@KESZk4MuYKdUXg^Gp>R*I4+z5o(vK*}~(|tH{r03y(*6B0pO!eE$g6 z<=SfDO-h#5?G}E3MXxOUp%#9Zg}>9n@3HWQS$J1MRR4!t_#_Lz&cdfy_#-TQe+z%4 zg?C$c%}F;7vhYV+^r;s97z>|a;RjmyObdUkh4)(c<1Bohg&$<$XIl8d7JjycA7bI> zS@;tye5Hjy(ZVmb@F!XLS_^-&gAPaxGg-^BcnHE07!e?3dObb8G!h0=z zwuR5L@Z&A~Obc(H!Y{V)UJGAq;d3nfN(+C6g>SU*XIl81 zE&S~kzRAMpTKH8K-fU5%b+v_`Y|*c=@KY>&vxU#I@S83CSr&eag`aBSw_5mo3%}jM zKWyQZg>SU*yDa=P3%|$0Pq*-{u2KI#+rlSV_!$;H#lp|D@ck|PITqe+;m@`3gDm`c z7CzO&KV#uDEd2QvKGVX_vhZFDe}RS1v+ye{{7eh~Hw!=8!WUThc@}=Qg|D>mg%*CX zg`Z>LYc2eh7Jj9LFS78B7QWcR-)!N17QV^Cmst2!7JjaUUv1&%S@<;;zSP1uTlfnt z{ALS3-@O_!NEgpY0Me}2yGYCEwTvd@$kF0)I-FTZeFy!0!|0mLc3I@Y{s{M7UPqR|#{A5Uv#X zCBobqgl7x9mN2&j;XHvKCp>^~roaynK9q2(z;_d7i63?gd@JF@38x5rEn$}KVVA&H z5N639-t`OT|7XH(!rKMDm@tz>c#FVQgjuqOn+3j*@G*o}3p|JLK*CJ|pG%mfdAL#F zsf3RsTr2PygpVg&DeySLg9y(Scr@X`g!2R*Mwq2|I8)#ugij!xD)7;SPbBOXcmUy( z2&V{q5Mh?uVVA%?2@fT_>u0e);Z(xg1>XBC;55Qp1pbaNOYCs7z&i;KC%jtVPYJW6 z4mSz>K4F&9;YNYqCOndGt-!AmW+@!56!;~=8H8sGyp}La-*BG5j}snEI8)#U2#+D0 zD)8NeS+a)R0^drQrD`}u;A;u96b-uszJf4I(D1IG#Quac32ztpV!~O3w+LKCn5Aa8 zS>Ou^XA@p6@EpS92{#FRE@76A;YNX{5}rV~R^T%TPb6F^@HoO=!m|Y)O*n^ep1{Kh zpFucN;30%r3Wie!KALbYVYk2o2u~uMBJe?kS=xnN0{0}$k}kY!uh^e3OS$lNf%mQf z%n~lVMd0rUvvdnL3%rwXKH=2@e@d98SGY;w_X)G)3O5S;Her@p;aY)TCCm~lTq*EN zgl7_-E$~{x=Mc^l_;JGL63!I(0mA1IP8IlW!Yq-(Zh>zl%+e^FBJj0@SrUa^0$)Lx zrA>I(f5rZUXA|Bo@Wq4+32za&iZDxR|-6iFcVOCw!otamlDnsco^Xe31N5gtrTPG2!Kew+LKC_|Jr!1-_7Q z9pTji&mmk-xJlr12{#aK1U%gv>b(lB-cb4>VCoHxy$`aj?T>bE;0qOkNF@0J3_$WD zI1*7q@z1;-u)5Y*ll)-bMF;rB68v=it*c}&wU*YuwPwCNv+ zr4M!6OuEq6wYW_84&FoBx;+Oh>N0Bs3b+yMjRNkwS#8@XuQ$}~8clzNMZbPeS8w1Y z@A{pmdlR;J-`Z0no%{Ba&Tpf$H?XPgQ}(YNdk*@!YL55TjZH=~SO&iE?~i%C{gm6K zPQsE<^WX-vHg!t{VZ!$tO865|3c95}jBftpAl#JITDSq!;sBsAR@;_Y;Taep`N&!q ze!^$sbF_QobZ_uiLIMWM4Sb^x!vws67BvvDjbu52P2S+dw%Wy@8k6=TN&X81 z8hxZ;T3;e59z) zk`6WZosAI18|>;0Rs&kx9~K*h<>_ts(VIMemwNC&ZEZP$mxHdlJ#GH9tU&$1Cxw1# zlDDA^b@~`A5^rFe8qO=~bx16d%?cj{Od~t2Mu(iBCn;-F{lF%CPRIdr6+X1Cfqp~X zUPW}E+M-H}iUpapAR^)7{%Q;q^=tAx_@kERue`>{a}6-ROPtQ5J=pf-YKSccS*Y$Q!iL>a%-=MgBZ{R2Hp>l(d(wDLHINMwT{;q|F{U4-{BvD zFSx8BNI^<4JE@_$W{zXp(aBFw>{YitxlVOGHDS?-s*+2h;RA0=b_x{f@*hlp32gHQ zGn2^qJcP(b{b2)A$T)<1q>v{#m(bW_7a@fp9k|qx?=VWJ_c6NpdfoiPLNu>nb1yVU zS2)%a<pBe0Q8?SV~ge~XT< zM@&(F!x(khNeR)}jL_nKfoWhiS5e&aDDL^++Txb9lUK$|u3rgCBju@G{1=FtFU_b^ z2@TDG>?D6L!$$H;uQUW1NH-s%n_oh0w3hXpYDBZFKZ*4!i`0P)Il=mYH>24b$absO zW#uDi1X|LX5jFhqn_;R2O2Dc^-jMn0T%i&=^zW}io%X*xwtv(f-D>WKE`HtKd%vfe zbTI0zUgI)oXYVBVZRhsx*7vu@AFOVT8NaOE`0)SpW`#$7gS34Y=GM;s-JV+Y8}biU zqhrS3zti#G{TkzEIpdpL9GbNS3pZ7bqQheu1~#e5P^2e#kEAqp6!7B%UosmngnYa{ zLYE?`XS2GNoPwUs@TycXUQS>m+SJ9s=LUADIp}WN)9dhig&j4&k742nzsG<#{JI-{ zr&;`tj>E5~;rAV`o$@<}9W}pln_m|2hTo0Q59jv==I_k!anWnX`O%)7-=E|03$vr< zw-57(%@jZ8LSv{Ll38*_B5$=`Bz&R zVnRav4Sn@)>M(d{?Q>0Na3$BjjS@09_*dp;RRXeS(YY<{?Og4_eaIaae(fu{!dKNb z5FX{__~3I)@oE?-#s~J1=yFY@UKENJ)sLM+>BnFfX+|a0dKfP^uotrA26n3=f$psY zQ?-MiL-(fQv$XC|FJnZt1!yqL4K1!z8}WHkLtAqFPhD7@EUe^+FA84_w?mDW;dX#r z1t3Lk$k&(~cxo|5Wb3A#7&%zSyxb9ss~E@QT-4m!BZS6H`KsMJ_|B1eQm1f?)>g_TDyl>?Rka3kaTc>Ne0_6reE^nIPe`Lgn>83N%ojhQKF308 zyRI3msEMmd15FsER$^$i6gcqqhBBc-t%`X-dF$43Qt*o_Fi=i#ktp~AN0=SzGio&e z1-Ga{BG0-!(5n;CcT&TT$@Nc2w~?H}AoKz$hM!529MMIL@_)o&M)@ZQix%~S=uRvD zJ+a_ZmFR6$@f4=0n%OH>`Mtr_DF1QV7-{lHwOEnPQ9i}Am47b8;Vh~!nt0T+)K*ZG zUoK;a^1qi!?p9;4G^za0&{W^-Pf?>OoL(fSV<@)m2idWd=w6c=KKCDy6FhYwYxUmh zVf4;vNgRk4l+8QTGK$vlfxm|?<=XPN-%*R`c*{3(#Y!=qbwO5v*_WmL7`_z8){%N0 zaBm#r+VEsdFbcPY_qL;dEQY=*u(a5S}k zhEJ^@;~&oDKv=HzEjTEf`>;7|T6RNMtP<8ST`0E>f!nGC zFnba9bg8*JBKsJGkxx)+c?0iDQ(CjS5RI+x+4TjZUrykc7YCs)!k@Ys6e!{lvy$t1 zFq9L#gL|6Xz^B3Cs9ciNA_&V5TqDoXBH;c6u32@bwfPU96u6i5mskRGz!o`tBO0~* zIl&3ohc+~UAOT9qYH46FgazPJ4H8Q)1a0d}j(jLyPlWuc7%aopv{dA1A)*gQ{ydCC z`L})T7<$WWK~zCgbj8GOwU9;xE5F zpIbrR`l2%l!-6lXq?k0K`+Grht6>K3PT^%tR}S*_>~kP!=8B|}weCt)ND zXvsLk|}A#rWG364}rGs)2`mSy$SwF!nIz; z6Rx*lLds7#l>RX0VsSk}s9My!UudqA0UNH_;M%$p<7c)dKb_gDZqH?x{monVO_J&f z%OWt`k`qiEh-r37zIu;j1n!@)PivX2=3$zQ+cZC^f_W)O99LZ=WQ&v3RtO}~@MZPz zXKihv#R+n}<1K1a>liy5nz61B_CfDSYfgJ*Eyh8IkGWD`gIF)5z)AGV32AybMRI)> z=#5Yb$yf1(Us@u_{3l36?e4=ovjW{ol@quiNsE8KP=c7-%;woBepbGi1P*F7qhkv` zVcfvWDh*(6XqnC~ZE74Wr4A7zq!&s3MkmEYg-G*8QP&1I~ zNRA)uz3O&1wA1$!TyjE-k~m)G2KFMh+ct#m|xBkl_1r$sR@SaG>vLq2j6OC zfTx3ulA(5}qoP9`XHW+KWe40$eSX;?KJ^QZO9^@R)%`bNVTpu`=@`J6@$6?Y>vodF1}TaAb$hxb*B4-g*6rzk<-G&Cn) zbwpP#(uv?)fTGa!G(*NHmu)&s+24FgUs4bV1DQ=dD}XAN~?Zq=zLA^rZbe zOQHgUZ*u({jBQ1VA}#|aNkoeKOplzv5t9PtN#n;XPD#G#$A*FHF~Ls5KoDId47|<0(J=5CbgW)rqZ0;}Lusb=ds?*Zgn`XQ z_ij+rd-~(5!@$=ZQ-^^fx>Ts!iCCAvCkzy$&UL~-e~usQeb>!y@bCLRE>0M@0OPAe zgvmB0xP99I_WwZM* zob@|!KImDQJ9ybjd3Zwb=ORFDQ}19j?5rFLuBQTry(?-GQ%gA-otd?E6T@BK0h($h0-sH<#Vq@!WK2l z@cAcT!{^lx!RImDx|en14R(pdwReH!-1dmQH>f5K66|}{O>S2jJ{-jJvIC5VT#tca zc_x~FLETKpKOoLg!B`&1kJ;kx%-G0}^e2+MEhK#gB0Pli!L6hb@p2lFcD!5x9Yo+r zitQ>wVSl+vZT%oNsVll3m)^_C^`&4NP3pOUuUT=*OH$RhocI|s@k|7OZ7Rjga}9Ki zd6wST$vhu|Rm?oU#gsXT8Z%D>W7I>*SG`3S2zoKoFiNE!-oP7mU!qjnmyq0W21vcZ z98@?tz3TpZS@PARfT-JxnnvHWK|fQ|TyK=vUk2A28jX}{=a;8A8hv0t3am@M!#;)& z?3T5cuI9w}+FisV&YgpK)7RbtYQ~bNW7h9NTUNengVAZBXN2hnHI!5V><4lG@n2-xrXC_mynHto5nJ-zCVXHj zJI={>>2zDOWxL$uy8|%~5?unA>ol710>I=3XZOpgy9Dn&Pp*G2k%m6lllEiX#Y}aJ zVpH8>n$@hg^Ff*$aOVap;V)ffNua|;z+wrHhj?5e_em^}!V1CDDSsd1)SSGxQ4Ir_ z8>-Re?{1ZiMXrt@3AFJgIP#3)0Kjq>5Gj9e$3&e20h~VQ@;5iIPhBTn5(ldH@qsph zEvV2|=vr-JW3Uen6;S?iA7G-|3(z|FneumwvB4mYfO8`^t~&4ih)g}QBo zcV}%{(F9jU`MVJ1@85L!`-m=oSFAw;=yF-W2Uau#Qf_h!_P+lbH~9Dc6qlUPLMeYs zFupoU*n-a{)g6?I_JiZ*hUU#y-S8RpY;yhcP;E}oKTy}dTPc=IvmScEbV09PfhJ)a zoTNzk`-tQ{%so!tgDlaFiX3L}zD{m%4vtoKs1Gq1^WHm{fOz^+&4^MqQp)-CyiodA zvtm5GFR?J->+kWpL3sogPapj*g2#csn0(~$@f$wOd&1{n^uUD3XAt>x zW3iEs&+z$3VBz!jKf&jI#HJ2;?+roLV@CAl9cmB8r{bE}8TqfVle}=fFla$MRsVw4 znHT=OkK|o-`r~`EBf0At3`mN<3&p|AejeeO=|cXS1Z*VVVZU%GbP<7By-Eu0iZR6H zURGP*X_x=#f~NH3S*D%;@@<5FRl0o6gq1!^QV<3f0Rj>{CE_`f$*1|1L0}^a0yz~ zY^pred%^{f9``>nGteY~uTFw*U|d)TsdE~X4j&Acf{A3+Nid(Jxi)pPxWYD7D+0-e zuEC%dL{U`+b#4^(qB!j~HPJ!sR;Pj^Q|1VuWO;2+qtKDzE={gG)FFoCK;26pT4GZs zjQ2NO{(~#^E%#sJ5~>L!t3gGwfq z&X0+2i@fSel60CMk%k_Hlho}=Os+owzRJ|cx3bHAurJ-)tKi(Q&#CL@f9S7m({ShVpr)nD&MTq?ufy%O6y*w4#Ecj*7-6L z{~!$G?1z|wj(?b_6aTRORaZ_tlztfe%hK4xVqwHTsE0oLk-$3sZGjWM0wB`t`CLdog$^Hkf1xYH=zil35HTLD z#C#ZUQ#lCEfv)Hz9u1TUNjxfrSd2$spt}{dVMIJPbFKvc$8iX>R)f76+Uv7z~YM&-hhvc1w-yX&Yy-5c|8;#&0F%I zohJ?V2iaG0DpqkamfZ{eu^{x>?6;VMQ-<=-q~rz`r?e|Y(dh!TKyILRLxf|N)I|CP|6#W34)Q!Rxd^V}2pj6C%SOHRsUX0HuMg6`= z8M>H*=_&rA!!%dRIIf6j8F~b!DkXSlWoV|ckxAw=#P@0;DC(uw`AzER7yCD`CMxdOlfl1KwIeR4d ze4P>KL^BO4Gm7#U)JYBs_ve9Pv>PB}ZBqy7rq)(j`5V+hXm5SjaOr0H|68t78B7(6 zY*X($sNL$#SG6oHK$&v}yIwHQ6q@^6UCjNh0eWcq-q6=E^`3-7=?`MER8Cum=y0?*8=y7m?%c(P)2x z<+YBoK`v%fwp5^r65(81?{auw&A7j{vENF|JJIxIbq+v8J-xASQx{^Uit&s>^_J@f zm5yudf%XPWq0qG0%|UZiMZ-$ zdbpO00sdM#YpB}^h_AorK>IUP$IgNFM2;Wqy=A!@+UeWl&y1$}zE%jFlo$VCNz%Pe z0;S3TjKC%LwNAumIncfi7H|%=a0cN}x)?gCB;{ z_ruq;5C_-bqT}GD7)O0YK8&TGK~OMaG@Op%7~IC9&7khakVFlMqJ|o(eo@q629?M` z^%m&AFN;*_TQuphcw_E+ScksVD%Wq+KMd91L4}TH7Zr1!7#sf*o%kmm#9M}L#&miT z4yAv9Nm|N$5^N;?Va8PE=fYNQo&9U0mamW`9pfKDN+WU2?-HKy^zF#lgT(e4;m++ms;6G+Sf$d z>yH!6whS@ujo%;%E zz$6lVj*LesLJ%Ep#c(s{rP#8nN_U4ZC)bytd$g>=7M*3)a!ep5TQp1NF^a8*%Ve#b zkYu<@eLh17B85||iR;fntB|b{GE9|2;du}xOG|`Yw?0Cn$ZXX%PJh0Is0?IaFe<&IJ%!&080&PKBg9)0 zg}S|sg!Ow8+XJXtoWxcRZ6UGkzSs@z^i5qFO>9qsld8Z!Cb3Ner78gIB({8fmc+JK zR+4^TV=~7JNMiekc-l64T7O0pE3t8BALmXj>bHm=gr`VJO`|DYj8Bk-QLER5SwHtl zGBd`-BPIM2H0%DL6FY7JfsP$l<5Nz{1eW}+@TX3{D8CG#Z2mk)j+FFw$^oPy#`7Cz z>;A}}2fzg*`4agv6H-QC`)=V?6EQ}(3;v0oKOnuG=s`X#hK|AkkzLO(G`0`%xx^2n zAfd5ci5NpfH<1)6@LBNEIZ8baH(;jA3>bKni5utB{QMZIfKF8~#t8{_nE?+1FKk8!divD(#MjD^5@+k}{W zcn`5~_VXb>1M54&Q3C5L>+~$oB1y-5I8*im|AA*l_5(M`VB1*FJk$)9mlF=94~k`( zCR8md{DNj#2-qaUv%xaDAGjG}b3c&D4#B?PF6v}IFhcY$`++53`5XIzvoYeY?FWt{ z$9DUHE|}qO?FZbh_s|)C`-a;HtxBZ!H(Y=AU6! zgv}rV>F)`f-%HJSc{5^%I)&p0dpFle*!(Xp&VFDSIH?T$V?6qBP^v+Iov?WrK6ls; z^b>g{Y~C)uw2fi&6S}$;Hviw*56sX)a{ZKXf)fdc(rZ!ISS9SY@N@dW{m*gw8`V*u zGVAA0$lHO2olcSVwmSZ;(ej-|lDP2?c8bP7 z8BAC{1mmd735U|3KP`r3nouGBVP<4m2-t~#U}?oah%NDt9T5MjI*Wgh8}g${Q%k_o zj(<|7;lMvlif~EmC>gEiZv0cF0{=vOLZtqYc7ID2aC+6a7^#;ERf`&Kq<&D$E{bY; z20q3|mZUz2+&;MME~!HAZdZlAZNz*DcvIB!Ooo3bokfAV8|_XEeuGF@=Tc~bG5Ag) zvd&~42O>8(4^Lz)V+`i~B95s~T{a76Q%ARIMe+Q%`RUl=cMJ7wqJAHYAQd`JkI{q5 z{a9_o1g%FHn>0O!O0MUrkpz>#$*EPj#_KK~cv$C2$- zxaDUGE%kDW99|CRVG1<9>Wt_(x&Be+l*Re(=snJ&gKz6r_s4BG-PxaU112jB?SVAy;Z_ zJi1G-40Vo?>n*@Wu1!xsu04Cr^KYY&Px_!S`~d`Vo_`CC-AMe;P!(6M^~&!!fD640ZPTSz!2)MhRl!Nc!I+=1^csUB2!BFDg2bP%lc z_aLqVsq@8YerfC=n3{LWf>_j|X?zhq*!LvJE<67n>Szq(d_6s}7GF=-?`X)w`oLGV z_wMnhdV^E37s%^xz7T`=sf2oebt;XYen$o`V<(;h9~cSYRG-H=T3$-)8z5@YM2j`i zVEEBm5W3Vik43D$5g$3j=OJEH!{+<0czy!km2AXv(64q_{uN)C=MAh|43z4DE|?j; z{|Kt$zqD}Z-qr9j;Kar|)H{?1E_5Y``7}J!4U5F{SF`gs>Phg&yJn7^??%fuwmc3~ z;1r8T`q2G1Y8>?wN`DScViLzr4md{0aQ||La%;Ejs$E;qDpHRcC2BXl;=M*yAn3LnRj+s3C;=s*LHfmK)O z@$eQsYgm{ve{8gRBO0Aqqr*yem;-6N!FBTaX=nkn-&X3Tn>iG##Uq5mQG_~`Yb6+x zljqi}bD3pHth!{O>6&;I{GG5qv`b8#!hrIE9cuo|Kb1|sZ7vvFIw=1fr??I{F0NT>i zH=L@`(-YD|zVZz@jX!bz9D4%BZm*|<9**j%M0A#3FgM1ZW=l+n)zeorO?!Wu0e3Ze z`cPb4{As-?NA%QP++l~>_mI|8cL)nTtr#Aor`4ik(bEt3XzS^pG7-_!xtu8UG!-Oj z9eIS-rD*RU`tP7rf0OQ!b=ShF8a)N2$HS?TARIk${?rrWQF}e@d@!n~(?nS8DrzfdL?N7Ieazsxb14}vH1yB0Z$Fx8wy=qvDo>mg8*WK&* zXzS@=nTY6V7$*va3;~I{0slZxsZl-s6_n~y=^oM3oiLB1ry}X`a9)g_IDg9bBO2T5 z>7@tI*{r)iaiCy&fiFf+DV(#Wh{UJc#q-+fX+OBD(bJXGqt??!5*$TOPm4S3P>+Bo z_4G6?fQRzaV)Qgyd{O-AUVOCm)F2ZPJ@w>7p{Fh&Q48=7^pqFX(^62Xv!#1PPmAah z#-GMWkB2K`^u+m7Pj8^Hy`FBpKcWTowdgE;VsVU~l;|YZpZwx^?ew$_CN_F1W*@Dm z9C0Gi(^bGyjuqfZJzYf$gwiLb#^@=7SnW^C@X^-OESZSt=~EfDO})%l;Pfq8Dct>NX|JT3Rp@D)=@n5}`qZKrC2bIe#42fu zxLrFXt%ZG!l1^tIt)zkCL87EmU@1o-cv4BFbh%La2)q;3%J>HptCchpA8jRNz#UAo zTPMS|si&ZL(Rea)D7wxvJIv8JSj$)LSlnbbEdt5!W)xPlOR5;>b`7SzL90A^>uNn zJ$I`;qJeE{JBV6a1=*%P1G4oK)JJ4E5<0{?3_dq)Eo^()v<--DdysASo3?#WLbM<6 z7pNfH1E&3BwtvyOU5_j6^U)qIL3A-B&ynQQ){itvqdJrA6Qb?6#SGD?PGI|S(e|b7 z+Iz9Rd$j#L(+*>U1;z&){t_;XEi6tYxgT=g52dcA({a}$FJUUgNVuQXZG8dvSDkLC z^!^~y|4sCW_P^*}-GBM-?tdp1NA!IWZ$a_;nV(ZIQe+>T{@4)i9wP6H7>&ku?~90h z|Mx#~nnd|zAiUmbW?=g5fk`*FcvfRu;ZkFv4LOqXG$z+i!d62z3op77(RP$>gBK^) z>u(Qw8goP4K0&a}3H%G@dzNHtxj%Vk zryKf2j$X^r17CWJwlI(-yo-_5R~RN(b8}>Pz17;L20Fw056AF)tz67|6|CoRBD~uW zFu|K!JI&tao!ANQO7ixs#s;}z0Hkfb5j)c4!O-M=AP(Qnuo)V=Zx9eS67dia`gs$1 zU*Phu_CS;M&ECLM8R+c|+>j}kkXL5jkSCYWOkDiOB@b?xjStC#LzQxwUYk64R%7yD zUsLkn1*?+>*EA;&Ube*>@}%U3Lj6IK6WD{(keGS=gfEfmH{^Ij4XL1Mk+;(%L5h}! zM8MEJ9IYV*AH6|o1H{2NEDqjUu{2oQ|YiZzs5q~IQE*WDoHt*MRvN{9j5LX54p z5GKo9{#PV}6mZk-z6yFoKmVb*f!Rqd?8ewe?MQ6nn`5}yfAV+{Zx7U{Jd#rz__-A? zV$5Xw^=MZoqM`NA(H*^#JwGxhh^2 z<;4Nrb_9q2oaY9wGn2fbn(bb^d=xJtRo-BV>f`uZ%}LhG-uRoISx$?K%LZPkUzHY> zFE|NSOAjLQV+K>;fq|FQARc!$G;2-xS4Vo8c|LR;i1`M#OolJ4oz}ae<5}@-khku1 z7rrnYTDD!1wQ8a?bxV_6{@&gYUc7<^wLfverTz6G&ZV?qOSaYq-oC1_^EB2?U09R* z7J-On>l2yWpz~;}TGC-QiCWIB>So$E=-JvCo!DnaPM}S{Bo?9Td++kER&j*jWo~ba zrwJcnArDc!t~S>-a+Q}7ZN7`CcA{Hj@G_#>F*w8G>YWsvf@7sAn5w4vX*J3O zu8i>m>FyYD{J=r{kQ*o-2!7-71x$hVdIRGJ!c)c%Odb09nf!uQPJO!e{ z<2l9Lz%DDH^ZD2sNc``H=B(uFU&cENqdFUdWGV0 zUCFex+>w_xeTOMPe~oNbKR^(PzR3-I9t8Sn2B${W86;{Z5%xG(=8Lf!)kt`NkOy8$ zuK$K@b;~xp{Dn;%>rTY2F9q|01smWH%R}#fgQ9J6bL$dhbb*I_Vg1W z%IN=E>I%Px6|McerWyU!hfN&bv&vfp2?L&{@L(Z;cPv|@lA%CoHYYIAP1@}M<*9VU z3(HS)sC0A3{2Iva37j0hN=6y)a%mf;YIz=oDY5=m?Xe}|6PdV+(d-RfjCa4v+*J3! zm?0e5Tz%C~^qdz>JGcYRJl-R|kP8WHp7Z^}o16_qbloPG7TaSh& zD&bh+3#iY~*cKuRfFSFf;AQ<=?~c?jSj%C9>K#$}@~>uMooTH%G<|~?&Ecom z8%#VFGjKto&3L_OOT#MDf{&}6j}1_N!x{tOm1;fjunqEW8ezoJa<;cYx zXA}9Y#myiW0*U@V-Cd;S4;v%MFYeNS#i*Ror1V+?#Z< z9&w)-dYw#?u}_?0oZ|)vB$&yh&Bfl~`-{5Z56KPdiCw;tYPFoBF&LsWaE*1$Cirp) zlDu{ezAriI8jX>>^AzV!5%1!}@DeljFA`mtDTeReM_;G~N2-)!s*NDFT;>KCB|Hi) zW5tmKxKWJ1oPu_Ubl8#bmnWgr*0A~o{i4Y@_Wq0GJ%2|TlIP_!gkay2Wx{k8CN8ik zMY7xmrbCe~)m$@p&0Kj=CU9Pj^K3EKt-PwOunh#o!?)UnlIy<)nkL8E=Js4YO^SeL zi#OQq(0n)aT7yF7TUqJ8tt@9eFqQ;-|7pQVsPfap10h6c>`AZ!BIJtiE#1r7z7iZz zsN_Z0HcNp_=(iegP|tQVj3JnGlAy2`&U%*0ki!ZZZr)9in5?@N9ztLA9D?MWRkyv1y8RZXcRjyUsFl0( z7%&cv-2xp$xr4v6lpFqw_$u-gt#F*S!hM?11wtq%vIr>Msn7-u(olhZl1=r#SNFeG zGn%XWH-Bq0N=F9>G5Iif(3hBF_#GhZ_YrrfC-b<#+SQZK-zK;eU1O$5jk!wW`fD8A z0d?m+y02T~U{v55i3=_rq^r*F-~~uj+Wmt|Q#JNOjn#`GxHLm!H)*Ua4UFK`iDxyi zmLFtMj9;l&ryVNh->Q_z@oV*}E>?2_|1rtnX1Y`GvWyP(X{RZ;zb$RuQa)gEZx?1> zd3!9}tr-rL!o#PXJhFQBX5%vcIYHU}!4a-Iimn24UBWtHHzHWX3(`J7GHyl!8H_Qb zS@^Fvnk;-VoQrO4668hJlwF4B8W=+Xpr%ndX~&1P>Pdr)ow#bb-gW7G&{4;r^A zF%_#vUe5IzM#B=o6!`vKAUPX(KAKM$ws>m6#-;vtz1&A`xRktu)q@~bBPxtqwctA4 z&>Iae9!rsezFNq@u1x@4>Na$h)r(V!Hxto)&4ip>&*-841z9Z~_e}g`ZSoAn2?bv8 zzov5N{Hi(WMMZ#;ylV=|D~f&deN})`yldw8sw%1rX3hlEA4##B`W7=plw5fTM#b#L zK@`Z;Bo)SP^}UE((+@fT3ikzft0p~*`Wx8+w}^JDOQF=Lhw&Mf4`D1P*z5;7o)hjt zKL#BJgB}9Fp@lCOx#6Ypfjy`ckJ^IAuNtO8 zMfG@LI#>C-7|~OYw+G9EOu?F34uN;DE^Aa{;9S^L@K1s)L$&mydY|6LmgU!C!~Ow- z!}S}qi`0Mgi*qi96wvI&fjC4|H$$%QOK3v=LSlc8!7^-~+eY_Dx!4GNboS~KGBR;? zEPU@pRB@3%iMW{vqcj&X-2!Af zSx@Q~C<|d-*NP#;(O`amL~A4wNk{#`1Nqh2IPtp^WdoDEk$n@65j}{#NMSIYTRn&Q znDC!TkH>mp6Ls&N`ba$vT;bq|y(Wv9FrLV_mexomLRxiX z2^!%reIR-s7EwfG=Nm$4ZnS}N(4<}zf;%E>^ghf{R|~Tv5$Yr45yYnt50{)az150P z;d6e9)L)vOp)9>SNW+7riFO>ju`k@`d^lD3aS^^&42AU)iHvt*$r@XHx))jx`VhM= z8JM6-8fgp(Ua45T3|`ksJj+f+@N&DtIl^YV=q_+W8NL3`=o6HW;TyyV!cYAK9>EN? zk!~CsyM(g}Y=Zju{$Rvhd94c?`cc?Nxo}J#?M}pBh~VQ#p!lH=5FsLzFt6uyL`7`y zv%!Z3UE(Z*6Mv^(yvot*6um!6)=FK33kn6-PFtxzpfh8`6_^L22ZCr5e9((1;@Alr zDlF&lGr~m&hY++9buM)Tmx{QgKgB7N;96n6%>`2!MoC{qmsb2OA}zml-jt-?gp#7? z*$E)j2Yhoe52xP7`;QN%4kPE;7ostGo*ml%DXL}q+OwxmpB_N=`66rD?w#xZdt{bQ zwu4_q^_)`oQa5kWUUeC|LfqtfzD6Re?&mJv!20B?mTR@%4JDN{CO>^}R^3;49o+gv zZ{3Ej%{#l)eR_KG(|!7_JnQG=r}KXqpZs+8zV)9bW;LtCx=&L*$xkl?$cA-)9eFH8%Cu7x>ws}D?JULU%C{`;n#;ikO<#DtvnD|Fbup` zw<8r@5-vRz{S%sZCid8?Mf=mrvl55`M{vW4Ky>kj&Pv>r)pac1G={pBf9y!t*BAs8 zr=iQ*v6y%3JC2?MuiB(AUd=&NyGN-&h+gJV;aB09&iSaWWT0C8XR*}vP;DqNGqkuX z^qaG1eOs5hmIS`Rw-y%hvm z$xn|sFtc_aG8QXvZ}JQI2}0Hz(D>vR68mMh_NH_Y;a%pmK}e9#?y6 zKM;JR36^%PYa>A$IK3(a?`7AXdLRg%2jmI7wEoL3Fn40s`n`#{p>q<(_josRWm;Ap z3V)7#an}0ni5NXMbXJ!an3WeD;4S(tEBS>HY3uiO8Q)_QwpR(78f?x7r8jg@*Q_w zbztoBx$rQHSUW?JPo@Az18xo)11`hp(a;?|ANm7-Z|fnN6XEemE~U=@-WL7k_x-)C z3WOf}?`;(j?&R-n;ruEm@T0us+-!>LzQTFg01A*B!m)GY?}G86!#1^_cr4lizGi4( zbL20AWuaB>Dyz@0)bsd?q@n4}dehj3zi_hAd47;JF3wXI^;0cZL#{_eUx1HS&j5xJ zTGyNN9!R%O|Me{_3;B~}M`+QkKUp?e|1q*M@}=0$A0!K!KUQ`cVzJy@Q#nSovqUuR zw0DbKT*S^_EJGauxrS1%$lohFQXOgJvQ%itTW_%24ddMKlVAONMgz3+Rn0CKLZq?WTo^b zRi&Si=!2<8ANBU1Z+-vKX3F=WysSOpXspUGZ;Igo)b9N-X?*{sH!ovX9pF5vTz)yE zIht0*JLouv@G0zo=T=$#hKB$^O+itv$7n1c4}-YTCGPmA<(%>K|5ps~`}L0PBd9HakNL1FYiMfYQkd;JxERR4Fwj*k9U zp!kCR7ws?l9|SY#_Yr*E0BP=)1@RmD?*snS|LqXz59$91WHj-A3_$(M-I5sp=l2ZY z`|yA4cVrE`&07cO;vU=w{weAK7%tWZGl8+!z?*T`K&Fcesuva%4pBa+c>?#3LRb$o zFo0PPr>=koCUQVyk1_ZhV~^3GF!p#6b1>^65!(H|>j4X(8!AN@;K!a~fcttm23SxJ z_D4addd++d+lT+d9OyKk{_+`wE}Y%}pZY zp@#E)g%7A$#$frr!m=@L`+x0=8u10;dvHqq4a<6CyKwRI}|V9S14Z2(aiT1 zZqh`XHPMnJ5XtuyP6v_62Yv8S{2%kM^{wl7+}Ga1O2w_pAim6dlUmMspAQ({yXeh% z=r@StPqz+Z-kSu zy8kG`crZW~nTXMk#$i2x7U!Wwe!=g~OWAX`+I<wlccB=*| zHq-9#)5b(n0@mtTXW$Uv5cdoYjYz=U@yqLP&6ai7Vf( zf{Dq?Djr%!G4XvLOqu7K`;#u1K31lV?~98QIbT|7QzB3BsU(gb>ia0BAGs%Db~QLZ z!ee06$PQINS)k8}n7DeJ77e9)VnsinSo3$i8u1yT=S4;T3;kz_khG|y+KK+{C0g_x zXp*9zMY>@6&QoYLocFd9{cVheyO~Dx|9lU~IRfiM^m`}^M8A@YY&Q*vLwS@Nme%hQ zvudsX6Q3b^WmNRfpiuRKkhG{0jAmNi9W zQx=H+7M=f8jvPw=3>n%I{Y%k}7JUH8qwfVjfpTN(3#;JoLE>u5ed$sT-KO4!{FM7+ zjuT9OFI}trP0ATrC3rsx#)_(Z`FDVRMdfJ}1acojx$E&yZt&Rjk$miSQ}nUh{h^wU zkKOK8iJ*5LyUl=E|k6&+0dH%PAWGjp(66w?YlCsZ`5DdwtOR_iP?E@Qz^j< z@7ocpY*VEemT&2kzav%#Bp4Zr5oqY1pveG$2adSyzJh`aI<$Ttb0s-$n6)dPIt|{|X4=pb&=Wl^lX8{E~ zc^*io`Yx&|t@2f4^3{-`w8-bK_E(jb&vn;Sm7a*(Ab#ImUzNM0tZ*)9%8Nl)1WnE< zESm2wsVOg_KFQG<$5P^n?utrM6qdP*=AoOfd~RfX4%TrfE#FC}<$!S&`b{YHl@(`K z)X-(zw66KFn7B);-Q^W9rM^SshtSpj!tx^DugT?~=fe%2>Y6g%2Exr9!ZC)P>Z`7- zD6a;#1d_zIX#-o6tAXy^<%J7C-RZ32=_f9^tfGv8G)=&V@h2tJ=|ZvPLwe{uiF^FD-IU8{(c^SU!666p5A$Hls&t zFCDZnWAx};M82|9`AHL;HrRdMqEi1n_cZrdw-e~Hb>N$25ARx7QCi$_XflX1a7=HP z%g7gJ7=-R@6HNw*Te~SEBf5hgkDIfW;3u}1<+S4lx8oQKE-bC`*C70KF2MA1qzxpG z_&>kif9h}acDbDX9jtR{)Kn1Q*y=&YRu6U|VVyjr+BLVjx}bDHWkr?0fXi6J$PES6 zzM=vrKM7H}MDG|}acOmBS>cjs&l;VMNYAh@qZJmJj#XF%F(WyM!lEKyWh}=9^O3t3 zR3Z@T1j_U(o%zrMWT;$HP*hY{G>?IoW74j-rgiSzlXq^yJGb7QJM_+d zcfT=FwZEduSHRJWAZfMaPo(8iWOj|#YqtQBRMy} z-}H~m-?TgY+kXGgX&^m)MEb~6GDeLabLv>r(Us7pYht(V`z7`0*=zsa2PCH)c+kOp z`u?e3|3fsvfI|;E{D>pnM;(34z+;a)e$e0{C!BcF$wO1qh7FhYtZ~`nJrgE+bIv$3 zchcl3d1p<{pEmvM88gp0w{T8Tv9DzAywVHjmn|r-sJy7E+F!G9(c&c+v$K}tgrSi# z$wUv-VLETRoFwG(BkuY9;>adl`HHh)JesAjtUB9x46V`er}K6DhvU!xT73Nfo7V*l()~mEy zM7?d%Yw>|vXpy3}mR6-$AB``dwrZ>vt*^QN+I#IYXU?1h;_bcn`|ij2zL~Ypzt>)S z@3q%n`!RFQE+2}=H-jDl-3Qu?Rn#cxKG4a?uNkYvTF|#ZH`6^h$f1C;C&wgYMgjc+j^%CzIapLp?z=A4Iw69&`k>7F1y2-2qw%x)!to^dRUWx_=ly zxPiX)E9eFE$giP4(9MrPF7_Js{T6aT%O6Glper7a$G6e_LC6QKeFA#Kc1rUI$_cs+ zv>9~rbI>E`k>^of(6uk19YLqR2)StYeV}VWryqj;Kx;ww6Mh)-XeaMaC@1K_myj=L z$6vq)O6Sh+C;Vm93wA>1yazy!fHs2Ch2I6_l{PeAq~V~#f6B?o+<+fMrUJ$PBt&3o zJl+G{im~}MV<(@Jm%Ti5mH6UEKKJR;si#vy;;F`G#Xvkhj)2Os`NQcox&BHB!Y#$O z;Y0Cga*nSuYZ(_3y-dc@aU;aTrp=c`@qPhT_!vTC4cT*Q9|J_o`79Rg&2 z;ICfqS%<%r_|h-5a4Y^7z*devli)wc!rzp_KLPdM4E~!;`BwfY@z<-;C_Pn!e=_>w zQj;I$2~&AcoC;!}lRXu2UEo`E96qYwzk+WY_!8wkcK!B%KNEfa>ZJTvd(x{Z@2cz? zB9*Gd)E;kuf8WLN_$N&MujIBGpzZNUK&+Fb-oeusmI}?cAzV5sIgx5yo~SprWcBT(*2M0LOLFS zoNiF>SK*+vt*g4KY`I;DKY~voe7oc~j?cda{EIYy)$#eM-)+(SXB?mZ1@Mn({_NxP zQ@<<3SR~8;DjfDP>RSfc)bAF7{}wOw^QeWt<~yD%yz71Etn;tV@a*+a>#+Nf_V@<) z4`QsUg$y$fv?JY;9w+b^b{he@4Atb1=C1R>AI&F$a})lk8vL6v#_e|Dm;IqZ@t+Nz zcTw(gjDZ`e+{2b~*Q#=_^VhDg)7N1vk)^%rcezlu)lz0ECsx2m?M zUZ$^B*~|2oAbst+c>FYssa_fwbsg(;{>XlSlSh)0%k=kB|GO$4{}j5Kx7yOKPU(00 zNKlxwm+9X{`pMtJbernG(URV={x8Y`u)0HmwzOaDu0e|4Nc_4|I5d*5yBe`{&HoS*BjMIjMK_IDcD zC*tX;81JA(zQqRbrb?mjQ$MID{@dg6KY-QSY~`o+Y+CP={owm!I0;gyars@8W7Ylf zIG&eE=m7m-0YpXA^UQis`Y$8C0`e!A@fb(Ao)mux z$Ghc!?QzoI%ki}&U$>#9A3ufo9_0TM=+TTf+qe$Cp)iefLbgSE&p}rh{TY4*u=3Zd zaojUivg&Rm`OgM_V0S!z$eKU<=5H&(ONo&2PX$jG$p`<(Z%-d!=Hz({L&V~>wML4h%c#Hrr$zTd0MLPmyxa! zbLK2-xv0KRCf9cj_{x8Uxh(9_EKgGTA2J1#-P{3wdEgVmCcmZKA47aC=HNY)ue3|p z?HoBj@Qjre3um{JMD!ohH@N^hb8ok`oT?o?EzI9X{AftxF9ZMd10Q_8+6Mm3;J*%O z&GJ@L-wdz!LE+@>+ekk2E!!XbnZJ+6H(B{-U*VafC&Y3y319&rC(yn?-HbIev;GO`@z!5`eRMD{VDVt zWUK57e!Cg~#Or@Y@tNEc~#&y4BwFHMw&Y{TH(b9h3yY#py_zZZq)kHj$+X~enPOx5WQ6ZZ z5518oUP#6l;7w zgxC3ez&H7j{`)@PZ!*PGzR%zd2L2!hrl0$7N6I@%_CuNYpViwGTA!t|`bOF`F%8>@hr=aT^AWHQAwG=ZIfsUnsmvU7x zzRAV7e5{C#pcqf2PgpZnyqw+~&lL}NijWBkfbcsWAMne(NVP#0<6$bs+ujnC|8^f{ z>s$Px8*;^AD#qH3(0e)J`Ha_4jK{J=8*;@RIpt6aWqBQa-9}%s7;jVP-^St#+P|F3 zf_;nF-%*w$>7jqm6F>1le` zmHAK)O0!(q!lo>7(PxFYF)cKjDV|UJ8!~;)GvVzlan#fNw=D69x9B%n;$5!~VORw4 zE65hE@%iq}5|5EBto8?2XNi0Kw;<&U8KIlA#7&tKkQW)lm1GPz($}3?$aR!$qfcf1 zYOXdzG{b9YZ$iKkPY5P(o$o5tU}wez*vD@&n&A^}$}GA&S3I8SLm0*k{4mM?YbF`b zkFrpVr?P@DldH!34k<6qEfV7QqLezCAs3Fk9U1 zxfJEz<)qY#I(k>c;!(ERn(J8q}12k7fyj(&t+LN4o?*KWexoS-(!jpeq~I--ihM!Y#+i`W)shkvS;j>2y-90 z6W=*S2yeRC$63^qgGj5zH){hDO@5_n{RR+TJPgu#KX{o$nBamA3~3(sf-uMmYsyrqrT;5S>iv_)}$ePXZq0X zS>g`Q7ZCodXXu73@v4`?Kk^O1HQeI=9KtX9hc3?&&t=pgd~4=szL}*4ly6XXK6#zg zz)209)WAs%oYcTc4V=`#Ne!ITz)209)WAs%xN2Z~gNj-;Pth$*_cQI`cvk`c&myqu zl~>lOit77`w);=p?q}KV=h*Jg=X-4Z%4;RxV~by2&DDxx%UNDuen?Sf6T99ilmOn* zCa*%KA7MJe@w9JE7wwVL^|$xqF`}bf5xq(dOe9nY{G=+cMcBip3tQUqdXY0$yW#l# zhjIFeOkGnX!A_C9HgH9-+a@pUhRbUb(|y==piARxaU=>|x||hUF#3ssE}h@|aaI1! zI2wd5{E95=qsu+Y_Y(su{_lLRs)-YYjw4Lc7(_yBYm~LgdgXvzT2bdmWdX%ZZhVy4SjcJH!4bz28+nEkB z9cH?T=~kvYnC@kIfaxKoN16KPaQ;lEF%2=TVY-lMJJUg?!%R0Z-O6+a)4fa&Fg?Wd zC{uqe=g)K+(-6}drVE+2GaY0)%ybjetxR_?-OKa<(?d*;GWFMS{!FJa4Kb}@x{zr* z(?O=gOgAyz%5(?Qy-W`3K;)IXQ=XF82(h-nSeg-qL-4l*5Px{2vlraPGKWqN?=A*M%}`s+D=rqh^)nAR{| z$h4j5Ak$%{o0x88x`XLnrU#fFVybdY{a)l%<4kIdLiBj5)g2{_c#)h~+W z6C1_y(a_>{+#oJSPpydJXou0>i|2HVjy9y#cM#gzYD8DG(ql9zXjfFpFj{(hTUH7w zLx(SFMM4rrIYX{2Wy`Y8RtSk9Z+sQYLZ}QE_w|Y5*4VOTc!a{P$Pal>^O_8N^n79; z&sQ{^YLn}=-52BjD8_!BUe9+l?cxYMf626^FUNg0K03Xg4{5qz{@EJ8^D~c5ujeTh zz)7}Fujf~q>iHB{BAYulY1xfb=w1()W74r0FQHKwiUH@*Rv8LDaJx%rekkXIA$DV!#FsdSzjV?VO)>O}P zRjkTOhl%##V@*$IyVIqq{7=1t3_tx~=4k!jq>Dd?SWzT;LBCY8IPbh9p zr`jB?Za*#a7F+trVHKn4Eb82ri}JEw_u_`K(DtR*JG#gBTq^Fz$8epo^f69gvFI}3Fd)Il( z2>yDF^B<=f8Moa^Ikqk)IoHw~K5*mrezP<+A5* ziAo82P&z%1S|dI1HhO$a#yvuhd&#(0=2UrfgHh4y#J_&9U_CK(?u zw4X}GPZ8SxB;(j!(SF4e;SmKw`wI&Udzy&;UucD7*du6HW{Lwo8SU3q?lUKYJxAIY#_O;S6!zw&i#mHyR5d3GxcQO7Q6)k8yCjQ1o1!#N=<0FjUq@u+x z#y6a&fTfH-%ea`IjMFJnB)^AoE&p`jX(;WM{ffVhmX zoALR;Nk5CYU3mLYT+94=|9Twr|3van7OU8vD;VF&{Cb~T>+=BcW7+M7dz1iew=c1r zz)po<$MP@qse0{aT>hsVaoVm{J+2trnE&U@AF|nlwyRY;j$&T}m10-GFd zSB0Ff-L3@7(R$E&9(ha&)_R`d=X$Yx&EE{%NpG#d(?qHt>tQ*ffeX&$GR6Zod^6+r z-ywc1J_bpAT;Oyo^1#qoHu976Q z4jm8viXSReK68ZNdWl;(RrqEX{27+h!vh^XTS(WLm`FP1Tjzp*#Rb321>XsLyvi!+ z`w4NtFr*eurRerUKhyjW7jfLP@49TC*_F2ktKX8%1$A$lC z#(P*l+7BFMeEaoEu-4n8Jm-4N0Z#V6=mEw52`V+m;;{eS zihB+Bqw~>-PVz66c(&Lzr1V!9pyPIg;iv)iX!L~{%Qf^J&fyiX$S69 z{_ncrBT`Os8R_n*3;&c;RC)HZ{lHVmD*)Un--zUACJSkI;ok||Y5aQBMb2S~!=GQE zgx|vU;77pRvwE zj$kctr}8gy!Jl@)GqGRlRL}Y9Q|&aD!6?2 z0)iPIb1r9*3ts1fe?{WZ{}v@*`|U2^WG8Rg)`=H0|CSpR{~<-h6^s}DhXUj~91y%! z;>=_rk4X6zfP?S2@aLo9ob2th5{I+?XC*+-d#iyv>HlIEe5VWks0%)}&{_U@F8D^^ z)E`G|{c(p2{{i4m^?lm~pEyPJqtOLIUWOu~7`T%j=DOf3fji~9UgGeFJU^#r|LJM>)>sS5KOFi+9*zo+h4JCu+B>{VUU3Yt|uAwPt%vjjcH4qJl z!w^^>EH{$g+fA=WZw#Fu>&5%fDZV6-9IxJrY~`>^pmHR|&q|gc-^uRG&?H|RoyuUA zQ8C!csI(FcB;E)dEU~@=nKcp&S;1=jTS#gnq>_c30tQqPoMjk|^TUzI1xC$+hN?*2 zxebP)6>rU=x+FYU+|$zAUmPq!d};yQBnS5q~Fy_>sJG-*pF!}}-8+9g+^{fT`;_VdY z7Ho?4L$KYo*-O|Yk6J*tZD=Ynl6@PzAY5HZps_awr`W$zi;`Y&Q2IWLGY!r;vHXrH z-R@&k`mV)y1e|=!hwO(5cjT;jtF~Kv`|&#J_V!|oD#kfg^NsqtrU*P;ThwgS{$)mM zSFAhQhj&tQJ0~E+Xp0$3x?+o4x{NlwQygzAA6S8-LzeY)Mf;;|#i3aMz**36j*-9j_+!^5PPhwpz$0e%?;Z^3S1HI5Z+S?oJ6*0W8yqCie zhB4AGif7J{r7`bj!DX9qp}bw!l=HWp>kebm6H{bl@X4iAXugbxd>iA--S25mr(yo zJt8FBdF=PG%lFh{%l-Zky?5>4VkD!CPL}T_3#y(RcSpa zM!8QKx@pSeHk+Yg&N7>6mRX&c`svTFc}Lou@BaQ8A~!Zg!PXQe09zLn_Js zvVRx7q>SsO4bkN%qz;);dv7$V`+ZV-@mw+(XfzKMs*|RYq7Bp!j&x>2th)+F6wn{B z6GM!6_OSwskcQa{D$n z8>Pi%BD$ipKe@#XgSa7tj(o61T^L!IGBjXLZuH>%p#FBFwPR@_0ZCVVnN7I7Cf3^; zMK>n%3)SM-l&&a7z=S%QN)6lwXKKY&_G7SIJkTFS7V`i1Nu6(IQs<)yMMCwuCnOD_ zaws;tp0qXTt@(HjyRDVcX-dJ8c`Zw$T1>c+WawUnYM|ZCdLYd6avI!AX>bo1<+>y= zjLt?APO^X$aY7ndhI3hBt%(Mt?hlPCJ(Sg8 z_0g5^Ajz7b$ptE_?UwB${NB#~C^@%qV{2z)XD1uRtftN-I38r6H!58P^kZ0* zYtgL{Ozq>OP%IQgTW7RH40LyOc3X^(%budzs>BF0lSUJqbd{R5EM96->YS)oN(4KR zGBPHzkAz8BEJD}V)ZmOT4gR*SknkeJFIUdg-Xyg=yaLlpoR1Z5#9R=XqBZr*nwC~f zWmeWjjBt5x6q@Wd`ooccA(YQL#=B{4JP;76ZT|~1^Xxog!@`s zdT6jyE~yE}^F%SCB=ss`)J5i@D0+U3Ng7RDAf$McDDmWj%+5%O(hVPXqajyHN~QJOkqOAJ%gGiVN1Mw^o`Au=<^`I}nQ zrHtZ1>bY`$+JMI?k2xAbhe2!CO?7S7_6e47^XO(!>t47%c~~f_pE8aI%NAhXOQ%-- zgRREwC&2(YcQqW#1w_I>SZ9yqDyg=q+Cu&N%-J7wok*|yvFgQ0&HcY5(9{)Mjtbe_ zp_(8piT10F2V+?jOWh^OgBGhS+O1WV5E~4k-E1P=$^-8qH#(9{oUB$KTt`Q04fMI# zEi#?So-i~=Zr`XL2i)vadbCRP!tzK=EvmsR2WGjfl;v=&tCK-Usn&9mZMc_GJO6Ul zc=CW$gEL2M3QHOiQMeEj{bx;Y$im*t4FwsGVWCC2KB!bz$`4N&T3ER!fY8^fL~f31=SV*D6ok zRY&n9ReNS62IZ9|X78z;BXu6H2R^s07|YVr>Uo;Vur<)oR4E->Vu?a4IPRGkc4yI8 z)q9L_*J5=vVQlT}X~AmRG6grN=XJ+0A4K)BDU;kiP|9UYptrq~tyI-d2%<}e+=Z04#u5?QVOk%zUzJvmsO)M4eB#LD;R z`5Q0PE#0%O&+MM$IphX|-Im(g zToBTIY9yP2jFg&BoVw~%2p9{Lm+EbTAw3T3c@iuGZPVS_gVwQ6&*&6PoK|`qLohBZ z#b!q1T=}y(a@7M$>IBSmq1b0~>e0tq)&v8!(Uu;zQrpr-RW`{t@H&tz$Z>@klFQDh z%j$y*N5)sKtPVR7_}v%_P#o9ow%&3omEI$#4KNx@)ov2z9EoMx+*aC!3XkzGLj^VLk$T0P&QAewGxdf9SQUps?DQLpn8|$KJjnjHeFWb-zTxfGA zmiGb3?rfDzof6Pl>S`Nt0d@}!{H_;v>KAZoK_Q1iIkt4u8PmOkovr#eIrOd6U)l5! P%l;=Z#GwXJZiK~9=Me(vhjN{eyJC#w&!8p zTuG^}qg?}BgQmJy)+VK<4oFE{ol<)=N9xwiHPDqn+Mbv9Oz6`kA@%H(9&0lby5zXe zopV&r{rTATj-%APL=Q4eX`M1_U%gwdHTvwRu<+ujS=PPi%3cro`y#~M6 z;rDv{-iY6u@XMc@@p}t?Z^iE&_`MUqP5AvQe(%9Af9};6*L}FI!tebCegM~p%;!gN zebjvBWi@^u!|&txeGjk&JH^*Q{m!|%c8ZrPK0U)^UXZSvf7$LkrB zZt;$7$v$T8irc=vcIm#u-+JPK0T)iWzW<80w+?#Z9N(QKE0zyG;NzYD_~wAWFSu>^ zd0(#W+q3&gr@l7(vVXh!5Bu}7e{A*MKIxf%HXJ{9MR@*236-zBx#!u?w+Fm3_n|&1 zeLkPp`onF*XWh7R_YI4mS=m-GKPzYR!5=rCwPnwbzD2uQcJ=*uVgDgRavr&q za!%G>_dV&ot8N>9$Ii8V8^&~R+jzp<6}OzS^|;4g$GE3YT6)sn+lDuGJMyVzecyWG z$;T5*-uk@c&TP*=zj|x>mOXcLfBC}KXMA?=+Rv`Nr0}(mj%(A zto-S+eYXww{i*LWFCOyN6Cbwpo$;@WW*&CTZ6%ILjix$Yy21lzj*rD(d4S91tOdIz z1I~SrjWC~|KDcxISU7iQmdYIF5by#*y=9=&dumyp3en8GcTjal)`8RMg?;9u9$=o#~-V9RFl}+8O-=apqeRN6$yZ zi6^JW(evmy{=Y7c9+Kk3&((3}^=X_qd~FlB;6K9-5YsuAJD0yG&ieW*{Gqct;T;Iy8GaY^(3yT#K%Ymudbt{>YZskqJT)xy?d7U`K_mR| z8~!AL{vgoTZq)Gm`r`Tm>x<*eepw@qG5BSOKg7GHX~cMgFE-GL*d{6HgTmFOS%b2R<|$jzUR%=nE)&ese+!;F(+#u={3 zT_ePQdbyhZsu5orJau`HYk$}IuNs8841-@$o|GnyfP2f2!oSo*$`lP_S;@~bqlaBa z500MCmG$1s)oeD7>&?9OA>VO)*9E%2*NjtO_|_I{#5ab)56JJN-?BpE+su5=bnI*R zI{NfTJ>Sc<{Si&y!|;6=bsfj4yjJ6n(HGY|(ND*H*%avcK-VFz?TJSTCCKFGEa>?t zoIEs{bC^_v_sM$i<=WNG?#Fc1^saXFFDQvjUNt}KQ9=0nv8xNKddwJN^KG{ zmt(J!jQ(9_d`EfQT))v$!2MF zxrQSCQ~z78(}?%s2mEO@{#?0A!{x?L#>CNc1<1s&CTn^pNB9ii_Hp%2*q3(9Y`5;_ znfbQY=iE5)(^XI~cR@vYLAAfI%3o06Dkv!}FLf2TsR#jN)ug=LIR^ah?#t-u>B;)_%GI+b1w81 z`G=+EmsKp9==0~4Lu*jOgi>Ewu?PA*ck-Da%kV7L`1G?2%W8a)?rCY>!t&xWUw%eAM<2L_lV^Nu}u)Jf}YG2htUlm07wN{ZVVi!HB8IUAx*bHCc z{OrQAvN?rC^F33~)b_WL;|u+TIrjAPQ(rKQ5ZvumoV;9QZ$-|fK8DD9jV+#_MZS*}q;994}^75>F#d9u8t z^cpW-V=t`iG+9g$5sbT>!o@n*S0%HhpF{{E>sBl3lxY=pc0X+f-%v*q+nqxxkf}y&niJcXdeJE^vHaFRcZO$v^1DtLRH0r z>Hd<8Sn2c5ESe0jPovnHc-oRmpN=&cV3cQZk*|{RGTl>ERZ)d#Suj$E6fB$qGrqAr zW0Rg^#n1nUV5pX>Y~C*24gFt#ZmmQPKig#2)<>Sc$CHc zc#!~=M^AIOKu4*TqVd`2(}R}b1<-wJL57pcp#D;LoIywQNk)<`oY{=>7FK5$*36w} zR-Be%!~{gavWT7G9=04@_h97=;l!&5!UUk<#ic&D5?s|+RaIV5P*#Bi0u;xrk!aoL;EkPFQgHaZ{JKuRdnVZpV2A)`bz zV8m!}&yHNG036m%3V671R;JRgP0|G?lz#EB&K08*NjQ4ODl*-iWujt28 zWrnE;v&u^6mivnHDqvq<6+?QA{5oz&RW&MRZ6K?lF8ZU&ijEe$(pY2t&&SG$k&LBJ z`Tu+{N3eXU7yl839F_*jVkFUvT|y^TT3Wk-rDlq(QYVu~wq70i>S;ySY}&~73_Yd4zSuj4 zicYwgQaoO6vyzk@TJlF=V>3BFiG z(eSc8pIo@0eN>Ar6QQE01RZA>tD}ybq}s_(cWT9s1Ziogvtsiu?b~sFJUQ@J_)+h6 zm|%v3>7-zd&W5><3LU|XB;>-!G!BZQ$G;@YkJ@`q4Ne%0h9mXbDNxmKYALcHe?7gJ zb(b-rqN>P;ac!eRoJhV!br@f|5v;0Wm!4H{Qv41{@As}+7PG zr~rikcf2u7B6L)82ddKYi)u=%d@(&8iKXWp2s&~EilZWE(q$l2WP~7Sc~RvOVP}qC zI6XOPfhPPo_h7-T&m~YI7i1Sqo>nkD-!rvfa@Hh|^eZef0#x~m3otdk%fx&vxuX=W z$SB?^`P0T_<$J~#V7Rk$vOA6zqlF?2@0wpVC%r(_;3!Hkm4#I>hVWZ3AICWhDo2jc zv_(a*6%Gs*`XVs9>tvx(bA5j9IZ$~mz#(AaTyB@4m*SdA-Oe+sb_Bu{Ll^r%Sh2*S zqw5rvRu-07I7d`!wy=o1;TR*8 zi^@5(=&;(HW1fx;W+8NFNE0?+ zVAM{v?^JLds3o;VZ0jV%SliMibUCXJ?^x|d@>C}!5VzGFS2od+V#t%XP?Fzp#E(-Z z6mlQ5BxhQIC!@-TDx@0pew$=4m~EM%=LtgGtkUpZdF2_&t^!{$yI|PKBO;%MTc3xWobJk= zIWucqPC*)^6yljP(QyPrwj*xAu!2cB({vylE+6$RC07@Dnp^{k_{>{{`ZjAfJcHkz zk8lZ2Kao#5ebbixy5o00)5;d7jTGkAu6!b${X-s6oGn3=u8T|GB-FP|yJ7_PqHO$6 z_l}MsP134w*^zq>^yucotwH%=FPAIf|B?T+Oq6Dn+?#W`+(6|Ww*+?zd%7+Mjz0;I zd4_4v1l*^z6nFTNTvr>M|BzBV$+Dm876aD|Al%(`Z=`=0*AUajd-nf$bUvQ2=;3fgh(qr2^S)5IQT&p{wZtxd2#TYwFRD_&Z5?Q_eOtMz92r2pAt z;s0#mU2SfGNYC$~I6p}i9=F~jKPeVIIf8Y$`dj!LExg;pn@1<4b&!R>$)ZoS@NNsA zVc{RJ@R=6=Nel0_@cf>M^OI-cA9Ikn&b08yTlm=)-aJwvt@AAW9Tt71g|D;li!HqK ztPh)OE&Np${Yndeg@tdl@aY!*W(#i~g^<=J3*ThXud?uWS@_i!{#gsZ#=@_*@XZ$f zdJDhV!Urt;77K44<&f5`7CvOrZ@2J^EWEPti!J=kCeARP)LQsv3twsB`{U^j{zP-K zZggAtTQo}k9c1C7nbqY=weUL2>P{IJ9*H9IlWF0jdEJHQqN4KXysNw9S$HR=vt_1* zN1}@S%(n1OzGmY*3y(w+`Kh$~skjvI{@KESZk4MuYKdUXg^Gp>R*I4+z5o(vK*}~(|tH{r03y(*6B0pO!eE$g6 z<=SfDO-h#5?G}E3MXxOUp%#9Zg}>9n@3HWQS$J1MRR4!t_#_Lz&cdfy_#-TQe+z%4 zg?C$c%}F;7vhYV+^r;s97z>|a;RjmyObdUkh4)(c<1Bohg&$<$XIl8d7JjycA7bI> zS@;tye5Hjy(ZVmb@F!XLS_^-&gAPaxGg-^BcnHE07!e?3dObb8G!h0=z zwuR5L@Z&A~Obc(H!Y{V)UJGAq;d3nfN(+C6g>SU*XIl81 zE&S~kzRAMpTKH8K-fU5%b+v_`Y|*c=@KY>&vxU#I@S83CSr&eag`aBSw_5mo3%}jM zKWyQZg>SU*yDa=P3%|$0Pq*-{u2KI#+rlSV_!$;H#lp|D@ck|PITqe+;m@`3gDm`c z7CzO&KV#uDEd2QvKGVX_vhZFDe}RS1v+ye{{7eh~Hw!=8!WUThc@}=Qg|D>mg%*CX zg`Z>LYc2eh7Jj9LFS78B7QWcR-)!N17QV^Cmst2!7JjaUUv1&%S@<;;zSP1uTlfnt z{ALS3-@O_!NEgpY0Me}2yGYCEwTvd@$kF0)I-FTZeFy!0!|0mLc3I@Y{s{M7UPqR|#{A5Uv#X zCBobqgl7x9mN2&j;XHvKCp>^~roaynK9q2(z;_d7i63?gd@JF@38x5rEn$}KVVA&H z5N639-t`OT|7XH(!rKMDm@tz>c#FVQgjuqOn+3j*@G*o}3p|JLK*CJ|pG%mfdAL#F zsf3RsTr2PygpVg&DeySLg9y(Scr@X`g!2R*Mwq2|I8)#ugij!xD)7;SPbBOXcmUy( z2&V{q5Mh?uVVA%?2@fT_>u0e);Z(xg1>XBC;55Qp1pbaNOYCs7z&i;KC%jtVPYJW6 z4mSz>K4F&9;YNYqCOndGt-!AmW+@!56!;~=8H8sGyp}La-*BG5j}snEI8)#U2#+D0 zD)8NeS+a)R0^drQrD`}u;A;u96b-uszJf4I(D1IG#Quac32ztpV!~O3w+LKCn5Aa8 zS>Ou^XA@p6@EpS92{#FRE@76A;YNX{5}rV~R^T%TPb6F^@HoO=!m|Y)O*n^ep1{Kh zpFucN;30%r3Wie!KALbYVYk2o2u~uMBJe?kS=xnN0{0}$k}kY!uh^e3OS$lNf%mQf z%n~lVMd0rUvvdnL3%rwXKH=2@e@d98SGY;w_X)G)3O5S;Her@p;aY)TCCm~lTq*EN zgl7_-E$~{x=Mc^l_;JGL63!I(0mA1IP8IlW!Yq-(Zh>zl%+e^FBJj0@SrUa^0$)Lx zrA>I(f5rZUXA|Bo@Wq4+32za&iZDxR|-6iFcVOCw!otamlDnsco^Xe31N5gtrTPG2!Kew+LKC_|Jr!1-_7Q z9pTji&mmk-xJlr12{#aK1U%gv>b(lB-cb4>VCoHxy$`aj?T>bE;0qOkNF@0J3_$WD zI1*7q@z1;-u)5Y*ll)-bMF;rB68v=it*c}&wU*YuwPwCNv+ zr4M!6OuEq6wYW_84&FoBx;+Oh>N0Bs3b+yMjRNkwS#8@XuQ$}~8clzNMZbPeS8w1Y z@A{pmdlR;J-`Z0no%{Ba&Tpf$H?XPgQ}(YNdk*@!YL55TjZH=~SO&iE?~i%C{gm6K zPQsE<^WX-vHg!t{VZ!$tO865|3c95}jBftpAl#JITDSq!;sBsAR@;_Y;Taep`N&!q ze!^$sbF_QobZ_uiLIMWM4Sb^x!vws67BvvDjbu52P2S+dw%Wy@8k6=TN&X81 z8hxZ;T3;e59z) zk`6WZosAI18|>;0Rs&kx9~K*h<>_ts(VIMemwNC&ZEZP$mxHdlJ#GH9tU&$1Cxw1# zlDDA^b@~`A5^rFe8qO=~bx16d%?cj{Od~t2Mu(iBCn;-F{lF%CPRIdr6+X1Cfqp~X zUPW}E+M-H}iUpapAR^)7{%Q;q^=tAx_@kERue`>{a}6-ROPtQ5J=pf-YKSccS*Y$Q!iL>a%-=MgBZ{R2Hp>l(d(wDLHINMwT{;q|F{U4-{BvD zFSx8BNI^<4JE@_$W{zXp(aBFw>{YitxlVOGHDS?-s*+2h;RA0=b_x{f@*hlp32gHQ zGn2^qJcP(b{b2)A$T)<1q>v{#m(bW_7a@fp9k|qx?=VWJ_c6NpdfoiPLNu>nb1yVU zS2)%a<pBe0Q8?SV~ge~XT< zM@&(F!x(khNeR)}jL_nKfoWhiS5e&aDDL^++Txb9lUK$|u3rgCBju@G{1=FtFU_b^ z2@TDG>?D6L!$$H;uQUW1NH-s%n_oh0w3hXpYDBZFKZ*4!i`0P)Il=mYH>24b$absO zW#uDi1X|LX5jFhqn_;R2O2Dc^-jMn0T%i&=^zW}io%X*xwtv(f-D>WKE`HtKd%vfe zbTI0zUgI)oXYVBVZRhsx*7vu@AFOVT8NaOE`0)SpW`#$7gS34Y=GM;s-JV+Y8}biU zqhrS3zti#G{TkzEIpdpL9GbNS3pZ7bqQheu1~#e5P^2e#kEAqp6!7B%UosmngnYa{ zLYE?`XS2GNoPwUs@TycXUQS>m+SJ9s=LUADIp}WN)9dhig&j4&k742nzsG<#{JI-{ zr&;`tj>E5~;rAV`o$@<}9W}pln_m|2hTo0Q59jv==I_k!anWnX`O%)7-=E|03$vr< zw-57(%@jZ8LSv{Ll38*_B5$=`Bz&R zVnRav4Sn@)>M(d{?Q>0Na3$BjjS@09_*dp;RRXeS(YY<{?Og4_eaIaae(fu{!dKNb z5FX{__~3I)@oE?-#s~J1=yFY@UKENJ)sLM+>BnFfX+|a0dKfP^uotrA26n3=f$psY zQ?-MiL-(fQv$XC|FJnZt1!yqL4K1!z8}WHkLtAqFPhD7@EUe^+FA84_w?mDW;dX#r z1t3Lk$k&(~cxo|5Wb3A#7&%zSyxb9ss~E@QT-4m!BZS6H`KsMJ_|B1eQm1f?)>g_TDyl>?Rka3kaTc>Ne0_6reE^nIPe`Lgn>83N%ojhQKF308 zyRI3msEMmd15FsER$^$i6gcqqhBBc-t%`X-dF$43Qt*o_Fi=i#ktp~AN0=SzGio&e z1-Ga{BG0-!(5n;CcT&TT$@Nc2w~?H}AoKz$hM!529MMIL@_)o&M)@ZQix%~S=uRvD zJ+a_ZmFR6$@f4=0n%OH>`Mtr_DF1QV7-{lHwOEnPQ9i}Am47b8;Vh~!nt0T+)K*ZG zUoK;a^1qi!?p9;4G^za0&{W^-Pf?>OoL(fSV<@)m2idWd=w6c=KKCDy6FhYwYxUmh zVf4;vNgRk4l+8QTGK$vlfxm|?<=XPN-%*R`c*{3(#Y!=qbwO5v*_WmL7`_z8){%N0 zaBm#r+VEsdFbcPY_qL;dEQY=*u(a5S}k zhEJ^@;~&oDKv=HzEjTEf`>;7|T6RNMtP<8ST`0E>f!nGC zFnba9bg8*JBKsJGkxx)+c?0iDQ(CjS5RI+x+4TjZUrykc7YCs)!k@Ys6e!{lvy$t1 zFq9L#gL|6Xz^B3Cs9ciNA_&V5TqDoXBH;c6u32@bwfPU96u6i5mskRGz!o`tBO0~* zIl&3ohc+~UAOT9qYH46FgazPJ4H8Q)1a0d}j(jLyPlWuc7%aopv{dA1A)*gQ{ydCC z`L})T7<$WWK~zCgbj8GOwU9;xE5F zpIbrR`l2%l!-6lXq?k0K`+Grht6>K3PT^%tR}S*_>~kP!=8B|}weCt)ND zXvsLk|}A#rWG364}rGs)2`mSy$SwF!nIz; z6Rx*lLds7#l>RX0VsSk}s9My!UudqA0UNH_;M%$p<7c)dKb_gDZqH?x{monVO_J&f z%OWt`k`qiEh-r37zIu;j1n!@)PivX2=3$zQ+cZC^f_W)O99LZ=WQ&v3RtO}~@MZPz zXKihv#R+n}<1K1a>liy5nz61B_CfDSYfgJ*Eyh8IkGWD`gIF)5z)AGV32AybMRI)> z=#5Yb$yf1(Us@u_{3l36?e4=ovjW{ol@quiNsE8KP=c7-%;woBepbGi1P*F7qhkv` zVcfvWDh*(6XqnC~ZE74Wr4A7zq!&s3MkmEYg-G*8QP&1I~ zNRA)uz3O&1wA1$!TyjE-k~m)G2KFMh+ct#m|xBkl_1r$sR@SaG>vLq2j6OC zfTx3ulA(5}qoP9`XHW+KWe40$eSX;?KJ^QZO9^@R)%`bNVTpu`=@`J6@$6?Y>vodF1}TaAb$hxb*B4-g*6rzk<-G&Cn) zbwpP#(uv?)fTGa!G(*NHmu)&s+24FgUs4bV1DQ=dD}XAN~?Zq=zLA^rZbe zOQHgUZ*u({jBQ1VA}#|aNkoeKOplzv5t9PtN#n;XPD#G#$A*FHF~Ls5KoDId47|<0(J=5CbgW)rqZ0;}Lusb=ds?*Zgn`XQ z_ij+rd-~(5!@$=ZQ-^^fx>Ts!iCCAvCkzy$&UL~-e~usQeb>!y@bCLRE>0M@0OPAe zgvmB0xP99I_WwZM* zob@|!KImDQJ9ybjd3Zwb=ORFDQ}19j?5rFLuBQTry(?-GQ%gA-otd?E6T@BK0h($h0-sH<#Vq@!WK2l z@cAcT!{^lx!RImDx|en14R(pdwReH!-1dmQH>f5K66|}{O>S2jJ{-jJvIC5VT#tca zc_x~FLETKpKOoLg!B`&1kJ;kx%-G0}^e2+MEhK#gB0Pli!L6hb@p2lFcD!5x9Yo+r zitQ>wVSl+vZT%oNsVll3m)^_C^`&4NP3pOUuUT=*OH$RhocI|s@k|7OZ7Rjga}9Ki zd6wST$vhu|Rm?oU#gsXT8Z%D>W7I>*SG`3S2zoKoFiNE!-oP7mU!qjnmyq0W21vcZ z98@?tz3TpZS@PARfT-JxnnvHWK|fQ|TyK=vUk2A28jX}{=a;8A8hv0t3am@M!#;)& z?3T5cuI9w}+FisV&YgpK)7RbtYQ~bNW7h9NTUNengVAZBXN2hnHI!5V><4lG@n2-xrXC_mynHto5nJ-zCVXHj zJI={>>2zDOWxL$uy8|%~5?unA>ol710>I=3XZOpgy9Dn&Pp*G2k%m6lllEiX#Y}aJ zVpH8>n$@hg^Ff*$aOVap;V)ffNua|;z+wrHhj?5e_em^}!V1CDDSsd1)SSGxQ4Ir_ z8>-Re?{1ZiMXrt@3AFJgIP#3)0Kjq>5Gj9e$3&e20h~VQ@;5iIPhBTn5(ldH@qsph zEvV2|=vr-JW3Uen6;S?iA7G-|3(z|FneumwvB4mYfO8`^t~&4ih)g}QBo zcV}%{(F9jU`MVJ1@85L!`-m=oSFAw;=yF-W2Uau#Qf_h!_P+lbH~9Dc6qlUPLMeYs zFupoU*n-a{)g6?I_JiZ*hUU#y-S8RpY;yhcP;E}oKTy}dTPc=IvmScEbV09PfhJ)a zoTNzk`-tQ{%so!tgDlaFiX3L}zD{m%4vtoKs1Gq1^WHm{fOz^+&4^MqQp)-CyiodA zvtm5GFR?J->+kWpL3sogPapj*g2#csn0(~$@f$wOd&1{n^uUD3XAt>x zW3iEs&+z$3VBz!jKf&jI#HJ2;?+roLV@CAl9cmB8r{bE}8TqfVle}=fFla$MRsVw4 znHT=OkK|o-`r~`EBf0At3`mN<3&p|AejeeO=|cXS1Z*VVVZU%GbP<7By-Eu0iZR6H zURGP*X_x=#f~NH3S*D%;@@<5FRl0o6gq1!^QV<3f0Rj>{CE_`f$*1|1L0}^a0yz~ zY^pred%^{f9``>nGteY~uTFw*U|d)TsdE~X4j&Acf{A3+Nid(Jxi)pPxWYD7D+0-e zuEC%dL{U`+b#4^(qB!j~HPJ!sR;Pj^Q|1VuWO;2+qtKDzE={gG)FFoCK;26pT4GZs zjQ2NO{(~#^E%#sJ5~>L!t3gGwfq z&X0+2i@fSel60CMk%k_Hlho}=Os+owzRJ|cx3bHAurJ-)tKi(Q&#CL@f9S7m({ShVpr)nD&MTq?ufy%O6y*w4#Ecj*7-6L z{~!$G?1z|wj(?b_6aTRORaZ_tlztfe%hK4xVqwHTsE0oLk-$3sZGjWM0wB`t`CLdog$^Hkf1xYH=zil35HTLD z#C#ZUQ#lCEfv)Hz9u1TUNjxfrSd2$spt}{dVMIJPbFKvc$8iX>R)f76+Uv7z~YM&-hhvc1w-yX&Yy-5c|8;#&0F%I zohJ?V2iaG0DpqkamfZ{eu^{x>?6;VMQ-<=-q~rz`r?e|Y(dh!TKyILRLxf|N)I|CP|6#W34)Q!Rxd^V}2pj6C%SOHRsUX0HuMg6`= z8M>H*=_&rA!!%dRIIf6j8F~b!DkXSlWoV|ckxAw=#P@0;DC(uw`AzER7yCD`CMxdOlfl1KwIeR4d ze4P>KL^BO4Gm7#U)JYBs_ve9Pv>PB}ZBqy7rq)(j`5V+hXm5SjaOr0H|68t78B7(6 zY*X($sNL$#SG6oHK$&v}yIwHQ6q@^6UCjNh0eWcq-q6=E^`3-7=?`MER8Cum=y0?*8=y7m?%c(P)2x z<+YBoK`v%fwp5^r65(81?{auw&A7j{vENF|JJIxIbq+v8J-xASQx{^Uit&s>^_J@f zm5yudf%XPWq0qG0%|UZiMZ-$ zdbpO00sdM#YpB}^h_AorK>IUP$IgNFM2;Wqy=A!@+UeWl&y1$}zE%jFlo$VCNz%Pe z0;S3TjKC%LwNAumIncfi7H|%=a0cN}x)?gCB;{ z_ruq;5C_-bqT}GD7)O0YK8&TGK~OMaG@Op%7~IC9&7khakVFlMqJ|o(eo@q629?M` z^%m&AFN;*_TQuphcw_E+ScksVD%Wq+KMd91L4}TH7Zr1!7#sf*o%kmm#9M}L#&miT z4yAv9Nm|N$5^N;?Va8PE=fYNQo&9U0mamW`9pfKDN+WU2?-HKy^zF#lgT(e4;m++ms;6G+Sf$d z>yH!6whS@ujo%;%E zz$6lVj*LesLJ%Ep#c(s{rP#8nN_U4ZC)bytd$g>=7M*3)a!ep5TQp1NF^a8*%Ve#b zkYu<@eLh17B85||iR;fntB|b{GE9|2;du}xOG|`Yw?0Cn$ZXX%PJh0Is0?IaFe<&IJ%!&080&PKBg9)0 zg}S|sg!Ow8+XJXtoWxcRZ6UGkzSs@z^i5qFO>9qsld8Z!Cb3Ner78gIB({8fmc+JK zR+4^TV=~7JNMiekc-l64T7O0pE3t8BALmXj>bHm=gr`VJO`|DYj8Bk-QLER5SwHtl zGBd`-BPIM2H0%DL6FY7JfsP$l<5Nz{1eW}+@TX3{D8CG#Z2mk)j+FFw$^oPy#`7Cz z>;A}}2fzg*`4agv6H-QC`)=V?6EQ}(3;v0oKOnuG=s`X#hK|AkkzLO(G`0`%xx^2n zAfd5ci5NpfH<1)6@LBNEIZ8baH(;jA3>bKni5utB{QMZIfKF8~#t8{_nE?+1FKk8!divD(#MjD^5@+k}{W zcn`5~_VXb>1M54&Q3C5L>+~$oB1y-5I8*im|AA*l_5(M`VB1*FJk$)9mlF=94~k`( zCR8md{DNj#2-qaUv%xaDAGjG}b3c&D4#B?PF6v}IFhcY$`++53`5XIzvoYeY?FWt{ z$9DUHE|}qO?FZbh_s|)C`-a;HtxBZ!H(Y=AU6! zgv}rV>F)`f-%HJSc{5^%I)&p0dpFle*!(Xp&VFDSIH?T$V?6qBP^v+Iov?WrK6ls; z^b>g{Y~C)uw2fi&6S}$;Hviw*56sX)a{ZKXf)fdc(rZ!ISS9SY@N@dW{m*gw8`V*u zGVAA0$lHO2olcSVwmSZ;(ej-|lDP2?c8bP7 z8BAC{1mmd735U|3KP`r3nouGBVP<4m2-t~#U}?oah%NDt9T5MjI*Wgh8}g${Q%k_o zj(<|7;lMvlif~EmC>gEiZv0cF0{=vOLZtqYc7ID2aC+6a7^#;ERf`&Kq<&D$E{bY; z20q3|mZUz2+&;MME~!HAZdZlAZNz*DcvIB!Ooo3bokfAV8|_XEeuGF@=Tc~bG5Ag) zvd&~42O>8(4^Lz)V+`i~B95s~T{a76Q%ARIMe+Q%`RUl=cMJ7wqJAHYAQd`JkI{q5 z{a9_o1g%FHn>0O!O0MUrkpz>#$*EPj#_KK~cv$C2$- zxaDUGE%kDW99|CRVG1<9>Wt_(x&Be+l*Re(=snJ&gKz6r_s4BG-PxaU112jB?SVAy;Z_ zJi1G-40Vo?>n*@Wu1!xsu04Cr^KYY&Px_!S`~d`Vo_`CC-AMe;P!(6M^~&!!fD640ZPTSz!2)MhRl!Nc!I+=1^csUB2!BFDg2bP%lc z_aLqVsq@8YerfC=n3{LWf>_j|X?zhq*!LvJE<67n>Szq(d_6s}7GF=-?`X)w`oLGV z_wMnhdV^E37s%^xz7T`=sf2oebt;XYen$o`V<(;h9~cSYRG-H=T3$-)8z5@YM2j`i zVEEBm5W3Vik43D$5g$3j=OJEH!{+<0czy!km2AXv(64q_{uN)C=MAh|43z4DE|?j; z{|Kt$zqD}Z-qr9j;Kar|)H{?1E_5Y``7}J!4U5F{SF`gs>Phg&yJn7^??%fuwmc3~ z;1r8T`q2G1Y8>?wN`DScViLzr4md{0aQ||La%;Ejs$E;qDpHRcC2BXl;=M*yAn3LnRj+s3C;=s*LHfmK)O z@$eQsYgm{ve{8gRBO0Aqqr*yem;-6N!FBTaX=nkn-&X3Tn>iG##Uq5mQG_~`Yb6+x zljqi}bD3pHth!{O>6&;I{GG5qv`b8#!hrIE9cuo|Kb1|sZ7vvFIw=1fr??I{F0NT>i zH=L@`(-YD|zVZz@jX!bz9D4%BZm*|<9**j%M0A#3FgM1ZW=l+n)zeorO?!Wu0e3Ze z`cPb4{As-?NA%QP++l~>_mI|8cL)nTtr#Aor`4ik(bEt3XzS^pG7-_!xtu8UG!-Oj z9eIS-rD*RU`tP7rf0OQ!b=ShF8a)N2$HS?TARIk${?rrWQF}e@d@!n~(?nS8DrzfdL?N7Ieazsxb14}vH1yB0Z$Fx8wy=qvDo>mg8*WK&* zXzS@=nTY6V7$*va3;~I{0slZxsZl-s6_n~y=^oM3oiLB1ry}X`a9)g_IDg9bBO2T5 z>7@tI*{r)iaiCy&fiFf+DV(#Wh{UJc#q-+fX+OBD(bJXGqt??!5*$TOPm4S3P>+Bo z_4G6?fQRzaV)Qgyd{O-AUVOCm)F2ZPJ@w>7p{Fh&Q48=7^pqFX(^62Xv!#1PPmAah z#-GMWkB2K`^u+m7Pj8^Hy`FBpKcWTowdgE;VsVU~l;|YZpZwx^?ew$_CN_F1W*@Dm z9C0Gi(^bGyjuqfZJzYf$gwiLb#^@=7SnW^C@X^-OESZSt=~EfDO})%l;Pfq8Dct>NX|JT3Rp@D)=@n5}`qZKrC2bIe#42fu zxLrFXt%ZG!l1^tIt)zkCL87EmU@1o-cv4BFbh%La2)q;3%J>HptCchpA8jRNz#UAo zTPMS|si&ZL(Rea)D7wxvJIv8JSj$)LSlnbbEdt5!W)xPlOR5;>b`7SzL90A^>uNn zJ$I`;qJeE{JBV6a1=*%P1G4oK)JJ4E5<0{?3_dq)Eo^()v<--DdysASo3?#WLbM<6 z7pNfH1E&3BwtvyOU5_j6^U)qIL3A-B&ynQQ){itvqdJrA6Qb?6#SGD?PGI|S(e|b7 z+Iz9Rd$j#L(+*>U1;z&){t_;XEi6tYxgT=g52dcA({a}$FJUUgNVuQXZG8dvSDkLC z^!^~y|4sCW_P^*}-GBM-?tdp1NA!IWZ$a_;nV(ZIQe+>T{@4)i9wP6H7>&ku?~90h z|Mx#~nnd|zAiUmbW?=g5fk`*FcvfRu;ZkFv4LOqXG$z+i!d62z3op77(RP$>gBK^) z>u(Qw8goP4K0&a}3H%G@dzNHtxj%Vk zryKf2j$X^r17CWJwlI(-yo-_5R~RN(b8}>Pz17;L20Fw056AF)tz67|6|CoRBD~uW zFu|K!JI&tao!ANQO7ixs#s;}z0Hkfb5j)c4!O-M=AP(Qnuo)V=Zx9eS67dia`gs$1 zU*Phu_CS;M&ECLM8R+c|+>j}kkXL5jkSCYWOkDiOB@b?xjStC#LzQxwUYk64R%7yD zUsLkn1*?+>*EA;&Ube*>@}%U3Lj6IK6WD{(keGS=gfEfmH{^Ij4XL1Mk+;(%L5h}! zM8MEJ9IYV*AH6|o1H{2NEDqjUu{2oQ|YiZzs5q~IQE*WDoHt*MRvN{9j5LX54p z5GKo9{#PV}6mZk-z6yFoKmVb*f!Rqd?8ewe?MQ6nn`5}yfAV+{Zx7U{Jd#rz__-A? zV$5Xw^=MZoqM`NA(H*^#JwGxhh^2 z<;4Nrb_9q2oaY9wGn2fbn(bb^d=xJtRo-BV>f`uZ%}LhG-uRoISx$?K%LZPkUzHY> zFE|NSOAjLQV+K>;fq|FQARc!$G;2-xS4Vo8c|LR;i1`M#OolJ4oz}ae<5}@-khku1 z7rrnYTDD!1wQ8a?bxV_6{@&gYUc7<^wLfverTz6G&ZV?qOSaYq-oC1_^EB2?U09R* z7J-On>l2yWpz~;}TGC-QiCWIB>So$E=-JvCo!DnaPM}S{Bo?9Td++kER&j*jWo~ba zrwJcnArDc!t~S>-a+Q}7ZN7`CcA{Hj@G_#>F*w8G>YWsvf@7sAn5w4vX*J3O zu8i>m>FyYD{J=r{kQ*o-2!7-71x$hVdIRGJ!c)c%Odb09nf!uQPJO!e{ z<2l9Lz%DDH^ZD2sNc``H=B(uFU&cENqdFUdWGV0 zUCFex+>w_xeTOMPe~oNbKR^(PzR3-I9t8Sn2B${W86;{Z5%xG(=8Lf!)kt`NkOy8$ zuK$K@b;~xp{Dn;%>rTY2F9q|01smWH%R}#fgQ9J6bL$dhbb*I_Vg1W z%IN=E>I%Px6|McerWyU!hfN&bv&vfp2?L&{@L(Z;cPv|@lA%CoHYYIAP1@}M<*9VU z3(HS)sC0A3{2Iva37j0hN=6y)a%mf;YIz=oDY5=m?Xe}|6PdV+(d-RfjCa4v+*J3! zm?0e5Tz%C~^qdz>JGcYRJl-R|kP8WHp7Z^}o16_qbloPG7TaSh& zD&bh+3#iY~*cKuRfFSFf;AQ<=?~c?jSj%C9>K#$}@~>uMooTH%G<|~?&Ecom z8%#VFGjKto&3L_OOT#MDf{&}6j}1_N!x{tOm1;fjunqEW8ezoJa<;cYx zXA}9Y#myiW0*U@V-Cd;S4;v%MFYeNS#i*Ror1V+?#Z< z9&w)-dYw#?u}_?0oZ|)vB$&yh&Bfl~`-{5Z56KPdiCw;tYPFoBF&LsWaE*1$Cirp) zlDu{ezAriI8jX>>^AzV!5%1!}@DeljFA`mtDTeReM_;G~N2-)!s*NDFT;>KCB|Hi) zW5tmKxKWJ1oPu_Ubl8#bmnWgr*0A~o{i4Y@_Wq0GJ%2|TlIP_!gkay2Wx{k8CN8ik zMY7xmrbCe~)m$@p&0Kj=CU9Pj^K3EKt-PwOunh#o!?)UnlIy<)nkL8E=Js4YO^SeL zi#OQq(0n)aT7yF7TUqJ8tt@9eFqQ;-|7pQVsPfap10h6c>`AZ!BIJtiE#1r7z7iZz zsN_Z0HcNp_=(iegP|tQVj3JnGlAy2`&U%*0ki!ZZZr)9in5?@N9ztLA9D?MWRkyv1y8RZXcRjyUsFl0( z7%&cv-2xp$xr4v6lpFqw_$u-gt#F*S!hM?11wtq%vIr>Msn7-u(olhZl1=r#SNFeG zGn%XWH-Bq0N=F9>G5Iif(3hBF_#GhZ_YrrfC-b<#+SQZK-zK;eU1O$5jk!wW`fD8A z0d?m+y02T~U{v55i3=_rq^r*F-~~uj+Wmt|Q#JNOjn#`GxHLm!H)*Ua4UFK`iDxyi zmLFtMj9;l&ryVNh->Q_z@oV*}E>?2_|1rtnX1Y`GvWyP(X{RZ;zb$RuQa)gEZx?1> zd3!9}tr-rL!o#PXJhFQBX5%vcIYHU}!4a-Iimn24UBWtHHzHWX3(`J7GHyl!8H_Qb zS@^Fvnk;-VoQrO4668hJlwF4B8W=+Xpr%ndX~&1P>Pdr)ow#bb-gW7G&{4;r^A zF%_#vUe5IzM#B=o6!`vKAUPX(KAKM$ws>m6#-;vtz1&A`xRktu)q@~bBPxtqwctA4 z&>Iae9!rsezFNq@u1x@4>Na$h)r(V!Hxto)&4ip>&*-841z9Z~_e}g`ZSoAn2?bv8 zzov5N{Hi(WMMZ#;ylV=|D~f&deN})`yldw8sw%1rX3hlEA4##B`W7=plw5fTM#b#L zK@`Z;Bo)SP^}UE((+@fT3ikzft0p~*`Wx8+w}^JDOQF=Lhw&Mf4`D1P*z5;7o)hjt zKL#BJgB}9Fp@lCOx#6Ypfjy`ckJ^IAuNtO8 zMfG@LI#>C-7|~OYw+G9EOu?F34uN;DE^Aa{;9S^L@K1s)L$&mydY|6LmgU!C!~Ow- z!}S}qi`0Mgi*qi96wvI&fjC4|H$$%QOK3v=LSlc8!7^-~+eY_Dx!4GNboS~KGBR;? zEPU@pRB@3%iMW{vqcj&X-2!Af zSx@Q~C<|d-*NP#;(O`amL~A4wNk{#`1Nqh2IPtp^WdoDEk$n@65j}{#NMSIYTRn&Q znDC!TkH>mp6Ls&N`ba$vT;bq|y(Wv9FrLV_mexomLRxiX z2^!%reIR-s7EwfG=Nm$4ZnS}N(4<}zf;%E>^ghf{R|~Tv5$Yr45yYnt50{)az150P z;d6e9)L)vOp)9>SNW+7riFO>ju`k@`d^lD3aS^^&42AU)iHvt*$r@XHx))jx`VhM= z8JM6-8fgp(Ua45T3|`ksJj+f+@N&DtIl^YV=q_+W8NL3`=o6HW;TyyV!cYAK9>EN? zk!~CsyM(g}Y=Zju{$Rvhd94c?`cc?Nxo}J#?M}pBh~VQ#p!lH=5FsLzFt6uyL`7`y zv%!Z3UE(Z*6Mv^(yvot*6um!6)=FK33kn6-PFtxzpfh8`6_^L22ZCr5e9((1;@Alr zDlF&lGr~m&hY++9buM)Tmx{QgKgB7N;96n6%>`2!MoC{qmsb2OA}zml-jt-?gp#7? z*$E)j2Yhoe52xP7`;QN%4kPE;7ostGo*ml%DXL}q+OwxmpB_N=`66rD?w#xZdt{bQ zwu4_q^_)`oQa5kWUUeC|LfqtfzD6Re?&mJv!20B?mTR@%4JDN{CO>^}R^3;49o+gv zZ{3Ej%{#l)eR_KG(|!7_JnQG=r}KXqpZs+8zV)9bW;LtCx=&L*$xkl?$cA-)9eFH8%Cu7x>ws}D?JULU%C{`;n#;ikO<#DtvnD|Fbup` zw<8r@5-vRz{S%sZCid8?Mf=mrvl55`M{vW4Ky>kj&Pv>r)pac1G={pBf9y!t*BAs8 zr=iQ*v6y%3JC2?MuiB(AUd=&NyGN-&h+gJV;aB09&iSaWWT0C8XR*}vP;DqNGqkuX z^qaG1eOs5hmIS`Rw-y%hvm z$xn|sFtc_aG8QXvZ}JQI2}0Hz(D>vR68mMh_NH_Y;a%pmK}e9#?y6 zKM;JR36^%PYa>A$IK3(a?`7AXdLRg%2jmI7wEoL3Fn40s`n`#{p>q<(_josRWm;Ap z3V)7#an}0ni5NXMbXJ!an3WeD;4S(tEBS>HY3uiO8Q)_QwpR(78f?x7r8jg@*Q_w zbztoBx$rQHSUW?JPo@Az18xo)11`hp(a;?|ANm7-Z|fnN6XEemE~U=@-WL7k_x-)C z3WOf}?`;(j?&R-n;ruEm@T0us+-!>LzQTFg01A*B!m)GY?}G86!#1^_cr4lizGi4( zbL20AWuaB>Dyz@0)bsd?q@n4}dehj3zi_hAd47;JF3wXI^;0cZL#{_eUx1HS&j5xJ zTGyNN9!R%O|Me{_3;B~}M`+QkKUp?e|1q*M@}=0$A0!K!KUQ`cVzJy@Q#nSovqUuR zw0DbKT*S^_EJGauxrS1%$lohFQXOgJvQ%itTW_%24ddMKlVAONMgz3+Rn0CKLZq?WTo^b zRi&Si=!2<8ANBU1Z+-vKX3F=WysSOpXspUGZ;Igo)b9N-X?*{sH!ovX9pF5vTz)yE zIht0*JLouv@G0zo=T=$#hKB$^O+itv$7n1c4}-YTCGPmA<(%>K|5ps~`}L0PBd9HakNL1FYiMfYQkd;JxERR4Fwj*k9U zp!kCR7ws?l9|SY#_Yr*E0BP=)1@RmD?*snS|LqXz59$91WHj-A3_$(M-I5sp=l2ZY z`|yA4cVrE`&07cO;vU=w{weAK7%tWZGl8+!z?*T`K&Fcesuva%4pBa+c>?#3LRb$o zFo0PPr>=koCUQVyk1_ZhV~^3GF!p#6b1>^65!(H|>j4X(8!AN@;K!a~fcttm23SxJ z_D4addd++d+lT+d9OyKk{_+`wE}Y%}pZY zp@#E)g%7A$#$frr!m=@L`+x0=8u10;dvHqq4a<6CyKwRI}|V9S14Z2(aiT1 zZqh`XHPMnJ5XtuyP6v_62Yv8S{2%kM^{wl7+}Ga1O2w_pAim6dlUmMspAQ({yXeh% z=r@StPqz+Z-kSu zy8kG`crZW~nTXMk#$i2x7U!Wwe!=g~OWAX`+I<wlccB=*| zHq-9#)5b(n0@mtTXW$Uv5cdoYjYz=U@yqLP&6ai7Vf( zf{Dq?Djr%!G4XvLOqu7K`;#u1K31lV?~98QIbT|7QzB3BsU(gb>ia0BAGs%Db~QLZ z!ee06$PQINS)k8}n7DeJ77e9)VnsinSo3$i8u1yT=S4;T3;kz_khG|y+KK+{C0g_x zXp*9zMY>@6&QoYLocFd9{cVheyO~Dx|9lU~IRfiM^m`}^M8A@YY&Q*vLwS@Nme%hQ zvudsX6Q3b^WmNRfpiuRKkhG{0jAmNi9W zQx=H+7M=f8jvPw=3>n%I{Y%k}7JUH8qwfVjfpTN(3#;JoLE>u5ed$sT-KO4!{FM7+ zjuT9OFI}trP0ATrC3rsx#)_(Z`FDVRMdfJ}1acojx$E&yZt&Rjk$miSQ}nUh{h^wU zkKOK8iJ*5LyUl=E|k6&+0dH%PAWGjp(66w?YlCsZ`5DdwtOR_iP?E@Qz^j< z@7ocpY*VEemT&2kzav%#Bp4Zr5oqY1pveG$2adSyzJh`aI<$Ttb0s-$n6)dPIt|{|X4=pb&=Wl^lX8{E~ zc^*io`Yx&|t@2f4^3{-`w8-bK_E(jb&vn;Sm7a*(Ab#ImUzNM0tZ*)9%8Nl)1WnE< zESm2wsVOg_KFQG<$5P^n?utrM6qdP*=AoOfd~RfX4%TrfE#FC}<$!S&`b{YHl@(`K z)X-(zw66KFn7B);-Q^W9rM^SshtSpj!tx^DugT?~=fe%2>Y6g%2Exr9!ZC)P>Z`7- zD6a;#1d_zIX#-o6tAXy^<%J7C-RZ32=_f9^tfGv8G)=&V@h2tJ=|ZvPLwe{uiF^FD-IU8{(c^SU!666p5A$Hls&t zFCDZnWAx};M82|9`AHL;HrRdMqEi1n_cZrdw-e~Hb>N$25ARx7QCi$_XflX1a7=HP z%g7gJ7=-R@6HNw*Te~SEBf5hgkDIfW;3u}1<+S4lx8oQKE-bC`*C70KF2MA1qzxpG z_&>kif9h}acDbDX9jtR{)Kn1Q*y=&YRu6U|VVyjr+BLVjx}bDHWkr?0fXi6J$PES6 zzM=vrKM7H}MDG|}acOmBS>cjs&l;VMNYAh@qZJmJj#XF%F(WyM!lEKyWh}=9^O3t3 zR3Z@T1j_U(o%zrMWT;$HP*hY{G>?IoW74j-rgiSzlXq^yJGb7QJM_+d zcfT=FwZEduSHRJWAZfMaPo(8iWOj|#YqtQBRMy} z-}H~m-?TgY+kXGgX&^m)MEb~6GDeLabLv>r(Us7pYht(V`z7`0*=zsa2PCH)c+kOp z`u?e3|3fsvfI|;E{D>pnM;(34z+;a)e$e0{C!BcF$wO1qh7FhYtZ~`nJrgE+bIv$3 zchcl3d1p<{pEmvM88gp0w{T8Tv9DzAywVHjmn|r-sJy7E+F!G9(c&c+v$K}tgrSi# z$wUv-VLETRoFwG(BkuY9;>adl`HHh)JesAjtUB9x46V`er}K6DhvU!xT73Nfo7V*l()~mEy zM7?d%Yw>|vXpy3}mR6-$AB``dwrZ>vt*^QN+I#IYXU?1h;_bcn`|ij2zL~Ypzt>)S z@3q%n`!RFQE+2}=H-jDl-3Qu?Rn#cxKG4a?uNkYvTF|#ZH`6^h$f1C;C&wgYMgjc+j^%CzIapLp?z=A4Iw69&`k>7F1y2-2qw%x)!to^dRUWx_=ly zxPiX)E9eFE$giP4(9MrPF7_Js{T6aT%O6Glper7a$G6e_LC6QKeFA#Kc1rUI$_cs+ zv>9~rbI>E`k>^of(6uk19YLqR2)StYeV}VWryqj;Kx;ww6Mh)-XeaMaC@1K_myj=L z$6vq)O6Sh+C;Vm93wA>1yazy!fHs2Ch2I6_l{PeAq~V~#f6B?o+<+fMrUJ$PBt&3o zJl+G{im~}MV<(@Jm%Ti5mH6UEKKJR;si#vy;;F`G#Xvkhj)2Os`NQcox&BHB!Y#$O z;Y0Cga*nSuYZ(_3y-dc@aU;aTrp=c`@qPhT_!vTC4cT*Q9|J_o`79Rg&2 z;ICfqS%<%r_|h-5a4Y^7z*devli)wc!rzp_KLPdM4E~!;`BwfY@z<-;C_Pn!e=_>w zQj;I$2~&AcoC;!}lRXu2UEo`E96qYwzk+WY_!8wkcK!B%KNEfa>ZJTvd(x{Z@2cz? zB9*Gd)E;kuf8WLN_$N&MujIBGpzZNUK&+Fb-oeusmI}?cAzV5sIgx5yo~SprWcBT(*2M0LOLFS zoNiF>SK*+vt*g4KY`I;DKY~voe7oc~j?cda{EIYy)$#eM-)+(SXB?mZ1@Mn({_NxP zQ@<<3SR~8;DjfDP>RSfc)bAF7{}wOw^QeWt<~yD%yz71Etn;tV@a*+a>#+Nf_V@<) z4`QsUg$y$fv?JY;9w+b^b{he@4Atb1=C1R>AI&F$a})lk8vL6v#_e|Dm;IqZ@t+Nz zcTw(gjDZ`e+{2b~*Q#=_^VhDg)7N1vk)^%rcezlu)lz0ECsx2m?M zUZ$^B*~|2oAbst+c>FYssa_fwbsg(;{>XlSlSh)0%k=kB|GO$4{}j5Kx7yOKPU(00 zNKlxwm+9X{`pMtJbernG(URV={x8Y`u)0HmwzOaDu0e|4Nc_4|I5d*5yBe`{&HoS*BjMIjMK_IDcD zC*tX;81JA(zQqRbrb?mjQ$MID{@dg6KY-QSY~`o+Y+CP={owm!I0;gyars@8W7Ylf zIG&eE=m7m-0YpXA^UQis`Y$8C0`e!A@fb(Ao)mux z$Ghc!?QzoI%ki}&U$>#9A3ufo9_0TM=+TTf+qe$Cp)iefLbgSE&p}rh{TY4*u=3Zd zaojUivg&Rm`OgM_V0S!z$eKU<=5H&(ONo&2PX$jG$p`<(Z%-d!=Hz({L&V~>wML4h%c#Hrr$zTd0MLPmyxa! zbLK2-xv0KRCf9cj_{x8Uxh(9_EKgGTA2J1#-P{3wdEgVmCcmZKA47aC=HNY)ue3|p z?HoBj@Qjre3um{JMD!ohH@N^hb8ok`oT?o?EzI9X{AftxF9ZMd10Q_8+6Mm3;J*%O z&GJ@L-wdz!LE+@>+ekk2E!!XbnZJ+6H(B{-U*VafC&Y3y319&rC(yn?-HbIev;GO`@z!5`eRMD{VDVt zWUK57e!Cg~#Or@Y@tNEc~#&y4BwFHMw&Y{TH(b9h3yY#py_zZZq)kHj$+X~enPOx5WQ6ZZ z5518oUP#6l;7w zgxC3ez&H7j{`)@PZ!*PGzR%zd2L2!hrl0$7N6I@%_CuNYpViwGTA!t|`bOF`F%8>@hr=aT^AWHQAwG=ZIfsUnsmvU7x zzRAV7e5{C#pcqf2PgpZnyqw+~&lL}NijWBkfbcsWAMne(NVP#0<6$bs+ujnC|8^f{ z>s$Px8*;^AD#qH3(0e)J`Ha_4jK{J=8*;@RIpt6aWqBQa-9}%s7;jVP-^St#+P|F3 zf_;nF-%*w$>7jqm6F>1le` zmHAK)O0!(q!lo>7(PxFYF)cKjDV|UJ8!~;)GvVzlan#fNw=D69x9B%n;$5!~VORw4 zE65hE@%iq}5|5EBto8?2XNi0Kw;<&U8KIlA#7&tKkQW)lm1GPz($}3?$aR!$qfcf1 zYOXdzG{b9YZ$iKkPY5P(o$o5tU}wez*vD@&n&A^}$}GA&S3I8SLm0*k{4mM?YbF`b zkFrpVr?P@DldH!34k<6qEfV7QqLezCAs3Fk9U1 zxfJEz<)qY#I(k>c;!(ERn(J8q}12k7fyj(&t+LN4o?*KWexoS-(!jpeq~I--ihM!Y#+i`W)shkvS;j>2y-90 z6W=*S2yeRC$63^qgGj5zH){hDO@5_n{RR+TJPgu#KX{o$nBamA3~3(sf-uMmYsyrqrT;5S>iv_)}$ePXZq0X zS>g`Q7ZCodXXu73@v4`?Kk^O1HQeI=9KtX9hc3?&&t=pgd~4=szL}*4ly6XXK6#zg zz)209)WAs%oYcTc4V=`#Ne!ITz)209)WAs%xN2Z~gNj-;Pth$*_cQI`cvk`c&myqu zl~>lOit77`w);=p?q}KV=h*Jg=X-4Z%4;RxV~by2&DDxx%UNDuen?Sf6T99ilmOn* zCa*%KA7MJe@w9JE7wwVL^|$xqF`}bf5xq(dOe9nY{G=+cMcBip3tQUqdXY0$yW#l# zhjIFeOkGnX!A_C9HgH9-+a@pUhRbUb(|y==piARxaU=>|x||hUF#3ssE}h@|aaI1! zI2wd5{E95=qsu+Y_Y(su{_lLRs)-YYjw4Lc7(_yBYm~LgdgXvzT2bdmWdX%ZZhVy4SjcJH!4bz28+nEkB z9cH?T=~kvYnC@kIfaxKoN16KPaQ;lEF%2=TVY-lMJJUg?!%R0Z-O6+a)4fa&Fg?Wd zC{uqe=g)K+(-6}drVE+2GaY0)%ybjetxR_?-OKa<(?d*;GWFMS{!FJa4Kb}@x{zr* z(?O=gOgAyz%5(?Qy-W`3K;)IXQ=XF82(h-nSeg-qL-4l*5Px{2vlraPGKWqN?=A*M%}`s+D=rqh^)nAR{| z$h4j5Ak$%{o0x88x`XLnrU#fFVybdY{a)l%<4kIdLiBj5)g2{_c#)h~+W z6C1_y(a_>{+#oJSPpydJXou0>i|2HVjy9y#cM#gzYD8DG(ql9zXjfFpFj{(hTUH7w zLx(SFMM4rrIYX{2Wy`Y8RtSk9Z+sQYLZ}QE_w|Y5*4VOTc!a{P$Pal>^O_8N^n79; z&sQ{^YLn}=-52BjD8_!BUe9+l?cxYMf626^FUNg0K03Xg4{5qz{@EJ8^D~c5ujeTh zz)7}Fujf~q>iHB{BAYulY1xfb=w1()W74r0FQHKwiUH@*Rv8LDaJx%rekkXIA$DV!#FsdSzjV?VO)>O}P zRjkTOhl%##V@*$IyVIqq{7=1t3_tx~=4k!jq>Dd?SWzT;LBCY8IPbh9p zr`jB?Za*#a7F+trVHKn4Eb82ri}JEw_u_`K(DtR*JG#gBTq^Fz$8epo^f69gvFI}3Fd)Il( z2>yDF^B<=f8Moa^Ikqk)IoHw~K5*mrezP<+A5* ziAo82P&z%1S|dI1HhO$a#yvuhd&#(0=2UrfgHh4y#J_&9U_CK(?u zw4X}GPZ8SxB;(j!(SF4e;SmKw`wI&Udzy&;UucD7*du6HW{Lwo8SU3q?lUKYJxAIY#_O;S6!zw&i#mHyR5d3GxcQO7Q6)k8yCjQ1o1!#N=<0FjUq@u+x z#y6a&fTfH-%ea`IjMFJnB)^AoE&p`jX(;WM{ffVhmX zoALR;Nk5CYU3mLYT+94=|9Twr|3van7OU8vD;VF&{Cb~T>+=BcW7+M7dz1iew=c1r zz)po<$MP@qse0{aT>hsVaoVm{J+2trnE&U@AF|nlwyRY;j$&T}m10-GFd zSB0Ff-L3@7(R$E&9(ha&)_R`d=X$Yx&EE{%NpG#d(?qHt>tQ*ffeX&$GR6Zod^6+r z-ywc1J_bpAT;Oyo^1#qoHu976Q z4jm8viXSReK68ZNdWl;(RrqEX{27+h!vh^XTS(WLm`FP1Tjzp*#Rb321>XsLyvi!+ z`w4NtFr*eurRerUKhyjW7jfLP@49TC*_F2ktKX8%1$A$lC z#(P*l+7BFMeEaoEu-4n8Jm-4N0Z#V6=mEw52`V+m;;{eS zihB+Bqw~>-PVz66c(&Lzr1V!9pyPIg;iv)iX!L~{%Qf^J&fyiX$S69 z{_ncrBT`Os8R_n*3;&c;RC)HZ{lHVmD*)Un--zUACJSkI;ok||Y5aQBMb2S~!=GQE zgx|vU;77pRvwE zj$kctr}8gy!Jl@)GqGRlRL}Y9Q|&aD!6?2 z0)iPIb1r9*3ts1fe?{WZ{}v@*`|U2^WG8Rg)`=H0|CSpR{~<-h6^s}DhXUj~91y%! z;>=_rk4X6zfP?S2@aLo9ob2th5{I+?XC*+-d#iyv>HlIEe5VWks0%)}&{_U@F8D^^ z)E`G|{c(p2{{i4m^?lm~pEyPJqtOLIUWOu~7`T%j=DOf3fji~9UgGeFJU^#r|LJM>)>sS5KOFi+9*zo+h4JCu+B>{VUU3Yt|uAwPt%vjjcH4qJl z!w^^>EH{$g+fA=WZw#Fu>&5%fDZV6-9IxJrY~`>^pmHR|&q|gc-^uRG&?H|RoyuUA zQ8C!csI(FcB;E)dEU~@=nKcp&S;1=jTS#gnq>_c30tQqPoMjk|^TUzI1xC$+hN?*2 zxebP)6>rU=x+FYU+|$zAUmPq!d};yQBnS5q~Fy_>sJG-*pF!}}-8+9g+^{fT`;_VdY z7Ho?4L$KYo*-O|Yk6J*tZD=Ynl6@PzAY5HZps_awr`W$zi;`Y&Q2IWLGY!r;vHXrH z-R@&k`mV)y1e|=!hwO(5cjT;jtF~Kv`|&#J_V!|oD#kfg^NsqtrU*P;ThwgS{$)mM zSFAhQhj&tQJ0~E+Xp0$3x?+o4x{NlwQygzAA6S8-LzeY)Mf;;|#i3aMz**36j*-9j_+!^5PPhwpz$0e%?;Z^3S1HI5Z+S?oJ6*0W8yqCie zhB4AGif7J{r7`bj!DX9qp}bw!l=HWp>kebm6H{bl@X4iAXugbxd>iA--S25mr(yo zJt8FBdF=PG%lFh{%l-Zky?5>4VkD!CPL}T_3#y(RcSpa zM!8QKx@pSeHk+Yg&N7>6mRX&c`svTFc}Lou@BaQ8A~!Zg!PXQe09zLn_Js zvVRx7q>SsO4bkN%qz;);dv7$V`+ZV-@mw+(XfzKMs*|RYq7Bp!j&x>2th)+F6wn{B z6GM!6_OSwskcQa{D$n z8>Pi%BD$ipKe@#XgSa7tj(o61T^L!IGBjXLZuH>%p#FBFwPR@_0ZCVVnN7I7Cf3^; zMK>n%3)SM-l&&a7z=S%QN)6lwXKKY&_G7SIJkTFS7V`i1Nu6(IQs<)yMMCwuCnOD_ zaws;tp0qXTt@(HjyRDVcX-dJ8c`Zw$T1>c+WawUnYM|ZCdLYd6avI!AX>bo1<+>y= zjLt?APO^X$aY7ndhI3hBt%(Mt?hlPCJ(Sg8 z_0g5^Ajz7b$ptE_?UwB${NB#~C^@%qV{2z)XD1uRtftN-I38r6H!58P^kZ0* zYtgL{Ozq>OP%IQgTW7RH40LyOc3X^(%budzs>BF0lSUJqbd{R5EM96->YS)oN(4KR zGBPHzkAz8BEJD}V)ZmOT4gR*SknkeJFIUdg-Xyg=yaLlpoR1Z5#9R=XqBZr*nwC~f zWmeWjjBt5x6q@Wd`ooccA(YQL#=B{4JP;76ZT|~1^Xxog!@`s zdT6jyE~yE}^F%SCB=ss`)J5i@D0+U3Ng7RDAf$McDDmWj%+5%O(hVPXqajyHN~QJOkqOAJ%gGiVN1Mw^o`Au=<^`I}nQ zrHtZ1>bY`$+JMI?k2xAbhe2!CO?7S7_6e47^XO(!>t47%c~~f_pE8aI%NAhXOQ%-- zgRREwC&2(YcQqW#1w_I>SZ9yqDyg=q+Cu&N%-J7wok*|yvFgQ0&HcY5(9{)Mjtbe_ zp_(8piT10F2V+?jOWh^OgBGhS+O1WV5E~4k-E1P=$^-8qH#(9{oUB$KTt`Q04fMI# zEi#?So-i~=Zr`XL2i)vadbCRP!tzK=EvmsR2WGjfl;v=&tCK-Usn&9mZMc_GJO6Ul zc=CW$gEL2M3QHOiQMeEj{bx;Y$im*t4FwsGVWCC2KB!bz$`4N&T3ER!fY8^fL~f31=SV*D6ok zRY&n9ReNS62IZ9|X78z;BXu6H2R^s07|YVr>Uo;Vur<)oR4E->Vu?a4IPRGkc4yI8 z)q9L_*J5=vVQlT}X~AmRG6grN=XJ+0A4K)BDU;kiP|9UYptrq~tyI-d2%<}e+=Z04#u5?QVOk%zUzJvmsO)M4eB#LD;R z`5Q0PE#0%O&+MM$IphX|-Im(g zToBTIY9yP2jFg&BoVw~%2p9{Lm+EbTAw3T3c@iuGZPVS_gVwQ6&*&6PoK|`qLohBZ z#b!q1T=}y(a@7M$>IBSmq1b0~>e0tq)&v8!(Uu;zQrpr-RW`{t@H&tz$Z>@klFQDh z%j$y*N5)sKtPVR7_}v%_P#o9ow%&3omEI$#4KNx@)ov2z9EoMx+*aC!3XkzGLj^VLk$T0P&QAewGxdf9SQUps?DQLpn8|$KJjnjHeFWb-zTxfGA zmiGb3?rfDzof6Pl>S`Nt0d@}!{H_;v>KAZoK_Q1iIkt4u8PmOkovr#eIrOd6U)l5! P%l;=Z#GuazH0^uT%U1ZAQC?N;)rgRTgJ*1435^qaOQ_Bv=idZ4pul7ZvryPOa z-bgSI4@JU`u0W_)?VJh(tzAj}(yAo?R%Ll~fI;>AED1%$K$Mc16pGigwMOzGu_Mc1t5=<-^U7rIFSr z_0mY)WM)j1(|1H|tja5mr0WZ=D#2Si=Lv8ok(14g*?^O$ja8dDlfcPBR-Awyl|4V~ z9s2p)87R)yo2$EUxD-$*n7pn1Rs|u#xoU_P()YxI34Lk{hnoe2pdwU*i~!h_RI_+p zw%1&@5k>pF{QQ>LC<}uB5X6ZeRTfdEora>KyBi@ z^p+bG=pw5tOC#=5Phv7F4OXB-8f_IQtq81oX;dti6OX_-iOIle(%P8KV{-(_jk?aEBr>I<%WhK~z68_FC7rjj~tmoKN0THuBG zmO_R+D1U`U&#q5il?%(Z!#>d{CHYYA$It_4@wEN&CBM7-C4f@pAj}k&mi+2&+F)OY zgM33=j;?8OmK%5$0+DGDoX@|MUBKJz-m>+DZQFP3tgc~EM6lV#S$VVb3kv7VEh?5u zO6SclTd=Tv(PEwOOvRF=&sI8?J@@?b6)RV*UbA-H`VG#FRjy5&sb8+GtM@iEDtq?s z^X)&-bg;RlwXOZoi!U8M66gqas$H*jhmQ61_Jt$;$D^_MiPujKoH~uc`aITcB&4yf zZii!ad&h}z{Di~p+~#y|*mQzgu5&K8v&y|jNA*RQv9$}QTZk}FB2>(soqq`q)gr)` zFrR{>TwL;|t*$6f*6i!S+{S$Uz$FU$_7>$ezHP79M0>GN2wA*yx^R%^kSd^bGkym7 zJXfvG4={dA57U{>*r~pFpo2JL@u)s_b1kk8#EG*r5DyS%M=VC1(FhvIbU9sMs=Wax zlAN6(b(7KV2*lK_Zoe81MmkjsN2kghdcsh+QyuVcb>}KTd?-eNV5F~44Z}3Tk+|w? zJkY)&77qk_SWdOu-xUq?scg~zW2k^wY?_Jz zaOA`FU*qwtV9rf&8O6g4`lK2hygnb1hq`(F{Vax_O{U{eV$f0D372TX&>Sw-!2#x* z2jeWbaIGkK{!tFXWmP|oP7r$jb(P-D_4fg4Ri8+Dkg@)3fXwwnfLYbAvgz^kdD2yS zH`nh3)T;gftAB~b;`$5VGS@!~7}jUyKx4v^Cb-Q;hsnMOwpDzB#mgqXIsQEsUuEKD zSo~TOj|A586YfK6{?;nRRgJM-GpKX-Fh}eJJ5+2Xb zUnyYbXAeV$@vws2(1+ZeubTsCo9B+cgL8Do`^-5XOq_$cKAs7y`VZ)b3nB05X>xaS z{hY(3AWtL@%|E}CWzX&2^dP(CN^pKwGeq2~^N6$NO-~OvK7rGv5KMv0&4F@G!#voX z>4JR}2x~6r34_~izzs0unaV#MXD=xu2)doWJPf%0TmAHUmr;&rS=mn5CK~dr1bv>N zKm2^I1Kj*>!7%KH72Yxfes~7_)fw;}z~>qEg}-l4&A?Ak{?xwk_anZCtmaAdPXcEU z75%q;>Q~=aS4Et@Iv1he5&lMBQ?2atH#Ic0dfWVMa;?wnCw{*gjfNwB{wI(0gB^(y zbs!W6XMZ#lj(7Qk-94-l|M=*m{|hBC{B$UpkK^`QU& literal 0 HcmV?d00001 diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o new file mode 100644 index 0000000000000000000000000000000000000000..bd32e748e877f91bad7aebd4e0e4efff1e686b1b GIT binary patch literal 86232 zcmeHw34B!5_5VvI2?-Dq5ftk-AX*f~On?ZeNK66~4HyY1)#@aK2}D9BCKEPA(FA2W z1W{|%{@RLF>sI%=i$-LTE*7m?+(8zJQNg9wJ^yp=^5#2t-U|Uy+kd^EyuACq@7#0F zJ@?%8y?5v0qLQ)6NlBItN!Dm9cBN6vnlV2XA0wh;tYubR{s>_m8}$u!p3FC&iGh5be@6b~{7J=; zugd&Q?`8X=hx(%zcuQJldi~KeI~LCG@kIFaCt2T;$d2ut(jQqX&qP)nS>un6>sUCK zsE+r2s!2*B!S((~(FT9Zg7x_wFZ-KTWuKk@^Zax2&pqdvtV0WlM|94if=T;*`g(tP zy~>(XUr~3===xw)L%@6DiQXIq%&4fHRuc>iDQ=h$tf(&xR)l8^I?}2O);Cl)goCx= zK}Q<5`WyF(X4Qq~QIh_lspkbN!$fT(2IZN-ikUHg>q%h*Mt9)GlfuIBdhx1fL?)FPdvB0|Ht{eEbD%Ba4vPA`yg);sD{ z1&#n6LFG1(j>}i9bLry$620N70=$6r&_y2fAwky`hNVC zYF90_ErD5~X^l0(hGT0hYWWDrCMv+Sd&ms3)5PHUjn(zR25L|mr~+442E7g8`s&*0 z-p2asqrKJCzDy6+d#h?HrV~x=G@`4d)@f=*JR|tEq~pAB z7+P=8In)uRmiF|sD2ZEA|&1GX!F49 zgh~anyYxqCP!U<{Yo$>|nEWnRP*ShV4zcp~|ESN8_WA$Af6n9; zi;|YRvO79D@+XPr=#uv~kk6~iu|wB2fAqkGk1yxSkk$MGEn$>IZ@NvBJxYl?d@qzZ z)xfn>*90$G-YASd&Qln1Ss3}otggkn+RCn2an)2MkuOM>lE}Z6X1COlP#JHzC5PhT zuB^;jU`fl|IuRegs3WWS%VeH?&92iNApx}lq@UszTvif!a4vDwZG%7Bw3zhvM;4`P znZ(0ZSF0UaWa--_Ef1Dzm88Ogw?Ep#9Q@IJs6)wWzJnB^P9>(#THmLN?m=c%(z1v% z`6!W*@RcPInO`kfWa{tlI?F9LnZ`MG_BxFkzf3R7!^n7xEgq^61{?LBjV#1eVWz$fJm07vp`lS_ER*; z9vPp_2HqlM8OF~fsk<;ftJ$gXA7yJryJq~b9E(9E(e6c6X)!Sxzi3PNkmBeG19>e% zcE81IQwGu}B6HoWt2+@1E-)HhE*g!<;9lG`$@UnU*7Bi&k+v_HjPOY*&)Ze5k!kK&Ic z=Y5iHeUMy#NrtuAb2!DXPC1zHds9wan{IuaGK}I6rsgfpu-a4W|1ZPZnAV@-&D~BU zd{sBS{KqYh{&trmakPLYX7G&KK&Ep2WoAL zBVRu?h_0!*6%;h+r8Y9F`9i{qqrY87r;^Cq(V;ZANtXl^(RETw&u<#t5k7c)Xi6h7EW$ zH@)rgH+_*59>4dbwl60BV>+@P8q=fcvx_hOgTHBqbf)Ik@b$&fl!27Z`XXPe zZ{1_WhZ^EHb<6N1)nY4FbA;=!$!g9gdZkoS*3x#-GP6cXXKmg5NE%ZWN6t-`>fbIX zNqwHyx0cgjfALf4Bte$cT8a^0rE5vcf@Pvhkg7@&yX%&%RB?0xb%R9~#?T)5>W zUtX|KPgjd0MM?~L3h~v&Ecg~jCtIS2pOVnY_@k2->t5b&CZ$SGJxijrUb>T4YpD5a zE?>@yjE`KLK0b2KViA3q+lu0dcs!-(=&F@K$t5aRCgeQ3xMfbdHlz|lvm@|qGE_-R zUAed?`sFBdk2aE7WycM0-ywPgxe)_3Bl{j#lzIv(o37LYe#e{~P`S8?sv-IPG{mrFV#Uu{)@3#Z?a-Ihj} zpFF*-h`nA+4ND@M1-%|}Y5&!wEU6TU>YKT1Q`JBfEY*ef75tAIc%4-De-04$bN#7? z`10OMx6Y%5s9TfrI?}BVlXj3Bz3b`oPP+AtXA1RrFQ*LtRl3!jno98{si}njDwR5~ z8&gyNo^HLKdaPwd(|k{)TPxG;o;eQ)#RvlrJgj`-pEAL z`I?`Pm5PU}S&L2*z?A*{O&9bde~hHacBRPoe!ggRxN*;Fo=Uu3TB2K3isHy2<0G}{ zg~!j$&RTMZsKq4dKed^;gp3wHmi;ekX8uIh-Mwa}l*&&uv5CzL&ts^Vil2Um)_aQ< zmmIlZaa*ZqR0uzd8o;+irKLV@(O;^%=}J3zE7g>#II$+j{f*WiP`+)VeEo_x~ab#rod@;qK7?GRX^qq|ZQV9@@%C zTGcXYk0)XK>+5K{jBH@H&r-Qq7p{kY4ub~jOR}1)No;J;P!jooN3>6oXUpEK?G%ym zG1LIaGTeiFHmZD5V^8C)tfkMh3q<|YEw#~5EW;mpu4x+$#lA_(T67AL`lH1(f-3IO z^!deESBxZ}=?fY&$%pKe&KNWG6U?QBMt#YtZJM?RncLp;fxEuw=vWrl-}y559|K!6dsddr+AsjD|LW(N;k5{C(pD!K$4_4Ij*($*QMjon{^GM zQZzeP0ZFOto8!1_Zr>Jn?b`D?P*LZ4Y0?qYyXNIRlxc-FkheXb+~=}PYish9>octt zp22^}wAwwX6#v+hO8D0v>P!}=q^`@fo=KrD^`jKu>zUT=sUgd{E-mllp4MAwl>LR> z@;3Ig{?Y9|YLl9KSS$UX2ssXz5c_bu{$+BBcL-Z?H^FV+8_6KP4rTN0@w z|MiF}N(s&gvsWEpP?#t!Il9om}+{fiNWeq*H7K<&$a9=LC(9)V5 z?w3Tq5$<0cNf{_2TqaZ&+Mx1gv=1%X(1IS%dyG~#Hr&@qs96)KjN!fKCa$9#5#<|5AT^QG99Cy7;{q8omLOblJDZMy?R3SpUH)G1aCvHL&h@=78D z50_;$?C^BKNH;i(t`S`~OjWNJUF#SW))poqd(oH95&b#z+nu>hgRdiS6 z*ZJLp{*)ncn@UJ^<>Z5H)g(krbH`KhK_3g_DcwZv0VLZrolrD3au}+cJMAu-gfx(g z!t~fSVdhMo_2sIwj`XrZ8_7XlN$%6!%X&X~N=K%(+B2BCV(O+T{-r0C@I@)q@hlUa z^%|^<%QCG$^&CNyW$u`N z$N%o*f167#k|XHY^>aj|9exkm|E-i9+Q*YcIXJeD zj|)m@AMYSQw2udiMC233G$kTZi1zVu?jG#+@muKo+jxCnr80M!RyCOVPSyIZ5Q*%m zi!mKL-b{CtNaxAA;wq6YF`pSCg~;dYqQCM(`}&Z$soK{~bV2I|d(lTuB!O}BvsgbW zUhFUOsrEa{eLU6TEUI=-(iFj58>eA$5#1_@%*{52#+2w>xa64d&A;GD66i+Vjf4p;Nnc-dkd-L>G^E?tvo)aaT|N2 zT0YTF$~t@ILi3rd=4**X%*|-tqNmkuH;ECkezj4J4C2Q>C6N;jr>QaNCdWZ3S&MF= zR7%x;V#)rGf(`3$SJJja$kFZbm0U>4Zp-KKg`o(* zFT1DyD%*Of2aRvG_88KXZC&4UHMIfPWzoGm`QMZL?-l;{4gb3`o0}9JaQvd)*;mgy zlfS3uol{`_wXt;Xt%tQo#rvdtzAkt^`DASUb0*nT`LBLvn$^s&N-&9fB6_Hzk;8EH zc;YJtVYu}-K?IK{t-G!lx|KItcez4kFMM3SoE`T2e9n0_$=kgL5dA2-E)O7L z<0+V&w!I`8Q&oU!J%nen@;zwfZEMThT0|Qw*AHku-$+h}^Z8pTiG98I>Q9^B9Iv!3 zWQ8Md!Ah{7k8RXCwOZK~ZP)iBbER$O0Ir8D^uQIIj zMp@R)NqIZdt<6dQqQZRJ)8~r}>r>B^e`Q$Dr40UihV@lSD#hs$E8$D|;p+9NsZV5B zFY?3HrZituhV@t)KNsB6E${XW>(=x>)aLTj)hqew>dpM`;S6ehcdCc2 zjijrlc?Wv379C45u1`&0(5xUpjGzJv&*aBg-H9mH(%&xT4q_T$xAcoviRM7RA@ii3 zUZ{aJJ=BT4uyf&Ftb>K3IVfbcWwzTk3Iwgy_Mw29NkgU+PrbQpJ4bOhI4|B;$*?`Db)j zkliN8D67m$y`MxqtbX^z;ZY)0_^jr4DcNIWiVmS^f|BQEtEUTBJR;nT_;)&O`T;xE zwL-!F(vI~DQImG(1tMPQaOqg-eKy+<+D;Qw3^9+AlasNcVl0&PLe-yJMQ5rCcYAi* z7)m7G572GL^+X`sjw>iuyml;4fvmQ-b-I|m5d@)pUgx)`I5&s|Vns~v6P+Q`Q~%wI zT+r^XXGINX#G@^l{=xVGXH5~IyUZWrxvU5RsX|lgf*&PW4qdQAPb#1t zYM}U*I@?RKU3vuTAjkotF1SHSF_XI1!H;HIFQunaoL&WkDkU}-Tehhc}XU1`S4F( zyA@Aczvh?A{;%OgbDM_=G3!#Tf^`(kI44_T!_AZxo~M-#d)DdGfT9aF{yu5L)V~ zgIWW7jzL%hyFn1a8rb~=ltgFH8$t`X58&s8v99M?AsOZkVz4h?jd2_7_aP2qoKH^= z#GqflqVMvGFR#+E#PN|Ku`db!{+~V(c<#S>BEY+R?cNI8??ej6F9~AL8-$-^xBXm? z*X`+K+gdR`hvzKE!u(+Gy@$Ds2kbF@V)KPIAwPDVLn_jIpqnut;CD)6>Gz&qpNaQL za9Z%1%lzSEF@JE{!J zQ|J}Dd(#H*>}kE3mP+w$X{m(oOrxROmuabQ^t2x8#?NND`TpF~`c3*m^5NfP9W$Xx92^XQXZd)>c?-}Xo^rae&T6NzjqYY`9r^pk&n zMdUWR=4aIO4eqP4;^%!<=%ujOcTsw075-?oH@&*1pWF(g(?%Zl-X5B_-rgf+A#Lv= z_rNNp`fAaKZ=Z#8{LzWjH<$KPAIP2KvMWm-DJPU-=WBn?c{%zxP2}KARN}q%B|9II zdS$Y8;yYA8v7qON^zHUCs;<1}S(*Qm_hxXH6j?EsAR(G^8uu=4Ny{zwQY|1%_@G?q z)|G|7X5sEoFIeekvi_*tZ6@{^6|E}rBOWRXH4~TL8LE!$UCmIulPP70GE%Slt4Cjg zgYJE$pNX@!=%*2`Rzm9@^gtaYv_ z!D5}jA6)@)k$aJW1PW~kRn9HqNksG-POM&gCYxwULStz#Qi4=bMPxs2=+p>r>0(=2|g;(yGUmhHBY_}iHODI-M>=Mf|gB%F6{ z;e7+L@Bt)!M-&^&snMJB7%eKsoW6B55GSLmfsK02{*qNZEQReP#Mm?b9sKro0m|V^ z`z9J6>1jZFTl*Hgx4M&iw>#eB=j=kG_6XkJ+P+cpwePo8QR{*vZ@0f8NtTK9ZDWo5 zHVbwCh+W)IOS~@!#wz_ba$y?vuSy<3lc?OEtmtc>!GAGDcX`eeC__$>g4&4 z(SOfiiht_qd;9*@l_{wdzdq$4qIoc7_^ta}@2AZFHT_Q=O!42P^^NRrJ(`wE@u$<6 z=8d%Bm+x;~({272`&rkd52pB<^uBHTS)0;RDc+XOG>bBZzq6mUB4hrm^uPOHiht0( z@0$IrNRL#CU)h6c?&>jo)qeDD-~5N^f6u`b|5aw+KkUb!B~bj)Os07$bNJ2sSuMTh zUrYb922=dWtiHe4k6-(v_@*qT`8q3i@qX6*+4H~bYu&%kV2W?vr|$=St#9^8rTAsN zndbMsbKmQ0{j>M{x9I=AgDJkaPu~~%S~vAcrTCqF#uCjZeU4q<*ZMF!$kNWrp9CbZ*i zxVq9i=_v1nirP`5P7^zk^N!u4M#+T_0|wZHS!}m|RO+veU-w?xFMa6L*o?vUK`{(zz&BRGli|uG;r< zr`O(+GOnOtly}hNskEbWqj%Vl5krO@liMh+d>8qK4apgHq(qfGdXr3qr1=xAB>DpI zz@FXGm(kL|L4@+bVITgN-z)pFQ)=>AiqaCa{7pQE80{&UX*O+H z9PLIyNt>JSS?GwgL8dL~LAM6d(NnF^@Sd)=zD2A9sW65~$Ms;kVO^jT`B!u?Jt_aT zp7D8FtZ1)^lilP=E@Zg{J;w4WzlX(ZZM=sChr{@v$kREQTn1h`)~kC{C~oH=pZJWI z44CEbWG%-_$L+nz;t^8#NRWSFo zwK9vI5|Or$^2%~cRN8~O8EK2PToT);l1{RdinNPW+9T7ukoNIZW>UoM7|UIy(spzy zzgvZ1GOI{y(eq6X$)?VZwt6y!1)r?ao}kk1iQKs=?Ny!HS(njT;ZwyVm+R{)(E+Kp z%Fq4O#LP55DMt5>rsGA$o4?JBD?{+DM>!)@XW6e)1Q9)yA^!37TyAA8slu;s?5>gs z9sFc34u|qT?O){AlZh?sI78i!^`+DgslL=p_ZO@CM^M}nc{tt914Gu3hIzBX6;tUP zu9xQ-IwpRiW(aSRZw;B+&|nQ=U`XJs2_y87^SILbP-U>8p{R6Z4L3Kg^H z;b&CTGzN)3@eXlr*%ZDZzIah3z7c`AADZAF!zs->lkyy_H%N1H;z{L5-i6rY%X+(! zj*RCkexhfWv}NK~5jv%{vnFYctbtKR#OHK^EaKQu*q4ige`R}L9)dh05O&X#$%@Ky zsBn>QV{J|K%wWwtb~RG~`@oR8iu&*nUoNI`A>9SZP?`Y5`&4JL^JF;|`-W@(S5vN{ zqS8qL_Ojt(qDHwJ9?-cfDpKkW+l4N}#bhR4o4{Emxw(N^6?MAYW%=-rHMtafJbCPg zqnycOHQA+Z`Ep`qTbN@i2gwue8H!6y;(dF1Wn~~Zw=!544p7Te6QuI)LMp8Pj^y#) z+f^a)sp5qUO)LVVIyp+&b+ULd!%&PgnAvhT%IQM7ctLTBNkO}vAID_zVjMg--pY=- z*<~se67#^}`TTo7@g0!^|IQO2>!H)CgQcfd#@E_}UZ9hz7;D&fRcm8P`HsssfAWnR zQEmm@dN6KwVm(-=S^n1C(LSz9a~XekO7A{*7o|tWSz1=Ky{Y!M=kKC;yo+#?x;NGS zw%lEm9ua44(c0`yt-m#U7qzuDVl{YgYW;1wyC|)VA(j5lY`w?qUDS@Z#_reit~Gs9 z>)q$>taL%*l*FDK4V@62vlqQ(_t`nC?91UktGc45dOl6PsQ1Y8({G>E1ZmWo1EW@J zNayzKDi>5@ST#wG7a1opMoW(!Xx+bVNT5DAoqx@>K0vc9`J1S60?3>K74`KM^RR=q zlZ`7m?d1HDK%k*cac^pTq*f6uY8G90Q8g!Nhm@+dr$e6?ywATWLI z+yMWgF#n)tb$DK2c8)cqGBj%z{iv@sgnj}uIAq*}$;XiMR?bxEgEInE_4K=xR151v zjdfzB=3D(+P76e0jmY3KMqTro7Kf#DTt$aksHVCD0;a!*uDhCEuVZ6+ey-Ei z^kUuKkk1?VcQt)E(Q-if57Tv5)6Wp8_Q!{X&QI59~(z z#SZEDH&?o9zhw^TdF|aye;{GJ+^&{nRVvyx$d1KF)Y7~S_NN$QYRT5dyPE!|l!D7> zPt)^yv6KGG3Flze&1?zV|H~*Q(yKLieWO)HOuLxrxlTCAU$4@OXQ?XACo}zhgy}K? zGHat^p#6~B56+AB=YEQqf2fM(=c;Rcs$`JDo$4&FBrV4^+@B&GPspb#5b-QjC#JKh z|3Q@4N&hL&%S5O@Kf5;d=Y4mbCp1ompCld^5v!de~prV zn2pGYp{B)~k~_(NL_LHqSLsUg*|0d zyhmcAiSn;@k-z+(GLc`UW%jaZ-|is)SO@u^YWar!E%DW)djCb` zflsFWd9!J!^3T~I6P3%8m_PU^Zsxx?C3dQRm)z@6{$4JAMPOkbS+yWiHrP&N`9+K&;G~X4x0AA zK*=|Yf2oqsV;&4<{eQ?s|9iWr|9vj{k9k!}ZB@cqf7;eALH~^|`X7=d6Yfg?1F4@D z{-@;V(-@V$Rs-s6+J8SvPbwsa*Cf=c?y&y+%CBkvu}Z#a|GT@W|D`VaukWJ%3taSX zbM*DnevZrXo88Ygl2oA!UM zi~3Jg>D6#cNu&4vx~TtnO6cT2W8RRgS`|n3pRsh9`d_HzoBE&2lPwCnvj4*>J)Pph zLY1E1wZovYWkdH?{S z@3&LRh^c=jrFYUleXFF$_Pc~2Q~#g3$ls~t-?t0-16<@URPtL@dbZyLI!yT!UF6@p zzfAbFO0Q35{>Qt>AG1xSP~E8Lze@=+BqfnW|MeCg*=5 z9j5%hEBU7X_dZyr-ffy7 zoBD?a%Ji4Zll|ZH|94#U7n2Q2#qWY*F!g`iMgKvc$yBKS6oO3skI!&!KM&%CEecEI z$^LKZzg(p^%xvAO()0VM7)<@?x2_%SKbL=Yhr&j%|Jih{*(vw5K626jm0=>e@Ov4P z|4scT6Mx1`{p)zJM}gl>#bD~s_BBWZ`4nClqcBJ*%>HvO9j5-bDftQh!-FLX7s!+S z-_*Y+&9j{J->K5`d$|}){ku_mC;b=pm6FDQ{uRW?)c;&1-_-x3d?|Gf3a7Z_8Uvqp z(ZB9wNwX{aKjET(EC0d>1+@P(x;FLi)6?1iL*qp9UD|)HN^knlPL-bDPsU){zk$*_ z*?;@tQvd6~|ECipQ-9jaMcCA||E1j7P`Fl}?Ej|ykD+-IV}_cR_cWR0FgvA;nEDT* z^iKLO%#o6GJ!Sttj}BA+Vi)j7b*zmp`Y%)I`JHeKrv9(F=wF^IC0(b+A*_Fh4paZ1^l~o$^L{R+78?p1msU`v zH_N~E9GPCcpDv@~zo~yYrFSa-&-_wSj!Mh=*VAF@f2E83jY_^6#wsp}>jz6*l6}sO={uBrKvmN9=OX=BCrv0RPs&#AEV??Qt9={t0U@sHqBF6e>44ZmEK&}Hq+nbl76E~ z&uumaFJ4gm05XV^{BpJMWZKV6KglKia+Q9dA7DA|c8Bs`NW9GQ|HwstdASt4EBWuc$oHQj>%U?n#$lH_$nQ-RoGCq0oc(`! zxr~mn5gG9s*O`>wDgU=A`F=&u{@+Z8ng2nQo-tGY#&QBFXnJ{-*#4ZM^*74TExpO_ zbQk@1D*bgmW&JM)eKbB-$v4Ysd%4v3D0#B~%TkdxXYdl0-X>6y-W4VyuXTET_g5;t zk$tP5N`G57O)1Z2{;zb&fBLCX(t27S;=uWj(xKDq{8RFTvLnc9ox%U@VG8;3h%OPnczh zr$0o)_L--*$yN-H*WYW?VZ*ab@g&f` zB_fXt`UN(K{k}&$xwCJH$Ol61F*Z2bj=@SJmHB4^MqV}@*_j7j?md-jfAUM)FYm>#I8AZmf)in1?W1S&k6Cw>dGUYc*Nhj zNbot)2IKjhWaAj|SYz-~#BUOOVt72ClN0C}@K^;2_&UKShR5?MN}!i~#wOq&2tF}9 zo{v9)Uh*k+!B2I;OI+{?2{=DjO%^N0^45Jo;jwoKh=I9+zSIVuwqtBJUU^Ln9t&$# z?7l~=bjGfA%wwIYqj6`C++`sS;|q^9NWaL4jAe z;FT^owwf^#k5v`BfSAXc4p*_L$EuE9K+GdnJ^)Zrk64k2$0t%bCc&x`&YwJSwKkT{ zBUT1t*E;60&ezenvq#Lt;~;V2v3Q0YAATeJDu(Of)ICDaW}A479piH0nQmh6h#6=+ z{j*9PO;?O6M76Hvqh_KC-1{a`#E>lfnjSU(ky$NIr|d?8-iagTMW9mj}A%s3E{ zagTLbB1niwjPMh0d8}U~f`Xn$#PQ)}vZv)R?s`q&-gsiV+NkJz8+W!UoVxS4@UFs# z#G#h8L*ZtN_=&>J8u_`x&76Is@CJjwN6Z8EwSH;f{A)X$-|G!r{xr4 zUMqO(Ckn4akm6p2Z#3{D6#j^TAFc3o!*IC@UuNJV6y9p!qZM9C;}i^q3g2$vrzm_7 z^SA3Qk^ivi7h=I>geAMd(Hn&=Ze`F&v5?1(^20mZm z>amG^ccH=$HSBYl!iO685``BT_*Dv@V&K;){5%8yox&Fw_{{=0K+^Urfg8plyiXcu zMf~GPT<}&I0cX6$_TeJLfM2Q9#=iPCD1b9v1h~aw>?%y zJfN;TR(BV?M*@C0nXEU=Pj$aDmhb^EKh>7~oeTac;j~1R5PDLUobX&1{8ShG8W;S2 z7yMxt{ACyXV;6iMT8MDc|5z8igzy0{f4oLnO%j93;r(`e4i|5J&$t1$GPAWT<}^KJnDj9>4M+qf`8(IA44r&_CgVzvO}^QO8ZU62eI?_#DD}!+L^#|7o?rW9tU`y`p_+;?f(| z2lV?Q=L)>SmaE@`xr1;geO9^PZwo%tY(AR*v9z?^8`c5zdma}E{5+ffFcn)ucz>8D z<|zEvF7$T_yvF9E--FmrxRd?|^sA&b-pK_1BbZH!uWot zyWhnTz}6(FLrllmE+B9}aYKl`y{UrBE_L>Xc21j8bh7b*6M3f_EI7#D!#ywTP3@d? z*h8K!+dDW(*u@SM>~9YHh{bKzl|Uo?wktHIXU5BN@&C9@*IXPlch_6FvD$I0oHk-h z$eW|TC)8Op?`C~5?kColJ=@mAVUriifW7rbpp(s9N(yKzjgkV|tFxqFDF35PAxjEq ztHqLn;ruU;|IwzEB?ZUvzmfdUCzFUYyon?sBB@WL@QK7ek~bs|n2+ z7YrBI(l$f1LCe_cV9m6mYNk4s$VL>+mAKkuPneT%pHFU^R8|?P3;J>k>VveEt%Qn7 zCzJ(7R4abI9DlH)PVIF{cVheeSiGMs?EzC=Nl63K8yW(YHPv(-pbd}etg8B8(3PUG zb`I_P=6bu+o0T=eirU1a4Pu*EQlYcELNmLxVta$`aYv~NBlnCEzM+NH4RxW0;JBL5 z)QXy-(l{&X?NqHmprV0P4F{?!s%sowo44e0*#JnEJP8}gyQ0 zU1S~1qPwYBE=P>7m>KLuZt3jOv9oE%$FhLquDN=%;@P}iF$qlAidO6rrhW9d;)W3K zuynk$G`z6Ve zi>q`6K2gzZ^^}p1(uPj_&T|3?9qdnoq)`wnfiyr{lDR8N~`2Vxty1r&ef72IygJdT(YQZ0}6300AXmIcEG4|^BUvZ1<- z%*`oksH~{t&3U1H=K%vG}2PYMzkxQ;|_Tf$WCI@yb*e9aWa23 zd7Of6d$J(WmFV1z^j9<#R5VVXp=zVlV%S*P8N0?VXG0He6LJE!K}78*J#9cWPI}kc zKpiiyGGirJV`t) z)7QBAG&Glb`FJNSt~FfL7>IRscUV=OhRM39f660q%%$2fpFx=GBhBJ8k(FIEomA6I zdNFXaYpL$e?YUW^T$!y{o%Q9J0*k6Uuk49Ug@Y6|R(IQ*ow_T%H9IyfWy9zfFD8`b z^Y9@svWyy$ig06nkcSW2UJ1XF;>*+7*T$ALf{m3(%mrUiLo=lbw23H+<~*yePIjD> zKBhrp4&!Zv+McESc7#=kH^ zdQsHJOljm3o|hk{0r=EL`n4IQsXb^rj!d;nE7=vY^X^6UVMMi9*RZ_p3^YV^ z*KQZPBvZ{x==8c;Yk9P*cC@t@-Dos8tsxYcAvS@gi^{nb0h%-NIFW*W{**%TTj=y@juX^@iGP}nDqM1O2%)cL({h~F$ELXZ;tRIj#@f2y^o10F#T54zx4gB|3xf~7ox)=ECH`dut*yh?k`bje5{FGJW zGbql1@j5y*uAc;QIo=2OJc@HL`7acx#F4*#1BmI*r$h6Gc{B z7)So}c-zKVXHBo4Uz+^06nzGr9{~DXg){x103QQ5+If<~S)T*w&~oW9tq3NcK?-O3 zARU_iSimt~d4M+n{TPLt`QmF1%%96z^Y4n?xIxwQZgwjm8V+o?d+5;gr!q)^y3c7Xll8KBqS?=ij#aP03^13s1F9GD() z{iYA&Yv|B+`%!;6p8V1N(hfiRkF>*oOZ|20M~j71rkx92@N)sj{8j^w z`3(b(`CSM&>iJ8+k^fDAqrW`_IP!TKaP+rzfTO>?1UT|}2XM68dw?T7?s037XK4LJH+J>V#J0pRFwivZ^~O8emrfaARN9>8&& zyc%#EA5LJ$q`)WC{|vy9{#?LuJXsAm^5OlzIq(VfUko_XUjsPO{~mCp&lKDx|5qrk z?QxWg9>vGZ*OR~>^Tl42%KNE1I4*`z- z<^sUq13rrYM?Y_I!LJ1z?fiSd-v|D;E1XYb0Dm6vBLIIx;cVv*0N7LH-aZF6Xq}S_*T#gseq3OpnF$Jc_c7C!zC64X< zIe?=+GXUR2am~LDaI_CUd*#4#aovD@l>_4+(xLfeKzq0i@B+ZG9he9>>RACe+N}z3 zq^|`W+uPZIBmH8)vAw+!aBOey037)|3OMTdB;ZK@GT>O>asG?#EzWJ6u^l)T z=+^BA7U(fwIA6wm z-3s)`|9-$RUoQfV?U?=@L^EHT6+Qdy$8_lO{S5eE{q-;d3Viy64o!aq;F|%*dG{8; z!$7|k@MgfVUA+@<949{kIOca1;ApqMDBR5NMxe+1wgZm&^{0~36!-UD%OjIM zHH{chVEZ8b!GQmZ?&*9TrEunRDBwQ8D*zt>cnI*50AB!jvBFuO`v9K=_-ep^4)_|t zrvr}kA;6J-KHx}yDd0%o0yvKMt^pkBmjjOc?{dLcxZtY+UjzAF4>;3^?{9 z?SLcwkK;-CTrVYwj81|5a~mDHUZ`!n1>OeuSwN5Vx*Bk7XK>tz^f+#O7x-TUe2`x6 zzsGvwc=C3j$MNL-fFqx$0Y^R80FLx;0*>u7jvH}2={9cU-z(<8`eS|3zkka(+Ib&t zkSH*Y#s=TlEQba{;dd>G&*zz4^ZWeVs122LZkk?9d-@q}Tg5viJ*t9>2~aMZIIaLiW(aHQA!Nt*e>aU@>9O?OYNI7u1AU%%vupRy`#(Ss_j`tA%81%&P{@L9`wnV;=Pd~ts{<|1Y zUPLPBavU$!N$~&wwDrjj&~ppu-#tm*U_aRk_)h@e2DtheGLc{G*M0`{Sg)r6z7qK0 zxD@I2^DnMh3(Acz#rS0D*#9SzXp60=yNaNm@gccBA>qkJ?0DF|3Uf*S`Tr{>jXk0+-_^I<$Wd104IW697j(`uUpKe@y{;?7wi`68o>GfFAoV z{d|h`M19=epZQqvG4)AT;|k`3`s@oh>VxAS)MqQuqaE;h&`Pl9zg+0QQaG!N{bLVS zkOH5ud~uwE<$EB|qdvHvhUGg{(X(6}58(4A>>p19{y5H=2{_hw{ylpRd}^aZ`_*c| zQO_3vN4vcOIMQzd{9WMR1~}4x2{_I-el_6R0RI!CXZj$C=ZC4~~0l0j~i4 z8v)00?}dQlxc4%JvpzWPy%O-%!2f!{*8qMq;7I>Rz>%K!cjv%zk^U*bk^awsBmE12 z<2dtGz>&|pfFqxOyWkywBcJZ+LVck>`eARtk^W%7QP0BxNBRMheM0+o4B#s%uKhe0 zaIAMD70!NmG0^*gejVVYfMfqP1#skF2{`s&GXY0CF9saPW7hzV{Feic`Mm{jr2nJB z&HQrP!h!t_^ZSfIC64*!F$@Q$NB;ayEClEI9Qm9A_)4HZ4REBN4mg%eBj7kr!1vA2|J~j< zy8`&2oqr8DjuUQFIG?gXfBoJ&C}$7n1z!T6 zb-)Lor(-*V^9a;uKQ;^nK5e2ym*ZgyXSp~I!S~j1TyY%m!Ewb{;8Owo#{-Vzhe?3r z_yONf!|_8U(Brsej>7qb_2Oc{u^;>e;8>3O_Ye3s(*G9dk^e1#BmKRABmEyy3N5~)NM~LJ62>E~L!hZnep99}U|M@oKgoVUQ``ZsSPPmSA;9%zKCJ751 z>*;NPqaE&1IMMx%27GxET~J{BOFFckuKyOVLw*ijtr)>co-%r~L_+!8y`Md`B zJ3#+A;Aqc6XrEE;X@H~L0N^NhA>b(YF2J!Le*$nU$G-r+67*jWIMU<$&p2Mf{tM|p z0zNoi!hQ$GOMSRtDVXJ}`yIwnPwaP4?ik>M{WX5)h2tfB{~6mu>|YR{0sPU<4S?f# zX}-eQEl#FG`=|b%i}8Vg-wk|lyriEeW)Llom-PE-jNb@+o&`QT0RJ1{Xtxc3<9O)} zz>yyN3&g(xdbEE=Dk(vMZ{v6g*V(Y29hxS{#d9!OHqd7c>8kzb0l?8eTU~H`&kE_g@}3pa<8wFEhkwV91KSzt zzX2TS2MFrK`u=Uk4;K?pZJ!@%{ID4E_2W9jkLwIL&cS{Y$2r)3{b!h(r(|yIztoK`NwqzY3Co;8KfQl8`l|{!Jq#Z#tDlczdR=Az~i)abm;NY zGYnE-9OvD=f7tHj_VJ&&V%!&=|GP-em{tIz7Xhf{h>+WY>qyl|DAx30{mg%gX<4ZDm;T| zas5H>tHbz>z~_13gX<431CDmv1URlgYy%wWaeWE#ZtSoW_=NWF4LGhp91J+l>stUv z{?`GH{($TMNPn}UXZv4Hhprb70H1Y$KMpvyC%FEP{GS8*O~B{yRJx$Rw~;;vaMXV| z;7EUh!dd?&I<)?$0zK+q1~}?}HsHv=3UJhaci&5oDn6_yuIDTR{3_fZvmgxK>rTlxPF4~H6i^MF7)`lB(5)I zrjalTtPk?<2RQQg0*>^90Y`ehj%V^8?Lx2Lt2gOS2YRfhKLdOX)%6dfR!+gJ{)e;XZIANBzbj9W=DT<=rCIQHXZOhEwb zss`i=X_y( z;kv-Vtm+EP5%7=M}P1Fj{b0%;GSsbA%L%>xX#y5z_DC#eu4d3 zDbVw`nVL^I;HiMm06YzFZlgGGIVJ%KwWt(&0a^Y_TH2=Q}RN|Q5=K)81avRQp^^DM=`S2K(1M^=;hsJpgmILEG zK<>W53>|K`@=>$ zv>h%4KIjkly)F8~EsEas2mG!9{o!%okN&U*aP)`g0OvZZ^?Vs{wA&jBXMNa*H9dZx zi{*~*eR0`odR%wS0=zdfroiQ%4LCku#`gbEphrD%{WTZT zt^_^Lb)laHIQoy$DDVmW2fvHKaydrPvp!4c(DnKR;Di1%4si6J zGXY2cnF=`i&v}5O|AYWXJud+q{pT{kkskM(MgO_cg&x1(LH~IY=+S>(037}2O~BEA zwkn+chx=%4=TCqh{U<$@h$!%F^dJ45j_E&xfFAv4DB$QnqX9?%84Ec2&ji5H&XX0+ z`n1rY^ED0V(SJgKqyJnCIQq{o07w713h>n+_gcVF&)We<|G67*q+bCz`p-JRk^W7< z(SNo9j{bx5S@fSYn8%_2==m)B&u5U|gMc3WM}H4)`cILfH~k0SCqe%?8~CIDQ~{3u zQwuoy&uqZaZVMF7`YeTf;dkHYKlt4@`p>PvAN>cv??(T54Cq&b+@}CXJ)Z|0{pV%C zk$x-S=szCfp#K~IIMNRW9Q|h~;OIZ&07w5R104P5EQPcG z@Y;p;pK72-|5*Sy`p;DgH~r_gK#%@&8{p_a4*-t-^Elw>KhFS;cKfr!S)XN)uUCK` z{bvi{=s%wTj{egDIQmaFHY5cuU-X}zfTNy=0FM517~n{s3po1EXuy%a6mayPDS)H@ z)BukDGZ%35pNkdFr?2VI{<9S5(SLpqIQq}S3OD^{CD5b){0(sQpACSc|7-*t{bxJi zXtx~-XMK3BN$2YupkD`gMt8cPz~zqqa{%DzKLY_r|2Z0P^dBGKsOJcUvs(MWIzTbd z-%Izj{uO}Z`syse(LRlUqudJ>&i07_|0vL-eQp4}H|TjQ;F#Z4F8E&oUjuSq0UY^k z104O~Uw|What~rkfy)u;_W>N~4*?wMeSjnVXuy&Fbik3m0&t{1A8@3<1aPFk5^$uy z5pblx4{)S^8gQh4-UZJT)|B?-HE`{R2Lj#)aJD-K_N!_-G(Ga^3-nCOfgtN_5tIK^ z^DOWH;A&bg)}OJyDD{Qh{eVBe%g2H1*G+V2eFiW{f%V-V=(7bX^?6Xm`P2_^{Y?!+ zUcetxaXt+KT(40xg#1@18a^TaR=~X~&i2_|{+#D4I3We(ufMTn9Q9=S-z$2)$AK@` zikST8RdFugR2Apb7!_w+4W$KA4!9ap353@)I554c%HsMF@n7OSRh&;-0Ph7jx4j&g zkG3sej{scz0ORF=>t|<-F9Cdi22^+i@B=hRXZ^h}%RLD2&w&15zz;?hXBg1y_d^)Z1AII1IS%j-0Urst{yvEL zi~?N0zrpwkfR9lPALAziUJST?_R6=zfS&~P%K#q(xc=^j`JW8E_X$VaMrC27@WZJ||Gug?c zO$$OG4LD8%WfephT-g zcjP&Ro~P3DG7HSJv%@2nBp^xU8Y0p*@uTU7IuVvvMah z+sRz*3y*E`Iho534sS2}YUChV zI_cnx&e%uxHXMAx8F`}o%7za$tZTSx-R_yQn?Ocp>ue?Dz`ybPDf;~hvP?geeU~>} z7D~U}&=E@i9_@S{?W}Mz@7H!-E$l=K4rYx5E5^Z!r?VC|K?FIsz;>R+%m*IV{zU8kpk4SDx$yJ?7q;Y_qte(x?7ZcmUU`|N z>*v_u-f;RIWta3I`j70&`cL~43g-a0u&V03zC?E{vN_Q`7>^B{*B9->E0S3M;aFEH zvNaj)uj&Cu==X)oLw%`OvM(BM?v2H}8xw-$2Y79Kft?j#;T_a$_u|qTR80Y-2PP>uyZO zy20MwXndeC+SL=wt9`nBu}n*yOr$*1SUNgBxE{){+!;NXS~~M9E6Yaq%^cZpFDu%5 zt}d|A?>T!K%TY?|1SexV=^r|o`ckM?rB|*yxNnz^>~_XxAc-@!SU<4IT94iYH!60w zHuk@0dTJ@OM} zPdApP%E*kFv+JSVoCL%m_XkR~lW7DejHg~2cFM{pv^EZ0n#I-in42t4=5K?qQSJPw62 zC(Z{#Co^m24jkH?43zJR3MfvW7<6_(3Z#v#8`oKahM9g!Mb#~oelk4P->>4UM&C{~ zhcbixtN|z?qs#}Snk6%3{;JWRgSym*LYWRw+G;Ab0&gF9GS~CJR*9CoRv;Y2l~k=I zvjW=aii+2kAVa1VURo<&I~!g?=_lBfaQan6eDGk=NtHXnuMZY2{86#>YS9wQdc9bc z?a?X^=Wpe4l*;3DqkX)Nl{T+^;A|4w2DA^TZmNwumvWrU+6pX_OH_@RxQ+am66w}P z>Md+=WzgU%LD=AzH|+XTw3o>=5YeXI`U5r*YA@%=_Hz0J?d4AJ;uA#+-z>J?DT0yc z;AGp&k(Up2X7674)cuu~kCRdTT8Fb|rJ7{zSy>9T8S3&YfZ+Vcf~QYC^)yF*>;TN) zJMby-^-6eeXm3+326}oYy<0^?nV=QUbe4v2ArYI~C{j(eY~=aMDb3fx$DN zCpsnT92n1?^oua0uiL$0=4?Hl2M!*%Kkzn>h#>61UiS>o;S6inq<3e<(!dU*XvIvZ zQ?oDJQ)F#{?0>3gD#X5Bqz6)Rft)OMg`23#DI#({vH?IUdgqoZ&J@enwG`|#!XwQ`S_y`7`S(W|`dPGmA z@-6VlYo6(?f4Qdj|HYaUNtkZXa%yeiPX6rH~>mn$AKTom*>UHhFu4q z6t4#!7Cpj&`=E#Hm_QpNaH7(CWA(qLps`t#?*nf_EXxp!M_Dn1k2Wwsg@7Y@ly|jmpxcM<3uwX z2|4dza|ej?0kn_OBSw00t5(QmT(rG4tZKlte?ZDpxgIQn7d792X9{FZ!Bo~G%6b&V zh02QK_-rb(knclC3*m72KB3vH9TVtFYx9e*5&E7z0zSDSjJrb--UP{{feD-Xk<$9R;0bCOtr6J(w(a- zy3VZw5w^E$TWM+6jHBbK2I{w1b&^LOJ|fgIzLv`z_!h) z=z4gjlKR=hG4<<1RX6n9R@M4}0jmmus>s@w8t4TB{?_b|B%zk-Ep>s~=E1(MRBxiM zJ+`?&4!=nRTiODV>Lo3SzQ#oVw&?nJEXUHGjP|AmLT%NNU@+KJ9o%A7C1deuo{E~@ z&Hdr(8Wzh#2@ZER(HY7r*dhun^_+Sj=d&&;9#ZvHlktrGFE>=UX zl2hB3O7`|`1VJreZ@y?S0yF7vO(wvm)HW8SjMy@f>XnD5dO}5JZWCB&SfYWdI>@|u z4Y>Fs;LnX=foeHwlaB+n62zfg`$e+_+x$?7Qtn`1ymwP9zAaZ*atg4ltNNqKR8_z) zd9u|ipY#wUH867L*PV%U*XpTID6rU=>jZiQPU%cVb(tJ_e)P=!ZTZh=A;?P+6IS0pyn z73)t$pwo!Qu%zER?Rh;#f!dltlh==;@4XM+D`O^hNnlY2{dWA`d*CSPK2(NR)34@# ziVPnW-4kcHv2X}2Y#1%Et=OaMX6`<0;>ed9HYe50YYtoN#92}DU_LN;<*t(luu9EK z>ViXhOGvO4#^aW@2u>@OG)KEqiR89Wdn8zwjHL#XeUVhK-5)Xf_yQjW{Gq;H+-1?b z9p*RSty)LzAb|l9I@9csF-hwuEiLCU_z;IL;r^<~%J3yC8p4stz~K5wD6)w*jYQz{ zTTRotx+p8XU~eRvOh&f>pl1S+wLFK*4JV6mT9rRK1Vn~{f%7Ag*44rG_A4UI9W9OR zp-WmK=q+!FM>yIZfubsh9_5dKRZmuqfUzkM+~UcGvt~8jgE|7m0V8qyWi&(2 zl`c=uOu~Ztt!DbJqj|Mot?VQRvEf8gJjbV6rUW-#4wLu|RguWXp`i#&hX)d{6RS71 zEwTlsdR>Xln_+{JRn?bB#i~}ebS#9b+_j1LV?B`#N!;61wK16(?8h&aKPudMtYsbV zBB7oz{FcLj-_on#Qr}YI>Ba8=4F<{I3Gb8TZ$)MZk{|aqPL^MN`y2cl4}-rGXfa6r zJ@7tR{YZ;J^7p~}Wcj&dC4c5H_=iwA1j*kG?~~O(jLZ-u|8?*_S^keI?tFgClgZC} zTh&?_@!(^Zh|4H_)@PwP5JQYU-Lv>)`Ed^|=J81Rah(J8m*6f_5m>*OuW~_y(OckB z{04qEy{k1sk!JFL4AR)Ag3Q`S%hFsAuszI#i_5cuh!4QiO@BRt5Y)P(j;gz<|EGYu z>0fh|W|I1`pE31s06lK{_mO_Jj;TedyQx14bZ+|hy68W_MgQ}pzgp$iUft zGSB*n2mj;5|E9sueEfWe_|5t=P8CwE%?cT2{(lMlZuxiA!lh-sNW577xSyQu=kmV< z>_l74dU_cNok#rqFsiwA5dd!beVv+v9%}q}A3&!55!P=A9wwn^w+v?ful3MB+^MYL z{cEC{qLTvI{}le;&M>_Adj)ZuWnoOtD*svj1zuZ`%I= z@gK_mhk?<}eqXQFFYU)M+O&V+GOVCw&-hyMMf|7of}s2}$Ln)*)zz^(irJPx&4 z)-3(V-i_*LZ6kiue|w1^f6J4>v_A#>ZvJ~9uDR|I_AdpT?qU;t$x#a zaer*N}cA`_{9x!Ql$29O7pA-{)b!Uv1~HtTPRM)BewU*k3xN z89Rv|?Oy?xY5$LaAFCP+LwR8h>1TRQG~d7Pp}&XpR}drWZ-R^Y8UH!u-}GN6={LVC zd?b$_7eYUeJ~jF8CjNFNq^Hk#zsG~$I$0BT8}ugsNzhNb=^rM3v;0i{RuBGh;-7yA z{b>(=^|1oHXB~q7N#eH+2iD`q4g_w0`pvR@9HHkp@Vm92VJiPlqQmkJ!)2ELFFf=Q zPg4JD9{TsW=x=e+fBdo9CbRxOK>FEU$_95U{A#TPek^~}e_s5iycNLj=D+%FS_QWg z^dFu_W`4$dNxxZ650m|8Ycbh7+KPdnN#fUN?*3!q&mlU-e2m{j{6_V$_7ndbhGW@& z=D)!s|7$4!`$;h7zXLAj=ltWEh@nD>ei1)bA>0A-Wiai>chh#He`C4k>c`Fz0`}u; z;WG6@_vNa;6Bm0STxWFHrhZLTct^S^)|&?lQ&1mNdY52ZMrMh|wrDbB@Yt&7H$Zr` z)k;@Bj@@aoz~#D{?Xm*CLD6IB=pfg@YztSC^1}=8S}gF}MY3&CXD%>|+T2MO;DwcU zIXJY)aQjzZ{`cM{>CG1Tl?1k^hxvG}-R0xCdYF&r+C@H|Yj^p0SiWZCwuK{pVX&>% zLJ$yJjj)ADwk2CtF5OlmQtlmNTfv`}OMi8Z!cQ*fDX%9Sxn#JJ@P!hDc!qG(qq_+2 zH0W<5JZ<2gCOm22|ETbj)P7Q#^f{uJ{XVAOL-@Ut7~)?f{80mci16J8{vU)tYv7L) z{v89~qj2a%jWAnHrc|Plg5}#*fFWRKXG8hPHna@4U;~F+uw7?zC?6J?T!LNr)vBm$ z3l=3@f}NdxDU9Oyy$3!Ivg$^^%mcp> z@VWf40+Medd;Z6R-Ufr+~0@u}1)Rv-3D8+F4?pWjoLE!0Q!$Mpizrr(XfMoBU3|=ZbNe*T099oZPs~ z>$)!kKBpMJEOg-cEmk!*`FIx44R7$kZ}7ms=z;&*1NTD}chl>5;KLsHEgtyi0G}o1 zA?%;o(1d1*`3A4YrWKwW?HT`-!WXkU_1=DXI~JzwbHsS$CyKd%&l2;E8p1!Q@Z5ZZ z*D;3yck{!I9{8gk`0thc+&tvFq_+Y-A>8CI1N?X~ZbC7s(BnbB%L9MF1AiLuxniC( zkK|8-PZu|P&H;RunE&uP-$oC5Tn~1WGwy-^)B~Rl--B*)?)1Q)@xZ6U`ly?nB_8+( zfY^;bhPcZxmGq#u+&1vhp7?j~97LYL_u%kDzCOJbmrqFWF^;?q>9FN6d)VSIPCU46 zXneOf1yWw*VTru63~n||uyN0ge8LTaF8Ysfhh_FWgPRRUDAQwmqML?8?4WdGIkL^E zli4C0ZiKCg;YK*y5pIODG2zAjF6zUb%`ztOy4qs10{g z>%3L_+v16>&{yRBE5BebQe6yW+5OzKPhA-ccp#v6Vz+g{NvuFM{69Q6f~KKhD{T9& z>xGTcN!XAY@H??+zgC7Rxoyt5Z0Fp3#N7zxs`|3JKuuFG{0qN<*vfcfeKa0y%`=BL zja!jObO26iq#_%ly>T~F)WIQ-?Y-KCpzQp{IQ%0+Jg?=cr*QK(_ET;e>3CJPHssvG zjX0Ofx>eClu?h6HZfR}af_-|#^*9-yE`mM!K@?iBGnsPll0e26a^MN6$lC6Bt83<( zbaJ7hkKo`Zt!kfS{f)2@NFhbY;K~ZKQE9nS@Q%*+d#W0|7Yw z(40(c?nrH@Q?;MDf~^;K;ZcPEp0dzGZTq(Vm~LJmz1klf=!*8^nJ&?s8Uy)4sMIIj zPi~oy&L;t-K`1L2cTo}9E`b#qk+AB-4Qst zGYGrTUAM5i)yntie3zT*qjRvzUDMGx(d4E{9b>{SuAniy_6blgRnsn@KI}6|k+pqW zH&eCd+EWdugY#=nsL!Z3x@W;k4BdR4?%&~L5S&VlLA&gN>MKW{Tr(&bcHDEIGH2Fv zx5ik&?sZxNoR0De&T0n&(3|j)Fzr+|*fOMglo0%9k0|EK)h;=Rp#P8L^p!R*JH)GE zL>J~f=U(2EJxE2_U!(^zKB!)(hC4Weuo}Oa@~VLDo7Ln5{c6y=dyRYfT2olC7qXf= zP{u=|9uQrNt+ zU`OUEMjx^C zU_Rh%RBBs83jVFY`a$|X3F!C05;j^EKz^@O*PKXp#UOu1zOtt_+iJitS2ZxIbq^#W zJ?g+BymSpkBQTK|>P_YLlfd$^wGOV|!GF}kP)F-Mh~v=%#(Blwr2mMZ$2Cr-AM?O@ zMb4DN>#ru>Ddb3dMg=bQ^13z3k+@&b%lvxf>q*P#O9O>i;&wHhwSFSk=u{!XGd<$qk@ zK_UMx5BZ-H^wR$O1TO9WlE7C$obCTA;pm_B0zcaI5SF)9K)svbVtaT83*uN7jK5p< zaQ}w>m+j&*c*kJsU7%rw{~g5Ho~s0oeG%jR0v{0gzX)8?KOk_dV=U((flK`x<`^ghU{k%coa(*=|aIBLUupP;9uuY*FAAvZ_m)|wA z{o))91ImfQ#q`%B2m$dOa4~)hf)LRDPPiEVG{i9=J<4Q!FM<$?;i`s<@$VoA0dd*B zexOi|uY@?$%kdHGHsik*^iuxs1TN*<)Q(WEY`-%^`;zi21TN=4K7q^jh;tYW=m+U% zIgh##(%60<#4(ukXK7gZ8NZ2`o_A;O)Z3N0+(2L&$u{}|z@SNeaqpqKsUw*vD^`YM6Ta>Tr2K>H;!=290StJ{L1o`{`|J0)^<7&XE`quj&cSB{<^?FA@Fwuew)A#3S8L_Z+)&JnnjQzLL$f9eD->FWh9>q)D?rQg;FT-K9LflK)t3CH?_Yf9|TgrJx8 z=Q@GQ`ZGp2`UkeWW#!y2=x-PJLjsrW_fdgMJ0BPFFA{S03VP}P?+aYY`Gvrx|9>TL zN&j1cOaGT)Mj@E>_5^`T|DP&wDId>qU_k$00~h=MY(X#mzf|DT{|@2!kpAxx^wR(R z0+;^B^CK8AU((KN2*(Gm;jo<?mCF%cpgrl9(|K|u?`rj{bY3C9lKMbP8tdg=e42weJqzrdxPuM>{-M9#-l1q2MsH!AF}KmYDS^xR1G&FoK3t}x=yJaU;_T;HgkyQ(8YAO#2}d=b5;(yYcK7G;3p~pyj`#+F z^Slx9K7sovj`&7_R|>pG;8H%WyK<27;|#*nNAbzZXI7-&&M)xvQ5@^lREp!Hp5lm? zP#hm@1LCCuzmwvKA0zOm1%8~s-x4_I9iehG5CY0MLB;eZslUD^)c&0 zE4pgcidBn4b29I-I#T_E=`EqozP`a^XSR26Ak@>@+n4IL=42Y@WST5cHGeE)U6;uu zdi#e4)7iv8XMal72YR!KOe&d34i02fH)J(<{cvwORfcu| z^Sjly^QJxeV(l>k@>Xsldyeh=hHDR#Ex8n&JwnZP;Zn|=Uvg7;f*X%NMIa^O7r7?# zsmR*MnwayaAJhRO{!9%a>zuWBIvsaRM)wdkceZmAwi6u>j&(rT4@ls{R!ylb<~$Z0 zYXfZOqvP?yH0l>~ei3(G*+*m#QimTTU#5OlCT-!Wl?C10~Ae|QQh?!2MtYh3Qm z^LFwu7{sc64$eHF{O}zv`)X)c#y)!ijl&+@zwX+|XCvz)pNk~cKibnAoIOSZqd|IP zL#P&iTC$^iaudPaxzP6b?RMc4#FLdO-t(7Jr^mn*4q5i2!KT~>6oO5KAJh&wOGofnvpJ+x0h<kvKgD`zv7L0CJ-MWo z+U-el7i3H7bskcA^r+66pOWT8kJ@=&4R&E!tz8&CY8SR0jytJicD{~DlsjKsVPvsM z4wCS~77R)HU%msgrk1!Gq4S6mmzz+Q$nJ4_iE&~9A5?Vk-{W_awknDE(rAxfWo6HT zmPf-++RihIespWCm7Qf5G8n?PqngLodOLS2J4@9j+mto(TSH}Nh$K`P+=k2wdlBad#|Yh`D~ z5w>)QxAWU}lU=7VVMp%u;MfX^w%hmb2IIJMLdL0aJ3kDKU&>8Hg10?pgE&_W;%NBw z$mrWu!*|CE!{f31!f5yq4eJo8TSxkp^wwI(oj*VU*lnDeSv0$AF!yI7FGMFGX&fAw zXo84r=MgNo8?YKnVblX8Id!C(tfZEZ?$x&cp!u(Du#+}y*-s$#-wenmm zw;6YF%~kv{R=4u=VMIo?DZ<%z+ev8XM0XXNm;m0fZ7+9)Wn<3LkfAO9R<%#{Q^*L8 z{S$PLI?csfnW`Pz@6q|Mx3=_LbWPm`D^O2 zv(N~%i4N3ME2}HJU;&GpCcp*ivH_xdQYNH3Q1#W5M3 zpe~s7gPgmI#hz>n5z>)+E?(&0m7N(GxuO9}<}P6HD7eBryRa61M_z@<9(P`4ZF3XD z*IF64WPQJ9VWCcjNh0o%DPWYj5sh6yUfFWRnVM4c-diW@wp zKVFpfjybQ<5$k7c^6f9K!#Yz|&+U2z8#_|Bov)eGNP|Rl4o}#Vx!t-2#XY8&JB8X_ zT`R@h5OL_py+o6-&BA0{Lh&p2Ty_9^G4VM-@*bj6JU^GG46+MQ$Z z!nY>Sj#YaHvOIss3fpR&9Ki?pyNbJF7mhpMB4%8*M<;5~iv|K7kN7&-VDup#B*i}0DKMVk7~&2_(s8ico_8jj3;qzy{gBY@ z`^l`rImYt^(&pV=W8B?$9-y%s6)`9pq@842=ph#G<<&m|iDXhzQyT>#OSsHs@P|rq z#Q4j?DgMH2h%G+}$ma@rgh{0{g9Dw}lzJLrGHdx@sB<{GG11+b?F?=1>>EyndIv)3 z)b+!uOg7Y$9_$Y#`+8FYSw*haKTi8G=WXMSkKC7U^tVJTAjm?T-QgNNJ!Tk zb>5=$MU=PRa(yfM+6s#v*7*_2c~FRU!Q5QslEJZ;0h0?MRv>`vQ4~(}ux$=V!#Ehd zib=rn=t$Y|D0^kT15XX*E1mnh%bcBL2PEL&v$7N`=xEW3`O4JWg|-ldMFgh`8=h0s z5ZOn@*oWzH9RW^<0Fj%92H}t37P1Sg>&*UX+(uJ>0My#AD*8ci>^x9Ju*H(Rsp=xG zArzFXvJB5j{YS`RI6eZd^T?yUYh-I{71XMY7nape*~K5!LyDe*%|0@Ew3;oav>oe0 z?{_tB@!#0@vF}x$1sKPj2%{ZMNNy1Qcz5p6@w#$ps8h&E*c(@#aNS&b#llr7La82Enm=@n91#+{*{CLjMFDsxEve?)=_7 zeX+}AyYl=vsh1;;d*a;TPGtCLZ0-}-kea}gj$I{V@JhWg0C@X;Qn|EP=^>l_B#z@k ztZ; zAcm(DM3ujo-oze{30YuD0OlwX+&PJpMR4aM?aoP@JU?`J3?^Cy6OBDdgzCvXI(8~J z_CIXU;SpjngRII*;vpq_Ce;uf7;sy{Pm>Sa_Na1^v0vjftKtI!+=N|t$UQ9=A3+nI z<8e^WLTJ6%6^I$lpoFLU-RAdco& z*CSeE6XETs9x|{Gn+GxHnYh!}P;0x-VK2~mmA5cVU5L5q?WUF79P5Q1^TuLt(do-Q z%)X3ugM+iWJ1Kq~jmpkG_M(U1h;x2Ju?v)H-&{ZL957EwrCwMEWrqG|bc9Ek=M!TQ z?Pk#8H%wl9%C!$ayXcD`xM{J77IDAk8p3^&E_CcN*1+*nZ@oBJzEHMCRfO757NK-} z(pMyIgerdeO&a6~8D7y-DB~kWv5A{#9>p`(cUXC*r}Z*5G6r+c{+Z6%Da5WXG?WFe z7A#&o^C_d{+gcF3LRK-xV%phu&dxq8OeV;4vAB~bf#oT9k?O8=vYi9Me3#R_OJ%3* zqwBpJ>oFESM#C>3X9^AKh_ek&{0A1Q?7AY4NqEOoSn)Mh?yrm zpkX-|zsFKa!J*__YLvW$vvuZ}1lKBlmAZ&Q9)FgV$5$phh%0=$giqo&K4a107^mM} zydh9qUQM*UoyOJ7KY^G&3f@C8; zlzJq6yb#z?GdeBMz@+UUwTSm^M2Pe}eHpn+b_Ci-YpU~#=_bme=+FR?{X~ZZ7c0?2 z&+4s2WzXDzZ{qtRwIf}G&8EcnD}hfcrJ?gIR-_GliT-@j6=^`~?2fU0bb9p4x^gt>ue^X=I-89S)JBXDxDroOQJ!ntn^fP%8HU6EoAu7CHqpH z15%D3AuplRV5pbkX;AW_F0;y_cT_~j5?-tC#9q_A`^aQ)GI}HuJ;MXZM51}&f`tp9 zj+!%pE|^ydop)I!^pg3N(3XW2&`U47q!PLi(vpMy{dA?!JTRC|H7{Mh_To&oGr0-m zg8gp)`w6cj6#J>t+FD@-u@S&trnlZwm-!m z;&}-^GPUZ;A0>#gk#BOMqwxPbK-Zw@~7JLlybkD}Nc#O7dIv#xtV%kbDYpUisujmE^bT3E_PRG$wiFZ$LvO z`4g9^9uq3#y=?}{Uin`DR!ROI&6M{x&4V(p{LcfcB!6VF>U2b9ET8rtul#=pR!ROY znk*#VD^-!dz4GZwzLNZPV zY0pGz#0R(0Q{=w}tdjf@nk*#V(^Zkbz4A{0tt5Z%m8#PsVva=e{|+DT_-CWNlKd0z zpNF(g@BM&`d=o!z@{!-F4aMi5caXouNB+?^)hUE_N{#rC zOt1W}`^aBOlTGv#bVTyb-#tF^t*GiWt_@4_&&9_p|3_NBHj^u9gEo*?p0|F~r~i=d ze}T(U6};in!D(6kL0H1)$ zaoQ8B1uoB90ZVU!q6@i2wZP^1C}7bEqdd`^S6Lr+LAf3Rmfj@XR#gb_PF)VpL$!)e z+X^q|ql2yJ5@Gs~i^w<-uxKYNPb*NZvPx9t{NGnjtZM;_cBJyO9@Q%AgDzOk$9TQl z%!L3)_Ht|!s#R90w<&F5+}ya7@23IxCZ?QMK=6?*0ikC(Ua~_u9+FkJ91!#3f+z&U zyqDt*vg(!t93k8)7rxBjQ~i90#=V^A4`^uRUBr3m>vk^IO!3gKY217M*`@I%oR_}t z)i}+MOyA^6jdhI#QU12Z>6|aqcezqysqvLs_Gx^)1aawM{+{ZGk7@e5J@k)jdL0Jc z*8kP?-*FLDcuM1kJov9Q{)`8wYQXx)6!iaqoGs#yttpNn_nsZ7=`TKb5COCj{ri1z zdeL2pzR?Gt>w{nEgVQ;+68~-=e3K8p75Lf03(fQ09X|AT`QZ2a;Eyu@Qe6E885!xf zKJ+Jj@EO=tD~Da<6+4Ec<{0bku!w28!gKq(TwtL#LEb~0{FFy3U znVz0BR5H&mkNMC)<%7TAgTLy7zu|+^JLQUY^TESD_+lS?l@H$KgKzf1Z}GwJ^1<)( z!N2W;@Attiyzl2X{kTGJPV%31sf%=ZdtSQCy%g80qJ}HjQf&dQX+;fJxuS;aUQxr9 zu&B|salEaCzHp@*Z^I34ybbsJ@iyEB$J;KYFWdmf+n5el-tjhE9)pCtgqbqTJ;U4~ ztQc^=@B)ip79^I&S1gId6DzL1dUbS7VohX8Jeq(K80^4c!u&$V!r!pbTZGgNc)ONJ z45fPqvOS69#!Xg|f5rnWGayiU?_hp{gDd9ju=Gfrr3QFD2Iz-5>CL@K{fBiVRQ_PdkB_>}XBD9jUN3roP-N8PpB?q2Q>k}; z8_071svjnG!59nXC%RKf{DFz3YpDUQVW0!ap)J0m#SfZv(Qmx&@13}SnW8&?n!E)4 z?rN$4`F3RK>eY$1#PT(XwX37663ZhU(bM<~M`aN4Q!1B>y<+v6C6U$9_5|2{D%LiY zo3A>hSu@i^FN%H1`6UzoB#Yd}{cRW{L!D_jA*$OIO%Hve)7Ex zZ3d_3OiDygSKkJw=SE7{miZm9!IvocNOthW=JT{|SMs z^SzQwSHyANFWl?Q(uGML?9C3QvdrHRsKxR zc83020{@V})pMqzpDys93VJy&($3Nj=WBY>XQ|-RB5-=vGy0J4Q6l;nJ_cVyAd(k1 z&(q%V<`p@wU#X}0+Yh3bdbVqNFaP@mPHWld^N7aDADRSyNZ=uXOS?&X(qEiYBDr!s zzQyR&@qS+TPaHHxAGt0%1pb7em;9d>xU@gr%TuCp(H*kk|F*zG0%W zEyu_3p+9(}L^$1@89XjJbpDplL1TO77UHF^yhdBb5{xDzQQctrVk^a&jlA7LYXSq*F zJ9lY4y>`392RG}N=%qhAE9l!$HujPGDa9^>f6`}Mj?n*NK`-~s4+{KW1--QM_XU4x z=VJnwc78+P(#|u^wQ3A1-=%2j2*JX9Etc#yWP&{RQzs@&p=Lh zrH0S<1ijn`4{DsmHwyYE1b%_Qe=cxoPw9v21ihR`x!${kJwGkzM+GkZ_InzqaeYS6 z)2{?5k$vR2>V!S7MVqn19F0@fEbxyDT#nb=Q&F=VFTIzfMA=+?4F9zPmwY}eaLLEK ze<%H=eQp)>bOtc|cM4qczf<6n|9=YnLcvGIbLofYgN736vlJgA*Y6zCPQ*xF{mBO? z5xyQD!>5lxBrkrWf*F@_b=(Ix=QQFY>Hph@{&9gzzdEjQGLy8=p9HF5G zx#G(jC;sxBV8%r_+1%J?r=XuMaQR##$tNqv?HT-eDU0O#;7A;6oZGePrBF{~sNtr;HEx3HnyS zXP?03`u(NADV7?2UKRKvfu9t3zrasvoa{4C;4{uZ1&MHJ=X!z5@m`>D?|7Sh=$n1$ z7yHm(3`omv*iuVMty(hZt4!rMoghJSh<$-IeQR|26Z=Aim6bp75ClM1D}037;kK69PX= i;2|B)iM~$YD+PYGz()iw-@boW;2#k5zY=)8!2ciIXxHEX literal 0 HcmV?d00001 diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o new file mode 100644 index 0000000000000000000000000000000000000000..bd3b5c200e2c35bd962ff105477e09423c49beb3 GIT binary patch literal 2720 zcmbtV%}*0i5PxM65CsczFk)gkiAFY*G{zWXT58KCHqZ#DK}jiPl>|yjyH(^MhbG3x z3rDa130^#tXrljxTue0a;>|=8oZs6w-IwJx5S?V-%>3r-eeUdJa@meZL@-6fEfHvp z3X$&!>ok8mjUPSVU~n2Adz|K% zhl}5(+fng)u4Bnl>GX}*==^eh!>h*<_H{ckHc^*a{6#!rk0&nss7f}Zcx3yoh-^h8 z!>7A@c4Y7`b^-X_$|1<7U@PHvf zQeoI@&>($h=<9?+#C(`!+}|#M8abM*i{ZOILPlVg?nLr&<1djf=J>Diaf&s~KTkM_ z@29T`5oJN~tHgOPbkpaPzIIN5*gw2f-cQEw5N4{+M=S5P$^jOxpC!yxe_z!fSFxzy zO<%aaOPHztu8KQq{Y&I$svqt36Yx4wA5#j~-yuw%zxKaFh#4tZ$RaRDV>} z*Vm8#X1M+v!cd?6NR+g%_!Y&O!575*ttLx@8hY752MxaO6&6~)h^qLlP(06{;ddmM z*8f1Q-%*bIemS1c1#dt6b`bJP)&Hd8nT3}HJv?{#=5g7GeyM=7B=^x5u8%ums_&@# zi~FHdxV~=FW%zZ9p9ea|vSpkx=3$x%aMKP0m%W$MwzwrdN_rAA0yg4W6B3T*pvtVwLxtk_&>Hl zxG8^8`l~}Hndh_F1{cp{7q&|!5$ef>soczDDp#1vW@j^Vg}KyZE>j?u1YA8;ss9C?`PYm9 literal 0 HcmV?d00001 diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile new file mode 100644 index 0000000..69e964f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile @@ -0,0 +1,6 @@ +# This file is generated by gyp; do not edit. + +export builddir_name ?= ./build/. +.PHONY: all +all: + $(MAKE) kerberos diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi new file mode 100644 index 0000000..e8ac042 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi @@ -0,0 +1,138 @@ +# Do not edit. File was generated by node-gyp's "configure" step +{ + "target_defaults": { + "cflags": [], + "default_configuration": "Release", + "defines": [], + "include_dirs": [], + "libraries": [] + }, + "variables": { + "clang": 0, + "gcc_version": 44, + "host_arch": "x64", + "icu_data_file": "icudt54l.dat", + "icu_data_in": "../../deps/icu/source/data/in/icudt54l.dat", + "icu_endianness": "l", + "icu_gyp_path": "tools/icu/icu-generic.gyp", + "icu_locales": "en,root", + "icu_path": "./deps/icu", + "icu_small": "true", + "icu_ver_major": "54", + "node_install_npm": "true", + "node_prefix": "/", + "node_shared_cares": "false", + "node_shared_http_parser": "false", + "node_shared_libuv": "false", + "node_shared_openssl": "false", + "node_shared_v8": "false", + "node_shared_zlib": "false", + "node_tag": "", + "node_use_dtrace": "false", + "node_use_etw": "false", + "node_use_mdb": "false", + "node_use_openssl": "true", + "node_use_perfctr": "false", + "openssl_no_asm": 0, + "python": "/data/opt/bin/python", + "target_arch": "x64", + "uv_library": "static_library", + "uv_parent_path": "/deps/uv/", + "uv_use_dtrace": "false", + "v8_enable_gdbjit": 0, + "v8_enable_i18n_support": 1, + "v8_no_strict_aliasing": 1, + "v8_optimized_debug": 0, + "v8_random_seed": 0, + "v8_use_snapshot": "false", + "want_separate_host_toolset": 0, + "nodedir": "/home/fmason/.node-gyp/0.12.7", + "copy_dev_lib": "true", + "standalone_static_library": 1, + "cache_lock_stale": "60000", + "sign_git_tag": "", + "user_agent": "npm/2.11.3 node/v0.12.7 linux x64", + "always_auth": "", + "bin_links": "true", + "key": "", + "description": "true", + "fetch_retries": "2", + "heading": "npm", + "if_present": "", + "init_version": "1.0.0", + "user": "", + "force": "", + "cache_min": "10", + "init_license": "ISC", + "editor": "vi", + "rollback": "true", + "tag_version_prefix": "v", + "cache_max": "Infinity", + "userconfig": "/home/fmason/.npmrc", + "engine_strict": "", + "init_author_name": "", + "init_author_url": "", + "tmp": "/tmp", + "depth": "Infinity", + "save_dev": "", + "usage": "", + "cafile": "", + "https_proxy": "", + "onload_script": "", + "rebuild_bundle": "true", + "save_bundle": "", + "shell": "/bin/bash", + "prefix": "/usr/local", + "browser": "", + "cache_lock_wait": "10000", + "registry": "https://registry.npmjs.org/", + "save_optional": "", + "scope": "", + "searchopts": "", + "versions": "", + "cache": "/home/fmason/.npm", + "ignore_scripts": "", + "searchsort": "name", + "version": "", + "local_address": "", + "viewer": "man", + "color": "true", + "fetch_retry_mintimeout": "10000", + "umask": "0002", + "fetch_retry_maxtimeout": "60000", + "message": "%s", + "ca": "", + "cert": "", + "global": "", + "link": "", + "access": "", + "save": "", + "unicode": "true", + "long": "", + "production": "", + "unsafe_perm": "true", + "node_version": "0.12.7", + "tag": "latest", + "git_tag_version": "true", + "shrinkwrap": "true", + "fetch_retry_factor": "10", + "npat": "", + "proprietary_attribs": "true", + "save_exact": "", + "strict_ssl": "true", + "dev": "", + "globalconfig": "/usr/local/etc/npmrc", + "init_module": "/home/fmason/.npm-init.js", + "parseable": "", + "globalignorefile": "/usr/local/etc/npmignore", + "cache_lock_retries": "10", + "save_prefix": "^", + "group": "1002", + "init_author_email": "", + "searchexclude": "", + "git": "git", + "optional": "true", + "json": "", + "spin": "true" + } +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk new file mode 100644 index 0000000..36824f0 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk @@ -0,0 +1,151 @@ +# This file is generated by gyp; do not edit. + +TOOLSET := target +TARGET := kerberos +DEFS_Debug := \ + '-DNODE_GYP_MODULE_NAME=kerberos' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-DBUILDING_NODE_EXTENSION' \ + '-DDEBUG' \ + '-D_DEBUG' + +# Flags passed to all source files. +CFLAGS_Debug := \ + -fPIC \ + -pthread \ + -Wall \ + -Wextra \ + -Wno-unused-parameter \ + -m64 \ + -g \ + -O0 + +# Flags passed to only C files. +CFLAGS_C_Debug := + +# Flags passed to only C++ files. +CFLAGS_CC_Debug := \ + -fno-rtti + +INCS_Debug := \ + -I/home/fmason/.node-gyp/0.12.7/src \ + -I/home/fmason/.node-gyp/0.12.7/deps/uv/include \ + -I/home/fmason/.node-gyp/0.12.7/deps/v8/include \ + -I$(srcdir)/node_modules/nan \ + -I/usr/include/mit-krb5 + +DEFS_Release := \ + '-DNODE_GYP_MODULE_NAME=kerberos' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-DBUILDING_NODE_EXTENSION' + +# Flags passed to all source files. +CFLAGS_Release := \ + -fPIC \ + -pthread \ + -Wall \ + -Wextra \ + -Wno-unused-parameter \ + -m64 \ + -O3 \ + -ffunction-sections \ + -fdata-sections \ + -fno-tree-vrp \ + -fno-tree-sink \ + -fno-omit-frame-pointer + +# Flags passed to only C files. +CFLAGS_C_Release := + +# Flags passed to only C++ files. +CFLAGS_CC_Release := \ + -fno-rtti + +INCS_Release := \ + -I/home/fmason/.node-gyp/0.12.7/src \ + -I/home/fmason/.node-gyp/0.12.7/deps/uv/include \ + -I/home/fmason/.node-gyp/0.12.7/deps/v8/include \ + -I$(srcdir)/node_modules/nan \ + -I/usr/include/mit-krb5 + +OBJS := \ + $(obj).target/$(TARGET)/lib/kerberos.o \ + $(obj).target/$(TARGET)/lib/worker.o \ + $(obj).target/$(TARGET)/lib/kerberosgss.o \ + $(obj).target/$(TARGET)/lib/base64.o \ + $(obj).target/$(TARGET)/lib/kerberos_context.o + +# Add to the list of files we specially track dependencies for. +all_deps += $(OBJS) + +# CFLAGS et al overrides must be target-local. +# See "Target-specific Variable Values" in the GNU Make manual. +$(OBJS): TOOLSET := $(TOOLSET) +$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) +$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) + +# Suffix rules, putting all outputs into $(obj). + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# Try building from generated source, too. + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# End of this set of suffix rules +### Rules for final target. +LDFLAGS_Debug := \ + -pthread \ + -rdynamic \ + -m64 + +LDFLAGS_Release := \ + -pthread \ + -rdynamic \ + -m64 + +LIBS := \ + -lkrb5 \ + -lgssapi_krb5 + +$(obj).target/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) +$(obj).target/kerberos.node: LIBS := $(LIBS) +$(obj).target/kerberos.node: TOOLSET := $(TOOLSET) +$(obj).target/kerberos.node: $(OBJS) FORCE_DO_CMD + $(call do_cmd,solink_module) + +all_deps += $(obj).target/kerberos.node +# Add target alias +.PHONY: kerberos +kerberos: $(builddir)/kerberos.node + +# Copy this to the executable output path. +$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) +$(builddir)/kerberos.node: $(obj).target/kerberos.node FORCE_DO_CMD + $(call do_cmd,copy) + +all_deps += $(builddir)/kerberos.node +# Short alias for building this executable. +.PHONY: kerberos.node +kerberos.node: $(obj).target/kerberos.node $(builddir)/kerberos.node + +# Add executable to "all" target. +.PHONY: all +all: $(builddir)/kerberos.node + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log new file mode 100644 index 0000000..5679d63 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log @@ -0,0 +1,25 @@ +../lib/kerberos.cc:848:43: error: no viable conversion from 'Handle' to 'Local' + Local info[2] = { Nan::Null(), result}; + ^~~~~~ +/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:269:26: note: candidate constructor (the implicit copy constructor) not viable: cannot bind base class object of type 'Handle' to derived class reference 'const v8::Local &' for 1st argument +template class Local : public Handle { + ^ +/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:272:29: note: candidate template ignored: could not match 'Local' against 'Handle' + template inline Local(Local that) + ^ +/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:281:29: note: candidate template ignored: could not match 'S *' against 'Handle' + template inline Local(S* that) : Handle(that) { } + ^ +1 error generated. +make: *** [Release/obj.target/kerberos/lib/kerberos.o] Error 1 +gyp ERR! build error +gyp ERR! stack Error: `make` failed with exit code: 2 +gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23) +gyp ERR! stack at ChildProcess.emit (events.js:98:17) +gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:820:12) +gyp ERR! System Darwin 14.3.0 +gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" +gyp ERR! cwd /Users/christkv/coding/projects/kerberos +gyp ERR! node -v v0.10.35 +gyp ERR! node-gyp -v v1.0.1 +gyp ERR! not ok diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js new file mode 100644 index 0000000..b8c8532 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js @@ -0,0 +1,6 @@ +// Get the Kerberos library +module.exports = require('./lib/kerberos'); +// Set up the auth processes +module.exports['processes'] = { + MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js new file mode 100644 index 0000000..f1e9231 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js @@ -0,0 +1,281 @@ +var format = require('util').format; + +var MongoAuthProcess = function(host, port, service_name) { + // Check what system we are on + if(process.platform == 'win32') { + this._processor = new Win32MongoProcessor(host, port, service_name); + } else { + this._processor = new UnixMongoProcessor(host, port, service_name); + } +} + +MongoAuthProcess.prototype.init = function(username, password, callback) { + this._processor.init(username, password, callback); +} + +MongoAuthProcess.prototype.transition = function(payload, callback) { + this._processor.transition(payload, callback); +} + +/******************************************************************* + * + * Win32 SSIP Processor for MongoDB + * + *******************************************************************/ +var Win32MongoProcessor = function(host, port, service_name) { + this.host = host; + this.port = port + // SSIP classes + this.ssip = require("../kerberos").SSIP; + // Set up first transition + this._transition = Win32MongoProcessor.first_transition(this); + // Set up service name + service_name = service_name || "mongodb"; + // Set up target + this.target = format("%s/%s", service_name, host); + // Number of retries + this.retries = 10; +} + +Win32MongoProcessor.prototype.init = function(username, password, callback) { + var self = this; + // Save the values used later + this.username = username; + this.password = password; + // Aquire credentials + this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { + if(err) return callback(err); + // Save credentials + self.security_credentials = security_credentials; + // Callback with success + callback(null); + }); +} + +Win32MongoProcessor.prototype.transition = function(payload, callback) { + if(this._transition == null) return callback(new Error("Transition finished")); + this._transition(payload, callback); +} + +Win32MongoProcessor.first_transition = function(self) { + return function(payload, callback) { + self.ssip.SecurityContext.initialize( + self.security_credentials, + self.target, + payload, function(err, security_context) { + if(err) return callback(err); + + // If no context try again until we have no more retries + if(!security_context.hasContext) { + if(self.retries == 0) return callback(new Error("Failed to initialize security context")); + // Update the number of retries + self.retries = self.retries - 1; + // Set next transition + return self.transition(payload, callback); + } + + // Set next transition + self._transition = Win32MongoProcessor.second_transition(self); + self.security_context = security_context; + // Return the payload + callback(null, security_context.payload); + }); + } +} + +Win32MongoProcessor.second_transition = function(self) { + return function(payload, callback) { + // Perform a step + self.security_context.initialize(self.target, payload, function(err, security_context) { + if(err) return callback(err); + + // If no context try again until we have no more retries + if(!security_context.hasContext) { + if(self.retries == 0) return callback(new Error("Failed to initialize security context")); + // Update the number of retries + self.retries = self.retries - 1; + // Set next transition + self._transition = Win32MongoProcessor.first_transition(self); + // Retry + return self.transition(payload, callback); + } + + // Set next transition + self._transition = Win32MongoProcessor.third_transition(self); + // Return the payload + callback(null, security_context.payload); + }); + } +} + +Win32MongoProcessor.third_transition = function(self) { + return function(payload, callback) { + var messageLength = 0; + // Get the raw bytes + var encryptedBytes = new Buffer(payload, 'base64'); + var encryptedMessage = new Buffer(messageLength); + // Copy first byte + encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); + // Set up trailer + var securityTrailerLength = encryptedBytes.length - messageLength; + var securityTrailer = new Buffer(securityTrailerLength); + // Copy the bytes + encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); + + // Types used + var SecurityBuffer = self.ssip.SecurityBuffer; + var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; + + // Set up security buffers + var buffers = [ + new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) + , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) + ]; + + // Set up the descriptor + var descriptor = new SecurityBufferDescriptor(buffers); + + // Decrypt the data + self.security_context.decryptMessage(descriptor, function(err, security_context) { + if(err) return callback(err); + + var length = 4; + if(self.username != null) { + length += self.username.length; + } + + var bytesReceivedFromServer = new Buffer(length); + bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION + bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION + bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION + bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION + + if(self.username != null) { + var authorization_id_bytes = new Buffer(self.username, 'utf8'); + authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); + } + + self.security_context.queryContextAttributes(0x00, function(err, sizes) { + if(err) return callback(err); + + var buffers = [ + new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) + , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) + , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) + ] + + var descriptor = new SecurityBufferDescriptor(buffers); + + self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { + if(err) return callback(err); + callback(null, security_context.payload); + }); + }); + }); + } +} + +/******************************************************************* + * + * UNIX MIT Kerberos processor + * + *******************************************************************/ +var UnixMongoProcessor = function(host, port, service_name) { + this.host = host; + this.port = port + // SSIP classes + this.Kerberos = require("../kerberos").Kerberos; + this.kerberos = new this.Kerberos(); + service_name = service_name || "mongodb"; + // Set up first transition + this._transition = UnixMongoProcessor.first_transition(this); + // Set up target + this.target = format("%s@%s", service_name, host); + // Number of retries + this.retries = 10; +} + +UnixMongoProcessor.prototype.init = function(username, password, callback) { + var self = this; + this.username = username; + this.password = password; + // Call client initiate + this.kerberos.authGSSClientInit( + self.target + , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { + self.context = context; + // Return the context + callback(null, context); + }); +} + +UnixMongoProcessor.prototype.transition = function(payload, callback) { + if(this._transition == null) return callback(new Error("Transition finished")); + this._transition(payload, callback); +} + +UnixMongoProcessor.first_transition = function(self) { + return function(payload, callback) { + self.kerberos.authGSSClientStep(self.context, '', function(err, result) { + if(err) return callback(err); + // Set up the next step + self._transition = UnixMongoProcessor.second_transition(self); + // Return the payload + callback(null, self.context.response); + }) + } +} + +UnixMongoProcessor.second_transition = function(self) { + return function(payload, callback) { + self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { + if(err && self.retries == 0) return callback(err); + // Attempt to re-establish a context + if(err) { + // Adjust the number of retries + self.retries = self.retries - 1; + // Call same step again + return self.transition(payload, callback); + } + + // Set up the next step + self._transition = UnixMongoProcessor.third_transition(self); + // Return the payload + callback(null, self.context.response || ''); + }); + } +} + +UnixMongoProcessor.third_transition = function(self) { + return function(payload, callback) { + // GSS Client Unwrap + self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { + if(err) return callback(err, false); + + // Wrap the response + self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { + if(err) return callback(err, false); + // Set up the next step + self._transition = UnixMongoProcessor.fourth_transition(self); + // Return the payload + callback(null, self.context.response); + }); + }); + } +} + +UnixMongoProcessor.fourth_transition = function(self) { + return function(payload, callback) { + // Clean up context + self.kerberos.authGSSClientClean(self.context, function(err, result) { + if(err) return callback(err, false); + // Set the transition to null + self._transition = null; + // Callback with valid authentication + callback(null, true); + }); + } +} + +// Set the process +exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c new file mode 100644 index 0000000..aca0a61 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c @@ -0,0 +1,134 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * 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. + **/ + +#include "base64.h" + +#include +#include +#include +#include + +void die2(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +// base64 tables +static char basis_64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static signed char index_64[128] = +{ + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 +}; +#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) + +// base64_encode : base64 encode +// +// value : data to encode +// vlen : length of data +// (result) : new char[] - c-str of result +char *base64_encode(const unsigned char *value, int vlen) +{ + char *result = (char *)malloc((vlen * 4) / 3 + 5); + if(result == NULL) die2("Memory allocation failed"); + char *out = result; + while (vlen >= 3) + { + *out++ = basis_64[value[0] >> 2]; + *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; + *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; + *out++ = basis_64[value[2] & 0x3F]; + value += 3; + vlen -= 3; + } + if (vlen > 0) + { + *out++ = basis_64[value[0] >> 2]; + unsigned char oval = (value[0] << 4) & 0x30; + if (vlen > 1) oval |= value[1] >> 4; + *out++ = basis_64[oval]; + *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; + *out++ = '='; + } + *out = '\0'; + + return result; +} + +// base64_decode : base64 decode +// +// value : c-str to decode +// rlen : length of decoded result +// (result) : new unsigned char[] - decoded result +unsigned char *base64_decode(const char *value, int *rlen) +{ + *rlen = 0; + int c1, c2, c3, c4; + + int vlen = strlen(value); + unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); + if(result == NULL) die2("Memory allocation failed"); + unsigned char *out = result; + + while (1) + { + if (value[0]==0) + return result; + c1 = value[0]; + if (CHAR64(c1) == -1) + goto base64_decode_error;; + c2 = value[1]; + if (CHAR64(c2) == -1) + goto base64_decode_error;; + c3 = value[2]; + if ((c3 != '=') && (CHAR64(c3) == -1)) + goto base64_decode_error;; + c4 = value[3]; + if ((c4 != '=') && (CHAR64(c4) == -1)) + goto base64_decode_error;; + + value += 4; + *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); + *rlen += 1; + if (c3 != '=') + { + *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); + *rlen += 1; + if (c4 != '=') + { + *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); + *rlen += 1; + } + } + } + +base64_decode_error: + *result = 0; + *rlen = 0; + return result; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h new file mode 100644 index 0000000..9152e6a --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h @@ -0,0 +1,22 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * 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. + **/ +#ifndef BASE64_H +#define BASE64_H + +char *base64_encode(const unsigned char *value, int vlen); +unsigned char *base64_decode(const char *value, int *rlen); + +#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc new file mode 100644 index 0000000..5b25d74 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc @@ -0,0 +1,893 @@ +#include "kerberos.h" +#include +#include +#include "worker.h" +#include "kerberos_context.h" + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) +#endif + +void die(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +// Call structs +typedef struct AuthGSSClientCall { + uint32_t flags; + char *uri; +} AuthGSSClientCall; + +typedef struct AuthGSSClientStepCall { + KerberosContext *context; + char *challenge; +} AuthGSSClientStepCall; + +typedef struct AuthGSSClientUnwrapCall { + KerberosContext *context; + char *challenge; +} AuthGSSClientUnwrapCall; + +typedef struct AuthGSSClientWrapCall { + KerberosContext *context; + char *challenge; + char *user_name; +} AuthGSSClientWrapCall; + +typedef struct AuthGSSClientCleanCall { + KerberosContext *context; +} AuthGSSClientCleanCall; + +typedef struct AuthGSSServerInitCall { + char *service; + bool constrained_delegation; + char *username; +} AuthGSSServerInitCall; + +typedef struct AuthGSSServerCleanCall { + KerberosContext *context; +} AuthGSSServerCleanCall; + +typedef struct AuthGSSServerStepCall { + KerberosContext *context; + char *auth_data; +} AuthGSSServerStepCall; + +Kerberos::Kerberos() : Nan::ObjectWrap() { +} + +Nan::Persistent Kerberos::constructor_template; + +void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("Kerberos").ToLocalChecked()); + + // Set up method for the Kerberos instance + Nan::SetPrototypeMethod(t, "authGSSClientInit", AuthGSSClientInit); + Nan::SetPrototypeMethod(t, "authGSSClientStep", AuthGSSClientStep); + Nan::SetPrototypeMethod(t, "authGSSClientUnwrap", AuthGSSClientUnwrap); + Nan::SetPrototypeMethod(t, "authGSSClientWrap", AuthGSSClientWrap); + Nan::SetPrototypeMethod(t, "authGSSClientClean", AuthGSSClientClean); + Nan::SetPrototypeMethod(t, "authGSSServerInit", AuthGSSServerInit); + Nan::SetPrototypeMethod(t, "authGSSServerClean", AuthGSSServerClean); + Nan::SetPrototypeMethod(t, "authGSSServerStep", AuthGSSServerStep); + + constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("Kerberos").ToLocalChecked(), t->GetFunction()); +} + +NAN_METHOD(Kerberos::New) { + // Create a Kerberos instance + Kerberos *kerberos = new Kerberos(); + // Return the kerberos object + kerberos->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientInit +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientInit(Worker *worker) { + gss_client_state *state; + gss_client_response *response; + + // Allocate state + state = (gss_client_state *)malloc(sizeof(gss_client_state)); + if(state == NULL) die("Memory allocation failed"); + + // Unpack the parameter data struct + AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; + // Start the kerberos client + response = authenticate_gss_client_init(call->uri, call->flags, state); + + // Release the parameter struct memory + free(call->uri); + free(call); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + free(state); + } else { + worker->return_value = state; + } + + // Free structure + free(response); +} + +static Local _map_authGSSClientInit(Worker *worker) { + KerberosContext *context = KerberosContext::New(); + context->state = (gss_client_state *)worker->return_value; + return context->handle(); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientInit) { + // Ensure valid call + if(info.Length() != 3) return Nan::ThrowError("Requires a service string uri, integer flags and a callback function"); + if(info.Length() == 3 && (!info[0]->IsString() || !info[1]->IsInt32() || !info[2]->IsFunction())) + return Nan::ThrowError("Requires a service string uri, integer flags and a callback function"); + + Local service = info[0]->ToString(); + // Convert uri string to c-string + char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); + if(service_str == NULL) die("Memory allocation failed"); + + // Write v8 string to c-string + service->WriteUtf8(service_str); + + // Allocate a structure + AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); + if(call == NULL) die("Memory allocation failed"); + call->flags =info[1]->ToInt32()->Uint32Value(); + call->uri = service_str; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[2]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientInit; + worker->mapper = _map_authGSSClientInit; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientStep +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientStep(Worker *worker) { + gss_client_state *state; + gss_client_response *response; + char *challenge; + + // Unpack the parameter data struct + AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; + // Get the state + state = call->context->state; + challenge = call->challenge; + + // Check what kind of challenge we have + if(call->challenge == NULL) { + challenge = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_client_step(state, challenge); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->challenge != NULL) free(call->challenge); + free(call); + free(response); +} + +static Local _map_authGSSClientStep(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientStep) { + // Ensure valid call + if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + + // Challenge string + char *challenge_str = NULL; + // Let's unpack the parameters + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsClientInstance()) { + return Nan::ThrowError("GSS context is not a client instance"); + } + + int callbackArg = 1; + + // If we have a challenge string + if(info.Length() == 3) { + // Unpack the challenge string + Local challenge = info[1]->ToString(); + // Convert uri string to c-string + challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); + if(challenge_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + challenge->WriteUtf8(challenge_str); + + callbackArg = 2; + } + + // Allocate a structure + AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientStepCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->challenge = challenge_str; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[callbackArg]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientStep; + worker->mapper = _map_authGSSClientStep; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientUnwrap +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientUnwrap(Worker *worker) { + gss_client_response *response; + char *challenge; + + // Unpack the parameter data struct + AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; + challenge = call->challenge; + + // Check what kind of challenge we have + if(call->challenge == NULL) { + challenge = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_client_unwrap(call->context->state, challenge); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->challenge != NULL) free(call->challenge); + free(call); + free(response); +} + +static Local _map_authGSSClientUnwrap(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientUnwrap) { + // Ensure valid call + if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + + // Challenge string + char *challenge_str = NULL; + // Let's unpack the parameters + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsClientInstance()) { + return Nan::ThrowError("GSS context is not a client instance"); + } + + // If we have a challenge string + if(info.Length() == 3) { + // Unpack the challenge string + Local challenge = info[1]->ToString(); + // Convert uri string to c-string + challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); + if(challenge_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + challenge->WriteUtf8(challenge_str); + } + + // Allocate a structure + AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->challenge = challenge_str; + + // Unpack the callback + Local callbackHandle = info.Length() == 3 ? Local::Cast(info[2]) : Local::Cast(info[1]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientUnwrap; + worker->mapper = _map_authGSSClientUnwrap; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientWrap +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientWrap(Worker *worker) { + gss_client_response *response; + char *user_name = NULL; + + // Unpack the parameter data struct + AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; + user_name = call->user_name; + + // Check what kind of challenge we have + if(call->user_name == NULL) { + user_name = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->challenge != NULL) free(call->challenge); + if(call->user_name != NULL) free(call->user_name); + free(call); + free(response); +} + +static Local _map_authGSSClientWrap(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientWrap) { + // Ensure valid call + if(info.Length() != 3 && info.Length() != 4) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); + if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); + if(info.Length() == 4 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsString() || !info[3]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); + + // Challenge string + char *challenge_str = NULL; + char *user_name_str = NULL; + + // Let's unpack the kerberos context + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsClientInstance()) { + return Nan::ThrowError("GSS context is not a client instance"); + } + + // Unpack the challenge string + Local challenge = info[1]->ToString(); + // Convert uri string to c-string + challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); + if(challenge_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + challenge->WriteUtf8(challenge_str); + + // If we have a user string + if(info.Length() == 4) { + // Unpack user name + Local user_name = info[2]->ToString(); + // Convert uri string to c-string + user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); + if(user_name_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + user_name->WriteUtf8(user_name_str); + } + + // Allocate a structure + AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->challenge = challenge_str; + call->user_name = user_name_str; + + // Unpack the callback + Local callbackHandle = info.Length() == 4 ? Local::Cast(info[3]) : Local::Cast(info[2]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientWrap; + worker->mapper = _map_authGSSClientWrap; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientClean +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientClean(Worker *worker) { + gss_client_response *response; + + // Unpack the parameter data struct + AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; + + // Perform authentication step + response = authenticate_gss_client_clean(call->context->state); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + free(call); + free(response); +} + +static Local _map_authGSSClientClean(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientClean) { + // Ensure valid call + if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function"); + if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function"); + + // Let's unpack the kerberos context + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsClientInstance()) { + return Nan::ThrowError("GSS context is not a client instance"); + } + + // Allocate a structure + AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[1]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientClean; + worker->mapper = _map_authGSSClientClean; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSServerInit +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSServerInit(Worker *worker) { + gss_server_state *state; + gss_client_response *response; + + // Allocate state + state = (gss_server_state *)malloc(sizeof(gss_server_state)); + if(state == NULL) die("Memory allocation failed"); + + // Unpack the parameter data struct + AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)worker->parameters; + // Start the kerberos service + response = authenticate_gss_server_init(call->service, call->constrained_delegation, call->username, state); + + // Release the parameter struct memory + free(call->service); + free(call->username); + free(call); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + free(state); + } else { + worker->return_value = state; + } + + // Free structure + free(response); +} + +static Local _map_authGSSServerInit(Worker *worker) { + KerberosContext *context = KerberosContext::New(); + context->server_state = (gss_server_state *)worker->return_value; + return context->handle(); +} + +// Server Initialize method +NAN_METHOD(Kerberos::AuthGSSServerInit) { + // Ensure valid call + if(info.Length() != 4) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function"); + + if(!info[0]->IsString() || + !info[1]->IsBoolean() || + !(info[2]->IsString() || info[2]->IsNull()) || + !info[3]->IsFunction() + ) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function"); + + if (!info[1]->BooleanValue() && !info[2]->IsNull()) return Nan::ThrowError("S4U2Self only possible when constrained delegation is enabled"); + + // Allocate a structure + AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)calloc(1, sizeof(AuthGSSServerInitCall)); + if(call == NULL) die("Memory allocation failed"); + + Local service = info[0]->ToString(); + // Convert service string to c-string + char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); + if(service_str == NULL) die("Memory allocation failed"); + + // Write v8 string to c-string + service->WriteUtf8(service_str); + + call->service = service_str; + + call->constrained_delegation = info[1]->BooleanValue(); + + if (info[2]->IsNull()) + { + call->username = NULL; + } + else + { + Local tmpString = info[2]->ToString(); + + char *tmpCstr = (char *)calloc(tmpString->Utf8Length() + 1, sizeof(char)); + if(tmpCstr == NULL) die("Memory allocation failed"); + + tmpString->WriteUtf8(tmpCstr); + + call->username = tmpCstr; + } + + // Unpack the callback + Local callbackHandle = Local::Cast(info[3]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSServerInit; + worker->mapper = _map_authGSSServerInit; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSServerClean +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSServerClean(Worker *worker) { + gss_client_response *response; + + // Unpack the parameter data struct + AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)worker->parameters; + + // Perform authentication step + response = authenticate_gss_server_clean(call->context->server_state); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + free(call); + free(response); +} + +static Local _map_authGSSServerClean(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSServerClean) { + // // Ensure valid call + if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function"); + if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function"); + + // Let's unpack the kerberos context + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsServerInstance()) { + return Nan::ThrowError("GSS context is not a server instance"); + } + + // Allocate a structure + AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)calloc(1, sizeof(AuthGSSServerCleanCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[1]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSServerClean; + worker->mapper = _map_authGSSServerClean; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSServerStep +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSServerStep(Worker *worker) { + gss_server_state *state; + gss_client_response *response; + char *auth_data; + + // Unpack the parameter data struct + AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)worker->parameters; + // Get the state + state = call->context->server_state; + auth_data = call->auth_data; + + // Check if we got auth_data or not + if(call->auth_data == NULL) { + auth_data = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_server_step(state, auth_data); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->auth_data != NULL) free(call->auth_data); + free(call); + free(response); +} + +static Local _map_authGSSServerStep(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSServerStep) { + // Ensure valid call + if(info.Length() != 3) return Nan::ThrowError("Requires a GSS context, auth-data string and callback function"); + if(!KerberosContext::HasInstance(info[0])) return Nan::ThrowError("1st arg must be a GSS context"); + if (!info[1]->IsString()) return Nan::ThrowError("2nd arg must be auth-data string"); + if (!info[2]->IsFunction()) return Nan::ThrowError("3rd arg must be a callback function"); + + // Auth-data string + char *auth_data_str = NULL; + // Let's unpack the parameters + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsServerInstance()) { + return Nan::ThrowError("GSS context is not a server instance"); + } + + // Unpack the auth_data string + Local auth_data = info[1]->ToString(); + // Convert uri string to c-string + auth_data_str = (char *)calloc(auth_data->Utf8Length() + 1, sizeof(char)); + if(auth_data_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + auth_data->WriteUtf8(auth_data_str); + + // Allocate a structure + AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)calloc(1, sizeof(AuthGSSServerStepCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->auth_data = auth_data_str; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[2]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSServerStep; + worker->mapper = _map_authGSSServerStep; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// UV Lib callbacks +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +void Kerberos::Process(uv_work_t* work_req) { + // Grab the worker + Worker *worker = static_cast(work_req->data); + // Execute the worker code + worker->execute(worker); +} + +void Kerberos::After(uv_work_t* work_req) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Get the worker reference + Worker *worker = static_cast(work_req->data); + + // If we have an error + if(worker->error) { + Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); + Local obj = err->ToObject(); + obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); + Local info[2] = { err, Nan::Null() }; + // Execute the error + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } else { + // // Map the data + Local result = worker->mapper(worker); + // Set up the callback with a null first + #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + Local info[2] = { Nan::Null(), result}; + #else + Local info[2] = { Nan::Null(), Nan::New(result)}; + #endif + + // Wrap the callback function call in a TryCatch so that we can call + // node's FatalException afterwards. This makes it possible to catch + // the exception from JavaScript land using the + // process.on('uncaughtException') event. + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } + + // Clean up the memory + delete worker->callback; + delete worker; +} + +// Exporting function +NAN_MODULE_INIT(init) { + Kerberos::Initialize(target); + KerberosContext::Initialize(target); +} + +NODE_MODULE(kerberos, init); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h new file mode 100644 index 0000000..beafa4d --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h @@ -0,0 +1,50 @@ +#ifndef KERBEROS_H +#define KERBEROS_H + +#include +#include +#include +#include + +#include "nan.h" +#include +#include + +extern "C" { + #include "kerberosgss.h" +} + +using namespace v8; +using namespace node; + +class Kerberos : public Nan::ObjectWrap { + +public: + Kerberos(); + ~Kerberos() {}; + + // Constructor used for creating new Kerberos objects from C++ + static Nan::Persistent constructor_template; + + // Initialize function for the object + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + + // Method available + static NAN_METHOD(AuthGSSClientInit); + static NAN_METHOD(AuthGSSClientStep); + static NAN_METHOD(AuthGSSClientUnwrap); + static NAN_METHOD(AuthGSSClientWrap); + static NAN_METHOD(AuthGSSClientClean); + static NAN_METHOD(AuthGSSServerInit); + static NAN_METHOD(AuthGSSServerClean); + static NAN_METHOD(AuthGSSServerStep); + +private: + static NAN_METHOD(New); + // Handles the uv calls + static void Process(uv_work_t* work_req); + // Called after work is done + static void After(uv_work_t* work_req); +}; + +#endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js new file mode 100644 index 0000000..c7bae58 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js @@ -0,0 +1,164 @@ +var kerberos = require('../build/Release/kerberos') + , KerberosNative = kerberos.Kerberos; + +var Kerberos = function() { + this._native_kerberos = new KerberosNative(); +} + +// callback takes two arguments, an error string if defined and a new context +// uri should be given as service@host. Services are not always defined +// in a straightforward way. Use 'HTTP' for SPNEGO / Negotiate authentication. +Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { + return this._native_kerberos.authGSSClientInit(uri, flags, callback); +} + +// This will obtain credentials using a credentials cache. To override the default +// location (posible /tmp/krb5cc_nnnnnn, where nnnn is your numeric uid) use +// the environment variable KRB5CNAME. +// The credentials (suitable for using in an 'Authenticate: ' header, when prefixed +// with 'Negotiate ') will be available as context.response inside the callback +// if no error is indicated. +// callback takes one argument, an error string if defined +Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { + if(typeof challenge == 'function') { + callback = challenge; + challenge = ''; + } + + return this._native_kerberos.authGSSClientStep(context, challenge, callback); +} + +Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { + if(typeof challenge == 'function') { + callback = challenge; + challenge = ''; + } + + return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); +} + +Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { + if(typeof user_name == 'function') { + callback = user_name; + user_name = ''; + } + + return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); +} + +// free memory used by a context created using authGSSClientInit. +// callback takes one argument, an error string if defined. +Kerberos.prototype.authGSSClientClean = function(context, callback) { + return this._native_kerberos.authGSSClientClean(context, callback); +} + +// The server will obtain credentials using a keytab. To override the +// default location (probably /etc/krb5.keytab) set the KRB5_KTNAME +// environment variable. +// The service name should be in the form service, or service@host.name +// e.g. for HTTP, use "HTTP" or "HTTP@my.host.name". See gss_import_name +// for GSS_C_NT_HOSTBASED_SERVICE. +// +// a boolean turns on "constrained_delegation". this enables acquisition of S4U2Proxy +// credentials which will be stored in a credentials cache during the authGSSServerStep +// method. this parameter is optional. +// +// when "constrained_delegation" is enabled, a username can (optionally) be provided and +// S4U2Self protocol transition will be initiated. In this case, we will not +// require any "auth" data during the authGSSServerStep. This parameter is optional +// but constrained_delegation MUST be enabled for this to work. When S4U2Self is +// used, the username will be assumed to have been already authenticated, and no +// actual authentication will be performed. This is basically a way to "bootstrap" +// kerberos credentials (which can then be delegated with S4U2Proxy) for a user +// authenticated externally. +// +// callback takes two arguments, an error string if defined and a new context +// +Kerberos.prototype.authGSSServerInit = function(service, constrained_delegation, username, callback) { + if(typeof(constrained_delegation) === 'function') { + callback = constrained_delegation; + constrained_delegation = false; + username = null; + } + + if (typeof(constrained_delegation) === 'string') { + throw new Error("S4U2Self protocol transation is not possible without enabling constrained delegation"); + } + + if (typeof(username) === 'function') { + callback = username; + username = null; + } + + constrained_delegation = !!constrained_delegation; + + return this._native_kerberos.authGSSServerInit(service, constrained_delegation, username, callback); +}; + +//callback takes one argument, an error string if defined. +Kerberos.prototype.authGSSServerClean = function(context, callback) { + return this._native_kerberos.authGSSServerClean(context, callback); +}; + +// authData should be the base64 encoded authentication data obtained +// from client, e.g., in the Authorization header (without the leading +// "Negotiate " string) during SPNEGO authentication. The authenticated user +// is available in context.username after successful authentication. +// callback takes one argument, an error string if defined. +// +// Note: when S4U2Self protocol transition was requested in the authGSSServerInit +// no actual authentication will be performed and authData will be ignored. +// +Kerberos.prototype.authGSSServerStep = function(context, authData, callback) { + return this._native_kerberos.authGSSServerStep(context, authData, callback); +}; + +Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { + return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); +} + +Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { + return this._native_kerberos.prepareOutboundPackage(principal, inputdata); +} + +Kerberos.prototype.decryptMessage = function(challenge) { + return this._native_kerberos.decryptMessage(challenge); +} + +Kerberos.prototype.encryptMessage = function(challenge) { + return this._native_kerberos.encryptMessage(challenge); +} + +Kerberos.prototype.queryContextAttribute = function(attribute) { + if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); + return this._native_kerberos.queryContextAttribute(attribute); +} + +// Some useful result codes +Kerberos.AUTH_GSS_CONTINUE = 0; +Kerberos.AUTH_GSS_COMPLETE = 1; + +// Some useful gss flags +Kerberos.GSS_C_DELEG_FLAG = 1; +Kerberos.GSS_C_MUTUAL_FLAG = 2; +Kerberos.GSS_C_REPLAY_FLAG = 4; +Kerberos.GSS_C_SEQUENCE_FLAG = 8; +Kerberos.GSS_C_CONF_FLAG = 16; +Kerberos.GSS_C_INTEG_FLAG = 32; +Kerberos.GSS_C_ANON_FLAG = 64; +Kerberos.GSS_C_PROT_READY_FLAG = 128; +Kerberos.GSS_C_TRANS_FLAG = 256; + +// Export Kerberos class +exports.Kerberos = Kerberos; + +// If we have SSPI (windows) +if(kerberos.SecurityCredentials) { + // Put all SSPI classes in it's own namespace + exports.SSIP = { + SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials + , SecurityContext: require('./win32/wrappers/security_context').SecurityContext + , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer + , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor + } +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc new file mode 100644 index 0000000..bf24118 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc @@ -0,0 +1,134 @@ +#include "kerberos_context.h" + +Nan::Persistent KerberosContext::constructor_template; + +KerberosContext::KerberosContext() : Nan::ObjectWrap() { + state = NULL; + server_state = NULL; +} + +KerberosContext::~KerberosContext() { +} + +KerberosContext* KerberosContext::New() { + Nan::HandleScope scope; + Local obj = Nan::New(constructor_template)->GetFunction()->NewInstance(); + KerberosContext *kerberos_context = Nan::ObjectWrap::Unwrap(obj); + return kerberos_context; +} + +NAN_METHOD(KerberosContext::New) { + // Create code object + KerberosContext *kerberos_context = new KerberosContext(); + // Wrap it + kerberos_context->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +void KerberosContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(static_cast(New)); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("KerberosContext").ToLocalChecked()); + + // Get prototype + Local proto = t->PrototypeTemplate(); + + // Getter for the response + Nan::SetAccessor(proto, Nan::New("response").ToLocalChecked(), KerberosContext::ResponseGetter); + + // Getter for the username + Nan::SetAccessor(proto, Nan::New("username").ToLocalChecked(), KerberosContext::UsernameGetter); + + // Getter for the targetname - server side only + Nan::SetAccessor(proto, Nan::New("targetname").ToLocalChecked(), KerberosContext::TargetnameGetter); + + Nan::SetAccessor(proto, Nan::New("delegatedCredentialsCache").ToLocalChecked(), KerberosContext::DelegatedCredentialsCacheGetter); + + // Set persistent + constructor_template.Reset(t); + // NanAssignPersistent(constructor_template, t); + + // Set the symbol + target->ForceSet(Nan::New("KerberosContext").ToLocalChecked(), t->GetFunction()); +} + + +// Response Setter / Getter +NAN_GETTER(KerberosContext::ResponseGetter) { + gss_client_state *client_state; + gss_server_state *server_state; + + // Unpack the object + KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); + + // Response could come from client or server state... + client_state = context->state; + server_state = context->server_state; + + // If client state is in use, take response from there, otherwise from server + char *response = client_state != NULL ? client_state->response : + server_state != NULL ? server_state->response : NULL; + + if(response == NULL) { + info.GetReturnValue().Set(Nan::Null()); + } else { + // Return the response + info.GetReturnValue().Set(Nan::New(response).ToLocalChecked()); + } +} + +// username Getter +NAN_GETTER(KerberosContext::UsernameGetter) { + // Unpack the object + KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); + + gss_client_state *client_state = context->state; + gss_server_state *server_state = context->server_state; + + // If client state is in use, take response from there, otherwise from server + char *username = client_state != NULL ? client_state->username : + server_state != NULL ? server_state->username : NULL; + + if(username == NULL) { + info.GetReturnValue().Set(Nan::Null()); + } else { + info.GetReturnValue().Set(Nan::New(username).ToLocalChecked()); + } +} + +// targetname Getter - server side only +NAN_GETTER(KerberosContext::TargetnameGetter) { + // Unpack the object + KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); + + gss_server_state *server_state = context->server_state; + + char *targetname = server_state != NULL ? server_state->targetname : NULL; + + if(targetname == NULL) { + info.GetReturnValue().Set(Nan::Null()); + } else { + info.GetReturnValue().Set(Nan::New(targetname).ToLocalChecked()); + } +} + +// targetname Getter - server side only +NAN_GETTER(KerberosContext::DelegatedCredentialsCacheGetter) { + // Unpack the object + KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); + + gss_server_state *server_state = context->server_state; + + char *delegated_credentials_cache = server_state != NULL ? server_state->delegated_credentials_cache : NULL; + + if(delegated_credentials_cache == NULL) { + info.GetReturnValue().Set(Nan::Null()); + } else { + info.GetReturnValue().Set(Nan::New(delegated_credentials_cache).ToLocalChecked()); + } +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h new file mode 100644 index 0000000..23eb577 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h @@ -0,0 +1,64 @@ +#ifndef KERBEROS_CONTEXT_H +#define KERBEROS_CONTEXT_H + +#include +#include +#include +#include + +#include "nan.h" +#include +#include + +extern "C" { + #include "kerberosgss.h" +} + +using namespace v8; +using namespace node; + +class KerberosContext : public Nan::ObjectWrap { + +public: + KerberosContext(); + ~KerberosContext(); + + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + inline bool IsClientInstance() { + return state != NULL; + } + + inline bool IsServerInstance() { + return server_state != NULL; + } + + // Constructor used for creating new Kerberos objects from C++ + static Nan::Persistent constructor_template; + + // Initialize function for the object + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + + // Public constructor + static KerberosContext* New(); + + // Handle to the kerberos client context + gss_client_state *state; + + // Handle to the kerberos server context + gss_server_state *server_state; + +private: + static NAN_METHOD(New); + // In either client state or server state + static NAN_GETTER(ResponseGetter); + static NAN_GETTER(UsernameGetter); + // Only in the "server_state" + static NAN_GETTER(TargetnameGetter); + static NAN_GETTER(DelegatedCredentialsCacheGetter); +}; +#endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c new file mode 100644 index 0000000..2fbca00 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c @@ -0,0 +1,931 @@ +/** + * Copyright (c) 2006-2010 Apple Inc. All rights reserved. + * + * 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. + * + **/ +/* + * S4U2Proxy implementation + * Copyright (C) 2015 David Mansfield + * Code inspired by mod_auth_kerb. + */ + +#include "kerberosgss.h" + +#include "base64.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +void die1(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +static gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min); +static gss_client_response *other_error(const char *fmt, ...); +static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem); + +static gss_client_response *store_gss_creds(gss_server_state *state); +static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context context, krb5_principal princ, krb5_ccache *ccache); + +/* +char* server_principal_details(const char* service, const char* hostname) +{ + char match[1024]; + int match_len = 0; + char* result = NULL; + + int code; + krb5_context kcontext; + krb5_keytab kt = NULL; + krb5_kt_cursor cursor = NULL; + krb5_keytab_entry entry; + char* pname = NULL; + + // Generate the principal prefix we want to match + snprintf(match, 1024, "%s/%s@", service, hostname); + match_len = strlen(match); + + code = krb5_init_context(&kcontext); + if (code) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot initialize Kerberos5 context", code)); + return NULL; + } + + if ((code = krb5_kt_default(kcontext, &kt))) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot get default keytab", code)); + goto end; + } + + if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot get sequence cursor from keytab", code)); + goto end; + } + + while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) + { + if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot parse principal name from keytab", code)); + goto end; + } + + if (strncmp(pname, match, match_len) == 0) + { + result = malloc(strlen(pname) + 1); + strcpy(result, pname); + krb5_free_unparsed_name(kcontext, pname); + krb5_free_keytab_entry_contents(kcontext, &entry); + break; + } + + krb5_free_unparsed_name(kcontext, pname); + krb5_free_keytab_entry_contents(kcontext, &entry); + } + + if (result == NULL) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Principal not found in keytab", -1)); + } + +end: + if (cursor) + krb5_kt_end_seq_get(kcontext, kt, &cursor); + if (kt) + krb5_kt_close(kcontext, kt); + krb5_free_context(kcontext); + + return result; +} +*/ +gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; + gss_client_response *response = NULL; + int ret = AUTH_GSS_COMPLETE; + + state->server_name = GSS_C_NO_NAME; + state->context = GSS_C_NO_CONTEXT; + state->gss_flags = gss_flags; + state->username = NULL; + state->response = NULL; + + // Import server name first + name_token.length = strlen(service); + name_token.value = (char *)service; + + maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); + + if (GSS_ERROR(maj_stat)) { + response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + +end: + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + return response; +} + +gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { + OM_uint32 min_stat; + int ret = AUTH_GSS_COMPLETE; + gss_client_response *response = NULL; + + if(state->context != GSS_C_NO_CONTEXT) + gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); + + if(state->server_name != GSS_C_NO_NAME) + gss_release_name(&min_stat, &state->server_name); + + if(state->username != NULL) { + free(state->username); + state->username = NULL; + } + + if (state->response != NULL) { + free(state->response); + state->response = NULL; + } + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + return response; +} + +gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_CONTINUE; + gss_client_response *response = NULL; + + // Always clear out the old response + if (state->response != NULL) { + free(state->response); + state->response = NULL; + } + + // If there is a challenge (data from the server) we need to give it to GSS + if (challenge && *challenge) { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + + // Do GSSAPI step + maj_stat = gss_init_sec_context(&min_stat, + GSS_C_NO_CREDENTIAL, + &state->context, + state->server_name, + GSS_C_NO_OID, + (OM_uint32)state->gss_flags, + 0, + GSS_C_NO_CHANNEL_BINDINGS, + &input_token, + NULL, + &output_token, + NULL, + NULL); + + if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { + response = gss_error(__func__, "gss_init_sec_context", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; + // Grab the client response to send back to the server + if(output_token.length) { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); + maj_stat = gss_release_buffer(&min_stat, &output_token); + } + + // Try to get the user name if we have completed all GSS operations + if (ret == AUTH_GSS_COMPLETE) { + gss_name_t gssuser = GSS_C_NO_NAME; + maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); + + if(GSS_ERROR(maj_stat)) { + response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + gss_buffer_desc name_token; + name_token.length = 0; + maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); + + if(GSS_ERROR(maj_stat)) { + if(name_token.value) + gss_release_buffer(&min_stat, &name_token); + gss_release_name(&min_stat, &gssuser); + + response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } else { + state->username = (char *)malloc(name_token.length + 1); + if(state->username == NULL) die1("Memory allocation failed"); + strncpy(state->username, (char*) name_token.value, name_token.length); + state->username[name_token.length] = 0; + gss_release_buffer(&min_stat, &name_token); + gss_release_name(&min_stat, &gssuser); + } + } + +end: + if(output_token.value) + gss_release_buffer(&min_stat, &output_token); + if(input_token.value) + free(input_token.value); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + gss_client_response *response = NULL; + int ret = AUTH_GSS_CONTINUE; + + // Always clear out the old response + if(state->response != NULL) { + free(state->response); + state->response = NULL; + } + + // If there is a challenge (data from the server) we need to give it to GSS + if(challenge && *challenge) { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + + // Do GSSAPI step + maj_stat = gss_unwrap(&min_stat, + state->context, + &input_token, + &output_token, + NULL, + NULL); + + if(maj_stat != GSS_S_COMPLETE) { + response = gss_error(__func__, "gss_unwrap", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } else { + ret = AUTH_GSS_COMPLETE; + } + + // Grab the client response + if(output_token.length) { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); + gss_release_buffer(&min_stat, &output_token); + } +end: + if(output_token.value) + gss_release_buffer(&min_stat, &output_token); + if(input_token.value) + free(input_token.value); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_CONTINUE; + gss_client_response *response = NULL; + char buf[4096], server_conf_flags; + unsigned long buf_size; + + // Always clear out the old response + if(state->response != NULL) { + free(state->response); + state->response = NULL; + } + + if(challenge && *challenge) { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + + if(user) { + // get bufsize + server_conf_flags = ((char*) input_token.value)[0]; + ((char*) input_token.value)[0] = 0; + buf_size = ntohl(*((long *) input_token.value)); + free(input_token.value); +#ifdef PRINTFS + printf("User: %s, %c%c%c\n", user, + server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', + server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', + server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); + printf("Maximum GSS token size is %ld\n", buf_size); +#endif + + // agree to terms (hack!) + buf_size = htonl(buf_size); // not relevant without integrity/privacy + memcpy(buf, &buf_size, 4); + buf[0] = GSS_AUTH_P_NONE; + // server decides if principal can log in as user + strncpy(buf + 4, user, sizeof(buf) - 4); + input_token.value = buf; + input_token.length = 4 + strlen(user); + } + + // Do GSSAPI wrap + maj_stat = gss_wrap(&min_stat, + state->context, + 0, + GSS_C_QOP_DEFAULT, + &input_token, + NULL, + &output_token); + + if (maj_stat != GSS_S_COMPLETE) { + response = gss_error(__func__, "gss_wrap", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } else + ret = AUTH_GSS_COMPLETE; + // Grab the client response to send back to the server + if (output_token.length) { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; + gss_release_buffer(&min_stat, &output_token); + } +end: + if (output_token.value) + gss_release_buffer(&min_stat, &output_token); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_server_init(const char *service, bool constrained_delegation, const char *username, gss_server_state *state) +{ + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_COMPLETE; + gss_client_response *response = NULL; + gss_cred_usage_t usage = GSS_C_ACCEPT; + + state->context = GSS_C_NO_CONTEXT; + state->server_name = GSS_C_NO_NAME; + state->client_name = GSS_C_NO_NAME; + state->server_creds = GSS_C_NO_CREDENTIAL; + state->client_creds = GSS_C_NO_CREDENTIAL; + state->username = NULL; + state->targetname = NULL; + state->response = NULL; + state->constrained_delegation = constrained_delegation; + state->delegated_credentials_cache = NULL; + + // Server name may be empty which means we aren't going to create our own creds + size_t service_len = strlen(service); + if (service_len != 0) + { + // Import server name first + name_token.length = strlen(service); + name_token.value = (char *)service; + + maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); + + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + if (state->constrained_delegation) + { + usage = GSS_C_BOTH; + } + + // Get credentials + maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, + GSS_C_NO_OID_SET, usage, &state->server_creds, NULL, NULL); + + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_acquire_cred", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + } + + // If a username was passed, perform the S4U2Self protocol transition to acquire + // a credentials from that user as if we had done gss_accept_sec_context. + // In this scenario, the passed username is assumed to be already authenticated + // by some external mechanism, and we are here to "bootstrap" some gss credentials. + // In authenticate_gss_server_step we will bypass the actual authentication step. + if (username != NULL) + { + gss_name_t gss_username; + + name_token.length = strlen(username); + name_token.value = (char *)username; + + maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_USER_NAME, &gss_username); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + maj_stat = gss_acquire_cred_impersonate_name(&min_stat, + state->server_creds, + gss_username, + GSS_C_INDEFINITE, + GSS_C_NO_OID_SET, + GSS_C_INITIATE, + &state->client_creds, + NULL, + NULL); + + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_acquire_cred_impersonate_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + } + + gss_release_name(&min_stat, &gss_username); + + if (response != NULL) + { + goto end; + } + + // because the username MAY be a "local" username, + // we want get the canonical name from the acquired creds. + maj_stat = gss_inquire_cred(&min_stat, state->client_creds, &state->client_name, NULL, NULL, NULL); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_inquire_cred", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + } + +end: + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_server_clean(gss_server_state *state) +{ + OM_uint32 min_stat; + int ret = AUTH_GSS_COMPLETE; + gss_client_response *response = NULL; + + if (state->context != GSS_C_NO_CONTEXT) + gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); + if (state->server_name != GSS_C_NO_NAME) + gss_release_name(&min_stat, &state->server_name); + if (state->client_name != GSS_C_NO_NAME) + gss_release_name(&min_stat, &state->client_name); + if (state->server_creds != GSS_C_NO_CREDENTIAL) + gss_release_cred(&min_stat, &state->server_creds); + if (state->client_creds != GSS_C_NO_CREDENTIAL) + gss_release_cred(&min_stat, &state->client_creds); + if (state->username != NULL) + { + free(state->username); + state->username = NULL; + } + if (state->targetname != NULL) + { + free(state->targetname); + state->targetname = NULL; + } + if (state->response != NULL) + { + free(state->response); + state->response = NULL; + } + if (state->delegated_credentials_cache) + { + // TODO: what about actually destroying the cache? It can't be done now as + // the whole point is having it around for the lifetime of the "session" + free(state->delegated_credentials_cache); + } + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *auth_data) +{ + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_CONTINUE; + gss_client_response *response = NULL; + + // Always clear out the old response + if (state->response != NULL) + { + free(state->response); + state->response = NULL; + } + + // we don't need to check the authentication token if S4U2Self protocol + // transition was done, because we already have the client credentials. + if (state->client_creds == GSS_C_NO_CREDENTIAL) + { + if (auth_data && *auth_data) + { + int len; + input_token.value = base64_decode(auth_data, &len); + input_token.length = len; + } + else + { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->message = strdup("No auth_data value in request from client"); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + maj_stat = gss_accept_sec_context(&min_stat, + &state->context, + state->server_creds, + &input_token, + GSS_C_NO_CHANNEL_BINDINGS, + &state->client_name, + NULL, + &output_token, + NULL, + NULL, + &state->client_creds); + + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_accept_sec_context", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + // Grab the server response to send back to the client + if (output_token.length) + { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); + maj_stat = gss_release_buffer(&min_stat, &output_token); + } + } + + // Get the user name + maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + state->username = (char *)malloc(output_token.length + 1); + strncpy(state->username, (char*) output_token.value, output_token.length); + state->username[output_token.length] = 0; + + // Get the target name if no server creds were supplied + if (state->server_creds == GSS_C_NO_CREDENTIAL) + { + gss_name_t target_name = GSS_C_NO_NAME; + maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + state->targetname = (char *)malloc(output_token.length + 1); + strncpy(state->targetname, (char*) output_token.value, output_token.length); + state->targetname[output_token.length] = 0; + } + + if (state->constrained_delegation && state->client_creds != GSS_C_NO_CREDENTIAL) + { + if ((response = store_gss_creds(state)) != NULL) + { + goto end; + } + } + + ret = AUTH_GSS_COMPLETE; + +end: + if (output_token.length) + gss_release_buffer(&min_stat, &output_token); + if (input_token.value) + free(input_token.value); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +static gss_client_response *store_gss_creds(gss_server_state *state) +{ + OM_uint32 maj_stat, min_stat; + krb5_principal princ = NULL; + krb5_ccache ccache = NULL; + krb5_error_code problem; + krb5_context context; + gss_client_response *response = NULL; + + problem = krb5_init_context(&context); + if (problem) { + response = other_error("No auth_data value in request from client"); + return response; + } + + problem = krb5_parse_name(context, state->username, &princ); + if (problem) { + response = krb5_ctx_error(context, problem); + goto end; + } + + if ((response = create_krb5_ccache(state, context, princ, &ccache))) + { + goto end; + } + + maj_stat = gss_krb5_copy_ccache(&min_stat, state->client_creds, ccache); + if (GSS_ERROR(maj_stat)) { + response = gss_error(__func__, "gss_krb5_copy_ccache", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + krb5_cc_close(context, ccache); + ccache = NULL; + + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + // TODO: something other than AUTH_GSS_COMPLETE? + response->return_code = AUTH_GSS_COMPLETE; + + end: + if (princ) + krb5_free_principal(context, princ); + if (ccache) + krb5_cc_destroy(context, ccache); + krb5_free_context(context); + + return response; +} + +static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context kcontext, krb5_principal princ, krb5_ccache *ccache) +{ + char *ccname = NULL; + int fd; + krb5_error_code problem; + krb5_ccache tmp_ccache = NULL; + gss_client_response *error = NULL; + + // TODO: mod_auth_kerb used a temp file under /run/httpd/krbcache. what can we do? + ccname = strdup("FILE:/tmp/krb5cc_nodekerberos_XXXXXX"); + if (!ccname) die1("Memory allocation failed"); + + fd = mkstemp(ccname + strlen("FILE:")); + if (fd < 0) { + error = other_error("mkstemp() failed: %s", strerror(errno)); + goto end; + } + + close(fd); + + problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache); + if (problem) { + error = krb5_ctx_error(kcontext, problem); + goto end; + } + + problem = krb5_cc_initialize(kcontext, tmp_ccache, princ); + if (problem) { + error = krb5_ctx_error(kcontext, problem); + goto end; + } + + state->delegated_credentials_cache = strdup(ccname); + + // TODO: how/when to cleanup the creds cache file? + // TODO: how to expose the credentials expiration time? + + *ccache = tmp_ccache; + tmp_ccache = NULL; + + end: + if (tmp_ccache) + krb5_cc_destroy(kcontext, tmp_ccache); + + if (ccname && error) + unlink(ccname); + + if (ccname) + free(ccname); + + return error; +} + + +gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min) { + OM_uint32 maj_stat, min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string; + + gss_client_response *response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + + char *message = NULL; + message = calloc(1024, 1); + if(message == NULL) die1("Memory allocation failed"); + + response->message = message; + + int nleft = 1024; + int n; + + n = snprintf(message, nleft, "%s(%s)", func, op); + message += n; + nleft -= n; + + do { + maj_stat = gss_display_status (&min_stat, + err_maj, + GSS_C_GSS_CODE, + GSS_C_NO_OID, + &msg_ctx, + &status_string); + if(GSS_ERROR(maj_stat)) + break; + + n = snprintf(message, nleft, ": %.*s", + (int)status_string.length, (char*)status_string.value); + message += n; + nleft -= n; + + gss_release_buffer(&min_stat, &status_string); + + maj_stat = gss_display_status (&min_stat, + err_min, + GSS_C_MECH_CODE, + GSS_C_NULL_OID, + &msg_ctx, + &status_string); + if(!GSS_ERROR(maj_stat)) { + n = snprintf(message, nleft, ": %.*s", + (int)status_string.length, (char*)status_string.value); + message += n; + nleft -= n; + + gss_release_buffer(&min_stat, &status_string); + } + } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); + + return response; +} + +static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem) +{ + gss_client_response *response = NULL; + const char *error_text = krb5_get_error_message(context, problem); + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->message = strdup(error_text); + // TODO: something other than AUTH_GSS_ERROR? AUTH_KRB5_ERROR ? + response->return_code = AUTH_GSS_ERROR; + krb5_free_error_message(context, error_text); + return response; +} + +static gss_client_response *other_error(const char *fmt, ...) +{ + size_t needed; + char *msg; + gss_client_response *response = NULL; + va_list ap, aps; + + va_start(ap, fmt); + + va_copy(aps, ap); + needed = snprintf(NULL, 0, fmt, aps); + va_end(aps); + + msg = malloc(needed); + if (!msg) die1("Memory allocation failed"); + + vsnprintf(msg, needed, fmt, ap); + va_end(ap); + + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->message = msg; + + // TODO: something other than AUTH_GSS_ERROR? + response->return_code = AUTH_GSS_ERROR; + + return response; +} + + +#pragma clang diagnostic pop + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h new file mode 100644 index 0000000..fa7e311 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h @@ -0,0 +1,73 @@ +/** + * Copyright (c) 2006-2009 Apple Inc. All rights reserved. + * + * 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. + **/ +#ifndef KERBEROS_GSS_H +#define KERBEROS_GSS_H + +#include + +#include +#include +#include + +#define krb5_get_err_text(context,code) error_message(code) + +#define AUTH_GSS_ERROR -1 +#define AUTH_GSS_COMPLETE 1 +#define AUTH_GSS_CONTINUE 0 + +#define GSS_AUTH_P_NONE 1 +#define GSS_AUTH_P_INTEGRITY 2 +#define GSS_AUTH_P_PRIVACY 4 + +typedef struct { + int return_code; + char *message; +} gss_client_response; + +typedef struct { + gss_ctx_id_t context; + gss_name_t server_name; + long int gss_flags; + char* username; + char* response; +} gss_client_state; + +typedef struct { + gss_ctx_id_t context; + gss_name_t server_name; + gss_name_t client_name; + gss_cred_id_t server_creds; + gss_cred_id_t client_creds; + char* username; + char* targetname; + char* response; + bool constrained_delegation; + char* delegated_credentials_cache; +} gss_server_state; + +// char* server_principal_details(const char* service, const char* hostname); + +gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); +gss_client_response *authenticate_gss_client_clean(gss_client_state *state); +gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); +gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); +gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); + +gss_client_response *authenticate_gss_server_init(const char* service, bool constrained_delegation, const char *username, gss_server_state* state); +gss_client_response *authenticate_gss_server_clean(gss_server_state *state); +gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *challenge); + +#endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js new file mode 100644 index 0000000..d9120fb --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js @@ -0,0 +1,15 @@ +// Load the native SSPI classes +var kerberos = require('../build/Release/kerberos') + , Kerberos = kerberos.Kerberos + , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer + , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor + , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials + , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; +var SSPI = function() { +} + +exports.SSPI = SSPI; +exports.SecurityBuffer = SecurityBuffer; +exports.SecurityBufferDescriptor = SecurityBufferDescriptor; +exports.SecurityCredentials = SecurityCredentials; +exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c new file mode 100644 index 0000000..502a021 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c @@ -0,0 +1,121 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * 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. + **/ + +#include "base64.h" + +#include +#include + +// base64 tables +static char basis_64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static signed char index_64[128] = +{ + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 +}; +#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) + +// base64_encode : base64 encode +// +// value : data to encode +// vlen : length of data +// (result) : new char[] - c-str of result +char *base64_encode(const unsigned char *value, int vlen) +{ + char *result = (char *)malloc((vlen * 4) / 3 + 5); + char *out = result; + unsigned char oval; + + while (vlen >= 3) + { + *out++ = basis_64[value[0] >> 2]; + *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; + *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; + *out++ = basis_64[value[2] & 0x3F]; + value += 3; + vlen -= 3; + } + if (vlen > 0) + { + *out++ = basis_64[value[0] >> 2]; + oval = (value[0] << 4) & 0x30; + if (vlen > 1) oval |= value[1] >> 4; + *out++ = basis_64[oval]; + *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; + *out++ = '='; + } + *out = '\0'; + + return result; +} + +// base64_decode : base64 decode +// +// value : c-str to decode +// rlen : length of decoded result +// (result) : new unsigned char[] - decoded result +unsigned char *base64_decode(const char *value, int *rlen) +{ + int c1, c2, c3, c4; + int vlen = (int)strlen(value); + unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); + unsigned char *out = result; + *rlen = 0; + + while (1) + { + if (value[0]==0) + return result; + c1 = value[0]; + if (CHAR64(c1) == -1) + goto base64_decode_error;; + c2 = value[1]; + if (CHAR64(c2) == -1) + goto base64_decode_error;; + c3 = value[2]; + if ((c3 != '=') && (CHAR64(c3) == -1)) + goto base64_decode_error;; + c4 = value[3]; + if ((c4 != '=') && (CHAR64(c4) == -1)) + goto base64_decode_error;; + + value += 4; + *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); + *rlen += 1; + if (c3 != '=') + { + *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); + *rlen += 1; + if (c4 != '=') + { + *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); + *rlen += 1; + } + } + } + +base64_decode_error: + *result = 0; + *rlen = 0; + return result; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h new file mode 100644 index 0000000..f0e1f06 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * 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. + **/ + +char *base64_encode(const unsigned char *value, int vlen); +unsigned char *base64_decode(const char *value, int *rlen); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc new file mode 100644 index 0000000..c7b583f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc @@ -0,0 +1,51 @@ +#include "kerberos.h" +#include +#include +#include "base64.h" +#include "wrappers/security_buffer.h" +#include "wrappers/security_buffer_descriptor.h" +#include "wrappers/security_context.h" +#include "wrappers/security_credentials.h" + +Nan::Persistent Kerberos::constructor_template; + +Kerberos::Kerberos() : Nan::ObjectWrap() { +} + +void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("Kerberos").ToLocalChecked()); + + // Set persistent + constructor_template.Reset(t); + + // Set the symbol + Nan::Set(target, Nan::New("Kerberos").ToLocalChecked(), t->GetFunction()); +} + +NAN_METHOD(Kerberos::New) { + // Load the security.dll library + load_library(); + // Create a Kerberos instance + Kerberos *kerberos = new Kerberos(); + // Return the kerberos object + kerberos->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +// Exporting function +NAN_MODULE_INIT(init) { + Kerberos::Initialize(target); + SecurityContext::Initialize(target); + SecurityBuffer::Initialize(target); + SecurityBufferDescriptor::Initialize(target); + SecurityCredentials::Initialize(target); +} + +NODE_MODULE(kerberos, init); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h new file mode 100644 index 0000000..0fd2760 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h @@ -0,0 +1,60 @@ +#ifndef KERBEROS_H +#define KERBEROS_H + +#include +#include +#include +#include "nan.h" + +extern "C" { + #include "kerberos_sspi.h" + #include "base64.h" +} + +using namespace v8; +using namespace node; + +class Kerberos : public Nan::ObjectWrap { + +public: + Kerberos(); + ~Kerberos() {}; + + // Constructor used for creating new Kerberos objects from C++ + static Nan::Persistent constructor_template; + + // Initialize function for the object + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + + // Method available + static NAN_METHOD(AcquireAlternateCredentials); + static NAN_METHOD(PrepareOutboundPackage); + static NAN_METHOD(DecryptMessage); + static NAN_METHOD(EncryptMessage); + static NAN_METHOD(QueryContextAttributes); + +private: + static NAN_METHOD(New); + + // Pointer to context object + SEC_WINNT_AUTH_IDENTITY m_Identity; + // credentials + CredHandle m_Credentials; + // Expiry time for ticket + TimeStamp Expiration; + // package info + SecPkgInfo m_PkgInfo; + // context + CtxtHandle m_Context; + // Do we have a context + bool m_HaveContext; + // Attributes + DWORD CtxtAttr; + + // Handles the uv calls + static void Process(uv_work_t* work_req); + // Called after work is done + static void After(uv_work_t* work_req); +}; + +#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c new file mode 100644 index 0000000..d75c9ab --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c @@ -0,0 +1,244 @@ +#include "kerberos_sspi.h" +#include +#include + +static HINSTANCE _sspi_security_dll = NULL; +static HINSTANCE _sspi_secur32_dll = NULL; + +/** + * Encrypt A Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { + // Create function pointer instance + encryptMessage_fn pfn_encryptMessage = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + // Map function to library method + pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); + // Check if the we managed to map function pointer + if(!pfn_encryptMessage) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); +} + +/** + * Acquire Credentials + */ +SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( + LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, + void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, + PCredHandle phCredential, PTimeStamp ptsExpiry +) { + SECURITY_STATUS status; + // Create function pointer instance + acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + // Map function + #ifdef _UNICODE + pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); + #else + pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); + #endif + + // Check if the we managed to map function pointer + if(!pfn_acquireCredentialsHandle) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Status + status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, + pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry + ); + + // Call the function + return status; +} + +/** + * Delete Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { + // Create function pointer instance + deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + // Map function + pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); + + // Check if the we managed to map function pointer + if(!pfn_deleteSecurityContext) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_deleteSecurityContext)(phContext); +} + +/** + * Decrypt Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { + // Create function pointer instance + decryptMessage_fn pfn_decryptMessage = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + // Map function + pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); + + // Check if the we managed to map function pointer + if(!pfn_decryptMessage) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); +} + +/** + * Initialize Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( + PCredHandle phCredential, PCtxtHandle phContext, + LPSTR pszTargetName, unsigned long fContextReq, + unsigned long Reserved1, unsigned long TargetDataRep, + PSecBufferDesc pInput, unsigned long Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, + unsigned long * pfContextAttr, PTimeStamp ptsExpiry +) { + SECURITY_STATUS status; + // Create function pointer instance + initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + // Map function + #ifdef _UNICODE + pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); + #else + pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); + #endif + + // Check if the we managed to map function pointer + if(!pfn_initializeSecurityContext) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Execute intialize context + status = (*pfn_initializeSecurityContext)( + phCredential, phContext, pszTargetName, fContextReq, + Reserved1, TargetDataRep, pInput, Reserved2, + phNewContext, pOutput, pfContextAttr, ptsExpiry + ); + + // Call the function + return status; +} +/** + * Query Context Attributes + */ +SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( + PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer +) { + // Create function pointer instance + queryContextAttributes_fn pfn_queryContextAttributes = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + #ifdef _UNICODE + pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); + #else + pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); + #endif + + // Check if the we managed to map function pointer + if(!pfn_queryContextAttributes) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_queryContextAttributes)( + phContext, ulAttribute, pBuffer + ); +} + +/** + * InitSecurityInterface + */ +PSecurityFunctionTable _ssip_InitSecurityInterface() { + INIT_SECURITY_INTERFACE InitSecurityInterface; + PSecurityFunctionTable pSecurityInterface = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return NULL; + + #ifdef _UNICODE + // Get the address of the InitSecurityInterface function. + InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( + _sspi_secur32_dll, + TEXT("InitSecurityInterfaceW")); + #else + // Get the address of the InitSecurityInterface function. + InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( + _sspi_secur32_dll, + TEXT("InitSecurityInterfaceA")); + #endif + + if(!InitSecurityInterface) { + printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); + return NULL; + } + + // Use InitSecurityInterface to get the function table. + pSecurityInterface = (*InitSecurityInterface)(); + + if(!pSecurityInterface) { + printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); + return NULL; + } + + return pSecurityInterface; +} + +/** + * Load security.dll dynamically + */ +int load_library() { + DWORD err; + // Load the library + _sspi_security_dll = LoadLibrary("security.dll"); + + // Check if the library loaded + if(_sspi_security_dll == NULL) { + err = GetLastError(); + return err; + } + + // Load the library + _sspi_secur32_dll = LoadLibrary("secur32.dll"); + + // Check if the library loaded + if(_sspi_secur32_dll == NULL) { + err = GetLastError(); + return err; + } + + return 0; +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h new file mode 100644 index 0000000..a3008dc --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h @@ -0,0 +1,106 @@ +#ifndef SSPI_C_H +#define SSPI_C_H + +#define SECURITY_WIN32 1 + +#include +#include + +/** + * Encrypt A Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); + +typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); + +/** + * Acquire Credentials + */ +SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( + LPSTR pszPrincipal, // Name of principal + LPSTR pszPackage, // Name of package + unsigned long fCredentialUse, // Flags indicating use + void * pvLogonId, // Pointer to logon ID + void * pAuthData, // Package specific data + SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func + void * pvGetKeyArgument, // Value to pass to GetKey() + PCredHandle phCredential, // (out) Cred Handle + PTimeStamp ptsExpiry // (out) Lifetime (optional) +); + +typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( + LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, + void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, + PCredHandle phCredential, PTimeStamp ptsExpiry + ); + +/** + * Delete Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( + PCtxtHandle phContext // Context to delete +); + +typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); + +/** + * Decrypt Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( + PCtxtHandle phContext, + PSecBufferDesc pMessage, + unsigned long MessageSeqNo, + unsigned long pfQOP +); + +typedef DWORD (WINAPI *decryptMessage_fn)( + PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); + +/** + * Initialize Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( + PCredHandle phCredential, // Cred to base context + PCtxtHandle phContext, // Existing context (OPT) + LPSTR pszTargetName, // Name of target + unsigned long fContextReq, // Context Requirements + unsigned long Reserved1, // Reserved, MBZ + unsigned long TargetDataRep, // Data rep of target + PSecBufferDesc pInput, // Input Buffers + unsigned long Reserved2, // Reserved, MBZ + PCtxtHandle phNewContext, // (out) New Context handle + PSecBufferDesc pOutput, // (inout) Output Buffers + unsigned long * pfContextAttr, // (out) Context attrs + PTimeStamp ptsExpiry // (out) Life span (OPT) +); + +typedef DWORD (WINAPI *initializeSecurityContext_fn)( + PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, + unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); + +/** + * Query Context Attributes + */ +SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( + PCtxtHandle phContext, // Context to query + unsigned long ulAttribute, // Attribute to query + void * pBuffer // Buffer for attributes +); + +typedef DWORD (WINAPI *queryContextAttributes_fn)( + PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); + +/** + * InitSecurityInterface + */ +PSecurityFunctionTable _ssip_InitSecurityInterface(); + +typedef DWORD (WINAPI *initSecurityInterface_fn) (); + +/** + * Load security.dll dynamically + */ +int load_library(); + +#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc new file mode 100644 index 0000000..e7a472f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc @@ -0,0 +1,7 @@ +#include "worker.h" + +Worker::Worker() { +} + +Worker::~Worker() { +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h new file mode 100644 index 0000000..c2ccb6b --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h @@ -0,0 +1,38 @@ +#ifndef WORKER_H_ +#define WORKER_H_ + +#include +#include +#include +#include + +using namespace node; +using namespace v8; + +class Worker { + public: + Worker(); + virtual ~Worker(); + + // libuv's request struct. + uv_work_t request; + // Callback + Nan::Callback *callback; + // Parameters + void *parameters; + // Results + void *return_value; + // Did we raise an error + bool error; + // The error message + char *error_message; + // Error code if not message + int error_code; + // Any return code + int return_code; + // Method we are going to fire + void (*execute)(Worker *worker); + Local (*mapper)(Worker *worker); +}; + +#endif // WORKER_H_ diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc new file mode 100644 index 0000000..fdf8e49 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc @@ -0,0 +1,101 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "security_buffer.h" + +using namespace node; + +Nan::Persistent SecurityBuffer::constructor_template; + +SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : Nan::ObjectWrap() { + this->size = size; + this->data = calloc(size, sizeof(char)); + this->security_type = security_type; + // Set up the data in the sec_buffer + this->sec_buffer.BufferType = security_type; + this->sec_buffer.cbBuffer = (unsigned long)size; + this->sec_buffer.pvBuffer = this->data; +} + +SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : Nan::ObjectWrap() { + this->size = size; + this->data = data; + this->security_type = security_type; + // Set up the data in the sec_buffer + this->sec_buffer.BufferType = security_type; + this->sec_buffer.cbBuffer = (unsigned long)size; + this->sec_buffer.pvBuffer = this->data; +} + +SecurityBuffer::~SecurityBuffer() { + free(this->data); +} + +NAN_METHOD(SecurityBuffer::New) { + SecurityBuffer *security_obj; + + if(info.Length() != 2) + return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); + + if(!info[0]->IsInt32()) + return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); + + if(!info[1]->IsInt32() && !Buffer::HasInstance(info[1])) + return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); + + // Unpack buffer type + uint32_t buffer_type = info[0]->ToUint32()->Value(); + + // If we have an integer + if(info[1]->IsInt32()) { + security_obj = new SecurityBuffer(buffer_type, info[1]->ToUint32()->Value()); + } else { + // Get the length of the Buffer + size_t length = Buffer::Length(info[1]->ToObject()); + // Allocate space for the internal void data pointer + void *data = calloc(length, sizeof(char)); + // Write the data to out of V8 heap space + memcpy(data, Buffer::Data(info[1]->ToObject()), length); + // Create new SecurityBuffer + security_obj = new SecurityBuffer(buffer_type, length, data); + } + + // Wrap it + security_obj->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +NAN_METHOD(SecurityBuffer::ToBuffer) { + // Unpack the Security Buffer object + SecurityBuffer *security_obj = Nan::ObjectWrap::Unwrap(info.This()); + // Create a Buffer + Local buffer = Nan::CopyBuffer((char *)security_obj->data, (uint32_t)security_obj->size).ToLocalChecked(); + // Return the buffer + info.GetReturnValue().Set(buffer); +} + +void SecurityBuffer::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("SecurityBuffer").ToLocalChecked()); + + // Class methods + Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer); + + // Set persistent + constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("SecurityBuffer").ToLocalChecked(), t->GetFunction()); +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h new file mode 100644 index 0000000..0c97d56 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h @@ -0,0 +1,48 @@ +#ifndef SECURITY_BUFFER_H +#define SECURITY_BUFFER_H + +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include +#include +#include +#include + +using namespace v8; +using namespace node; + +class SecurityBuffer : public Nan::ObjectWrap { + public: + SecurityBuffer(uint32_t security_type, size_t size); + SecurityBuffer(uint32_t security_type, size_t size, void *data); + ~SecurityBuffer(); + + // Internal values + void *data; + size_t size; + uint32_t security_type; + SecBuffer sec_buffer; + + // Has instance check + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + // Functions available from V8 + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + static NAN_METHOD(ToBuffer); + + // Constructor used for creating new Long objects from C++ + static Nan::Persistent constructor_template; + + private: + static NAN_METHOD(New); +}; + +#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js new file mode 100644 index 0000000..4996163 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js @@ -0,0 +1,12 @@ +var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; + +// Add some attributes +SecurityBufferNative.VERSION = 0; +SecurityBufferNative.EMPTY = 0; +SecurityBufferNative.DATA = 1; +SecurityBufferNative.TOKEN = 2; +SecurityBufferNative.PADDING = 9; +SecurityBufferNative.STREAM = 10; + +// Export the modified class +exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc new file mode 100644 index 0000000..fce0d81 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc @@ -0,0 +1,182 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include "security_buffer_descriptor.h" +#include "security_buffer.h" + +Nan::Persistent SecurityBufferDescriptor::constructor_template; + +SecurityBufferDescriptor::SecurityBufferDescriptor() : Nan::ObjectWrap() { +} + +SecurityBufferDescriptor::SecurityBufferDescriptor(const Nan::Persistent& arrayObjectPersistent) : Nan::ObjectWrap() { + SecurityBuffer *security_obj = NULL; + // Get the Local value + Local arrayObject = Nan::New(arrayObjectPersistent); + + // Safe reference to array + this->arrayObject = arrayObject; + + // Unpack the array and ensure we have a valid descriptor + this->secBufferDesc.cBuffers = arrayObject->Length(); + this->secBufferDesc.ulVersion = SECBUFFER_VERSION; + + if(arrayObject->Length() == 1) { + // Unwrap the buffer + security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); + // Assign the buffer + this->secBufferDesc.pBuffers = &security_obj->sec_buffer; + } else { + this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; + this->secBufferDesc.cBuffers = arrayObject->Length(); + + // Assign the buffers + for(uint32_t i = 0; i < arrayObject->Length(); i++) { + security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); + this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; + this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; + this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; + } + } +} + +SecurityBufferDescriptor::~SecurityBufferDescriptor() { +} + +size_t SecurityBufferDescriptor::bufferSize() { + SecurityBuffer *security_obj = NULL; + + if(this->secBufferDesc.cBuffers == 1) { + security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); + return security_obj->size; + } else { + int bytesToAllocate = 0; + + for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { + bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; + } + + // Return total size + return bytesToAllocate; + } +} + +char *SecurityBufferDescriptor::toBuffer() { + SecurityBuffer *security_obj = NULL; + char *data = NULL; + + if(this->secBufferDesc.cBuffers == 1) { + security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); + data = (char *)malloc(security_obj->size * sizeof(char)); + memcpy(data, security_obj->data, security_obj->size); + } else { + size_t bytesToAllocate = this->bufferSize(); + char *data = (char *)calloc(bytesToAllocate, sizeof(char)); + int offset = 0; + + for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { + memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); + offset +=this->secBufferDesc.pBuffers[i].cbBuffer; + } + + // Return the data + return data; + } + + return data; +} + +NAN_METHOD(SecurityBufferDescriptor::New) { + SecurityBufferDescriptor *security_obj; + Nan::Persistent arrayObject; + + if(info.Length() != 1) + return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); + + if(!info[0]->IsInt32() && !info[0]->IsArray()) + return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); + + if(info[0]->IsArray()) { + Local array = Local::Cast(info[0]); + // Iterate over all items and ensure we the right type + for(uint32_t i = 0; i < array->Length(); i++) { + if(!SecurityBuffer::HasInstance(array->Get(i))) { + return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); + } + } + } + + // We have a single integer + if(info[0]->IsInt32()) { + // Create new SecurityBuffer instance + Local argv[] = {Nan::New(0x02), info[0]}; + Local security_buffer = Nan::New(SecurityBuffer::constructor_template)->GetFunction()->NewInstance(2, argv); + // Create a new array + Local array = Nan::New(1); + // Set the first value + array->Set(0, security_buffer); + + // Create persistent handle + Nan::Persistent persistenHandler; + persistenHandler.Reset(array); + + // Create descriptor + security_obj = new SecurityBufferDescriptor(persistenHandler); + } else { + // Create a persistent handler + Nan::Persistent persistenHandler; + persistenHandler.Reset(Local::Cast(info[0])); + // Create a descriptor + security_obj = new SecurityBufferDescriptor(persistenHandler); + } + + // Wrap it + security_obj->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +NAN_METHOD(SecurityBufferDescriptor::ToBuffer) { + // Unpack the Security Buffer object + SecurityBufferDescriptor *security_obj = Nan::ObjectWrap::Unwrap(info.This()); + + // Get the buffer + char *buffer_data = security_obj->toBuffer(); + size_t buffer_size = security_obj->bufferSize(); + + // Create a Buffer + Local buffer = Nan::CopyBuffer(buffer_data, (uint32_t)buffer_size).ToLocalChecked(); + + // Return the buffer + info.GetReturnValue().Set(buffer); +} + +void SecurityBufferDescriptor::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("SecurityBufferDescriptor").ToLocalChecked()); + + // Class methods + Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer); + + // Set persistent + constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("SecurityBufferDescriptor").ToLocalChecked(), t->GetFunction()); +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h new file mode 100644 index 0000000..dc28f7e --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h @@ -0,0 +1,46 @@ +#ifndef SECURITY_BUFFER_DESCRIPTOR_H +#define SECURITY_BUFFER_DESCRIPTOR_H + +#include +#include +#include + +#include +#include +#include +#include + +using namespace v8; +using namespace node; + +class SecurityBufferDescriptor : public Nan::ObjectWrap { + public: + Local arrayObject; + SecBufferDesc secBufferDesc; + + SecurityBufferDescriptor(); + SecurityBufferDescriptor(const Nan::Persistent& arrayObjectPersistent); + ~SecurityBufferDescriptor(); + + // Has instance check + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + char *toBuffer(); + size_t bufferSize(); + + // Functions available from V8 + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + static NAN_METHOD(ToBuffer); + + // Constructor used for creating new Long objects from C++ + static Nan::Persistent constructor_template; + + private: + static NAN_METHOD(New); +}; + +#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js new file mode 100644 index 0000000..9421392 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js @@ -0,0 +1,3 @@ +var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; +// Export the modified class +exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc new file mode 100644 index 0000000..5d7ad54 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc @@ -0,0 +1,856 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "security_context.h" +#include "security_buffer_descriptor.h" + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) +#endif + +static LPSTR DisplaySECError(DWORD ErrCode); + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// UV Lib callbacks +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void Process(uv_work_t* work_req) { + // Grab the worker + Worker *worker = static_cast(work_req->data); + // Execute the worker code + worker->execute(worker); +} + +static void After(uv_work_t* work_req) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Get the worker reference + Worker *worker = static_cast(work_req->data); + + // If we have an error + if(worker->error) { + Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); + Local obj = err->ToObject(); + obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); + Local info[2] = { err, Nan::Null() }; + // Execute the error + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } else { + // // Map the data + Local result = worker->mapper(worker); + // Set up the callback with a null first + Local info[2] = { Nan::Null(), result}; + // Wrap the callback function call in a TryCatch so that we can call + // node's FatalException afterwards. This makes it possible to catch + // the exception from JavaScript land using the + // process.on('uncaughtException') event. + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } + + // Clean up the memory + delete worker->callback; + delete worker; +} + +Nan::Persistent SecurityContext::constructor_template; + +SecurityContext::SecurityContext() : Nan::ObjectWrap() { +} + +SecurityContext::~SecurityContext() { + if(this->hasContext) { + _sspi_DeleteSecurityContext(&this->m_Context); + } +} + +NAN_METHOD(SecurityContext::New) { + PSecurityFunctionTable pSecurityInterface = NULL; + DWORD dwNumOfPkgs; + SECURITY_STATUS status; + + // Create code object + SecurityContext *security_obj = new SecurityContext(); + // Get security table interface + pSecurityInterface = _ssip_InitSecurityInterface(); + // Call the security interface + status = (*pSecurityInterface->EnumerateSecurityPackages)( + &dwNumOfPkgs, + &security_obj->m_PkgInfo); + if(status != SEC_E_OK) { + printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); + return Nan::ThrowError("Failed in retrieving security packages"); + } + + // Wrap it + security_obj->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +// +// Async InitializeContext +// +typedef struct SecurityContextStaticInitializeCall { + char *service_principal_name_str; + char *decoded_input_str; + int decoded_input_str_length; + SecurityContext *context; +} SecurityContextStaticInitializeCall; + +static void _initializeContext(Worker *worker) { + // Status of operation + SECURITY_STATUS status; + BYTE *out_bound_data_str = NULL; + SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; + + // Structures used for c calls + SecBufferDesc ibd, obd; + SecBuffer ib, ob; + + // + // Prepare data structure for returned data from SSPI + ob.BufferType = SECBUFFER_TOKEN; + ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; + // Allocate space for return data + out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; + ob.pvBuffer = out_bound_data_str; + // prepare buffer description + obd.cBuffers = 1; + obd.ulVersion = SECBUFFER_VERSION; + obd.pBuffers = &ob; + + // + // Prepare the data we are passing to the SSPI method + if(call->decoded_input_str_length > 0) { + ib.BufferType = SECBUFFER_TOKEN; + ib.cbBuffer = call->decoded_input_str_length; + ib.pvBuffer = call->decoded_input_str; + // prepare buffer description + ibd.cBuffers = 1; + ibd.ulVersion = SECBUFFER_VERSION; + ibd.pBuffers = &ib; + } + + // Perform initialization step + status = _sspi_initializeSecurityContext( + &call->context->security_credentials->m_Credentials + , NULL + , const_cast(call->service_principal_name_str) + , 0x02 // MUTUAL + , 0 + , 0 // Network + , call->decoded_input_str_length > 0 ? &ibd : NULL + , 0 + , &call->context->m_Context + , &obd + , &call->context->CtxtAttr + , &call->context->Expiration + ); + + // If we have a ok or continue let's prepare the result + if(status == SEC_E_OK + || status == SEC_I_COMPLETE_NEEDED + || status == SEC_I_CONTINUE_NEEDED + || status == SEC_I_COMPLETE_AND_CONTINUE + ) { + call->context->hasContext = true; + call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); + + // Set the context + worker->return_code = status; + worker->return_value = call->context; + } else if(status == SEC_E_INSUFFICIENT_MEMORY) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INSUFFICIENT_MEMORY There is not enough memory available to complete the requested action."; + } else if(status == SEC_E_INTERNAL_ERROR) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INTERNAL_ERROR An error occurred that did not map to an SSPI error code."; + } else if(status == SEC_E_INVALID_HANDLE) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INVALID_HANDLE The handle passed to the function is not valid."; + } else if(status == SEC_E_INVALID_TOKEN) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INVALID_TOKEN The error is due to a malformed input token, such as a token corrupted in transit, a token of incorrect size, or a token passed into the wrong security package. Passing a token to the wrong package can happen if the client and server did not negotiate the proper security package."; + } else if(status == SEC_E_LOGON_DENIED) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_LOGON_DENIED The logon failed."; + } else if(status == SEC_E_NO_AUTHENTICATING_AUTHORITY) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_NO_AUTHENTICATING_AUTHORITY No authority could be contacted for authentication. The domain name of the authenticating party could be wrong, the domain could be unreachable, or there might have been a trust relationship failure."; + } else if(status == SEC_E_NO_CREDENTIALS) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_NO_CREDENTIALS No credentials are available in the security package."; + } else if(status == SEC_E_TARGET_UNKNOWN) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_TARGET_UNKNOWN The target was not recognized."; + } else if(status == SEC_E_UNSUPPORTED_FUNCTION) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_UNSUPPORTED_FUNCTION A context attribute flag that is not valid (ISC_REQ_DELEGATE or ISC_REQ_PROMPT_FOR_CREDS) was specified in the fContextReq parameter."; + } else if(status == SEC_E_WRONG_PRINCIPAL) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_WRONG_PRINCIPAL The principal that received the authentication request is not the same as the one passed into the pszTargetName parameter. This indicates a failure in mutual authentication."; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } + + // Clean up data + if(call->decoded_input_str != NULL) free(call->decoded_input_str); + if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); +} + +static Local _map_initializeContext(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return context->handle(); +} + +NAN_METHOD(SecurityContext::InitializeContext) { + char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; + int decoded_input_str_length = NULL; + // Store reference to security credentials + SecurityCredentials *security_credentials = NULL; + + // We need 3 parameters + if(info.Length() != 4) + return Nan::ThrowError("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); + + // First parameter must be an instance of SecurityCredentials + if(!SecurityCredentials::HasInstance(info[0])) + return Nan::ThrowError("First parameter for Initialize must be an instance of SecurityCredentials"); + + // Second parameter must be a string + if(!info[1]->IsString()) + return Nan::ThrowError("Second parameter for Initialize must be a string"); + + // Third parameter must be a base64 encoded string + if(!info[2]->IsString()) + return Nan::ThrowError("Second parameter for Initialize must be a string"); + + // Third parameter must be a callback + if(!info[3]->IsFunction()) + return Nan::ThrowError("Third parameter for Initialize must be a callback function"); + + // Let's unpack the values + Local service_principal_name = info[1]->ToString(); + service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); + service_principal_name->WriteUtf8(service_principal_name_str); + + // Unpack the user name + Local input = info[2]->ToString(); + + if(input->Utf8Length() > 0) { + input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); + input->WriteUtf8(input_str); + + // Now let's get the base64 decoded string + decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); + // Free original allocation + free(input_str); + } + + // Unpack the Security credentials + security_credentials = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); + // Create Security context instance + Local security_context_value = Nan::New(constructor_template)->GetFunction()->NewInstance(); + // Unwrap the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(security_context_value); + // Add a reference to the security_credentials + security_context->security_credentials = security_credentials; + + // Build the call function + SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); + call->context = security_context; + call->decoded_input_str = decoded_input_str; + call->decoded_input_str_length = decoded_input_str_length; + call->service_principal_name_str = service_principal_name_str; + + // Callback + Local callback = Local::Cast(info[3]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _initializeContext; + worker->mapper = _map_initializeContext; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +NAN_GETTER(SecurityContext::PayloadGetter) { + // Unpack the context object + SecurityContext *context = Nan::ObjectWrap::Unwrap(info.This()); + // Return the low bits + info.GetReturnValue().Set(Nan::New(context->payload).ToLocalChecked()); +} + +NAN_GETTER(SecurityContext::HasContextGetter) { + // Unpack the context object + SecurityContext *context = Nan::ObjectWrap::Unwrap(info.This()); + // Return the low bits + info.GetReturnValue().Set(Nan::New(context->hasContext)); +} + +// +// Async InitializeContextStep +// +typedef struct SecurityContextStepStaticInitializeCall { + char *service_principal_name_str; + char *decoded_input_str; + int decoded_input_str_length; + SecurityContext *context; +} SecurityContextStepStaticInitializeCall; + +static void _initializeContextStep(Worker *worker) { + // Outbound data array + BYTE *out_bound_data_str = NULL; + // Status of operation + SECURITY_STATUS status; + // Unpack data + SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; + SecurityContext *context = call->context; + // Structures used for c calls + SecBufferDesc ibd, obd; + SecBuffer ib, ob; + + // + // Prepare data structure for returned data from SSPI + ob.BufferType = SECBUFFER_TOKEN; + ob.cbBuffer = context->m_PkgInfo->cbMaxToken; + // Allocate space for return data + out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; + ob.pvBuffer = out_bound_data_str; + // prepare buffer description + obd.cBuffers = 1; + obd.ulVersion = SECBUFFER_VERSION; + obd.pBuffers = &ob; + + // + // Prepare the data we are passing to the SSPI method + if(call->decoded_input_str_length > 0) { + ib.BufferType = SECBUFFER_TOKEN; + ib.cbBuffer = call->decoded_input_str_length; + ib.pvBuffer = call->decoded_input_str; + // prepare buffer description + ibd.cBuffers = 1; + ibd.ulVersion = SECBUFFER_VERSION; + ibd.pBuffers = &ib; + } + + // Perform initialization step + status = _sspi_initializeSecurityContext( + &context->security_credentials->m_Credentials + , context->hasContext == true ? &context->m_Context : NULL + , const_cast(call->service_principal_name_str) + , 0x02 // MUTUAL + , 0 + , 0 // Network + , call->decoded_input_str_length ? &ibd : NULL + , 0 + , &context->m_Context + , &obd + , &context->CtxtAttr + , &context->Expiration + ); + + // If we have a ok or continue let's prepare the result + if(status == SEC_E_OK + || status == SEC_I_COMPLETE_NEEDED + || status == SEC_I_CONTINUE_NEEDED + || status == SEC_I_COMPLETE_AND_CONTINUE + ) { + // Set the new payload + if(context->payload != NULL) free(context->payload); + context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); + worker->return_code = status; + worker->return_value = context; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } + + // Clean up data + if(call->decoded_input_str != NULL) free(call->decoded_input_str); + if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); +} + +static Local _map_initializeContextStep(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return context->handle(); +} + +NAN_METHOD(SecurityContext::InitalizeStep) { + char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; + int decoded_input_str_length = NULL; + + // We need 3 parameters + if(info.Length() != 3) + return Nan::ThrowError("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); + + // Second parameter must be a string + if(!info[0]->IsString()) + return Nan::ThrowError("First parameter for Initialize must be a string"); + + // Third parameter must be a base64 encoded string + if(!info[1]->IsString()) + return Nan::ThrowError("Second parameter for Initialize must be a string"); + + // Third parameter must be a base64 encoded string + if(!info[2]->IsFunction()) + return Nan::ThrowError("Third parameter for Initialize must be a callback function"); + + // Let's unpack the values + Local service_principal_name = info[0]->ToString(); + service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); + service_principal_name->WriteUtf8(service_principal_name_str); + + // Unpack the user name + Local input = info[1]->ToString(); + + if(input->Utf8Length() > 0) { + input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); + input->WriteUtf8(input_str); + // Now let's get the base64 decoded string + decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); + // Free input string + free(input_str); + } + + // Unwrap the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); + + // Create call structure + SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); + call->context = security_context; + call->decoded_input_str = decoded_input_str; + call->decoded_input_str_length = decoded_input_str_length; + call->service_principal_name_str = service_principal_name_str; + + // Callback + Local callback = Local::Cast(info[2]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _initializeContextStep; + worker->mapper = _map_initializeContextStep; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +// Async EncryptMessage +// +typedef struct SecurityContextEncryptMessageCall { + SecurityContext *context; + SecurityBufferDescriptor *descriptor; + unsigned long flags; +} SecurityContextEncryptMessageCall; + +static void _encryptMessage(Worker *worker) { + SECURITY_STATUS status; + // Unpack call + SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; + // Unpack the security context + SecurityContext *context = call->context; + SecurityBufferDescriptor *descriptor = call->descriptor; + + // Let's execute encryption + status = _sspi_EncryptMessage( + &context->m_Context + , call->flags + , &descriptor->secBufferDesc + , 0 + ); + + // We've got ok + if(status == SEC_E_OK) { + int bytesToAllocate = (int)descriptor->bufferSize(); + // Free up existing payload + if(context->payload != NULL) free(context->payload); + // Save the payload + context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); + // Set result + worker->return_code = status; + worker->return_value = context; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } +} + +static Local _map_encryptMessage(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return context->handle(); +} + +NAN_METHOD(SecurityContext::EncryptMessage) { + if(info.Length() != 3) + return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + if(!SecurityBufferDescriptor::HasInstance(info[0])) + return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + if(!info[1]->IsUint32()) + return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + if(!info[2]->IsFunction()) + return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + + // Unpack the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); + + // Unpack the descriptor + SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); + + // Create call structure + SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); + call->context = security_context; + call->descriptor = descriptor; + call->flags = (unsigned long)info[1]->ToInteger()->Value(); + + // Callback + Local callback = Local::Cast(info[2]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _encryptMessage; + worker->mapper = _map_encryptMessage; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +// Async DecryptMessage +// +typedef struct SecurityContextDecryptMessageCall { + SecurityContext *context; + SecurityBufferDescriptor *descriptor; +} SecurityContextDecryptMessageCall; + +static void _decryptMessage(Worker *worker) { + unsigned long quality = 0; + SECURITY_STATUS status; + + // Unpack parameters + SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; + SecurityContext *context = call->context; + SecurityBufferDescriptor *descriptor = call->descriptor; + + // Let's execute encryption + status = _sspi_DecryptMessage( + &context->m_Context + , &descriptor->secBufferDesc + , 0 + , (unsigned long)&quality + ); + + // We've got ok + if(status == SEC_E_OK) { + int bytesToAllocate = (int)descriptor->bufferSize(); + // Free up existing payload + if(context->payload != NULL) free(context->payload); + // Save the payload + context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); + // Set return values + worker->return_code = status; + worker->return_value = context; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } +} + +static Local _map_decryptMessage(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return context->handle(); +} + +NAN_METHOD(SecurityContext::DecryptMessage) { + if(info.Length() != 2) + return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); + if(!SecurityBufferDescriptor::HasInstance(info[0])) + return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); + if(!info[1]->IsFunction()) + return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); + + // Unpack the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); + // Unpack the descriptor + SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); + // Create call structure + SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); + call->context = security_context; + call->descriptor = descriptor; + + // Callback + Local callback = Local::Cast(info[1]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _decryptMessage; + worker->mapper = _map_decryptMessage; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +// Async QueryContextAttributes +// +typedef struct SecurityContextQueryContextAttributesCall { + SecurityContext *context; + uint32_t attribute; +} SecurityContextQueryContextAttributesCall; + +static void _queryContextAttributes(Worker *worker) { + SECURITY_STATUS status; + + // Cast to data structure + SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; + + // Allocate some space + SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); + // Let's grab the query context attribute + status = _sspi_QueryContextAttributes( + &call->context->m_Context, + call->attribute, + sizes + ); + + if(status == SEC_E_OK) { + worker->return_code = status; + worker->return_value = sizes; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } +} + +static Local _map_queryContextAttributes(Worker *worker) { + // Cast to data structure + SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; + // Unpack the attribute + uint32_t attribute = call->attribute; + + // Convert data + if(attribute == SECPKG_ATTR_SIZES) { + SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; + // Create object + Local value = Nan::New(); + value->Set(Nan::New("maxToken").ToLocalChecked(), Nan::New(uint32_t(sizes->cbMaxToken))); + value->Set(Nan::New("maxSignature").ToLocalChecked(), Nan::New(uint32_t(sizes->cbMaxSignature))); + value->Set(Nan::New("blockSize").ToLocalChecked(), Nan::New(uint32_t(sizes->cbBlockSize))); + value->Set(Nan::New("securityTrailer").ToLocalChecked(), Nan::New(uint32_t(sizes->cbSecurityTrailer))); + return value; + } + + // Return the value + return Nan::Null(); +} + +NAN_METHOD(SecurityContext::QueryContextAttributes) { + if(info.Length() != 2) + return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); + if(!info[0]->IsInt32()) + return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); + if(!info[1]->IsFunction()) + return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); + + // Unpack the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); + + // Unpack the int value + uint32_t attribute = info[0]->ToInt32()->Value(); + + // Check that we have a supported attribute + if(attribute != SECPKG_ATTR_SIZES) + return Nan::ThrowError("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); + + // Create call structure + SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); + call->attribute = attribute; + call->context = security_context; + + // Callback + Local callback = Local::Cast(info[1]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _queryContextAttributes; + worker->mapper = _map_queryContextAttributes; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +void SecurityContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(static_cast(SecurityContext::New)); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("SecurityContext").ToLocalChecked()); + + // Class methods + Nan::SetMethod(t, "initialize", SecurityContext::InitializeContext); + + // Set up method for the instance + Nan::SetPrototypeMethod(t, "initialize", SecurityContext::InitalizeStep); + Nan::SetPrototypeMethod(t, "decryptMessage", SecurityContext::DecryptMessage); + Nan::SetPrototypeMethod(t, "queryContextAttributes", SecurityContext::QueryContextAttributes); + Nan::SetPrototypeMethod(t, "encryptMessage", SecurityContext::EncryptMessage); + + // Get prototype + Local proto = t->PrototypeTemplate(); + + // Getter for the response + Nan::SetAccessor(proto, Nan::New("payload").ToLocalChecked(), SecurityContext::PayloadGetter); + Nan::SetAccessor(proto, Nan::New("hasContext").ToLocalChecked(), SecurityContext::HasContextGetter); + + // Set persistent + SecurityContext::constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("SecurityContext").ToLocalChecked(), t->GetFunction()); +} + +static LPSTR DisplaySECError(DWORD ErrCode) { + LPSTR pszName = NULL; // WinError.h + + switch(ErrCode) { + case SEC_E_BUFFER_TOO_SMALL: + pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; + break; + + case SEC_E_CRYPTO_SYSTEM_INVALID: + pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; + break; + case SEC_E_INCOMPLETE_MESSAGE: + pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; + break; + + case SEC_E_INVALID_HANDLE: + pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_INVALID_TOKEN: + pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; + break; + + case SEC_E_MESSAGE_ALTERED: + pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_OUT_OF_SEQUENCE: + pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; + break; + + case SEC_E_QOP_NOT_SUPPORTED: + pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; + break; + + case SEC_I_CONTEXT_EXPIRED: + pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; + break; + + case SEC_I_RENEGOTIATE: + pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; + break; + + case SEC_E_ENCRYPT_FAILURE: + pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; + break; + + case SEC_E_DECRYPT_FAILURE: + pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; + break; + case -1: + pszName = "Failed to load security.dll library"; + break; + } + + return pszName; +} + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h new file mode 100644 index 0000000..1d9387d --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h @@ -0,0 +1,74 @@ +#ifndef SECURITY_CONTEXT_H +#define SECURITY_CONTEXT_H + +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include +#include +#include +#include +#include "security_credentials.h" +#include "../worker.h" +#include + +extern "C" { + #include "../kerberos_sspi.h" + #include "../base64.h" +} + +using namespace v8; +using namespace node; + +class SecurityContext : public Nan::ObjectWrap { + public: + SecurityContext(); + ~SecurityContext(); + + // Security info package + PSecPkgInfo m_PkgInfo; + // Do we have a context + bool hasContext; + // Reference to security credentials + SecurityCredentials *security_credentials; + // Security context + CtxtHandle m_Context; + // Attributes + DWORD CtxtAttr; + // Expiry time for ticket + TimeStamp Expiration; + // Payload + char *payload; + + // Has instance check + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + // Functions available from V8 + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + static NAN_METHOD(InitializeContext); + static NAN_METHOD(InitalizeStep); + static NAN_METHOD(DecryptMessage); + static NAN_METHOD(QueryContextAttributes); + static NAN_METHOD(EncryptMessage); + + // Payload getter + static NAN_GETTER(PayloadGetter); + // hasContext getter + static NAN_GETTER(HasContextGetter); + + // Constructor used for creating new Long objects from C++ + static Nan::Persistent constructor_template; + + // private: + // Create a new instance + static NAN_METHOD(New); +}; + +#endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js new file mode 100644 index 0000000..ef04e92 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js @@ -0,0 +1,3 @@ +var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; +// Export the modified class +exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc new file mode 100644 index 0000000..732af3f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc @@ -0,0 +1,348 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "security_credentials.h" + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) +#endif + +static LPSTR DisplaySECError(DWORD ErrCode); + +Nan::Persistent SecurityCredentials::constructor_template; + +SecurityCredentials::SecurityCredentials() : Nan::ObjectWrap() { +} + +SecurityCredentials::~SecurityCredentials() { +} + +NAN_METHOD(SecurityCredentials::New) { + // Create security credentials instance + SecurityCredentials *security_credentials = new SecurityCredentials(); + // Wrap it + security_credentials->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +// Call structs +typedef struct SecurityCredentialCall { + char *package_str; + char *username_str; + char *password_str; + char *domain_str; + SecurityCredentials *credentials; +} SecurityCredentialCall; + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientInit +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authSSPIAquire(Worker *worker) { + // Status of operation + SECURITY_STATUS status; + + // Unpack data + SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; + + // // Unwrap the credentials + // SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; + SecurityCredentials *security_credentials = new SecurityCredentials(); + + // If we have domain string + if(call->domain_str != NULL) { + security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); + security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); + } else { + security_credentials->m_Identity.Domain = NULL; + security_credentials->m_Identity.DomainLength = 0; + } + + // Set up the user + security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); + security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); + + // If we have a password string + if(call->password_str != NULL) { + // Set up the password + security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); + security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); + } + + #ifdef _UNICODE + security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; + #else + security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; + #endif + + // Attempt to acquire credentials + status = _sspi_AcquireCredentialsHandle( + NULL, + call->package_str, + SECPKG_CRED_OUTBOUND, + NULL, + call->password_str != NULL ? &security_credentials->m_Identity : NULL, + NULL, NULL, + &security_credentials->m_Credentials, + &security_credentials->Expiration + ); + + // We have an error + if(status != SEC_E_OK) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } else { + worker->return_code = status; + worker->return_value = security_credentials; + } + + // Free up parameter structure + if(call->package_str != NULL) free(call->package_str); + if(call->domain_str != NULL) free(call->domain_str); + if(call->password_str != NULL) free(call->password_str); + if(call->username_str != NULL) free(call->username_str); + free(call); +} + +static Local _map_authSSPIAquire(Worker *worker) { + return Nan::Null(); +} + +NAN_METHOD(SecurityCredentials::Aquire) { + char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; + // Unpack the variables + if(info.Length() != 2 && info.Length() != 3 && info.Length() != 4 && info.Length() != 5) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(!info[0]->IsString()) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(!info[1]->IsString()) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(info.Length() == 3 && (!info[2]->IsString() && !info[2]->IsFunction())) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(info.Length() == 4 && (!info[3]->IsString() && !info[3]->IsUndefined() && !info[3]->IsNull()) && !info[3]->IsFunction()) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(info.Length() == 5 && !info[4]->IsFunction()) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + Local callbackHandle; + + // Figure out which parameter is the callback + if(info.Length() == 5) { + callbackHandle = Local::Cast(info[4]); + } else if(info.Length() == 4) { + callbackHandle = Local::Cast(info[3]); + } else if(info.Length() == 3) { + callbackHandle = Local::Cast(info[2]); + } + + // Unpack the package + Local package = info[0]->ToString(); + package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); + package->WriteUtf8(package_str); + + // Unpack the user name + Local username = info[1]->ToString(); + username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); + username->WriteUtf8(username_str); + + // If we have a password + if(info.Length() == 3 || info.Length() == 4 || info.Length() == 5) { + Local password = info[2]->ToString(); + password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); + password->WriteUtf8(password_str); + } + + // If we have a domain + if((info.Length() == 4 || info.Length() == 5) && info[3]->IsString()) { + Local domain = info[3]->ToString(); + domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); + domain->WriteUtf8(domain_str); + } + + // Allocate call structure + SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); + call->domain_str = domain_str; + call->package_str = package_str; + call->password_str = password_str; + call->username_str = username_str; + + // Unpack the callback + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authSSPIAquire; + worker->mapper = _map_authSSPIAquire; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +void SecurityCredentials::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("SecurityCredentials").ToLocalChecked()); + + // Class methods + Nan::SetMethod(t, "aquire", Aquire); + + // Set persistent + constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("SecurityCredentials").ToLocalChecked(), t->GetFunction()); + + // Attempt to load the security.dll library + load_library(); +} + +static LPSTR DisplaySECError(DWORD ErrCode) { + LPSTR pszName = NULL; // WinError.h + + switch(ErrCode) { + case SEC_E_BUFFER_TOO_SMALL: + pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; + break; + + case SEC_E_CRYPTO_SYSTEM_INVALID: + pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; + break; + case SEC_E_INCOMPLETE_MESSAGE: + pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; + break; + + case SEC_E_INVALID_HANDLE: + pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_INVALID_TOKEN: + pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; + break; + + case SEC_E_MESSAGE_ALTERED: + pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_OUT_OF_SEQUENCE: + pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; + break; + + case SEC_E_QOP_NOT_SUPPORTED: + pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; + break; + + case SEC_I_CONTEXT_EXPIRED: + pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; + break; + + case SEC_I_RENEGOTIATE: + pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; + break; + + case SEC_E_ENCRYPT_FAILURE: + pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; + break; + + case SEC_E_DECRYPT_FAILURE: + pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; + break; + case -1: + pszName = "Failed to load security.dll library"; + break; + + } + + return pszName; +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// UV Lib callbacks +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +void SecurityCredentials::Process(uv_work_t* work_req) { + // Grab the worker + Worker *worker = static_cast(work_req->data); + // Execute the worker code + worker->execute(worker); +} + +void SecurityCredentials::After(uv_work_t* work_req) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Get the worker reference + Worker *worker = static_cast(work_req->data); + + // If we have an error + if(worker->error) { + Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); + Local obj = err->ToObject(); + obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); + Local info[2] = { err, Nan::Null() }; + // Execute the error + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } else { + SecurityCredentials *return_value = (SecurityCredentials *)worker->return_value; + // Create a new instance + Local result = Nan::New(constructor_template)->GetFunction()->NewInstance(); + // Unwrap the credentials + SecurityCredentials *security_credentials = Nan::ObjectWrap::Unwrap(result); + // Set the values + security_credentials->m_Identity = return_value->m_Identity; + security_credentials->m_Credentials = return_value->m_Credentials; + security_credentials->Expiration = return_value->Expiration; + // Set up the callback with a null first + Local info[2] = { Nan::Null(), result}; + // Wrap the callback function call in a TryCatch so that we can call + // node's FatalException afterwards. This makes it possible to catch + // the exception from JavaScript land using the + // process.on('uncaughtException') event. + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } + + // Clean up the memory + delete worker->callback; + delete worker; +} + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h new file mode 100644 index 0000000..71751a0 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h @@ -0,0 +1,68 @@ +#ifndef SECURITY_CREDENTIALS_H +#define SECURITY_CREDENTIALS_H + +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include +#include +#include +#include +#include +#include "../worker.h" +#include + +extern "C" { + #include "../kerberos_sspi.h" +} + +// SEC_WINNT_AUTH_IDENTITY makes it unusually hard +// to compile for both Unicode and ansi, so I use this macro: +#ifdef _UNICODE +#define USTR(str) (str) +#else +#define USTR(str) ((unsigned char*)(str)) +#endif + +using namespace v8; +using namespace node; + +class SecurityCredentials : public Nan::ObjectWrap { + public: + SecurityCredentials(); + ~SecurityCredentials(); + + // Pointer to context object + SEC_WINNT_AUTH_IDENTITY m_Identity; + // credentials + CredHandle m_Credentials; + // Expiry time for ticket + TimeStamp Expiration; + + // Has instance check + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + // Functions available from V8 + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + static NAN_METHOD(Aquire); + + // Constructor used for creating new Long objects from C++ + static Nan::Persistent constructor_template; + + private: + // Create a new instance + static NAN_METHOD(New); + // Handles the uv calls + static void Process(uv_work_t* work_req); + // Called after work is done + static void After(uv_work_t* work_req); +}; + +#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js new file mode 100644 index 0000000..4215c92 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js @@ -0,0 +1,22 @@ +var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; + +// Add simple kebros helper +SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { + if(typeof password == 'function') { + callback = password; + password = null; + } else if(typeof domain == 'function') { + callback = domain; + domain = null; + } + + // We are going to use the async version + if(typeof callback == 'function') { + return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); + } else { + return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); + } +} + +// Export the modified class +exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc new file mode 100644 index 0000000..e7a472f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc @@ -0,0 +1,7 @@ +#include "worker.h" + +Worker::Worker() { +} + +Worker::~Worker() { +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h new file mode 100644 index 0000000..1b0dced --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h @@ -0,0 +1,38 @@ +#ifndef WORKER_H_ +#define WORKER_H_ + +#include +#include +#include +#include + +using namespace node; +using namespace v8; + +class Worker { + public: + Worker(); + virtual ~Worker(); + + // libuv's request struct. + uv_work_t request; + // Callback + Nan::Callback *callback; + // Parameters + void *parameters; + // Results + void *return_value; + // Did we raise an error + bool error; + // The error message + char *error_message; + // Error code if not message + int error_code; + // Any return code + int return_code; + // Method we are going to fire + void (*execute)(Worker *worker); + Local (*mapper)(Worker *worker); +}; + +#endif // WORKER_H_ diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc new file mode 100644 index 0000000..47971da --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc @@ -0,0 +1,30 @@ +## DNT config file +## see https://github.com/rvagg/dnt + +NODE_VERSIONS="\ + master \ + v0.11.13 \ + v0.10.30 \ + v0.10.29 \ + v0.10.28 \ + v0.10.26 \ + v0.10.25 \ + v0.10.24 \ + v0.10.23 \ + v0.10.22 \ + v0.10.21 \ + v0.10.20 \ + v0.10.19 \ + v0.8.28 \ + v0.8.27 \ + v0.8.26 \ + v0.8.24 \ +" +OUTPUT_PREFIX="nan-" +TEST_CMD=" \ + cd /dnt/ && \ + npm install && \ + node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ + node_modules/.bin/tap --gc test/js/*-test.js \ +" + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md new file mode 100644 index 0000000..457e7c4 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md @@ -0,0 +1,374 @@ +# NAN ChangeLog + +**Version 2.0.9: current Node 4.0.0, Node 12: 0.12.7, Node 10: 0.10.40, iojs: 3.2.0** + +### 2.0.9 Sep 8 2015 + + - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7 + +### 2.0.8 Aug 28 2015 + + - Work around duplicate linking bug in clang 11902da + +### 2.0.7 Aug 26 2015 + + - Build: Repackage + +### 2.0.6 Aug 26 2015 + + - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1 + - Bugfix: Remove unused static std::map instances 525bddc + - Bugfix: Make better use of maybe versions of APIs bfba85b + - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d + +### 2.0.5 Aug 10 2015 + + - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1 + - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d + +### 2.0.4 Aug 6 2015 + + - Build: Repackage + +### 2.0.3 Aug 6 2015 + + - Bugfix: Don't use clang++ / g++ syntax extension. 231450e + +### 2.0.2 Aug 6 2015 + + - Build: Repackage + +### 2.0.1 Aug 6 2015 + + - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687 + - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601 + - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f + - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed + +### 2.0.0 Jul 31 2015 + + - Change: Renamed identifiers with leading underscores b5932b4 + - Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1 + - Change: Replace NanScope and NanEscpableScope macros with classes 47751c4 + - Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99 + - Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5 + - Change: Rename NanNewBuffer to NanCopyBuffer d6af78d + - Change: Remove Nan prefix from all names 72d1f67 + - Change: Update Buffer API for new upstream changes d5d3291 + - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a + - Change: Get rid of Handles e6c0daf + - Feature: Support io.js 3 with V8 4.4 + - Feature: Introduce NanPersistent 7fed696 + - Feature: Introduce NanGlobal 4408da1 + - Feature: Added NanTryCatch 10f1ca4 + - Feature: Update for V8 v4.3 4b6404a + - Feature: Introduce NanNewOneByteString c543d32 + - Feature: Introduce namespace Nan 67ed1b1 + - Removal: Remove NanLocker and NanUnlocker dd6e401 + - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9 + - Removal: Remove NanReturn* macros d90a25c + - Removal: Remove HasInstance e8f84fe + + +### 1.9.0 Jul 31 2015 + + - Feature: Added `NanFatalException` 81d4a2c + - Feature: Added more error types 4265f06 + - Feature: Added dereference and function call operators to NanCallback c4b2ed0 + - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c + - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6 + - Feature: Added NanErrnoException dd87d9e + - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130 + - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c + - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b + +### 1.8.4 Apr 26 2015 + + - Build: Repackage + +### 1.8.3 Apr 26 2015 + + - Bugfix: Include missing header 1af8648 + +### 1.8.2 Apr 23 2015 + + - Build: Repackage + +### 1.8.1 Apr 23 2015 + + - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 + +### 1.8.0 Apr 23 2015 + + - Feature: Allow primitives with NanReturnValue 2e4475e + - Feature: Added comparison operators to NanCallback 55b075e + - Feature: Backport thread local storage 15bb7fa + - Removal: Remove support for signatures with arguments 8a2069d + - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 + +### 1.7.0 Feb 28 2015 + + - Feature: Made NanCallback::Call accept optional target 8d54da7 + - Feature: Support atom-shell 0.21 0b7f1bb + +### 1.6.2 Feb 6 2015 + + - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 + +### 1.6.1 Jan 23 2015 + + - Build: version bump + +### 1.5.3 Jan 23 2015 + + - Build: repackage + +### 1.6.0 Jan 23 2015 + + - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af + - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 + - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 + +### 1.5.2 Jan 23 2015 + + - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 + - Bugfix: Readded missing String constructors 18d828f + - Bugfix: Add overload handling NanNew(..) 5ef813b + - Bugfix: Fix uv_work_cb versioning 997e4ae + - Bugfix: Add function factory and test 4eca89c + - Bugfix: Add object template factory and test cdcb951 + - Correctness: Lifted an io.js related typedef c9490be + - Correctness: Make explicit downcasts of String lengths 00074e6 + - Windows: Limit the scope of disabled warning C4530 83d7deb + +### 1.5.1 Jan 15 2015 + + - Build: version bump + +### 1.4.3 Jan 15 2015 + + - Build: version bump + +### 1.4.2 Jan 15 2015 + + - Feature: Support io.js 0dbc5e8 + +### 1.5.0 Jan 14 2015 + + - Feature: Support io.js b003843 + - Correctness: Improved NanNew internals 9cd4f6a + - Feature: Implement progress to NanAsyncWorker 8d6a160 + +### 1.4.1 Nov 8 2014 + + - Bugfix: Handle DEBUG definition correctly + - Bugfix: Accept int as Boolean + +### 1.4.0 Nov 1 2014 + + - Feature: Added NAN_GC_CALLBACK 6a5c245 + - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 + - Correctness: Added constness to references in NanHasInstance 02c61cd + - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 + - Windoze: Shut Visual Studio up when compiling 8d558c1 + - License: Switch to plain MIT from custom hacked MIT license 11de983 + - Build: Added test target to Makefile e232e46 + - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 + - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 + - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 + +### 1.3.0 Aug 2 2014 + + - Added NanNew(std::string) + - Added NanNew(std::string&) + - Added NanAsciiString helper class + - Added NanUtf8String helper class + - Added NanUcs2String helper class + - Deprecated NanRawString() + - Deprecated NanCString() + - Added NanGetIsolateData(v8::Isolate *isolate) + - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) + - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) + - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + +### 1.2.0 Jun 5 2014 + + - Add NanSetPrototypeTemplate + - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, + introduced _NanWeakCallbackDispatcher + - Removed -Wno-unused-local-typedefs from test builds + - Made test builds Windows compatible ('Sleep()') + +### 1.1.2 May 28 2014 + + - Release to fix more stuff-ups in 1.1.1 + +### 1.1.1 May 28 2014 + + - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 + +### 1.1.0 May 25 2014 + + - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead + - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), + (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, + v8::String::ExternalAsciiStringResource* + - Deprecate NanSymbol() + - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker + +### 1.0.0 May 4 2014 + + - Heavy API changes for V8 3.25 / Node 0.11.13 + - Use cpplint.py + - Removed NanInitPersistent + - Removed NanPersistentToLocal + - Removed NanFromV8String + - Removed NanMakeWeak + - Removed NanNewLocal + - Removed NAN_WEAK_CALLBACK_OBJECT + - Removed NAN_WEAK_CALLBACK_DATA + - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions + - Introduce NanUndefined, NanNull, NanTrue and NanFalse + - Introduce NanEscapableScope and NanEscapeScope + - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) + - Introduce NanMakeCallback for node::MakeCallback + - Introduce NanSetTemplate + - Introduce NanGetCurrentContext + - Introduce NanCompileScript and NanRunScript + - Introduce NanAdjustExternalMemory + - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback + - Introduce NanGetHeapStatistics + - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() + +### 0.8.0 Jan 9 2014 + + - NanDispose -> NanDisposePersistent, deprecate NanDispose + - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() + +### 0.7.1 Jan 9 2014 + + - Fixes to work against debug builds of Node + - Safer NanPersistentToLocal (avoid reinterpret_cast) + - Speed up common NanRawString case by only extracting flattened string when necessary + +### 0.7.0 Dec 17 2013 + + - New no-arg form of NanCallback() constructor. + - NanCallback#Call takes Handle rather than Local + - Removed deprecated NanCallback#Run method, use NanCallback#Call instead + - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS + - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() + - Introduce NanRawString() for char* (or appropriate void*) from v8::String + (replacement for NanFromV8String) + - Introduce NanCString() for null-terminated char* from v8::String + +### 0.6.0 Nov 21 2013 + + - Introduce NanNewLocal(v8::Handle value) for use in place of + v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 + +### 0.5.2 Nov 16 2013 + + - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public + +### 0.5.1 Nov 12 2013 + + - Use node::MakeCallback() instead of direct v8::Function::Call() + +### 0.5.0 Nov 11 2013 + + - Added @TooTallNate as collaborator + - New, much simpler, "include_dirs" for binding.gyp + - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros + +### 0.4.4 Nov 2 2013 + + - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ + +### 0.4.3 Nov 2 2013 + + - Include node_object_wrap.h, removed from node.h for Node 0.11.8. + +### 0.4.2 Nov 2 2013 + + - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for + Node 0.11.8 release. + +### 0.4.1 Sep 16 2013 + + - Added explicit `#include ` as it was removed from node.h for v0.11.8 + +### 0.4.0 Sep 2 2013 + + - Added NAN_INLINE and NAN_DEPRECATED and made use of them + - Added NanError, NanTypeError and NanRangeError + - Cleaned up code + +### 0.3.2 Aug 30 2013 + + - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent + in NanAsyncWorker + +### 0.3.1 Aug 20 2013 + + - fix "not all control paths return a value" compile warning on some platforms + +### 0.3.0 Aug 19 2013 + + - Made NAN work with NPM + - Lots of fixes to NanFromV8String, pulling in features from new Node core + - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API + - Added optional error number argument for NanThrowError() + - Added NanInitPersistent() + - Added NanReturnNull() and NanReturnEmptyString() + - Added NanLocker and NanUnlocker + - Added missing scopes + - Made sure to clear disposed Persistent handles + - Changed NanAsyncWorker to allocate error messages on the heap + - Changed NanThrowError(Local) to NanThrowError(Handle) + - Fixed leak in NanAsyncWorker when errmsg is used + +### 0.2.2 Aug 5 2013 + + - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() + +### 0.2.1 Aug 5 2013 + + - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for + NanFromV8String() + +### 0.2.0 Aug 5 2013 + + - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, + NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY + - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, + _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, + _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, + _NAN_PROPERTY_QUERY_ARGS + - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer + - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, + NAN_WEAK_CALLBACK_DATA, NanMakeWeak + - Renamed THROW_ERROR to _NAN_THROW_ERROR + - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) + - Added NanBufferUse(char*, uint32_t) + - Added NanNewContextHandle(v8::ExtensionConfiguration*, + v8::Handle, v8::Handle) + - Fixed broken NanCallback#GetFunction() + - Added optional encoding and size arguments to NanFromV8String() + - Added NanGetPointerSafe() and NanSetPointerSafe() + - Added initial test suite (to be expanded) + - Allow NanUInt32OptionValue to convert any Number object + +### 0.1.0 Jul 21 2013 + + - Added `NAN_GETTER`, `NAN_SETTER` + - Added `NanThrowError` with single Local argument + - Added `NanNewBufferHandle` with single uint32_t argument + - Added `NanHasInstance(Persistent&, Handle)` + - Added `Local NanCallback#GetFunction()` + - Added `NanCallback#Call(int, Local[])` + - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md new file mode 100644 index 0000000..77666cd --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md @@ -0,0 +1,13 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2015 NAN contributors +----------------------------------- + +*NAN contributors listed at * + +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/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md new file mode 100644 index 0000000..db3daec --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md @@ -0,0 +1,367 @@ +Native Abstractions for Node.js +=============================== + +**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.12 as well as io.js.** + +***Current version: 2.0.9*** + +*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* + +[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) + +[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](http://travis-ci.org/nodejs/nan) +[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) + +Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. + +This project also contains some helper utilities that make addon development a bit more pleasant. + + * **[News & Updates](#news)** + * **[Usage](#usage)** + * **[Example](#example)** + * **[API](#api)** + * **[Tests](#tests)** + * **[Governance & Contributing](#governance)** + + +## News & Updates + + +## Usage + +Simply add **NAN** as a dependency in the *package.json* of your Node addon: + +``` bash +$ npm install --save nan +``` + +Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: + +``` python +"include_dirs" : [ + "` when compiling your addon. + + +## Example + +Just getting started with Nan? Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. + +For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. + +For another example, see **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. + + +## API + +Additional to the NAN documentation below, please consult: + +* [The V8 Getting Started Guide](https://developers.google.com/v8/get_started) +* [The V8 Embedders Guide](https://developers.google.com/v8/embed) +* [V8 API Documentation](http://v8docs.nodesource.com/) + + + +### JavaScript-accessible methods + +A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://developers.google.com/v8/embed#templates) for further information. + +In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. + +* **Method argument types** + - Nan::FunctionCallbackInfo + - Nan::PropertyCallbackInfo + - Nan::ReturnValue +* **Method declarations** + - Method declaration + - Getter declaration + - Setter declaration + - Property getter declaration + - Property setter declaration + - Property enumerator declaration + - Property deleter declaration + - Property query declaration + - Index getter declaration + - Index setter declaration + - Index enumerator declaration + - Index deleter declaration + - Index query declaration +* Method and template helpers + - Nan::SetMethod() + - Nan::SetNamedPropertyHandler() + - Nan::SetIndexedPropertyHandler() + - Nan::SetPrototypeMethod() + - Nan::SetTemplate() + - Nan::SetPrototypeTemplate() + - Nan::SetInstanceTemplate() + +### Scopes + +A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. + +A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. + +The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. + + - Nan::HandleScope + - Nan::EscapableHandleScope + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). + +### Persistent references + +An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. + +Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. + + - Nan::PersistentBase & v8::PersistentBase + - Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits + - Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits + - Nan::Persistent + - Nan::Global + - Nan::WeakCallbackInfo + - Nan::WeakCallbackType + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). + +### New + +NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. + + - Nan::New() + - Nan::Undefined() + - Nan::Null() + - Nan::True() + - Nan::False() + - Nan::EmptyString() + + +### Converters + +NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. + + - Nan::To() + +### Maybe Types + +The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. + +* **Maybe Types** + - Nan::MaybeLocal + - Nan::Maybe + - Nan::Nothing + - Nan::Just +* **Maybe Helpers** + - Nan::ToDetailString() + - Nan::ToArrayIndex() + - Nan::Equals() + - Nan::NewInstance() + - Nan::GetFunction() + - Nan::Set() + - Nan::ForceSet() + - Nan::Get() + - Nan::GetPropertyAttributes() + - Nan::Has() + - Nan::Delete() + - Nan::GetPropertyNames() + - Nan::GetOwnPropertyNames() + - Nan::SetPrototype() + - Nan::ObjectProtoToString() + - Nan::HasOwnProperty() + - Nan::HasRealNamedProperty() + - Nan::HasRealIndexedProperty() + - Nan::HasRealNamedCallbackProperty() + - Nan::GetRealNamedPropertyInPrototypeChain() + - Nan::GetRealNamedProperty() + - Nan::CallAsFunction() + - Nan::CallAsConstructor() + - Nan::GetSourceLine() + - Nan::GetLineNumber() + - Nan::GetStartColumn() + - Nan::GetEndColumn() + - Nan::CloneElementAt() + +### Script + +NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. + + - Nan::CompileScript() + - Nan::RunScript() + + +### Errors + +NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. + +Note that an Error object is simply a specialized form of `v8::Value`. + +Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. + + - Nan::Error() + - Nan::RangeError() + - Nan::ReferenceError() + - Nan::SyntaxError() + - Nan::TypeError() + - Nan::ThrowError() + - Nan::ThrowRangeError() + - Nan::ThrowReferenceError() + - Nan::ThrowSyntaxError() + - Nan::ThrowTypeError() + - Nan::FatalException() + - Nan::ErrnoException() + - Nan::TryCatch + + +### Buffers + +NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. + + - Nan::NewBuffer() + - Nan::CopyBuffer() + - Nan::FreeCallback() + +### Nan::Callback + +`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. + + - Nan::Callback + +### Asynchronous work helpers + +`Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier. + + - Nan::AsyncWorker + - Nan::AsyncProgressWorker + - Nan::AsyncQueueWorker + +### Strings & Bytes + +Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. + + - Nan::Encoding + - Nan::Encode() + - Nan::DecodeBytes() + - Nan::DecodeWrite() + + +### V8 internals + +The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. + + - NAN_GC_CALLBACK() + - Nan::AddGCEpilogueCallback() + - Nan::RemoveGCEpilogueCallback() + - Nan::AddGCPrologueCallback() + - Nan::RemoveGCPrologueCallback() + - Nan::GetHeapStatistics() + - Nan::SetCounterFunction() + - Nan::SetCreateHistogramFunction() + - Nan::SetAddHistogramSampleFunction() + - Nan::IdleNotification() + - Nan::LowMemoryNotification() + - Nan::ContextDisposedNotification() + - Nan::GetInternalFieldPointer() + - Nan::SetInternalFieldPointer() + - Nan::AdjustExternalMemory() + + +### Miscellaneous V8 Helpers + + - Nan::Utf8String + - Nan::GetCurrentContext() + - Nan::SetIsolateData() + - Nan::GetIsolateData() + + +### Miscellaneous Node Helpers + + - Nan::MakeCallback() + - Nan::ObjectWrap + - NAN_MODULE_INIT() + - Nan::Export() + + + + + +### Tests + +To run the NAN tests do: + +``` sh +npm install +npm run-script rebuild-tests +npm test +``` + +Or just: + +``` sh +npm install +make test +``` + + +## Governance & Contributing + +NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group + +### Addon API Working Group (WG) + +The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. + +Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project [README.md](./README.md#collaborators). + +Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. + +_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. + +For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). + +### Consensus Seeking Process + +The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. + +Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. + +If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. + +### Developer's Certificate of Origin 1.0 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or +* (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or +* (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. + + +### WG Members / Collaborators + + + + + + + + + +
    Rod VaggGitHub/rvaggTwitter/@rvagg
    Benjamin ByholmGitHub/kkoopa-
    Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
    Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
    Brett LawsonGitHub/brett19Twitter/@brett19x
    Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
    David SiegelGitHub/agnat-
    + +## Licence & copyright + +Copyright (c) 2015 NAN WG Members / Collaborators (listed above). + +Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml new file mode 100644 index 0000000..1378d31 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml @@ -0,0 +1,38 @@ +# http://www.appveyor.com/docs/appveyor-yml + +# Test against these versions of Io.js and Node.js. +environment: + matrix: + # node.js + - nodejs_version: "0.8" + - nodejs_version: "0.10" + - nodejs_version: "0.12" + # io.js + - nodejs_version: "1" + - nodejs_version: "2" + - nodejs_version: "3" + +# Install scripts. (runs after repo cloning) +install: + # Get the latest stable version of Node 0.STABLE.latest + - ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version} + - ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)} + - IF %nodejs_version% LSS 1 npm -g install npm + - IF %nodejs_version% LSS 1 set PATH=%APPDATA%\npm;%PATH% + # Typical npm stuff. + - npm install + - IF %nodejs_version% EQU 0.8 (node node_modules\node-gyp\bin\node-gyp.js rebuild --msvs_version=2013 --directory test) ELSE (npm run rebuild-tests) + +# Post-install test scripts. +test_script: + # Output useful info for debugging. + - node --version + - npm --version + # run tests + - IF %nodejs_version% LSS 1 (npm test) ELSE (iojs node_modules\tap\bin\tap.js --gc test/js/*-test.js) + +# Don't actually build. +build: off + +# Set build version format here instead of in the admin panel. +version: "{build}" diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh new file mode 100755 index 0000000..75a975a --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +files=" \ + methods.md \ + scopes.md \ + persistent.md \ + new.md \ + converters.md \ + maybe_types.md \ + script.md \ + errors.md \ + buffers.md \ + callback.md \ + asyncworker.md \ + string_bytes.md \ + v8_internals.md \ + v8_misc.md \ + node_misc.md \ +" + +__dirname=$(dirname "${BASH_SOURCE[0]}") +head=$(perl -e 'while (<>) { if (!$en){print;} if ($_=~/ NanNew("foo").ToLocalChecked() */ + if (arguments[groups[3][0]] === 'NanNew') { + return [arguments[0], '.ToLocalChecked()'].join(''); + } + + /* insert warning for removed functions as comment on new line above */ + switch (arguments[groups[4][0]]) { + case 'GetIndexedPropertiesExternalArrayData': + case 'GetIndexedPropertiesExternalArrayDataLength': + case 'GetIndexedPropertiesExternalArrayDataType': + case 'GetIndexedPropertiesPixelData': + case 'GetIndexedPropertiesPixelDataLength': + case 'HasIndexedPropertiesInExternalArrayData': + case 'HasIndexedPropertiesInPixelData': + case 'SetIndexedPropertiesToExternalArrayData': + case 'SetIndexedPropertiesToPixelData': + return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join(''); + default: + } + + /* remove unnecessary NanScope() */ + switch (arguments[groups[5][0]]) { + case 'NAN_GETTER': + case 'NAN_METHOD': + case 'NAN_SETTER': + case 'NAN_INDEX_DELETER': + case 'NAN_INDEX_ENUMERATOR': + case 'NAN_INDEX_GETTER': + case 'NAN_INDEX_QUERY': + case 'NAN_INDEX_SETTER': + case 'NAN_PROPERTY_DELETER': + case 'NAN_PROPERTY_ENUMERATOR': + case 'NAN_PROPERTY_GETTER': + case 'NAN_PROPERTY_QUERY': + case 'NAN_PROPERTY_SETTER': + return arguments[groups[5][0] - 1]; + default: + } + + /* Value converstion */ + switch (arguments[groups[6][0]]) { + case 'Boolean': + case 'Int32': + case 'Integer': + case 'Number': + case 'Object': + case 'String': + case 'Uint32': + return [arguments[groups[6][0] - 2], 'NanTo(', arguments[groups[6][0] - 1]].join(''); + default: + } + + /* other value conversion */ + switch (arguments[groups[7][0]]) { + case 'BooleanValue': + return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); + case 'Int32Value': + return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); + case 'IntegerValue': + return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); + case 'Uint32Value': + return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); + default: + } + + /* NAN_WEAK_CALLBACK */ + if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') { + return ['template\nvoid ', + arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo &data)'].join(''); + } + + /* use methods on NAN classes instead */ + switch (arguments[groups[9][0]]) { + case 'NanDisposePersistent': + return [arguments[groups[9][0] + 1], '.Reset('].join(''); + case 'NanObjectWrapHandle': + return [arguments[groups[9][0] + 1], '->handle('].join(''); + default: + } + + /* use method on NanPersistent instead */ + if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') { + return arguments[groups[10][0] + 1] + '.SetWeak('; + } + + /* These return Maybes, the upper ones take no arguments */ + switch (arguments[groups[11][0]]) { + case 'GetEndColumn': + case 'GetFunction': + case 'GetLineNumber': + case 'GetOwnPropertyNames': + case 'GetPropertyNames': + case 'GetSourceLine': + case 'GetStartColumn': + case 'NewInstance': + case 'ObjectProtoToString': + case 'ToArrayIndex': + case 'ToDetailString': + return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join(''); + case 'CallAsConstructor': + case 'CallAsFunction': + case 'CloneElementAt': + case 'Delete': + case 'ForceSet': + case 'Get': + case 'GetPropertyAttributes': + case 'GetRealNamedProperty': + case 'GetRealNamedPropertyInPrototypeChain': + case 'Has': + case 'HasOwnProperty': + case 'HasRealIndexedProperty': + case 'HasRealNamedCallbackProperty': + case 'HasRealNamedProperty': + case 'Set': + case 'SetAccessor': + case 'SetIndexedPropertyHandler': + case 'SetNamedPropertyHandler': + case 'SetPrototype': + return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join(''); + default: + } + + /* Automatic ToLocalChecked(), take it or leave it */ + switch (arguments[groups[12][0]]) { + case 'Date': + case 'String': + case 'RegExp': + return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join(''); + default: + } + + /* NanEquals is now required for uniformity */ + if (arguments[groups[13][0]] === 'Equals') { + return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join(''); + } + + /* use method on replacement class instead */ + if (arguments[groups[14][0]] === 'NanAssignPersistent') { + return [arguments[groups[14][0] + 1], '.Reset('].join(''); + } + + /* args --> info */ + if (arguments[groups[15][0]] === 'args') { + return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join(''); + } + + /* ObjectWrap --> NanObjectWrap */ + if (arguments[groups[16][0]] === 'ObjectWrap') { + return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join(''); + } + + /* Persistent --> NanPersistent */ + if (arguments[groups[17][0]] === 'Persistent') { + return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join(''); + } + + /* This should not happen. A switch is probably missing a case if it does. */ + throw 'Unhandled match: ' + arguments[0]; +} + +/* reads a file, runs replacement and writes it back */ +function processFile(file) { + fs.readFile(file, {encoding: 'utf8'}, function (err, data) { + if (err) { + throw err; + } + + /* run replacement twice, might need more runs */ + fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) { + if (err) { + throw err; + } + }); + }); +} + +/* process file names from command line and process the identified files */ +for (i = 2, length = process.argv.length; i < length; i++) { + glob(process.argv[i], function (err, matches) { + if (err) { + throw err; + } + matches.forEach(processFile); + }); +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md new file mode 100644 index 0000000..7f07e4b --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md @@ -0,0 +1,14 @@ +1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, +false positives and missed opportunities. The input files are rewritten in place. Make sure that +you have backups. You will have to manually review the changes afterwards and do some touchups. + +```sh +$ tools/1to2.js + + Usage: 1to2 [options] + + Options: + + -h, --help output usage information + -V, --version output the version number +``` diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json new file mode 100644 index 0000000..2dcdd78 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json @@ -0,0 +1,19 @@ +{ + "name": "1to2", + "version": "1.0.0", + "description": "NAN 1 -> 2 Migration Script", + "main": "1to2.js", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/nan.git" + }, + "contributors": [ + "Benjamin Byholm (https://github.com/kkoopa/)", + "Mathias Küsel (https://github.com/mathiask88/)" + ], + "dependencies": { + "glob": "~5.0.10", + "commander": "~2.8.1" + }, + "license": "MIT" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json new file mode 100644 index 0000000..9955d1f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json @@ -0,0 +1,55 @@ +{ + "name": "kerberos", + "version": "0.0.15", + "description": "Kerberos library for Node.js", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/christkv/kerberos.git" + }, + "keywords": [ + "kerberos", + "security", + "authentication" + ], + "dependencies": { + "nan": "~2.0" + }, + "devDependencies": { + "nodeunit": "latest" + }, + "scripts": { + "install": "(node-gyp rebuild) || (exit 0)", + "test": "nodeunit ./test" + }, + "author": { + "name": "Christian Amor Kvalheim" + }, + "license": "Apache 2.0", + "gitHead": "035be2e4619d7f3d7ea5103da1f60a6045ef8d7c", + "bugs": { + "url": "https://github.com/christkv/kerberos/issues" + }, + "homepage": "https://github.com/christkv/kerberos", + "_id": "kerberos@0.0.15", + "_shasum": "c7dd5a2d311ce79c308c2670a9187d9bf745ed52", + "_from": "kerberos@>=0.0.0 <0.1.0", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "c7dd5a2d311ce79c308c2670a9187d9bf745ed52", + "tarball": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.15.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-0.0.15.tgz" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js new file mode 100644 index 0000000..a06c5fd --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js @@ -0,0 +1,34 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Simple initialize of Kerberos object'] = function(test) { + var Kerberos = require('../lib/kerberos.js').Kerberos; + var kerberos = new Kerberos(); + // console.dir(kerberos) + + // Initiate kerberos client + kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { + console.log("===================================== authGSSClientInit") + test.equal(null, err); + test.ok(context != null && typeof context == 'object'); + // console.log("===================================== authGSSClientInit") + console.dir(err) + console.dir(context) + // console.dir(typeof result) + + // Perform the first step + kerberos.authGSSClientStep(context, function(err, result) { + console.log("===================================== authGSSClientStep") + console.dir(err) + console.dir(result) + console.dir(context) + + test.done(); + }); + }); +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js new file mode 100644 index 0000000..c8509db --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js @@ -0,0 +1,15 @@ +if (/^win/.test(process.platform)) { + +exports['Simple initialize of Kerberos win32 object'] = function(test) { + var KerberosNative = require('../build/Release/kerberos').Kerberos; + // console.dir(KerberosNative) + var kerberos = new KerberosNative(); + console.log("=========================================== 0") + console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); + console.log("=========================================== 1") + console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); + console.log("=========================================== 2") + test.done(); +} + +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js new file mode 100644 index 0000000..3531b6b --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js @@ -0,0 +1,41 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Initialize a security Buffer Descriptor'] = function(test) { + var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor + SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; + + // Create descriptor with single Buffer + var securityDescriptor = new SecurityBufferDescriptor(100); + try { + // Fail to work due to no valid Security Buffer + securityDescriptor = new SecurityBufferDescriptor(["hello"]); + test.ok(false); + } catch(err){} + + // Should Correctly construct SecurityBuffer + var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); + securityDescriptor = new SecurityBufferDescriptor([buffer]); + // Should correctly return a buffer + var result = securityDescriptor.toBuffer(); + test.equal(100, result.length); + + // Should Correctly construct SecurityBuffer + var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + securityDescriptor = new SecurityBufferDescriptor([buffer]); + var result = securityDescriptor.toBuffer(); + test.equal("hello world", result.toString()); + + // Test passing in more than one Buffer + var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); + securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); + var result = securityDescriptor.toBuffer(); + test.equal("hello worldadam and eve", result.toString()); + test.done(); +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js new file mode 100644 index 0000000..b52b959 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js @@ -0,0 +1,22 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Initialize a security Buffer'] = function(test) { + var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; + // Create empty buffer + var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); + var buffer = securityBuffer.toBuffer(); + test.equal(100, buffer.length); + + // Access data passed in + var allocated_buffer = new Buffer(256); + securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); + buffer = securityBuffer.toBuffer(); + test.deepEqual(allocated_buffer, buffer); + test.done(); +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js new file mode 100644 index 0000000..7758180 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js @@ -0,0 +1,55 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Initialize a set of security credentials'] = function(test) { + var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; + + // Aquire some credentials + try { + var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); + } catch(err) { + console.dir(err) + test.ok(false); + } + + + + // console.dir(SecurityCredentials); + + // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor + // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; + + // // Create descriptor with single Buffer + // var securityDescriptor = new SecurityBufferDescriptor(100); + // try { + // // Fail to work due to no valid Security Buffer + // securityDescriptor = new SecurityBufferDescriptor(["hello"]); + // test.ok(false); + // } catch(err){} + + // // Should Correctly construct SecurityBuffer + // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); + // securityDescriptor = new SecurityBufferDescriptor([buffer]); + // // Should correctly return a buffer + // var result = securityDescriptor.toBuffer(); + // test.equal(100, result.length); + + // // Should Correctly construct SecurityBuffer + // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + // securityDescriptor = new SecurityBufferDescriptor([buffer]); + // var result = securityDescriptor.toBuffer(); + // test.equal("hello world", result.toString()); + + // // Test passing in more than one Buffer + // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); + // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); + // var result = securityDescriptor.toBuffer(); + // test.equal("hello worldadam and eve", result.toString()); + test.done(); +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/package.json new file mode 100644 index 0000000..f690f67 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/package.json @@ -0,0 +1,66 @@ +{ + "name": "mongodb-core", + "version": "1.2.14", + "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", + "main": "index.js", + "scripts": { + "test": "node test/runner.js -t functional" + }, + "repository": { + "type": "git", + "url": "git://github.com/christkv/mongodb-core.git" + }, + "keywords": [ + "mongodb", + "core" + ], + "dependencies": { + "bson": "~0.4", + "kerberos": "~0.0" + }, + "devDependencies": { + "integra": "0.1.8", + "optimist": "latest", + "jsdoc": "3.3.0-alpha8", + "semver": "4.1.0", + "gleak": "0.5.0", + "mongodb-tools": "~1.0", + "mkdirp": "0.5.0", + "rimraf": "2.2.6", + "mongodb-version-manager": "^0.7.1", + "co": "4.5.4" + }, + "optionalDependencies": { + "kerberos": "~0.0" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/mongodb-core/issues" + }, + "homepage": "https://github.com/christkv/mongodb-core", + "gitHead": "ea4e6c9fe93e4ace4cbffb816d47ee282c1cd844", + "_id": "mongodb-core@1.2.14", + "_shasum": "0f1393778b71f1e2b86228fd160ec9ad5a8cd9a3", + "_from": "mongodb-core@1.2.14", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "0f1393778b71f1e2b86228fd160ec9ad5a8cd9a3", + "tarball": "http://registry.npmjs.org/mongodb-core/-/mongodb-core-1.2.14.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-1.2.14.tgz" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat new file mode 100644 index 0000000..25ccf0b --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat @@ -0,0 +1,11000 @@ +1 2 +2 1 +3 0 +4 0 +5 1 +6 0 +7 0 +8 0 +9 0 +10 1 +11 0 +12 0 +13 0 +14 1 +15 0 +16 0 +17 0 +18 1 +19 0 +20 0 +21 0 +22 1 +23 0 +24 0 +25 0 +26 0 +27 1 +28 0 +29 0 +30 0 +31 1 +32 0 +33 0 +34 0 +35 0 +36 0 +37 1 +38 0 +39 0 +40 0 +41 0 +42 0 +43 1 +44 0 +45 0 +46 0 +47 0 +48 0 +49 0 +50 0 +51 0 +52 0 +53 0 +54 0 +55 0 +56 0 +57 0 +58 0 +59 1 +60 0 +61 2 +62 0 +63 0 +64 1 +65 0 +66 0 +67 0 +68 1 +69 0 +70 0 +71 0 +72 0 +73 1 +74 0 +75 0 +76 0 +77 0 +78 0 +79 1 +80 0 +81 0 +82 0 +83 0 +84 0 +85 0 +86 1 +87 0 +88 0 +89 0 +90 0 +91 0 +92 0 +93 1 +94 0 +95 0 +96 0 +97 0 +98 0 +99 0 +100 0 +101 1 +102 0 +103 0 +104 0 +105 0 +106 0 +107 0 +108 1 +109 0 +110 0 +111 0 +112 0 +113 0 +114 0 +115 1 +116 0 +117 0 +118 0 +119 1 +120 0 +121 0 +122 0 +123 0 +124 0 +125 0 +126 1 +127 0 +128 1 +129 0 +130 0 +131 0 +132 1 +133 1 +134 0 +135 0 +136 0 +137 1 +138 0 +139 0 +140 0 +141 0 +142 0 +143 0 +144 1 +145 0 +146 0 +147 0 +148 0 +149 0 +150 0 +151 0 +152 0 +153 1 +154 0 +155 0 +156 0 +157 0 +158 0 +159 0 +160 0 +161 0 +162 0 +163 0 +164 0 +165 0 +166 0 +167 0 +168 0 +169 0 +170 1 +171 0 +172 0 +173 0 +174 0 +175 0 +176 0 +177 0 +178 1 +179 0 +180 0 +181 0 +182 0 +183 0 +184 0 +185 0 +186 1 +187 0 +188 0 +189 0 +190 0 +191 0 +192 1 +193 0 +194 0 +195 0 +196 1 +197 0 +198 0 +199 0 +200 1 +201 0 +202 0 +203 0 +204 0 +205 0 +206 0 +207 1 +208 0 +209 0 +210 0 +211 0 +212 0 +213 0 +214 0 +215 1 +216 0 +217 0 +218 0 +219 0 +220 0 +221 0 +222 0 +223 1 +224 0 +225 0 +226 0 +227 0 +228 0 +229 0 +230 1 +231 0 +232 0 +233 0 +234 0 +235 0 +236 0 +237 1 +238 0 +239 0 +240 0 +241 0 +242 0 +243 0 +244 0 +245 1 +246 0 +247 0 +248 0 +249 0 +250 0 +251 0 +252 0 +253 0 +254 1 +255 0 +256 0 +257 0 +258 0 +259 1 +260 0 +261 0 +262 0 +263 0 +264 0 +265 1 +266 0 +267 0 +268 0 +269 0 +270 0 +271 0 +272 1 +273 0 +274 0 +275 0 +276 0 +277 0 +278 0 +279 0 +280 0 +281 1 +282 0 +283 1 +284 0 +285 0 +286 1 +287 0 +288 0 +289 0 +290 0 +291 1 +292 0 +293 0 +294 0 +295 0 +296 1 +297 0 +298 0 +299 0 +300 0 +301 0 +302 0 +303 1 +304 0 +305 0 +306 0 +307 0 +308 0 +309 1 +310 0 +311 0 +312 0 +313 0 +314 0 +315 0 +316 1 +317 0 +318 0 +319 0 +320 0 +321 0 +322 0 +323 0 +324 0 +325 1 +326 0 +327 0 +328 0 +329 0 +330 0 +331 0 +332 0 +333 0 +334 1 +335 0 +336 0 +337 0 +338 0 +339 0 +340 0 +341 0 +342 0 +343 1 +344 0 +345 0 +346 0 +347 0 +348 0 +349 0 +350 0 +351 0 +352 1 +353 0 +354 0 +355 0 +356 0 +357 0 +358 0 +359 0 +360 0 +361 1 +362 0 +363 0 +364 0 +365 0 +366 0 +367 0 +368 0 +369 1 +370 0 +371 0 +372 0 +373 0 +374 0 +375 0 +376 0 +377 1 +378 0 +379 0 +380 0 +381 0 +382 0 +383 0 +384 0 +385 1 +386 0 +387 0 +388 0 +389 0 +390 1 +391 0 +392 0 +393 0 +394 0 +395 0 +396 0 +397 0 +398 0 +399 0 +400 0 +401 0 +402 1 +403 0 +404 0 +405 0 +406 0 +407 0 +408 0 +409 0 +410 1 +411 0 +412 0 +413 0 +414 0 +415 0 +416 0 +417 0 +418 0 +419 1 +420 0 +421 0 +422 0 +423 0 +424 0 +425 0 +426 0 +427 1 +428 0 +429 0 +430 0 +431 0 +432 0 +433 0 +434 0 +435 1 +436 0 +437 0 +438 0 +439 0 +440 0 +441 0 +442 0 +443 1 +444 0 +445 0 +446 0 +447 0 +448 0 +449 0 +450 1 +451 0 +452 0 +453 0 +454 0 +455 0 +456 1 +457 0 +458 0 +459 0 +460 0 +461 0 +462 0 +463 0 +464 1 +465 0 +466 0 +467 0 +468 0 +469 0 +470 0 +471 0 +472 0 +473 1 +474 0 +475 0 +476 0 +477 0 +478 0 +479 0 +480 0 +481 1 +482 0 +483 0 +484 0 +485 0 +486 0 +487 0 +488 0 +489 0 +490 1 +491 0 +492 0 +493 0 +494 0 +495 0 +496 0 +497 0 +498 0 +499 0 +500 0 +501 0 +502 0 +503 0 +504 1 +505 0 +506 0 +507 0 +508 0 +509 0 +510 0 +511 0 +512 1 +513 0 +514 0 +515 0 +516 0 +517 0 +518 0 +519 4 +520 0 +521 1 +522 0 +523 0 +524 0 +525 1 +526 0 +527 0 +528 0 +529 0 +530 1 +531 0 +532 0 +533 0 +534 1 +535 0 +536 0 +537 0 +538 0 +539 1 +540 0 +541 0 +542 0 +543 0 +544 0 +545 1 +546 0 +547 0 +548 0 +549 0 +550 0 +551 1 +552 0 +553 0 +554 0 +555 0 +556 0 +557 0 +558 0 +559 1 +560 0 +561 0 +562 0 +563 0 +564 0 +565 0 +566 0 +567 1 +568 0 +569 0 +570 0 +571 0 +572 0 +573 0 +574 0 +575 0 +576 1 +577 0 +578 0 +579 0 +580 0 +581 0 +582 0 +583 0 +584 0 +585 0 +586 0 +587 0 +588 0 +589 0 +590 0 +591 0 +592 0 +593 1 +594 0 +595 0 +596 0 +597 0 +598 0 +599 0 +600 0 +601 0 +602 1 +603 0 +604 0 +605 0 +606 0 +607 0 +608 0 +609 0 +610 0 +611 1 +612 0 +613 0 +614 0 +615 0 +616 0 +617 0 +618 0 +619 0 +620 1 +621 0 +622 0 +623 0 +624 0 +625 0 +626 0 +627 0 +628 0 +629 1 +630 0 +631 0 +632 0 +633 0 +634 0 +635 0 +636 0 +637 0 +638 0 +639 1 +640 0 +641 0 +642 0 +643 0 +644 0 +645 0 +646 1 +647 0 +648 0 +649 0 +650 0 +651 0 +652 1 +653 1 +654 0 +655 0 +656 1 +657 0 +658 1 +659 0 +660 0 +661 0 +662 0 +663 0 +664 1 +665 0 +666 0 +667 0 +668 0 +669 0 +670 0 +671 0 +672 0 +673 0 +674 0 +675 0 +676 0 +677 1 +678 0 +679 0 +680 0 +681 0 +682 0 +683 0 +684 0 +685 0 +686 1 +687 0 +688 0 +689 0 +690 0 +691 0 +692 0 +693 0 +694 0 +695 1 +696 0 +697 0 +698 0 +699 0 +700 0 +701 0 +702 0 +703 1 +704 0 +705 0 +706 0 +707 0 +708 0 +709 0 +710 0 +711 0 +712 1 +713 0 +714 0 +715 0 +716 0 +717 0 +718 0 +719 0 +720 1 +721 0 +722 0 +723 0 +724 0 +725 0 +726 0 +727 0 +728 1 +729 0 +730 0 +731 0 +732 0 +733 0 +734 0 +735 0 +736 0 +737 1 +738 0 +739 0 +740 0 +741 0 +742 0 +743 0 +744 0 +745 1 +746 0 +747 0 +748 0 +749 0 +750 0 +751 0 +752 0 +753 1 +754 0 +755 0 +756 0 +757 0 +758 0 +759 0 +760 0 +761 1 +762 0 +763 0 +764 0 +765 0 +766 0 +767 0 +768 1 +769 0 +770 0 +771 0 +772 0 +773 0 +774 0 +775 0 +776 0 +777 1 +778 0 +779 0 +780 0 +781 0 +782 0 +783 0 +784 0 +785 0 +786 1 +787 0 +788 0 +789 0 +790 0 +791 0 +792 1 +793 0 +794 0 +795 0 +796 0 +797 0 +798 0 +799 0 +800 0 +801 1 +802 0 +803 0 +804 0 +805 0 +806 0 +807 0 +808 0 +809 0 +810 0 +811 0 +812 0 +813 0 +814 0 +815 0 +816 0 +817 0 +818 0 +819 0 +820 1 +821 0 +822 0 +823 0 +824 0 +825 0 +826 0 +827 0 +828 0 +829 1 +830 0 +831 0 +832 0 +833 0 +834 0 +835 0 +836 0 +837 1 +838 0 +839 0 +840 0 +841 0 +842 0 +843 0 +844 0 +845 0 +846 1 +847 0 +848 0 +849 0 +850 0 +851 0 +852 0 +853 0 +854 0 +855 2 +856 0 +857 0 +858 0 +859 0 +860 0 +861 0 +862 1 +863 0 +864 0 +865 0 +866 0 +867 0 +868 0 +869 0 +870 0 +871 1 +872 0 +873 0 +874 0 +875 0 +876 0 +877 0 +878 1 +879 0 +880 0 +881 0 +882 0 +883 0 +884 0 +885 0 +886 0 +887 0 +888 0 +889 0 +890 0 +891 0 +892 0 +893 0 +894 0 +895 0 +896 1 +897 0 +898 0 +899 0 +900 0 +901 0 +902 0 +903 0 +904 0 +905 0 +906 1 +907 0 +908 0 +909 0 +910 0 +911 0 +912 0 +913 0 +914 0 +915 1 +916 0 +917 0 +918 0 +919 0 +920 0 +921 0 +922 1 +923 0 +924 0 +925 0 +926 0 +927 0 +928 0 +929 0 +930 1 +931 0 +932 0 +933 0 +934 0 +935 0 +936 0 +937 0 +938 0 +939 1 +940 0 +941 0 +942 0 +943 0 +944 0 +945 0 +946 0 +947 0 +948 0 +949 1 +950 0 +951 0 +952 0 +953 0 +954 0 +955 0 +956 0 +957 0 +958 1 +959 0 +960 0 +961 0 +962 0 +963 0 +964 0 +965 0 +966 0 +967 0 +968 1 +969 0 +970 0 +971 0 +972 0 +973 0 +974 0 +975 0 +976 0 +977 0 +978 1 +979 0 +980 0 +981 0 +982 0 +983 0 +984 0 +985 0 +986 0 +987 0 +988 1 +989 0 +990 0 +991 0 +992 0 +993 0 +994 0 +995 0 +996 0 +997 1 +998 0 +999 0 +1000 0 +1001 0 +1002 0 +1003 0 +1004 0 +1005 1 +1006 0 +1007 0 +1008 0 +1009 0 +1010 0 +1011 0 +1012 1 +1013 0 +1014 0 +1015 0 +1016 0 +1017 0 +1018 0 +1019 0 +1020 0 +1021 0 +1022 0 +1023 0 +1024 0 +1025 0 +1026 0 +1027 0 +1028 0 +1029 0 +1030 0 +1031 1 +1032 0 +1033 0 +1034 0 +1035 0 +1036 0 +1037 0 +1038 0 +1039 0 +1040 0 +1041 0 +1042 1 +1043 0 +1044 0 +1045 0 +1046 0 +1047 0 +1048 0 +1049 0 +1050 1 +1051 0 +1052 0 +1053 0 +1054 0 +1055 0 +1056 0 +1057 1 +1058 0 +1059 0 +1060 0 +1061 0 +1062 0 +1063 0 +1064 0 +1065 0 +1066 0 +1067 1 +1068 0 +1069 0 +1070 0 +1071 0 +1072 0 +1073 0 +1074 0 +1075 0 +1076 0 +1077 1 +1078 0 +1079 0 +1080 0 +1081 0 +1082 0 +1083 0 +1084 0 +1085 0 +1086 0 +1087 1 +1088 0 +1089 0 +1090 0 +1091 0 +1092 0 +1093 0 +1094 1 +1095 0 +1096 0 +1097 0 +1098 0 +1099 0 +1100 0 +1101 0 +1102 1 +1103 0 +1104 0 +1105 0 +1106 0 +1107 0 +1108 0 +1109 0 +1110 0 +1111 1 +1112 0 +1113 0 +1114 0 +1115 0 +1116 0 +1117 0 +1118 0 +1119 0 +1120 1 +1121 0 +1122 0 +1123 0 +1124 0 +1125 0 +1126 0 +1127 0 +1128 0 +1129 0 +1130 1 +1131 0 +1132 0 +1133 0 +1134 0 +1135 0 +1136 0 +1137 0 +1138 0 +1139 0 +1140 1 +1141 0 +1142 0 +1143 0 +1144 0 +1145 0 +1146 0 +1147 0 +1148 0 +1149 0 +1150 0 +1151 1 +1152 0 +1153 0 +1154 0 +1155 0 +1156 0 +1157 0 +1158 0 +1159 0 +1160 1 +1161 0 +1162 0 +1163 0 +1164 0 +1165 0 +1166 0 +1167 1 +1168 0 +1169 0 +1170 0 +1171 0 +1172 0 +1173 0 +1174 0 +1175 0 +1176 1 +1177 0 +1178 0 +1179 0 +1180 0 +1181 0 +1182 1 +1183 0 +1184 0 +1185 0 +1186 0 +1187 0 +1188 0 +1189 0 +1190 1 +1191 0 +1192 0 +1193 0 +1194 0 +1195 0 +1196 0 +1197 0 +1198 1 +1199 0 +1200 0 +1201 0 +1202 0 +1203 0 +1204 0 +1205 0 +1206 1 +1207 0 +1208 0 +1209 0 +1210 0 +1211 0 +1212 0 +1213 0 +1214 0 +1215 0 +1216 1 +1217 0 +1218 0 +1219 0 +1220 0 +1221 0 +1222 0 +1223 0 +1224 0 +1225 0 +1226 1 +1227 0 +1228 0 +1229 0 +1230 0 +1231 0 +1232 0 +1233 0 +1234 0 +1235 0 +1236 0 +1237 0 +1238 0 +1239 1 +1240 0 +1241 0 +1242 0 +1243 0 +1244 0 +1245 0 +1246 0 +1247 0 +1248 1 +1249 0 +1250 0 +1251 0 +1252 0 +1253 0 +1254 0 +1255 0 +1256 0 +1257 1 +1258 0 +1259 0 +1260 0 +1261 0 +1262 0 +1263 0 +1264 0 +1265 0 +1266 1 +1267 0 +1268 0 +1269 0 +1270 0 +1271 0 +1272 0 +1273 0 +1274 0 +1275 1 +1276 0 +1277 0 +1278 0 +1279 0 +1280 0 +1281 0 +1282 0 +1283 0 +1284 0 +1285 0 +1286 0 +1287 0 +1288 0 +1289 0 +1290 0 +1291 0 +1292 0 +1293 1 +1294 0 +1295 0 +1296 0 +1297 0 +1298 0 +1299 0 +1300 0 +1301 0 +1302 0 +1303 0 +1304 0 +1305 0 +1306 0 +1307 0 +1308 0 +1309 0 +1310 1 +1311 0 +1312 0 +1313 0 +1314 0 +1315 0 +1316 0 +1317 0 +1318 1 +1319 0 +1320 0 +1321 0 +1322 0 +1323 0 +1324 0 +1325 0 +1326 0 +1327 1 +1328 0 +1329 0 +1330 0 +1331 0 +1332 0 +1333 0 +1334 0 +1335 0 +1336 1 +1337 0 +1338 0 +1339 0 +1340 0 +1341 0 +1342 0 +1343 0 +1344 0 +1345 0 +1346 1 +1347 0 +1348 0 +1349 0 +1350 0 +1351 0 +1352 0 +1353 0 +1354 0 +1355 0 +1356 1 +1357 0 +1358 0 +1359 0 +1360 0 +1361 0 +1362 0 +1363 0 +1364 0 +1365 1 +1366 0 +1367 0 +1368 0 +1369 0 +1370 0 +1371 0 +1372 0 +1373 1 +1374 0 +1375 0 +1376 0 +1377 0 +1378 0 +1379 0 +1380 0 +1381 0 +1382 0 +1383 1 +1384 0 +1385 0 +1386 0 +1387 0 +1388 0 +1389 0 +1390 0 +1391 0 +1392 1 +1393 0 +1394 0 +1395 0 +1396 0 +1397 0 +1398 0 +1399 0 +1400 1 +1401 0 +1402 0 +1403 0 +1404 0 +1405 0 +1406 0 +1407 0 +1408 0 +1409 0 +1410 1 +1411 0 +1412 0 +1413 0 +1414 0 +1415 0 +1416 0 +1417 0 +1418 0 +1419 0 +1420 1 +1421 0 +1422 0 +1423 0 +1424 0 +1425 0 +1426 0 +1427 0 +1428 0 +1429 0 +1430 0 +1431 1 +1432 0 +1433 0 +1434 0 +1435 0 +1436 0 +1437 0 +1438 0 +1439 0 +1440 0 +1441 1 +1442 0 +1443 0 +1444 0 +1445 0 +1446 0 +1447 2 +1448 0 +1449 0 +1450 0 +1451 0 +1452 0 +1453 0 +1454 0 +1455 1 +1456 0 +1457 0 +1458 0 +1459 0 +1460 0 +1461 0 +1462 0 +1463 0 +1464 0 +1465 1 +1466 0 +1467 0 +1468 0 +1469 0 +1470 0 +1471 0 +1472 0 +1473 0 +1474 0 +1475 1 +1476 0 +1477 0 +1478 0 +1479 0 +1480 0 +1481 0 +1482 0 +1483 0 +1484 0 +1485 1 +1486 0 +1487 0 +1488 0 +1489 0 +1490 0 +1491 0 +1492 0 +1493 0 +1494 1 +1495 0 +1496 0 +1497 0 +1498 0 +1499 0 +1500 0 +1501 0 +1502 0 +1503 1 +1504 0 +1505 0 +1506 0 +1507 0 +1508 0 +1509 0 +1510 0 +1511 0 +1512 0 +1513 0 +1514 0 +1515 0 +1516 0 +1517 0 +1518 0 +1519 0 +1520 1 +1521 0 +1522 0 +1523 0 +1524 0 +1525 0 +1526 0 +1527 0 +1528 0 +1529 1 +1530 0 +1531 0 +1532 0 +1533 0 +1534 0 +1535 0 +1536 0 +1537 0 +1538 0 +1539 1 +1540 0 +1541 0 +1542 0 +1543 0 +1544 0 +1545 0 +1546 0 +1547 0 +1548 1 +1549 0 +1550 0 +1551 0 +1552 0 +1553 0 +1554 0 +1555 0 +1556 0 +1557 1 +1558 0 +1559 0 +1560 0 +1561 0 +1562 0 +1563 0 +1564 0 +1565 0 +1566 0 +1567 1 +1568 0 +1569 0 +1570 0 +1571 0 +1572 0 +1573 0 +1574 0 +1575 1 +1576 0 +1577 0 +1578 0 +1579 0 +1580 0 +1581 0 +1582 0 +1583 0 +1584 1 +1585 0 +1586 0 +1587 0 +1588 0 +1589 0 +1590 0 +1591 0 +1592 0 +1593 1 +1594 0 +1595 0 +1596 0 +1597 0 +1598 0 +1599 0 +1600 0 +1601 0 +1602 1 +1603 0 +1604 0 +1605 0 +1606 0 +1607 0 +1608 0 +1609 0 +1610 0 +1611 1 +1612 0 +1613 0 +1614 0 +1615 0 +1616 0 +1617 0 +1618 0 +1619 0 +1620 0 +1621 1 +1622 0 +1623 0 +1624 0 +1625 0 +1626 0 +1627 0 +1628 0 +1629 0 +1630 0 +1631 1 +1632 0 +1633 0 +1634 0 +1635 0 +1636 0 +1637 0 +1638 0 +1639 0 +1640 1 +1641 0 +1642 0 +1643 0 +1644 0 +1645 0 +1646 0 +1647 0 +1648 0 +1649 0 +1650 1 +1651 0 +1652 0 +1653 0 +1654 0 +1655 0 +1656 0 +1657 0 +1658 0 +1659 0 +1660 1 +1661 0 +1662 0 +1663 0 +1664 0 +1665 0 +1666 0 +1667 0 +1668 0 +1669 0 +1670 1 +1671 0 +1672 0 +1673 0 +1674 0 +1675 0 +1676 0 +1677 0 +1678 0 +1679 0 +1680 1 +1681 0 +1682 0 +1683 0 +1684 0 +1685 0 +1686 0 +1687 0 +1688 0 +1689 0 +1690 1 +1691 0 +1692 0 +1693 0 +1694 0 +1695 0 +1696 0 +1697 0 +1698 0 +1699 0 +1700 0 +1701 1 +1702 0 +1703 0 +1704 0 +1705 0 +1706 0 +1707 0 +1708 1 +1709 0 +1710 0 +1711 0 +1712 0 +1713 0 +1714 0 +1715 0 +1716 1 +1717 0 +1718 0 +1719 0 +1720 0 +1721 0 +1722 0 +1723 0 +1724 0 +1725 0 +1726 0 +1727 0 +1728 0 +1729 0 +1730 0 +1731 0 +1732 0 +1733 0 +1734 1 +1735 0 +1736 0 +1737 0 +1738 0 +1739 0 +1740 0 +1741 0 +1742 0 +1743 1 +1744 0 +1745 0 +1746 0 +1747 0 +1748 0 +1749 0 +1750 0 +1751 0 +1752 0 +1753 1 +1754 0 +1755 0 +1756 0 +1757 0 +1758 0 +1759 0 +1760 0 +1761 0 +1762 0 +1763 1 +1764 0 +1765 0 +1766 0 +1767 0 +1768 0 +1769 0 +1770 0 +1771 0 +1772 0 +1773 1 +1774 0 +1775 0 +1776 0 +1777 0 +1778 0 +1779 0 +1780 0 +1781 0 +1782 0 +1783 1 +1784 0 +1785 0 +1786 0 +1787 0 +1788 0 +1789 0 +1790 0 +1791 0 +1792 0 +1793 1 +1794 0 +1795 0 +1796 0 +1797 0 +1798 0 +1799 0 +1800 0 +1801 0 +1802 0 +1803 1 +1804 0 +1805 0 +1806 0 +1807 0 +1808 0 +1809 0 +1810 0 +1811 0 +1812 0 +1813 1 +1814 0 +1815 0 +1816 0 +1817 0 +1818 0 +1819 0 +1820 0 +1821 0 +1822 1 +1823 0 +1824 0 +1825 0 +1826 0 +1827 0 +1828 0 +1829 1 +1830 0 +1831 0 +1832 0 +1833 0 +1834 0 +1835 0 +1836 0 +1837 0 +1838 0 +1839 1 +1840 0 +1841 0 +1842 0 +1843 0 +1844 0 +1845 0 +1846 0 +1847 0 +1848 0 +1849 1 +1850 0 +1851 0 +1852 0 +1853 0 +1854 0 +1855 0 +1856 0 +1857 0 +1858 0 +1859 1 +1860 0 +1861 0 +1862 0 +1863 0 +1864 0 +1865 0 +1866 0 +1867 0 +1868 0 +1869 1 +1870 0 +1871 0 +1872 0 +1873 0 +1874 0 +1875 0 +1876 0 +1877 0 +1878 0 +1879 1 +1880 0 +1881 0 +1882 0 +1883 0 +1884 0 +1885 0 +1886 0 +1887 0 +1888 0 +1889 1 +1890 0 +1891 0 +1892 0 +1893 0 +1894 0 +1895 0 +1896 0 +1897 0 +1898 0 +1899 0 +1900 0 +1901 0 +1902 0 +1903 0 +1904 0 +1905 0 +1906 0 +1907 0 +1908 0 +1909 0 +1910 1 +1911 0 +1912 0 +1913 0 +1914 0 +1915 0 +1916 0 +1917 0 +1918 0 +1919 0 +1920 0 +1921 0 +1922 0 +1923 0 +1924 0 +1925 0 +1926 0 +1927 0 +1928 0 +1929 0 +1930 1 +1931 0 +1932 0 +1933 0 +1934 0 +1935 0 +1936 0 +1937 0 +1938 0 +1939 1 +1940 0 +1941 0 +1942 0 +1943 0 +1944 0 +1945 0 +1946 0 +1947 0 +1948 0 +1949 1 +1950 0 +1951 0 +1952 0 +1953 0 +1954 0 +1955 0 +1956 0 +1957 0 +1958 1 +1959 0 +1960 0 +1961 0 +1962 0 +1963 0 +1964 0 +1965 0 +1966 0 +1967 0 +1968 1 +1969 0 +1970 0 +1971 0 +1972 0 +1973 0 +1974 0 +1975 0 +1976 0 +1977 0 +1978 1 +1979 0 +1980 0 +1981 0 +1982 0 +1983 0 +1984 0 +1985 0 +1986 0 +1987 0 +1988 1 +1989 0 +1990 0 +1991 0 +1992 0 +1993 0 +1994 0 +1995 0 +1996 1 +1997 0 +1998 0 +1999 0 +2000 0 +2001 0 +2002 0 +2003 0 +2004 1 +2005 0 +2006 0 +2007 0 +2008 0 +2009 0 +2010 0 +2011 0 +2012 0 +2013 0 +2014 1 +2015 0 +2016 0 +2017 0 +2018 0 +2019 0 +2020 0 +2021 0 +2022 0 +2023 0 +2024 1 +2025 0 +2026 0 +2027 0 +2028 0 +2029 0 +2030 0 +2031 0 +2032 0 +2033 1 +2034 0 +2035 0 +2036 0 +2037 0 +2038 0 +2039 0 +2040 0 +2041 2 +2042 0 +2043 0 +2044 0 +2045 0 +2046 0 +2047 0 +2048 0 +2049 1 +2050 0 +2051 0 +2052 0 +2053 0 +2054 0 +2055 0 +2056 0 +2057 0 +2058 0 +2059 0 +2060 0 +2061 0 +2062 0 +2063 0 +2064 0 +2065 0 +2066 0 +2067 1 +2068 0 +2069 0 +2070 0 +2071 0 +2072 0 +2073 0 +2074 0 +2075 0 +2076 1 +2077 0 +2078 0 +2079 0 +2080 0 +2081 0 +2082 0 +2083 0 +2084 0 +2085 0 +2086 1 +2087 0 +2088 0 +2089 0 +2090 0 +2091 0 +2092 0 +2093 0 +2094 0 +2095 0 +2096 1 +2097 0 +2098 0 +2099 0 +2100 0 +2101 0 +2102 0 +2103 0 +2104 0 +2105 1 +2106 0 +2107 0 +2108 0 +2109 0 +2110 0 +2111 0 +2112 0 +2113 0 +2114 0 +2115 0 +2116 1 +2117 0 +2118 0 +2119 0 +2120 0 +2121 0 +2122 0 +2123 0 +2124 0 +2125 1 +2126 0 +2127 0 +2128 0 +2129 0 +2130 0 +2131 0 +2132 0 +2133 1 +2134 0 +2135 0 +2136 0 +2137 0 +2138 0 +2139 0 +2140 0 +2141 1 +2142 0 +2143 0 +2144 0 +2145 0 +2146 0 +2147 0 +2148 0 +2149 0 +2150 1 +2151 0 +2152 0 +2153 0 +2154 0 +2155 0 +2156 0 +2157 0 +2158 0 +2159 1 +2160 0 +2161 0 +2162 0 +2163 0 +2164 0 +2165 0 +2166 0 +2167 0 +2168 0 +2169 1 +2170 0 +2171 0 +2172 0 +2173 0 +2174 0 +2175 0 +2176 0 +2177 1 +2178 0 +2179 0 +2180 0 +2181 0 +2182 0 +2183 0 +2184 0 +2185 0 +2186 0 +2187 1 +2188 0 +2189 0 +2190 0 +2191 0 +2192 0 +2193 0 +2194 0 +2195 0 +2196 1 +2197 0 +2198 0 +2199 0 +2200 0 +2201 0 +2202 0 +2203 0 +2204 1 +2205 0 +2206 0 +2207 0 +2208 0 +2209 0 +2210 0 +2211 0 +2212 0 +2213 0 +2214 1 +2215 0 +2216 0 +2217 0 +2218 0 +2219 0 +2220 0 +2221 0 +2222 0 +2223 0 +2224 1 +2225 0 +2226 0 +2227 0 +2228 0 +2229 0 +2230 0 +2231 0 +2232 0 +2233 1 +2234 0 +2235 0 +2236 0 +2237 0 +2238 0 +2239 0 +2240 0 +2241 0 +2242 1 +2243 0 +2244 0 +2245 0 +2246 0 +2247 0 +2248 0 +2249 0 +2250 1 +2251 0 +2252 0 +2253 0 +2254 0 +2255 0 +2256 0 +2257 0 +2258 0 +2259 0 +2260 1 +2261 0 +2262 0 +2263 0 +2264 0 +2265 0 +2266 0 +2267 0 +2268 0 +2269 0 +2270 1 +2271 0 +2272 0 +2273 0 +2274 0 +2275 0 +2276 0 +2277 0 +2278 0 +2279 0 +2280 1 +2281 0 +2282 0 +2283 0 +2284 0 +2285 0 +2286 0 +2287 0 +2288 0 +2289 0 +2290 1 +2291 0 +2292 0 +2293 0 +2294 0 +2295 0 +2296 0 +2297 0 +2298 1 +2299 0 +2300 0 +2301 0 +2302 0 +2303 0 +2304 0 +2305 0 +2306 1 +2307 0 +2308 0 +2309 0 +2310 0 +2311 0 +2312 0 +2313 0 +2314 0 +2315 1 +2316 0 +2317 0 +2318 0 +2319 0 +2320 0 +2321 0 +2322 0 +2323 0 +2324 0 +2325 1 +2326 0 +2327 0 +2328 0 +2329 0 +2330 0 +2331 0 +2332 0 +2333 0 +2334 0 +2335 1 +2336 0 +2337 0 +2338 0 +2339 0 +2340 0 +2341 0 +2342 0 +2343 0 +2344 0 +2345 1 +2346 0 +2347 0 +2348 0 +2349 0 +2350 0 +2351 0 +2352 0 +2353 1 +2354 0 +2355 0 +2356 0 +2357 0 +2358 0 +2359 0 +2360 0 +2361 1 +2362 0 +2363 0 +2364 0 +2365 0 +2366 0 +2367 0 +2368 0 +2369 0 +2370 0 +2371 1 +2372 0 +2373 0 +2374 0 +2375 0 +2376 0 +2377 0 +2378 0 +2379 0 +2380 0 +2381 1 +2382 0 +2383 0 +2384 0 +2385 0 +2386 0 +2387 0 +2388 0 +2389 0 +2390 1 +2391 0 +2392 0 +2393 0 +2394 0 +2395 0 +2396 0 +2397 0 +2398 0 +2399 0 +2400 0 +2401 0 +2402 0 +2403 0 +2404 0 +2405 0 +2406 0 +2407 0 +2408 0 +2409 0 +2410 0 +2411 1 +2412 0 +2413 0 +2414 0 +2415 0 +2416 0 +2417 0 +2418 0 +2419 0 +2420 0 +2421 1 +2422 0 +2423 0 +2424 0 +2425 0 +2426 0 +2427 0 +2428 0 +2429 0 +2430 0 +2431 0 +2432 0 +2433 0 +2434 0 +2435 0 +2436 0 +2437 0 +2438 0 +2439 0 +2440 1 +2441 0 +2442 0 +2443 0 +2444 0 +2445 0 +2446 0 +2447 0 +2448 0 +2449 0 +2450 0 +2451 1 +2452 0 +2453 0 +2454 0 +2455 0 +2456 0 +2457 0 +2458 0 +2459 0 +2460 0 +2461 1 +2462 0 +2463 0 +2464 0 +2465 0 +2466 0 +2467 0 +2468 0 +2469 1 +2470 0 +2471 0 +2472 0 +2473 0 +2474 0 +2475 0 +2476 0 +2477 1 +2478 0 +2479 0 +2480 0 +2481 0 +2482 0 +2483 0 +2484 0 +2485 0 +2486 1 +2487 0 +2488 0 +2489 0 +2490 0 +2491 0 +2492 0 +2493 0 +2494 0 +2495 0 +2496 1 +2497 0 +2498 0 +2499 0 +2500 0 +2501 0 +2502 0 +2503 0 +2504 0 +2505 0 +2506 1 +2507 0 +2508 0 +2509 0 +2510 0 +2511 0 +2512 0 +2513 0 +2514 0 +2515 0 +2516 1 +2517 0 +2518 0 +2519 0 +2520 0 +2521 0 +2522 0 +2523 0 +2524 0 +2525 0 +2526 0 +2527 1 +2528 0 +2529 0 +2530 0 +2531 0 +2532 0 +2533 0 +2534 0 +2535 0 +2536 0 +2537 1 +2538 0 +2539 0 +2540 0 +2541 0 +2542 0 +2543 0 +2544 0 +2545 0 +2546 0 +2547 0 +2548 0 +2549 0 +2550 0 +2551 0 +2552 0 +2553 0 +2554 0 +2555 0 +2556 0 +2557 1 +2558 0 +2559 0 +2560 0 +2561 0 +2562 0 +2563 0 +2564 0 +2565 0 +2566 1 +2567 0 +2568 0 +2569 0 +2570 0 +2571 0 +2572 0 +2573 0 +2574 0 +2575 1 +2576 0 +2577 0 +2578 0 +2579 0 +2580 0 +2581 0 +2582 0 +2583 0 +2584 1 +2585 0 +2586 0 +2587 0 +2588 0 +2589 0 +2590 0 +2591 0 +2592 0 +2593 0 +2594 0 +2595 1 +2596 0 +2597 0 +2598 0 +2599 0 +2600 0 +2601 0 +2602 0 +2603 0 +2604 0 +2605 1 +2606 0 +2607 0 +2608 0 +2609 0 +2610 0 +2611 0 +2612 0 +2613 0 +2614 0 +2615 0 +2616 0 +2617 0 +2618 0 +2619 0 +2620 0 +2621 0 +2622 0 +2623 0 +2624 0 +2625 1 +2626 0 +2627 0 +2628 0 +2629 0 +2630 0 +2631 0 +2632 0 +2633 0 +2634 0 +2635 1 +2636 0 +2637 0 +2638 0 +2639 1 +2640 0 +2641 0 +2642 0 +2643 1 +2644 0 +2645 0 +2646 0 +2647 0 +2648 0 +2649 0 +2650 0 +2651 0 +2652 0 +2653 1 +2654 0 +2655 0 +2656 0 +2657 0 +2658 0 +2659 0 +2660 0 +2661 0 +2662 0 +2663 1 +2664 0 +2665 0 +2666 0 +2667 0 +2668 0 +2669 0 +2670 0 +2671 1 +2672 0 +2673 0 +2674 0 +2675 0 +2676 0 +2677 0 +2678 0 +2679 1 +2680 0 +2681 0 +2682 0 +2683 0 +2684 0 +2685 0 +2686 0 +2687 0 +2688 0 +2689 1 +2690 0 +2691 0 +2692 0 +2693 0 +2694 0 +2695 0 +2696 0 +2697 0 +2698 0 +2699 1 +2700 0 +2701 0 +2702 0 +2703 0 +2704 0 +2705 0 +2706 0 +2707 0 +2708 0 +2709 1 +2710 0 +2711 0 +2712 0 +2713 0 +2714 0 +2715 0 +2716 1 +2717 0 +2718 0 +2719 0 +2720 0 +2721 0 +2722 0 +2723 0 +2724 1 +2725 0 +2726 0 +2727 0 +2728 0 +2729 0 +2730 0 +2731 0 +2732 0 +2733 0 +2734 1 +2735 0 +2736 0 +2737 0 +2738 0 +2739 0 +2740 0 +2741 0 +2742 0 +2743 0 +2744 1 +2745 0 +2746 0 +2747 0 +2748 0 +2749 0 +2750 0 +2751 0 +2752 0 +2753 1 +2754 0 +2755 0 +2756 0 +2757 0 +2758 0 +2759 0 +2760 0 +2761 0 +2762 0 +2763 1 +2764 0 +2765 0 +2766 0 +2767 0 +2768 0 +2769 0 +2770 0 +2771 0 +2772 0 +2773 1 +2774 0 +2775 0 +2776 0 +2777 0 +2778 0 +2779 0 +2780 0 +2781 0 +2782 0 +2783 1 +2784 0 +2785 0 +2786 0 +2787 0 +2788 0 +2789 0 +2790 0 +2791 0 +2792 1 +2793 0 +2794 0 +2795 0 +2796 0 +2797 0 +2798 0 +2799 0 +2800 0 +2801 0 +2802 0 +2803 0 +2804 0 +2805 0 +2806 0 +2807 0 +2808 0 +2809 0 +2810 0 +2811 0 +2812 0 +2813 0 +2814 0 +2815 0 +2816 0 +2817 0 +2818 0 +2819 0 +2820 0 +2821 1 +2822 0 +2823 0 +2824 0 +2825 0 +2826 0 +2827 0 +2828 0 +2829 0 +2830 0 +2831 1 +2832 0 +2833 0 +2834 0 +2835 0 +2836 0 +2837 0 +2838 0 +2839 0 +2840 0 +2841 1 +2842 0 +2843 0 +2844 0 +2845 0 +2846 0 +2847 0 +2848 0 +2849 0 +2850 0 +2851 1 +2852 0 +2853 0 +2854 0 +2855 0 +2856 0 +2857 0 +2858 0 +2859 0 +2860 0 +2861 1 +2862 0 +2863 0 +2864 0 +2865 0 +2866 0 +2867 0 +2868 0 +2869 0 +2870 0 +2871 1 +2872 0 +2873 0 +2874 0 +2875 0 +2876 0 +2877 0 +2878 0 +2879 0 +2880 1 +2881 0 +2882 0 +2883 0 +2884 0 +2885 0 +2886 0 +2887 0 +2888 1 +2889 0 +2890 0 +2891 0 +2892 0 +2893 0 +2894 0 +2895 0 +2896 0 +2897 1 +2898 0 +2899 0 +2900 0 +2901 0 +2902 0 +2903 0 +2904 0 +2905 0 +2906 1 +2907 0 +2908 0 +2909 0 +2910 0 +2911 0 +2912 0 +2913 0 +2914 1 +2915 0 +2916 0 +2917 0 +2918 0 +2919 0 +2920 0 +2921 0 +2922 1 +2923 0 +2924 0 +2925 0 +2926 0 +2927 0 +2928 0 +2929 0 +2930 0 +2931 0 +2932 0 +2933 0 +2934 0 +2935 0 +2936 0 +2937 0 +2938 1 +2939 0 +2940 0 +2941 0 +2942 0 +2943 0 +2944 0 +2945 0 +2946 0 +2947 0 +2948 0 +2949 1 +2950 0 +2951 0 +2952 0 +2953 0 +2954 0 +2955 0 +2956 0 +2957 0 +2958 0 +2959 1 +2960 0 +2961 0 +2962 0 +2963 0 +2964 0 +2965 0 +2966 0 +2967 0 +2968 1 +2969 0 +2970 0 +2971 0 +2972 0 +2973 0 +2974 0 +2975 0 +2976 0 +2977 1 +2978 0 +2979 0 +2980 0 +2981 0 +2982 0 +2983 0 +2984 0 +2985 0 +2986 0 +2987 1 +2988 0 +2989 0 +2990 0 +2991 0 +2992 0 +2993 0 +2994 0 +2995 0 +2996 0 +2997 1 +2998 0 +2999 0 +3000 0 +3001 0 +3002 0 +3003 0 +3004 0 +3005 0 +3006 0 +3007 0 +3008 0 +3009 0 +3010 0 +3011 0 +3012 0 +3013 0 +3014 0 +3015 1 +3016 0 +3017 0 +3018 0 +3019 0 +3020 0 +3021 0 +3022 0 +3023 0 +3024 0 +3025 1 +3026 0 +3027 0 +3028 0 +3029 0 +3030 0 +3031 0 +3032 0 +3033 0 +3034 1 +3035 0 +3036 0 +3037 0 +3038 0 +3039 0 +3040 0 +3041 0 +3042 1 +3043 0 +3044 0 +3045 0 +3046 0 +3047 0 +3048 0 +3049 0 +3050 0 +3051 0 +3052 1 +3053 0 +3054 0 +3055 0 +3056 0 +3057 0 +3058 0 +3059 0 +3060 0 +3061 0 +3062 1 +3063 0 +3064 0 +3065 0 +3066 0 +3067 0 +3068 0 +3069 0 +3070 0 +3071 0 +3072 1 +3073 0 +3074 0 +3075 0 +3076 0 +3077 0 +3078 0 +3079 0 +3080 0 +3081 0 +3082 1 +3083 0 +3084 0 +3085 0 +3086 0 +3087 0 +3088 0 +3089 0 +3090 0 +3091 0 +3092 1 +3093 0 +3094 0 +3095 0 +3096 0 +3097 0 +3098 0 +3099 0 +3100 0 +3101 0 +3102 1 +3103 0 +3104 0 +3105 0 +3106 0 +3107 0 +3108 0 +3109 0 +3110 0 +3111 0 +3112 1 +3113 0 +3114 0 +3115 0 +3116 0 +3117 0 +3118 0 +3119 0 +3120 1 +3121 0 +3122 0 +3123 0 +3124 0 +3125 0 +3126 0 +3127 0 +3128 0 +3129 1 +3130 0 +3131 0 +3132 0 +3133 0 +3134 0 +3135 0 +3136 0 +3137 0 +3138 0 +3139 1 +3140 0 +3141 0 +3142 0 +3143 0 +3144 0 +3145 0 +3146 0 +3147 0 +3148 0 +3149 1 +3150 0 +3151 0 +3152 0 +3153 0 +3154 0 +3155 0 +3156 0 +3157 1 +3158 0 +3159 0 +3160 0 +3161 0 +3162 0 +3163 0 +3164 0 +3165 1 +3166 0 +3167 0 +3168 0 +3169 0 +3170 0 +3171 0 +3172 0 +3173 0 +3174 0 +3175 1 +3176 0 +3177 0 +3178 0 +3179 0 +3180 0 +3181 0 +3182 0 +3183 0 +3184 0 +3185 1 +3186 0 +3187 0 +3188 0 +3189 0 +3190 0 +3191 0 +3192 0 +3193 0 +3194 0 +3195 0 +3196 1 +3197 0 +3198 0 +3199 0 +3200 0 +3201 0 +3202 0 +3203 0 +3204 0 +3205 0 +3206 0 +3207 1 +3208 0 +3209 0 +3210 0 +3211 0 +3212 0 +3213 0 +3214 0 +3215 1 +3216 0 +3217 0 +3218 0 +3219 0 +3220 0 +3221 0 +3222 0 +3223 1 +3224 0 +3225 0 +3226 0 +3227 0 +3228 0 +3229 0 +3230 0 +3231 0 +3232 1 +3233 0 +3234 1 +3235 0 +3236 0 +3237 0 +3238 0 +3239 1 +3240 0 +3241 0 +3242 0 +3243 0 +3244 0 +3245 0 +3246 0 +3247 0 +3248 1 +3249 0 +3250 0 +3251 0 +3252 0 +3253 0 +3254 0 +3255 0 +3256 0 +3257 0 +3258 1 +3259 0 +3260 0 +3261 0 +3262 0 +3263 0 +3264 0 +3265 0 +3266 0 +3267 0 +3268 0 +3269 1 +3270 0 +3271 0 +3272 0 +3273 0 +3274 0 +3275 0 +3276 0 +3277 0 +3278 1 +3279 0 +3280 0 +3281 0 +3282 0 +3283 0 +3284 0 +3285 0 +3286 0 +3287 1 +3288 0 +3289 0 +3290 0 +3291 0 +3292 0 +3293 0 +3294 0 +3295 0 +3296 0 +3297 1 +3298 0 +3299 0 +3300 0 +3301 0 +3302 0 +3303 0 +3304 0 +3305 0 +3306 0 +3307 1 +3308 0 +3309 0 +3310 0 +3311 0 +3312 0 +3313 0 +3314 0 +3315 0 +3316 0 +3317 1 +3318 0 +3319 0 +3320 0 +3321 0 +3322 0 +3323 0 +3324 0 +3325 1 +3326 0 +3327 0 +3328 0 +3329 0 +3330 0 +3331 0 +3332 0 +3333 0 +3334 0 +3335 1 +3336 0 +3337 0 +3338 0 +3339 0 +3340 0 +3341 0 +3342 0 +3343 0 +3344 1 +3345 0 +3346 0 +3347 0 +3348 0 +3349 0 +3350 0 +3351 0 +3352 0 +3353 0 +3354 1 +3355 0 +3356 0 +3357 0 +3358 0 +3359 0 +3360 0 +3361 0 +3362 0 +3363 0 +3364 0 +3365 1 +3366 0 +3367 0 +3368 0 +3369 0 +3370 0 +3371 0 +3372 0 +3373 0 +3374 0 +3375 1 +3376 0 +3377 0 +3378 0 +3379 0 +3380 0 +3381 0 +3382 0 +3383 0 +3384 0 +3385 0 +3386 1 +3387 0 +3388 0 +3389 0 +3390 0 +3391 0 +3392 0 +3393 0 +3394 0 +3395 0 +3396 0 +3397 1 +3398 0 +3399 0 +3400 0 +3401 0 +3402 0 +3403 0 +3404 0 +3405 0 +3406 0 +3407 1 +3408 0 +3409 0 +3410 0 +3411 0 +3412 0 +3413 0 +3414 0 +3415 0 +3416 0 +3417 1 +3418 0 +3419 0 +3420 0 +3421 0 +3422 0 +3423 0 +3424 0 +3425 0 +3426 0 +3427 0 +3428 1 +3429 0 +3430 0 +3431 0 +3432 0 +3433 0 +3434 0 +3435 0 +3436 0 +3437 1 +3438 0 +3439 0 +3440 0 +3441 0 +3442 0 +3443 0 +3444 0 +3445 1 +3446 0 +3447 0 +3448 0 +3449 0 +3450 0 +3451 0 +3452 0 +3453 0 +3454 1 +3455 0 +3456 0 +3457 0 +3458 0 +3459 0 +3460 0 +3461 0 +3462 0 +3463 0 +3464 1 +3465 0 +3466 0 +3467 0 +3468 0 +3469 0 +3470 0 +3471 0 +3472 0 +3473 0 +3474 1 +3475 0 +3476 0 +3477 0 +3478 0 +3479 0 +3480 0 +3481 0 +3482 0 +3483 0 +3484 1 +3485 0 +3486 0 +3487 0 +3488 0 +3489 0 +3490 0 +3491 0 +3492 0 +3493 0 +3494 1 +3495 0 +3496 0 +3497 0 +3498 0 +3499 0 +3500 0 +3501 0 +3502 0 +3503 0 +3504 1 +3505 0 +3506 0 +3507 0 +3508 0 +3509 0 +3510 0 +3511 0 +3512 0 +3513 0 +3514 1 +3515 0 +3516 0 +3517 0 +3518 0 +3519 0 +3520 0 +3521 0 +3522 0 +3523 0 +3524 1 +3525 0 +3526 0 +3527 0 +3528 0 +3529 0 +3530 0 +3531 0 +3532 0 +3533 1 +3534 0 +3535 0 +3536 0 +3537 0 +3538 0 +3539 0 +3540 0 +3541 0 +3542 0 +3543 0 +3544 0 +3545 0 +3546 0 +3547 0 +3548 0 +3549 0 +3550 0 +3551 1 +3552 0 +3553 0 +3554 0 +3555 0 +3556 0 +3557 0 +3558 0 +3559 0 +3560 0 +3561 1 +3562 0 +3563 0 +3564 0 +3565 0 +3566 0 +3567 0 +3568 0 +3569 0 +3570 1 +3571 0 +3572 0 +3573 0 +3574 0 +3575 0 +3576 0 +3577 0 +3578 0 +3579 0 +3580 1 +3581 0 +3582 0 +3583 0 +3584 0 +3585 0 +3586 0 +3587 0 +3588 0 +3589 0 +3590 1 +3591 0 +3592 0 +3593 0 +3594 0 +3595 0 +3596 0 +3597 0 +3598 0 +3599 1 +3600 0 +3601 0 +3602 0 +3603 0 +3604 0 +3605 0 +3606 0 +3607 0 +3608 0 +3609 1 +3610 0 +3611 0 +3612 0 +3613 0 +3614 0 +3615 0 +3616 0 +3617 0 +3618 0 +3619 0 +3620 1 +3621 0 +3622 0 +3623 0 +3624 0 +3625 0 +3626 0 +3627 0 +3628 0 +3629 0 +3630 1 +3631 0 +3632 0 +3633 0 +3634 0 +3635 0 +3636 0 +3637 0 +3638 0 +3639 1 +3640 0 +3641 0 +3642 0 +3643 0 +3644 0 +3645 1 +3646 0 +3647 0 +3648 0 +3649 0 +3650 0 +3651 1 +3652 0 +3653 0 +3654 0 +3655 0 +3656 0 +3657 0 +3658 1 +3659 0 +3660 0 +3661 0 +3662 0 +3663 0 +3664 0 +3665 0 +3666 1 +3667 0 +3668 0 +3669 0 +3670 0 +3671 0 +3672 0 +3673 0 +3674 0 +3675 0 +3676 1 +3677 0 +3678 0 +3679 0 +3680 0 +3681 0 +3682 0 +3683 0 +3684 0 +3685 1 +3686 0 +3687 0 +3688 0 +3689 0 +3690 0 +3691 0 +3692 0 +3693 0 +3694 0 +3695 1 +3696 0 +3697 0 +3698 0 +3699 0 +3700 0 +3701 0 +3702 0 +3703 0 +3704 0 +3705 0 +3706 1 +3707 0 +3708 0 +3709 0 +3710 0 +3711 0 +3712 0 +3713 0 +3714 0 +3715 0 +3716 1 +3717 0 +3718 0 +3719 0 +3720 0 +3721 0 +3722 0 +3723 0 +3724 0 +3725 0 +3726 0 +3727 0 +3728 0 +3729 0 +3730 0 +3731 0 +3732 0 +3733 0 +3734 0 +3735 0 +3736 1 +3737 0 +3738 0 +3739 0 +3740 0 +3741 0 +3742 0 +3743 0 +3744 0 +3745 0 +3746 1 +3747 0 +3748 0 +3749 0 +3750 0 +3751 0 +3752 0 +3753 0 +3754 0 +3755 0 +3756 1 +3757 0 +3758 0 +3759 0 +3760 0 +3761 0 +3762 0 +3763 1 +3764 0 +3765 0 +3766 0 +3767 0 +3768 0 +3769 0 +3770 0 +3771 1 +3772 0 +3773 0 +3774 0 +3775 0 +3776 0 +3777 0 +3778 1 +3779 0 +3780 0 +3781 0 +3782 0 +3783 0 +3784 0 +3785 0 +3786 0 +3787 0 +3788 0 +3789 0 +3790 0 +3791 0 +3792 0 +3793 0 +3794 0 +3795 0 +3796 0 +3797 1 +3798 0 +3799 0 +3800 0 +3801 0 +3802 0 +3803 0 +3804 0 +3805 0 +3806 1 +3807 0 +3808 0 +3809 0 +3810 0 +3811 0 +3812 0 +3813 0 +3814 0 +3815 0 +3816 0 +3817 1 +3818 0 +3819 0 +3820 0 +3821 0 +3822 0 +3823 0 +3824 0 +3825 0 +3826 0 +3827 1 +3828 0 +3829 1 +3830 0 +3831 0 +3832 0 +3833 0 +3834 1 +3835 0 +3836 0 +3837 0 +3838 0 +3839 0 +3840 0 +3841 0 +3842 0 +3843 0 +3844 0 +3845 1 +3846 0 +3847 0 +3848 0 +3849 0 +3850 0 +3851 0 +3852 0 +3853 0 +3854 0 +3855 1 +3856 0 +3857 0 +3858 0 +3859 0 +3860 0 +3861 0 +3862 0 +3863 1 +3864 0 +3865 0 +3866 0 +3867 0 +3868 0 +3869 0 +3870 0 +3871 0 +3872 0 +3873 1 +3874 0 +3875 0 +3876 0 +3877 0 +3878 0 +3879 0 +3880 0 +3881 0 +3882 0 +3883 1 +3884 0 +3885 0 +3886 0 +3887 0 +3888 0 +3889 0 +3890 0 +3891 0 +3892 0 +3893 0 +3894 1 +3895 0 +3896 0 +3897 0 +3898 0 +3899 0 +3900 0 +3901 0 +3902 0 +3903 0 +3904 0 +3905 1 +3906 0 +3907 0 +3908 0 +3909 0 +3910 0 +3911 0 +3912 0 +3913 0 +3914 1 +3915 0 +3916 0 +3917 0 +3918 0 +3919 0 +3920 0 +3921 0 +3922 0 +3923 0 +3924 0 +3925 1 +3926 0 +3927 0 +3928 0 +3929 0 +3930 0 +3931 0 +3932 0 +3933 0 +3934 1 +3935 0 +3936 0 +3937 0 +3938 0 +3939 0 +3940 0 +3941 0 +3942 0 +3943 0 +3944 0 +3945 1 +3946 0 +3947 0 +3948 0 +3949 0 +3950 0 +3951 0 +3952 0 +3953 0 +3954 0 +3955 1 +3956 0 +3957 0 +3958 0 +3959 0 +3960 0 +3961 0 +3962 0 +3963 0 +3964 0 +3965 0 +3966 1 +3967 0 +3968 0 +3969 0 +3970 0 +3971 0 +3972 0 +3973 0 +3974 0 +3975 1 +3976 0 +3977 0 +3978 0 +3979 0 +3980 0 +3981 0 +3982 0 +3983 0 +3984 1 +3985 0 +3986 0 +3987 0 +3988 0 +3989 0 +3990 0 +3991 0 +3992 0 +3993 0 +3994 1 +3995 0 +3996 0 +3997 0 +3998 0 +3999 0 +4000 0 +4001 0 +4002 0 +4003 0 +4004 0 +4005 0 +4006 0 +4007 0 +4008 0 +4009 0 +4010 0 +4011 0 +4012 0 +4013 0 +4014 1 +4015 0 +4016 0 +4017 0 +4018 0 +4019 0 +4020 0 +4021 0 +4022 0 +4023 0 +4024 1 +4025 0 +4026 0 +4027 0 +4028 0 +4029 0 +4030 0 +4031 0 +4032 0 +4033 0 +4034 0 +4035 1 +4036 0 +4037 0 +4038 0 +4039 0 +4040 0 +4041 0 +4042 0 +4043 0 +4044 0 +4045 1 +4046 0 +4047 0 +4048 0 +4049 0 +4050 0 +4051 0 +4052 0 +4053 0 +4054 0 +4055 0 +4056 1 +4057 0 +4058 0 +4059 0 +4060 0 +4061 0 +4062 0 +4063 0 +4064 0 +4065 0 +4066 1 +4067 0 +4068 0 +4069 0 +4070 0 +4071 0 +4072 0 +4073 0 +4074 1 +4075 0 +4076 0 +4077 0 +4078 0 +4079 0 +4080 0 +4081 0 +4082 0 +4083 0 +4084 1 +4085 0 +4086 0 +4087 0 +4088 0 +4089 0 +4090 0 +4091 0 +4092 0 +4093 1 +4094 0 +4095 0 +4096 0 +4097 0 +4098 0 +4099 0 +4100 0 +4101 0 +4102 1 +4103 0 +4104 0 +4105 0 +4106 0 +4107 0 +4108 0 +4109 0 +4110 0 +4111 0 +4112 1 +4113 0 +4114 0 +4115 0 +4116 0 +4117 0 +4118 0 +4119 0 +4120 0 +4121 0 +4122 1 +4123 0 +4124 0 +4125 0 +4126 0 +4127 0 +4128 0 +4129 0 +4130 0 +4131 0 +4132 0 +4133 1 +4134 0 +4135 0 +4136 0 +4137 0 +4138 0 +4139 0 +4140 0 +4141 0 +4142 0 +4143 0 +4144 1 +4145 0 +4146 0 +4147 0 +4148 0 +4149 0 +4150 0 +4151 0 +4152 0 +4153 0 +4154 1 +4155 0 +4156 0 +4157 0 +4158 0 +4159 0 +4160 0 +4161 0 +4162 0 +4163 0 +4164 0 +4165 1 +4166 0 +4167 0 +4168 0 +4169 0 +4170 0 +4171 0 +4172 0 +4173 0 +4174 0 +4175 0 +4176 1 +4177 0 +4178 0 +4179 0 +4180 0 +4181 0 +4182 0 +4183 0 +4184 0 +4185 1 +4186 0 +4187 0 +4188 0 +4189 0 +4190 0 +4191 0 +4192 0 +4193 0 +4194 0 +4195 1 +4196 0 +4197 0 +4198 0 +4199 0 +4200 0 +4201 0 +4202 0 +4203 0 +4204 0 +4205 0 +4206 0 +4207 0 +4208 0 +4209 0 +4210 0 +4211 0 +4212 1 +4213 0 +4214 0 +4215 0 +4216 0 +4217 0 +4218 0 +4219 0 +4220 0 +4221 1 +4222 0 +4223 0 +4224 0 +4225 0 +4226 0 +4227 0 +4228 0 +4229 0 +4230 1 +4231 0 +4232 0 +4233 0 +4234 0 +4235 0 +4236 0 +4237 0 +4238 0 +4239 1 +4240 0 +4241 0 +4242 0 +4243 0 +4244 0 +4245 0 +4246 0 +4247 0 +4248 0 +4249 1 +4250 0 +4251 0 +4252 0 +4253 0 +4254 0 +4255 0 +4256 0 +4257 0 +4258 1 +4259 0 +4260 0 +4261 0 +4262 0 +4263 0 +4264 0 +4265 0 +4266 0 +4267 0 +4268 1 +4269 0 +4270 0 +4271 0 +4272 0 +4273 0 +4274 0 +4275 0 +4276 0 +4277 0 +4278 1 +4279 0 +4280 0 +4281 0 +4282 0 +4283 0 +4284 0 +4285 0 +4286 0 +4287 0 +4288 0 +4289 1 +4290 0 +4291 0 +4292 0 +4293 0 +4294 0 +4295 0 +4296 0 +4297 0 +4298 0 +4299 1 +4300 0 +4301 0 +4302 0 +4303 0 +4304 0 +4305 0 +4306 0 +4307 0 +4308 0 +4309 1 +4310 0 +4311 0 +4312 0 +4313 0 +4314 0 +4315 0 +4316 0 +4317 0 +4318 1 +4319 0 +4320 0 +4321 0 +4322 0 +4323 0 +4324 0 +4325 0 +4326 0 +4327 1 +4328 0 +4329 0 +4330 0 +4331 0 +4332 0 +4333 0 +4334 0 +4335 0 +4336 0 +4337 1 +4338 0 +4339 0 +4340 0 +4341 0 +4342 0 +4343 0 +4344 0 +4345 0 +4346 0 +4347 1 +4348 0 +4349 0 +4350 0 +4351 0 +4352 0 +4353 0 +4354 0 +4355 1 +4356 0 +4357 0 +4358 0 +4359 0 +4360 0 +4361 0 +4362 0 +4363 0 +4364 0 +4365 0 +4366 0 +4367 0 +4368 0 +4369 0 +4370 0 +4371 0 +4372 0 +4373 0 +4374 1 +4375 0 +4376 0 +4377 0 +4378 0 +4379 0 +4380 0 +4381 0 +4382 0 +4383 0 +4384 1 +4385 0 +4386 0 +4387 0 +4388 0 +4389 0 +4390 0 +4391 0 +4392 0 +4393 1 +4394 0 +4395 0 +4396 0 +4397 0 +4398 0 +4399 0 +4400 0 +4401 0 +4402 0 +4403 1 +4404 0 +4405 0 +4406 0 +4407 0 +4408 0 +4409 0 +4410 0 +4411 0 +4412 1 +4413 0 +4414 0 +4415 0 +4416 0 +4417 0 +4418 0 +4419 0 +4420 0 +4421 0 +4422 0 +4423 1 +4424 0 +4425 0 +4426 0 +4427 0 +4428 0 +4429 0 +4430 2 +4431 0 +4432 0 +4433 0 +4434 0 +4435 0 +4436 0 +4437 1 +4438 0 +4439 0 +4440 0 +4441 0 +4442 0 +4443 0 +4444 0 +4445 1 +4446 0 +4447 0 +4448 0 +4449 0 +4450 0 +4451 0 +4452 0 +4453 0 +4454 1 +4455 0 +4456 0 +4457 0 +4458 0 +4459 0 +4460 0 +4461 0 +4462 1 +4463 0 +4464 0 +4465 0 +4466 0 +4467 0 +4468 0 +4469 0 +4470 0 +4471 1 +4472 0 +4473 0 +4474 0 +4475 0 +4476 0 +4477 0 +4478 0 +4479 0 +4480 1 +4481 0 +4482 0 +4483 0 +4484 0 +4485 0 +4486 0 +4487 0 +4488 1 +4489 0 +4490 0 +4491 0 +4492 0 +4493 0 +4494 0 +4495 0 +4496 0 +4497 1 +4498 0 +4499 0 +4500 0 +4501 0 +4502 0 +4503 0 +4504 0 +4505 1 +4506 0 +4507 0 +4508 0 +4509 0 +4510 0 +4511 0 +4512 0 +4513 1 +4514 0 +4515 0 +4516 0 +4517 0 +4518 0 +4519 0 +4520 1 +4521 0 +4522 0 +4523 0 +4524 0 +4525 0 +4526 0 +4527 0 +4528 0 +4529 1 +4530 0 +4531 0 +4532 0 +4533 0 +4534 0 +4535 0 +4536 0 +4537 0 +4538 1 +4539 0 +4540 0 +4541 0 +4542 0 +4543 0 +4544 0 +4545 0 +4546 1 +4547 0 +4548 0 +4549 0 +4550 0 +4551 0 +4552 1 +4553 0 +4554 0 +4555 0 +4556 0 +4557 0 +4558 0 +4559 1 +4560 0 +4561 0 +4562 0 +4563 0 +4564 0 +4565 0 +4566 0 +4567 1 +4568 0 +4569 0 +4570 0 +4571 0 +4572 0 +4573 0 +4574 0 +4575 1 +4576 0 +4577 0 +4578 0 +4579 0 +4580 0 +4581 0 +4582 0 +4583 1 +4584 0 +4585 0 +4586 0 +4587 0 +4588 0 +4589 0 +4590 0 +4591 1 +4592 0 +4593 0 +4594 0 +4595 0 +4596 0 +4597 0 +4598 0 +4599 0 +4600 1 +4601 0 +4602 0 +4603 0 +4604 0 +4605 0 +4606 0 +4607 1 +4608 0 +4609 0 +4610 0 +4611 0 +4612 0 +4613 0 +4614 0 +4615 0 +4616 1 +4617 0 +4618 0 +4619 0 +4620 0 +4621 0 +4622 0 +4623 0 +4624 0 +4625 1 +4626 0 +4627 0 +4628 0 +4629 0 +4630 0 +4631 0 +4632 0 +4633 0 +4634 1 +4635 0 +4636 0 +4637 0 +4638 0 +4639 0 +4640 0 +4641 0 +4642 0 +4643 0 +4644 0 +4645 0 +4646 0 +4647 0 +4648 0 +4649 0 +4650 0 +4651 0 +4652 1 +4653 0 +4654 0 +4655 0 +4656 0 +4657 0 +4658 0 +4659 0 +4660 0 +4661 1 +4662 0 +4663 0 +4664 0 +4665 1 +4666 0 +4667 0 +4668 0 +4669 0 +4670 0 +4671 0 +4672 1 +4673 0 +4674 0 +4675 0 +4676 0 +4677 0 +4678 1 +4679 0 +4680 0 +4681 0 +4682 0 +4683 0 +4684 0 +4685 0 +4686 1 +4687 0 +4688 0 +4689 0 +4690 0 +4691 0 +4692 0 +4693 0 +4694 1 +4695 0 +4696 0 +4697 0 +4698 0 +4699 0 +4700 0 +4701 0 +4702 1 +4703 0 +4704 0 +4705 0 +4706 0 +4707 0 +4708 0 +4709 1 +4710 0 +4711 0 +4712 0 +4713 0 +4714 0 +4715 0 +4716 0 +4717 1 +4718 0 +4719 0 +4720 0 +4721 0 +4722 0 +4723 0 +4724 0 +4725 1 +4726 0 +4727 0 +4728 0 +4729 0 +4730 0 +4731 0 +4732 0 +4733 0 +4734 1 +4735 0 +4736 0 +4737 0 +4738 0 +4739 0 +4740 0 +4741 0 +4742 0 +4743 0 +4744 1 +4745 0 +4746 0 +4747 0 +4748 0 +4749 0 +4750 0 +4751 0 +4752 1 +4753 0 +4754 0 +4755 0 +4756 0 +4757 0 +4758 0 +4759 0 +4760 1 +4761 0 +4762 0 +4763 0 +4764 0 +4765 0 +4766 0 +4767 0 +4768 0 +4769 1 +4770 0 +4771 0 +4772 0 +4773 0 +4774 0 +4775 0 +4776 0 +4777 0 +4778 1 +4779 0 +4780 0 +4781 0 +4782 0 +4783 0 +4784 0 +4785 0 +4786 1 +4787 0 +4788 0 +4789 0 +4790 0 +4791 0 +4792 0 +4793 0 +4794 0 +4795 0 +4796 1 +4797 0 +4798 0 +4799 0 +4800 0 +4801 0 +4802 0 +4803 0 +4804 1 +4805 0 +4806 0 +4807 0 +4808 0 +4809 0 +4810 0 +4811 0 +4812 0 +4813 1 +4814 0 +4815 0 +4816 0 +4817 0 +4818 0 +4819 0 +4820 0 +4821 0 +4822 1 +4823 0 +4824 0 +4825 0 +4826 0 +4827 0 +4828 0 +4829 0 +4830 0 +4831 1 +4832 0 +4833 0 +4834 0 +4835 0 +4836 0 +4837 0 +4838 0 +4839 0 +4840 0 +4841 0 +4842 0 +4843 0 +4844 0 +4845 0 +4846 0 +4847 0 +4848 0 +4849 0 +4850 0 +4851 0 +4852 0 +4853 0 +4854 0 +4855 0 +4856 0 +4857 0 +4858 0 +4859 0 +4860 0 +4861 0 +4862 0 +4863 0 +4864 0 +4865 1 +4866 0 +4867 0 +4868 0 +4869 0 +4870 0 +4871 0 +4872 1 +4873 0 +4874 0 +4875 0 +4876 0 +4877 0 +4878 0 +4879 0 +4880 1 +4881 0 +4882 0 +4883 0 +4884 0 +4885 0 +4886 0 +4887 0 +4888 0 +4889 0 +4890 1 +4891 0 +4892 0 +4893 0 +4894 0 +4895 0 +4896 0 +4897 0 +4898 1 +4899 0 +4900 0 +4901 0 +4902 0 +4903 0 +4904 0 +4905 1 +4906 0 +4907 0 +4908 0 +4909 0 +4910 0 +4911 0 +4912 0 +4913 1 +4914 0 +4915 0 +4916 0 +4917 0 +4918 0 +4919 0 +4920 0 +4921 0 +4922 0 +4923 1 +4924 0 +4925 0 +4926 0 +4927 0 +4928 0 +4929 0 +4930 0 +4931 0 +4932 0 +4933 1 +4934 0 +4935 0 +4936 0 +4937 0 +4938 0 +4939 0 +4940 0 +4941 0 +4942 0 +4943 0 +4944 0 +4945 0 +4946 0 +4947 0 +4948 1 +4949 0 +4950 0 +4951 0 +4952 0 +4953 0 +4954 0 +4955 0 +4956 1 +4957 0 +4958 0 +4959 0 +4960 0 +4961 0 +4962 0 +4963 0 +4964 1 +4965 0 +4966 0 +4967 0 +4968 0 +4969 0 +4970 0 +4971 0 +4972 1 +4973 0 +4974 0 +4975 0 +4976 0 +4977 0 +4978 0 +4979 1 +4980 0 +4981 0 +4982 0 +4983 0 +4984 0 +4985 0 +4986 0 +4987 1 +4988 0 +4989 0 +4990 0 +4991 0 +4992 0 +4993 0 +4994 1 +4995 0 +4996 0 +4997 0 +4998 0 +4999 0 +5000 0 +5001 0 +5002 0 +5003 1 +5004 0 +5005 0 +5006 0 +5007 0 +5008 0 +5009 0 +5010 0 +5011 0 +5012 1 +5013 0 +5014 0 +5015 0 +5016 0 +5017 0 +5018 0 +5019 0 +5020 1 +5021 0 +5022 0 +5023 0 +5024 0 +5025 0 +5026 0 +5027 0 +5028 0 +5029 1 +5030 0 +5031 0 +5032 0 +5033 0 +5034 0 +5035 0 +5036 0 +5037 1 +5038 0 +5039 0 +5040 0 +5041 0 +5042 0 +5043 0 +5044 0 +5045 1 +5046 0 +5047 0 +5048 0 +5049 0 +5050 0 +5051 0 +5052 0 +5053 1 +5054 0 +5055 0 +5056 0 +5057 0 +5058 0 +5059 0 +5060 0 +5061 0 +5062 1 +5063 0 +5064 0 +5065 0 +5066 0 +5067 0 +5068 0 +5069 0 +5070 0 +5071 0 +5072 0 +5073 0 +5074 0 +5075 0 +5076 0 +5077 0 +5078 0 +5079 1 +5080 0 +5081 0 +5082 0 +5083 0 +5084 0 +5085 0 +5086 1 +5087 0 +5088 0 +5089 0 +5090 0 +5091 0 +5092 0 +5093 0 +5094 1 +5095 0 +5096 0 +5097 0 +5098 0 +5099 0 +5100 0 +5101 0 +5102 0 +5103 1 +5104 0 +5105 0 +5106 0 +5107 0 +5108 0 +5109 0 +5110 1 +5111 0 +5112 0 +5113 0 +5114 0 +5115 0 +5116 0 +5117 0 +5118 1 +5119 0 +5120 0 +5121 0 +5122 0 +5123 0 +5124 0 +5125 0 +5126 0 +5127 1 +5128 0 +5129 0 +5130 0 +5131 0 +5132 0 +5133 0 +5134 1 +5135 0 +5136 0 +5137 0 +5138 0 +5139 0 +5140 0 +5141 1 +5142 0 +5143 0 +5144 0 +5145 0 +5146 0 +5147 0 +5148 0 +5149 1 +5150 0 +5151 0 +5152 0 +5153 0 +5154 0 +5155 0 +5156 0 +5157 0 +5158 1 +5159 0 +5160 0 +5161 0 +5162 0 +5163 0 +5164 0 +5165 0 +5166 0 +5167 1 +5168 0 +5169 0 +5170 0 +5171 0 +5172 0 +5173 0 +5174 0 +5175 1 +5176 0 +5177 0 +5178 0 +5179 0 +5180 0 +5181 0 +5182 1 +5183 0 +5184 0 +5185 0 +5186 0 +5187 0 +5188 0 +5189 0 +5190 1 +5191 0 +5192 0 +5193 0 +5194 0 +5195 0 +5196 0 +5197 0 +5198 0 +5199 1 +5200 0 +5201 0 +5202 0 +5203 0 +5204 0 +5205 0 +5206 0 +5207 0 +5208 1 +5209 0 +5210 0 +5211 0 +5212 0 +5213 0 +5214 0 +5215 0 +5216 0 +5217 0 +5218 1 +5219 0 +5220 0 +5221 0 +5222 0 +5223 0 +5224 0 +5225 0 +5226 1 +5227 0 +5228 0 +5229 0 +5230 0 +5231 0 +5232 0 +5233 0 +5234 1 +5235 0 +5236 0 +5237 0 +5238 0 +5239 0 +5240 0 +5241 0 +5242 1 +5243 0 +5244 0 +5245 0 +5246 0 +5247 0 +5248 0 +5249 0 +5250 0 +5251 1 +5252 0 +5253 0 +5254 0 +5255 0 +5256 0 +5257 0 +5258 0 +5259 0 +5260 0 +5261 0 +5262 0 +5263 0 +5264 0 +5265 0 +5266 0 +5267 0 +5268 1 +5269 0 +5270 0 +5271 0 +5272 0 +5273 0 +5274 0 +5275 0 +5276 1 +5277 0 +5278 0 +5279 0 +5280 0 +5281 0 +5282 0 +5283 1 +5284 0 +5285 0 +5286 0 +5287 0 +5288 0 +5289 0 +5290 0 +5291 0 +5292 0 +5293 1 +5294 0 +5295 0 +5296 0 +5297 0 +5298 0 +5299 0 +5300 0 +5301 1 +5302 0 +5303 0 +5304 0 +5305 0 +5306 0 +5307 0 +5308 0 +5309 0 +5310 1 +5311 0 +5312 0 +5313 0 +5314 0 +5315 0 +5316 0 +5317 0 +5318 1 +5319 0 +5320 0 +5321 0 +5322 0 +5323 0 +5324 0 +5325 1 +5326 0 +5327 0 +5328 0 +5329 0 +5330 0 +5331 0 +5332 0 +5333 0 +5334 0 +5335 0 +5336 0 +5337 0 +5338 0 +5339 0 +5340 0 +5341 0 +5342 1 +5343 0 +5344 0 +5345 0 +5346 0 +5347 0 +5348 0 +5349 1 +5350 0 +5351 0 +5352 0 +5353 0 +5354 0 +5355 0 +5356 0 +5357 0 +5358 1 +5359 0 +5360 0 +5361 0 +5362 0 +5363 0 +5364 0 +5365 0 +5366 1 +5367 0 +5368 0 +5369 0 +5370 0 +5371 0 +5372 0 +5373 1 +5374 0 +5375 0 +5376 0 +5377 0 +5378 0 +5379 0 +5380 0 +5381 1 +5382 0 +5383 0 +5384 0 +5385 0 +5386 0 +5387 0 +5388 0 +5389 0 +5390 1 +5391 0 +5392 0 +5393 0 +5394 0 +5395 0 +5396 0 +5397 0 +5398 1 +5399 0 +5400 0 +5401 0 +5402 0 +5403 0 +5404 0 +5405 0 +5406 1 +5407 0 +5408 0 +5409 0 +5410 0 +5411 0 +5412 0 +5413 0 +5414 1 +5415 0 +5416 0 +5417 0 +5418 0 +5419 0 +5420 0 +5421 0 +5422 1 +5423 0 +5424 0 +5425 0 +5426 0 +5427 0 +5428 0 +5429 0 +5430 0 +5431 0 +5432 0 +5433 0 +5434 0 +5435 0 +5436 0 +5437 0 +5438 1 +5439 0 +5440 0 +5441 0 +5442 0 +5443 0 +5444 0 +5445 0 +5446 0 +5447 1 +5448 0 +5449 0 +5450 0 +5451 0 +5452 0 +5453 0 +5454 0 +5455 0 +5456 1 +5457 0 +5458 0 +5459 0 +5460 0 +5461 0 +5462 0 +5463 0 +5464 1 +5465 0 +5466 0 +5467 0 +5468 0 +5469 0 +5470 0 +5471 0 +5472 1 +5473 0 +5474 0 +5475 0 +5476 0 +5477 0 +5478 0 +5479 0 +5480 0 +5481 1 +5482 0 +5483 0 +5484 0 +5485 0 +5486 0 +5487 0 +5488 0 +5489 1 +5490 0 +5491 0 +5492 0 +5493 0 +5494 0 +5495 0 +5496 0 +5497 0 +5498 1 +5499 0 +5500 0 +5501 0 +5502 0 +5503 0 +5504 0 +5505 0 +5506 1 +5507 0 +5508 0 +5509 0 +5510 0 +5511 0 +5512 0 +5513 0 +5514 1 +5515 0 +5516 0 +5517 0 +5518 0 +5519 0 +5520 0 +5521 0 +5522 0 +5523 1 +5524 0 +5525 0 +5526 0 +5527 0 +5528 0 +5529 0 +5530 0 +5531 1 +5532 0 +5533 0 +5534 0 +5535 0 +5536 0 +5537 0 +5538 0 +5539 0 +5540 1 +5541 0 +5542 0 +5543 0 +5544 0 +5545 0 +5546 0 +5547 0 +5548 0 +5549 1 +5550 0 +5551 0 +5552 0 +5553 0 +5554 0 +5555 0 +5556 0 +5557 0 +5558 0 +5559 0 +5560 0 +5561 0 +5562 0 +5563 0 +5564 0 +5565 1 +5566 0 +5567 0 +5568 0 +5569 0 +5570 0 +5571 1 +5572 0 +5573 0 +5574 0 +5575 0 +5576 0 +5577 0 +5578 0 +5579 1 +5580 0 +5581 0 +5582 0 +5583 0 +5584 0 +5585 0 +5586 0 +5587 0 +5588 1 +5589 0 +5590 0 +5591 0 +5592 0 +5593 0 +5594 0 +5595 0 +5596 1 +5597 0 +5598 0 +5599 0 +5600 0 +5601 0 +5602 0 +5603 0 +5604 0 +5605 0 +5606 1 +5607 0 +5608 0 +5609 0 +5610 0 +5611 0 +5612 0 +5613 0 +5614 1 +5615 0 +5616 0 +5617 0 +5618 0 +5619 0 +5620 0 +5621 0 +5622 1 +5623 0 +5624 0 +5625 0 +5626 0 +5627 0 +5628 0 +5629 0 +5630 0 +5631 0 +5632 0 +5633 0 +5634 0 +5635 0 +5636 0 +5637 0 +5638 1 +5639 0 +5640 0 +5641 0 +5642 0 +5643 0 +5644 0 +5645 0 +5646 0 +5647 1 +5648 0 +5649 0 +5650 0 +5651 0 +5652 0 +5653 0 +5654 1 +5655 0 +5656 0 +5657 0 +5658 0 +5659 0 +5660 0 +5661 0 +5662 1 +5663 0 +5664 0 +5665 0 +5666 0 +5667 0 +5668 0 +5669 0 +5670 1 +5671 0 +5672 0 +5673 0 +5674 0 +5675 0 +5676 0 +5677 0 +5678 0 +5679 1 +5680 2 +5681 1 +5682 0 +5683 0 +5684 0 +5685 0 +5686 0 +5687 1 +5688 0 +5689 0 +5690 0 +5691 0 +5692 1 +5693 0 +5694 0 +5695 0 +5696 0 +5697 1 +5698 0 +5699 0 +5700 0 +5701 0 +5702 0 +5703 0 +5704 0 +5705 1 +5706 0 +5707 0 +5708 0 +5709 0 +5710 0 +5711 1 +5712 0 +5713 0 +5714 0 +5715 0 +5716 0 +5717 0 +5718 0 +5719 0 +5720 0 +5721 0 +5722 0 +5723 0 +5724 0 +5725 0 +5726 1 +5727 0 +5728 0 +5729 0 +5730 0 +5731 0 +5732 0 +5733 0 +5734 1 +5735 0 +5736 0 +5737 0 +5738 0 +5739 0 +5740 0 +5741 0 +5742 1 +5743 0 +5744 0 +5745 0 +5746 0 +5747 0 +5748 0 +5749 0 +5750 0 +5751 1 +5752 0 +5753 0 +5754 0 +5755 0 +5756 0 +5757 0 +5758 0 +5759 1 +5760 0 +5761 0 +5762 0 +5763 0 +5764 0 +5765 0 +5766 1 +5767 0 +5768 0 +5769 0 +5770 0 +5771 0 +5772 0 +5773 0 +5774 1 +5775 0 +5776 0 +5777 0 +5778 0 +5779 0 +5780 0 +5781 0 +5782 1 +5783 0 +5784 0 +5785 0 +5786 0 +5787 0 +5788 0 +5789 0 +5790 0 +5791 1 +5792 0 +5793 0 +5794 0 +5795 0 +5796 0 +5797 0 +5798 0 +5799 0 +5800 1 +5801 0 +5802 0 +5803 0 +5804 0 +5805 0 +5806 0 +5807 0 +5808 0 +5809 1 +5810 0 +5811 0 +5812 0 +5813 0 +5814 0 +5815 0 +5816 1 +5817 0 +5818 0 +5819 0 +5820 0 +5821 0 +5822 0 +5823 0 +5824 0 +5825 1 +5826 0 +5827 0 +5828 0 +5829 0 +5830 0 +5831 0 +5832 0 +5833 0 +5834 1 +5835 0 +5836 0 +5837 0 +5838 0 +5839 0 +5840 0 +5841 0 +5842 1 +5843 0 +5844 0 +5845 0 +5846 0 +5847 0 +5848 0 +5849 0 +5850 1 +5851 0 +5852 0 +5853 0 +5854 0 +5855 0 +5856 0 +5857 0 +5858 1 +5859 0 +5860 0 +5861 0 +5862 0 +5863 0 +5864 0 +5865 0 +5866 0 +5867 1 +5868 0 +5869 0 +5870 0 +5871 0 +5872 0 +5873 0 +5874 0 +5875 1 +5876 0 +5877 0 +5878 0 +5879 0 +5880 0 +5881 0 +5882 0 +5883 0 +5884 1 +5885 0 +5886 0 +5887 0 +5888 0 +5889 0 +5890 0 +5891 1 +5892 0 +5893 0 +5894 0 +5895 0 +5896 0 +5897 0 +5898 0 +5899 0 +5900 1 +5901 0 +5902 0 +5903 0 +5904 0 +5905 0 +5906 0 +5907 0 +5908 0 +5909 1 +5910 0 +5911 0 +5912 0 +5913 0 +5914 0 +5915 0 +5916 0 +5917 1 +5918 0 +5919 0 +5920 0 +5921 0 +5922 0 +5923 0 +5924 0 +5925 0 +5926 1 +5927 0 +5928 0 +5929 0 +5930 0 +5931 0 +5932 0 +5933 0 +5934 1 +5935 0 +5936 0 +5937 0 +5938 0 +5939 0 +5940 0 +5941 0 +5942 0 +5943 0 +5944 1 +5945 0 +5946 0 +5947 0 +5948 0 +5949 0 +5950 0 +5951 0 +5952 0 +5953 0 +5954 0 +5955 0 +5956 0 +5957 0 +5958 0 +5959 0 +5960 0 +5961 0 +5962 0 +5963 0 +5964 0 +5965 0 +5966 0 +5967 0 +5968 0 +5969 0 +5970 1 +5971 0 +5972 0 +5973 0 +5974 0 +5975 0 +5976 0 +5977 0 +5978 1 +5979 0 +5980 0 +5981 0 +5982 0 +5983 0 +5984 0 +5985 0 +5986 0 +5987 1 +5988 0 +5989 0 +5990 0 +5991 0 +5992 0 +5993 0 +5994 0 +5995 0 +5996 1 +5997 0 +5998 0 +5999 0 +6000 0 +6001 0 +6002 0 +6003 0 +6004 0 +6005 0 +6006 1 +6007 0 +6008 0 +6009 0 +6010 0 +6011 0 +6012 0 +6013 0 +6014 1 +6015 0 +6016 0 +6017 0 +6018 0 +6019 0 +6020 0 +6021 0 +6022 0 +6023 1 +6024 0 +6025 0 +6026 0 +6027 0 +6028 0 +6029 0 +6030 0 +6031 1 +6032 0 +6033 0 +6034 0 +6035 0 +6036 0 +6037 0 +6038 1 +6039 0 +6040 0 +6041 0 +6042 0 +6043 0 +6044 0 +6045 0 +6046 0 +6047 0 +6048 1 +6049 0 +6050 0 +6051 0 +6052 0 +6053 0 +6054 0 +6055 1 +6056 0 +6057 0 +6058 0 +6059 0 +6060 0 +6061 1 +6062 0 +6063 0 +6064 0 +6065 0 +6066 0 +6067 0 +6068 1 +6069 0 +6070 0 +6071 0 +6072 0 +6073 0 +6074 0 +6075 0 +6076 1 +6077 0 +6078 0 +6079 0 +6080 0 +6081 0 +6082 0 +6083 0 +6084 0 +6085 1 +6086 0 +6087 0 +6088 0 +6089 0 +6090 0 +6091 0 +6092 0 +6093 0 +6094 0 +6095 1 +6096 0 +6097 0 +6098 0 +6099 0 +6100 0 +6101 0 +6102 0 +6103 0 +6104 1 +6105 0 +6106 0 +6107 0 +6108 0 +6109 0 +6110 0 +6111 0 +6112 1 +6113 0 +6114 0 +6115 0 +6116 0 +6117 0 +6118 0 +6119 0 +6120 0 +6121 0 +6122 0 +6123 0 +6124 0 +6125 1 +6126 0 +6127 0 +6128 0 +6129 0 +6130 0 +6131 0 +6132 0 +6133 0 +6134 0 +6135 0 +6136 0 +6137 0 +6138 0 +6139 0 +6140 0 +6141 0 +6142 1 +6143 0 +6144 0 +6145 0 +6146 0 +6147 0 +6148 0 +6149 0 +6150 1 +6151 0 +6152 0 +6153 0 +6154 0 +6155 0 +6156 0 +6157 0 +6158 0 +6159 1 +6160 0 +6161 0 +6162 0 +6163 0 +6164 0 +6165 0 +6166 0 +6167 1 +6168 0 +6169 0 +6170 0 +6171 0 +6172 0 +6173 0 +6174 0 +6175 1 +6176 0 +6177 0 +6178 0 +6179 0 +6180 0 +6181 0 +6182 0 +6183 1 +6184 0 +6185 0 +6186 0 +6187 0 +6188 0 +6189 0 +6190 0 +6191 0 +6192 1 +6193 0 +6194 0 +6195 0 +6196 0 +6197 0 +6198 0 +6199 0 +6200 0 +6201 1 +6202 0 +6203 0 +6204 0 +6205 0 +6206 0 +6207 0 +6208 0 +6209 0 +6210 1 +6211 0 +6212 0 +6213 0 +6214 0 +6215 0 +6216 0 +6217 1 +6218 0 +6219 0 +6220 0 +6221 0 +6222 0 +6223 0 +6224 0 +6225 1 +6226 0 +6227 0 +6228 0 +6229 0 +6230 0 +6231 0 +6232 0 +6233 0 +6234 1 +6235 0 +6236 0 +6237 0 +6238 0 +6239 0 +6240 0 +6241 1 +6242 0 +6243 0 +6244 0 +6245 0 +6246 0 +6247 0 +6248 0 +6249 0 +6250 1 +6251 0 +6252 0 +6253 0 +6254 0 +6255 0 +6256 0 +6257 0 +6258 1 +6259 0 +6260 0 +6261 0 +6262 0 +6263 0 +6264 0 +6265 0 +6266 0 +6267 0 +6268 1 +6269 0 +6270 0 +6271 0 +6272 0 +6273 0 +6274 0 +6275 0 +6276 0 +6277 1 +6278 0 +6279 0 +6280 0 +6281 0 +6282 0 +6283 0 +6284 0 +6285 1 +6286 0 +6287 0 +6288 0 +6289 0 +6290 0 +6291 0 +6292 1 +6293 0 +6294 0 +6295 0 +6296 0 +6297 0 +6298 0 +6299 1 +6300 0 +6301 0 +6302 0 +6303 0 +6304 0 +6305 0 +6306 0 +6307 1 +6308 0 +6309 0 +6310 0 +6311 0 +6312 0 +6313 0 +6314 0 +6315 1 +6316 0 +6317 0 +6318 0 +6319 0 +6320 0 +6321 0 +6322 0 +6323 0 +6324 1 +6325 0 +6326 0 +6327 0 +6328 0 +6329 0 +6330 0 +6331 0 +6332 1 +6333 0 +6334 0 +6335 0 +6336 0 +6337 0 +6338 0 +6339 0 +6340 0 +6341 1 +6342 0 +6343 0 +6344 0 +6345 0 +6346 0 +6347 0 +6348 0 +6349 0 +6350 1 +6351 0 +6352 0 +6353 0 +6354 0 +6355 0 +6356 0 +6357 0 +6358 1 +6359 0 +6360 0 +6361 0 +6362 0 +6363 0 +6364 0 +6365 0 +6366 1 +6367 0 +6368 0 +6369 0 +6370 0 +6371 0 +6372 0 +6373 0 +6374 0 +6375 1 +6376 0 +6377 0 +6378 0 +6379 0 +6380 0 +6381 0 +6382 0 +6383 1 +6384 0 +6385 0 +6386 0 +6387 0 +6388 0 +6389 0 +6390 0 +6391 4 +6392 0 +6393 1 +6394 0 +6395 0 +6396 0 +6397 1 +6398 0 +6399 0 +6400 0 +6401 0 +6402 1 +6403 0 +6404 0 +6405 0 +6406 0 +6407 1 +6408 0 +6409 0 +6410 0 +6411 0 +6412 1 +6413 0 +6414 0 +6415 0 +6416 0 +6417 0 +6418 1 +6419 0 +6420 0 +6421 0 +6422 0 +6423 0 +6424 0 +6425 1 +6426 0 +6427 0 +6428 0 +6429 0 +6430 0 +6431 0 +6432 0 +6433 0 +6434 1 +6435 0 +6436 0 +6437 0 +6438 0 +6439 0 +6440 0 +6441 0 +6442 0 +6443 1 +6444 0 +6445 0 +6446 0 +6447 0 +6448 0 +6449 0 +6450 0 +6451 0 +6452 1 +6453 0 +6454 0 +6455 0 +6456 0 +6457 0 +6458 0 +6459 0 +6460 0 +6461 0 +6462 0 +6463 1 +6464 0 +6465 0 +6466 0 +6467 0 +6468 0 +6469 0 +6470 0 +6471 0 +6472 1 +6473 0 +6474 0 +6475 0 +6476 0 +6477 0 +6478 0 +6479 0 +6480 0 +6481 0 +6482 1 +6483 0 +6484 0 +6485 0 +6486 0 +6487 0 +6488 0 +6489 0 +6490 0 +6491 0 +6492 1 +6493 0 +6494 0 +6495 0 +6496 0 +6497 0 +6498 0 +6499 0 +6500 0 +6501 0 +6502 0 +6503 0 +6504 0 +6505 0 +6506 0 +6507 0 +6508 0 +6509 0 +6510 0 +6511 0 +6512 1 +6513 0 +6514 0 +6515 0 +6516 0 +6517 0 +6518 0 +6519 0 +6520 0 +6521 1 +6522 0 +6523 0 +6524 0 +6525 0 +6526 0 +6527 0 +6528 0 +6529 0 +6530 0 +6531 1 +6532 0 +6533 0 +6534 0 +6535 0 +6536 0 +6537 0 +6538 0 +6539 0 +6540 1 +6541 0 +6542 0 +6543 0 +6544 0 +6545 0 +6546 0 +6547 0 +6548 0 +6549 0 +6550 1 +6551 0 +6552 0 +6553 0 +6554 0 +6555 0 +6556 0 +6557 0 +6558 0 +6559 0 +6560 1 +6561 0 +6562 0 +6563 0 +6564 0 +6565 0 +6566 0 +6567 0 +6568 0 +6569 1 +6570 0 +6571 0 +6572 0 +6573 0 +6574 0 +6575 0 +6576 0 +6577 1 +6578 0 +6579 0 +6580 0 +6581 0 +6582 0 +6583 0 +6584 0 +6585 0 +6586 1 +6587 0 +6588 0 +6589 0 +6590 0 +6591 0 +6592 0 +6593 0 +6594 0 +6595 1 +6596 0 +6597 0 +6598 0 +6599 0 +6600 0 +6601 0 +6602 0 +6603 0 +6604 1 +6605 0 +6606 0 +6607 0 +6608 0 +6609 0 +6610 0 +6611 0 +6612 0 +6613 1 +6614 0 +6615 0 +6616 0 +6617 0 +6618 0 +6619 0 +6620 0 +6621 0 +6622 1 +6623 0 +6624 0 +6625 0 +6626 0 +6627 0 +6628 0 +6629 0 +6630 0 +6631 1 +6632 0 +6633 0 +6634 0 +6635 0 +6636 0 +6637 0 +6638 0 +6639 0 +6640 1 +6641 0 +6642 0 +6643 0 +6644 0 +6645 0 +6646 0 +6647 0 +6648 0 +6649 0 +6650 1 +6651 0 +6652 0 +6653 0 +6654 0 +6655 0 +6656 0 +6657 0 +6658 0 +6659 0 +6660 1 +6661 0 +6662 0 +6663 0 +6664 0 +6665 0 +6666 0 +6667 0 +6668 0 +6669 1 +6670 0 +6671 0 +6672 0 +6673 0 +6674 0 +6675 0 +6676 0 +6677 0 +6678 0 +6679 1 +6680 0 +6681 0 +6682 0 +6683 0 +6684 0 +6685 0 +6686 0 +6687 0 +6688 1 +6689 0 +6690 0 +6691 0 +6692 0 +6693 0 +6694 0 +6695 0 +6696 0 +6697 0 +6698 1 +6699 0 +6700 0 +6701 0 +6702 0 +6703 0 +6704 0 +6705 0 +6706 1 +6707 0 +6708 0 +6709 0 +6710 0 +6711 0 +6712 0 +6713 0 +6714 0 +6715 0 +6716 1 +6717 0 +6718 0 +6719 0 +6720 0 +6721 0 +6722 0 +6723 0 +6724 0 +6725 0 +6726 1 +6727 0 +6728 0 +6729 0 +6730 0 +6731 0 +6732 0 +6733 0 +6734 0 +6735 0 +6736 0 +6737 1 +6738 0 +6739 0 +6740 0 +6741 0 +6742 0 +6743 0 +6744 0 +6745 0 +6746 1 +6747 0 +6748 0 +6749 0 +6750 0 +6751 0 +6752 0 +6753 0 +6754 0 +6755 0 +6756 1 +6757 0 +6758 0 +6759 0 +6760 0 +6761 0 +6762 0 +6763 0 +6764 0 +6765 0 +6766 1 +6767 0 +6768 0 +6769 0 +6770 0 +6771 0 +6772 0 +6773 0 +6774 0 +6775 1 +6776 0 +6777 0 +6778 0 +6779 0 +6780 0 +6781 0 +6782 0 +6783 0 +6784 1 +6785 0 +6786 0 +6787 0 +6788 0 +6789 0 +6790 0 +6791 0 +6792 0 +6793 0 +6794 1 +6795 0 +6796 0 +6797 0 +6798 0 +6799 0 +6800 0 +6801 0 +6802 0 +6803 1 +6804 0 +6805 0 +6806 0 +6807 0 +6808 0 +6809 0 +6810 0 +6811 0 +6812 0 +6813 1 +6814 0 +6815 0 +6816 0 +6817 0 +6818 0 +6819 0 +6820 0 +6821 0 +6822 0 +6823 0 +6824 1 +6825 0 +6826 0 +6827 0 +6828 0 +6829 0 +6830 0 +6831 0 +6832 1 +6833 0 +6834 0 +6835 0 +6836 0 +6837 0 +6838 0 +6839 0 +6840 0 +6841 0 +6842 1 +6843 0 +6844 0 +6845 0 +6846 0 +6847 0 +6848 0 +6849 0 +6850 0 +6851 1 +6852 0 +6853 0 +6854 0 +6855 0 +6856 0 +6857 0 +6858 0 +6859 0 +6860 0 +6861 0 +6862 1 +6863 0 +6864 0 +6865 0 +6866 0 +6867 0 +6868 0 +6869 0 +6870 0 +6871 1 +6872 0 +6873 0 +6874 0 +6875 0 +6876 0 +6877 0 +6878 0 +6879 1 +6880 0 +6881 0 +6882 0 +6883 0 +6884 0 +6885 0 +6886 1 +6887 0 +6888 0 +6889 0 +6890 0 +6891 0 +6892 0 +6893 0 +6894 0 +6895 1 +6896 0 +6897 0 +6898 0 +6899 0 +6900 0 +6901 0 +6902 0 +6903 0 +6904 0 +6905 0 +6906 0 +6907 0 +6908 0 +6909 0 +6910 0 +6911 0 +6912 0 +6913 0 +6914 1 +6915 0 +6916 0 +6917 0 +6918 0 +6919 0 +6920 0 +6921 0 +6922 0 +6923 1 +6924 0 +6925 0 +6926 0 +6927 0 +6928 0 +6929 0 +6930 0 +6931 0 +6932 0 +6933 0 +6934 1 +6935 0 +6936 0 +6937 0 +6938 0 +6939 0 +6940 0 +6941 0 +6942 0 +6943 0 +6944 1 +6945 0 +6946 0 +6947 0 +6948 0 +6949 0 +6950 0 +6951 0 +6952 0 +6953 0 +6954 1 +6955 0 +6956 0 +6957 0 +6958 0 +6959 0 +6960 0 +6961 0 +6962 0 +6963 0 +6964 1 +6965 0 +6966 0 +6967 0 +6968 0 +6969 0 +6970 0 +6971 0 +6972 0 +6973 0 +6974 1 +6975 0 +6976 0 +6977 0 +6978 0 +6979 0 +6980 0 +6981 0 +6982 0 +6983 1 +6984 0 +6985 0 +6986 0 +6987 0 +6988 0 +6989 0 +6990 0 +6991 0 +6992 1 +6993 0 +6994 0 +6995 0 +6996 0 +6997 0 +6998 0 +6999 0 +7000 0 +7001 1 +7002 0 +7003 0 +7004 0 +7005 0 +7006 0 +7007 0 +7008 0 +7009 0 +7010 1 +7011 0 +7012 0 +7013 0 +7014 0 +7015 0 +7016 0 +7017 0 +7018 0 +7019 0 +7020 1 +7021 0 +7022 0 +7023 0 +7024 0 +7025 0 +7026 0 +7027 0 +7028 0 +7029 0 +7030 1 +7031 0 +7032 0 +7033 0 +7034 0 +7035 0 +7036 0 +7037 0 +7038 0 +7039 1 +7040 0 +7041 0 +7042 0 +7043 0 +7044 0 +7045 0 +7046 0 +7047 0 +7048 1 +7049 0 +7050 0 +7051 0 +7052 0 +7053 0 +7054 0 +7055 0 +7056 0 +7057 0 +7058 0 +7059 1 +7060 0 +7061 0 +7062 0 +7063 0 +7064 0 +7065 0 +7066 0 +7067 0 +7068 0 +7069 1 +7070 0 +7071 0 +7072 0 +7073 0 +7074 0 +7075 0 +7076 0 +7077 0 +7078 0 +7079 1 +7080 0 +7081 0 +7082 0 +7083 0 +7084 0 +7085 0 +7086 0 +7087 1 +7088 0 +7089 0 +7090 0 +7091 0 +7092 0 +7093 0 +7094 0 +7095 0 +7096 0 +7097 1 +7098 0 +7099 0 +7100 0 +7101 0 +7102 0 +7103 0 +7104 0 +7105 1 +7106 0 +7107 0 +7108 0 +7109 0 +7110 0 +7111 0 +7112 0 +7113 0 +7114 1 +7115 0 +7116 0 +7117 0 +7118 0 +7119 0 +7120 0 +7121 0 +7122 0 +7123 0 +7124 1 +7125 0 +7126 0 +7127 0 +7128 0 +7129 0 +7130 0 +7131 0 +7132 0 +7133 0 +7134 1 +7135 0 +7136 0 +7137 0 +7138 0 +7139 0 +7140 0 +7141 0 +7142 0 +7143 1 +7144 0 +7145 0 +7146 0 +7147 0 +7148 0 +7149 0 +7150 0 +7151 0 +7152 1 +7153 0 +7154 0 +7155 0 +7156 0 +7157 0 +7158 0 +7159 0 +7160 0 +7161 0 +7162 1 +7163 0 +7164 0 +7165 0 +7166 0 +7167 0 +7168 0 +7169 0 +7170 0 +7171 0 +7172 1 +7173 0 +7174 0 +7175 0 +7176 0 +7177 0 +7178 0 +7179 0 +7180 0 +7181 0 +7182 1 +7183 0 +7184 0 +7185 0 +7186 0 +7187 0 +7188 0 +7189 0 +7190 0 +7191 0 +7192 0 +7193 1 +7194 0 +7195 0 +7196 0 +7197 0 +7198 0 +7199 0 +7200 0 +7201 0 +7202 0 +7203 1 +7204 0 +7205 0 +7206 0 +7207 0 +7208 0 +7209 0 +7210 0 +7211 0 +7212 0 +7213 0 +7214 0 +7215 0 +7216 0 +7217 0 +7218 0 +7219 0 +7220 0 +7221 0 +7222 1 +7223 0 +7224 0 +7225 0 +7226 0 +7227 0 +7228 0 +7229 0 +7230 0 +7231 0 +7232 1 +7233 0 +7234 0 +7235 0 +7236 0 +7237 0 +7238 0 +7239 0 +7240 0 +7241 0 +7242 0 +7243 1 +7244 0 +7245 0 +7246 0 +7247 0 +7248 0 +7249 0 +7250 0 +7251 0 +7252 0 +7253 1 +7254 0 +7255 0 +7256 0 +7257 0 +7258 0 +7259 0 +7260 0 +7261 0 +7262 0 +7263 0 +7264 1 +7265 0 +7266 0 +7267 0 +7268 0 +7269 0 +7270 0 +7271 0 +7272 0 +7273 0 +7274 1 +7275 0 +7276 0 +7277 0 +7278 0 +7279 0 +7280 0 +7281 0 +7282 0 +7283 0 +7284 0 +7285 1 +7286 0 +7287 0 +7288 0 +7289 0 +7290 0 +7291 0 +7292 0 +7293 0 +7294 0 +7295 0 +7296 0 +7297 0 +7298 0 +7299 0 +7300 0 +7301 0 +7302 0 +7303 0 +7304 1 +7305 0 +7306 0 +7307 0 +7308 0 +7309 0 +7310 0 +7311 0 +7312 0 +7313 0 +7314 0 +7315 1 +7316 0 +7317 0 +7318 0 +7319 0 +7320 0 +7321 0 +7322 0 +7323 0 +7324 1 +7325 0 +7326 0 +7327 0 +7328 0 +7329 0 +7330 0 +7331 0 +7332 0 +7333 1 +7334 0 +7335 0 +7336 0 +7337 0 +7338 0 +7339 0 +7340 0 +7341 0 +7342 1 +7343 0 +7344 0 +7345 0 +7346 0 +7347 0 +7348 0 +7349 0 +7350 0 +7351 0 +7352 1 +7353 0 +7354 0 +7355 0 +7356 0 +7357 0 +7358 0 +7359 0 +7360 0 +7361 0 +7362 0 +7363 1 +7364 0 +7365 0 +7366 0 +7367 0 +7368 0 +7369 0 +7370 0 +7371 0 +7372 1 +7373 0 +7374 0 +7375 0 +7376 0 +7377 0 +7378 0 +7379 0 +7380 0 +7381 0 +7382 1 +7383 0 +7384 0 +7385 0 +7386 0 +7387 0 +7388 0 +7389 0 +7390 0 +7391 1 +7392 0 +7393 0 +7394 0 +7395 0 +7396 0 +7397 0 +7398 0 +7399 0 +7400 0 +7401 1 +7402 0 +7403 0 +7404 0 +7405 0 +7406 0 +7407 0 +7408 0 +7409 0 +7410 0 +7411 0 +7412 1 +7413 0 +7414 0 +7415 0 +7416 0 +7417 0 +7418 0 +7419 0 +7420 0 +7421 0 +7422 1 +7423 0 +7424 0 +7425 0 +7426 0 +7427 0 +7428 0 +7429 0 +7430 0 +7431 0 +7432 1 +7433 0 +7434 0 +7435 0 +7436 0 +7437 0 +7438 0 +7439 0 +7440 0 +7441 1 +7442 0 +7443 0 +7444 0 +7445 0 +7446 0 +7447 0 +7448 0 +7449 1 +7450 0 +7451 0 +7452 0 +7453 0 +7454 0 +7455 0 +7456 0 +7457 0 +7458 0 +7459 0 +7460 1 +7461 0 +7462 0 +7463 0 +7464 0 +7465 0 +7466 0 +7467 0 +7468 0 +7469 1 +7470 0 +7471 0 +7472 0 +7473 0 +7474 0 +7475 0 +7476 0 +7477 0 +7478 1 +7479 0 +7480 0 +7481 0 +7482 0 +7483 0 +7484 0 +7485 0 +7486 0 +7487 1 +7488 0 +7489 0 +7490 0 +7491 0 +7492 0 +7493 0 +7494 0 +7495 0 +7496 0 +7497 1 +7498 0 +7499 0 +7500 0 +7501 0 +7502 0 +7503 0 +7504 0 +7505 0 +7506 0 +7507 0 +7508 1 +7509 0 +7510 0 +7511 0 +7512 0 +7513 0 +7514 0 +7515 0 +7516 0 +7517 0 +7518 1 +7519 0 +7520 0 +7521 0 +7522 0 +7523 0 +7524 0 +7525 0 +7526 0 +7527 0 +7528 0 +7529 0 +7530 0 +7531 0 +7532 0 +7533 0 +7534 0 +7535 0 +7536 0 +7537 0 +7538 0 +7539 1 +7540 0 +7541 0 +7542 0 +7543 0 +7544 0 +7545 0 +7546 0 +7547 0 +7548 0 +7549 2 +7550 0 +7551 0 +7552 0 +7553 0 +7554 0 +7555 0 +7556 0 +7557 1 +7558 0 +7559 0 +7560 0 +7561 0 +7562 0 +7563 0 +7564 0 +7565 0 +7566 0 +7567 0 +7568 1 +7569 0 +7570 0 +7571 0 +7572 0 +7573 0 +7574 0 +7575 0 +7576 0 +7577 0 +7578 0 +7579 0 +7580 0 +7581 0 +7582 0 +7583 0 +7584 0 +7585 0 +7586 0 +7587 0 +7588 1 +7589 0 +7590 0 +7591 0 +7592 0 +7593 0 +7594 0 +7595 0 +7596 0 +7597 0 +7598 0 +7599 1 +7600 0 +7601 0 +7602 0 +7603 0 +7604 0 +7605 0 +7606 0 +7607 0 +7608 0 +7609 0 +7610 1 +7611 0 +7612 0 +7613 0 +7614 0 +7615 0 +7616 0 +7617 0 +7618 0 +7619 0 +7620 0 +7621 1 +7622 0 +7623 0 +7624 0 +7625 0 +7626 0 +7627 1 +7628 0 +7629 0 +7630 0 +7631 0 +7632 0 +7633 0 +7634 1 +7635 0 +7636 0 +7637 0 +7638 0 +7639 0 +7640 0 +7641 1 +7642 0 +7643 0 +7644 0 +7645 0 +7646 0 +7647 0 +7648 0 +7649 1 +7650 0 +7651 0 +7652 0 +7653 0 +7654 0 +7655 0 +7656 0 +7657 0 +7658 0 +7659 0 +7660 1 +7661 0 +7662 0 +7663 0 +7664 0 +7665 0 +7666 0 +7667 0 +7668 0 +7669 0 +7670 1 +7671 0 +7672 0 +7673 0 +7674 0 +7675 0 +7676 0 +7677 0 +7678 0 +7679 0 +7680 0 +7681 1 +7682 0 +7683 0 +7684 0 +7685 0 +7686 0 +7687 0 +7688 0 +7689 0 +7690 0 +7691 1 +7692 0 +7693 0 +7694 0 +7695 0 +7696 0 +7697 0 +7698 0 +7699 0 +7700 0 +7701 0 +7702 1 +7703 0 +7704 0 +7705 0 +7706 0 +7707 0 +7708 0 +7709 0 +7710 0 +7711 0 +7712 1 +7713 0 +7714 0 +7715 0 +7716 0 +7717 0 +7718 0 +7719 0 +7720 0 +7721 0 +7722 1 +7723 0 +7724 0 +7725 0 +7726 0 +7727 0 +7728 0 +7729 0 +7730 0 +7731 0 +7732 1 +7733 0 +7734 0 +7735 0 +7736 0 +7737 0 +7738 0 +7739 0 +7740 0 +7741 0 +7742 1 +7743 0 +7744 0 +7745 0 +7746 0 +7747 0 +7748 0 +7749 0 +7750 0 +7751 0 +7752 1 +7753 0 +7754 0 +7755 0 +7756 0 +7757 0 +7758 0 +7759 0 +7760 0 +7761 1 +7762 0 +7763 0 +7764 0 +7765 0 +7766 0 +7767 0 +7768 0 +7769 0 +7770 1 +7771 0 +7772 0 +7773 0 +7774 0 +7775 0 +7776 0 +7777 0 +7778 0 +7779 1 +7780 0 +7781 0 +7782 0 +7783 0 +7784 0 +7785 0 +7786 0 +7787 0 +7788 0 +7789 1 +7790 0 +7791 0 +7792 0 +7793 0 +7794 0 +7795 0 +7796 0 +7797 0 +7798 0 +7799 1 +7800 0 +7801 0 +7802 0 +7803 0 +7804 0 +7805 0 +7806 0 +7807 0 +7808 0 +7809 0 +7810 1 +7811 0 +7812 0 +7813 0 +7814 0 +7815 0 +7816 0 +7817 0 +7818 0 +7819 1 +7820 0 +7821 0 +7822 0 +7823 0 +7824 0 +7825 0 +7826 0 +7827 0 +7828 1 +7829 0 +7830 0 +7831 0 +7832 0 +7833 0 +7834 0 +7835 0 +7836 0 +7837 0 +7838 0 +7839 1 +7840 0 +7841 0 +7842 0 +7843 0 +7844 0 +7845 0 +7846 0 +7847 0 +7848 0 +7849 1 +7850 0 +7851 0 +7852 0 +7853 0 +7854 0 +7855 0 +7856 0 +7857 0 +7858 1 +7859 0 +7860 0 +7861 0 +7862 0 +7863 0 +7864 0 +7865 0 +7866 0 +7867 0 +7868 1 +7869 0 +7870 0 +7871 0 +7872 0 +7873 0 +7874 0 +7875 0 +7876 0 +7877 0 +7878 0 +7879 0 +7880 0 +7881 0 +7882 0 +7883 0 +7884 0 +7885 0 +7886 0 +7887 1 +7888 0 +7889 0 +7890 0 +7891 0 +7892 0 +7893 0 +7894 0 +7895 0 +7896 0 +7897 0 +7898 1 +7899 0 +7900 0 +7901 0 +7902 0 +7903 0 +7904 0 +7905 0 +7906 0 +7907 0 +7908 1 +7909 0 +7910 0 +7911 0 +7912 0 +7913 0 +7914 0 +7915 0 +7916 0 +7917 0 +7918 1 +7919 0 +7920 0 +7921 0 +7922 0 +7923 0 +7924 0 +7925 0 +7926 0 +7927 0 +7928 1 +7929 0 +7930 0 +7931 0 +7932 0 +7933 0 +7934 0 +7935 0 +7936 0 +7937 0 +7938 1 +7939 0 +7940 0 +7941 0 +7942 0 +7943 0 +7944 0 +7945 0 +7946 0 +7947 0 +7948 1 +7949 0 +7950 0 +7951 0 +7952 0 +7953 0 +7954 0 +7955 0 +7956 0 +7957 0 +7958 1 +7959 0 +7960 0 +7961 0 +7962 0 +7963 0 +7964 0 +7965 0 +7966 0 +7967 0 +7968 1 +7969 0 +7970 0 +7971 0 +7972 0 +7973 0 +7974 0 +7975 0 +7976 0 +7977 0 +7978 1 +7979 0 +7980 0 +7981 0 +7982 0 +7983 0 +7984 0 +7985 1 +7986 0 +7987 0 +7988 0 +7989 0 +7990 0 +7991 0 +7992 0 +7993 0 +7994 0 +7995 1 +7996 0 +7997 0 +7998 0 +7999 0 +8000 0 +8001 0 +8002 0 +8003 0 +8004 0 +8005 0 +8006 1 +8007 0 +8008 0 +8009 0 +8010 0 +8011 0 +8012 0 +8013 0 +8014 0 +8015 1 +8016 0 +8017 0 +8018 0 +8019 0 +8020 0 +8021 0 +8022 0 +8023 0 +8024 0 +8025 1 +8026 0 +8027 0 +8028 0 +8029 0 +8030 0 +8031 0 +8032 0 +8033 0 +8034 0 +8035 0 +8036 1 +8037 0 +8038 0 +8039 0 +8040 0 +8041 0 +8042 0 +8043 0 +8044 0 +8045 0 +8046 1 +8047 0 +8048 0 +8049 0 +8050 0 +8051 0 +8052 0 +8053 0 +8054 0 +8055 0 +8056 0 +8057 1 +8058 0 +8059 0 +8060 0 +8061 0 +8062 0 +8063 0 +8064 0 +8065 0 +8066 0 +8067 1 +8068 0 +8069 0 +8070 0 +8071 0 +8072 0 +8073 0 +8074 0 +8075 0 +8076 0 +8077 0 +8078 1 +8079 0 +8080 0 +8081 0 +8082 0 +8083 0 +8084 0 +8085 0 +8086 0 +8087 0 +8088 1 +8089 0 +8090 0 +8091 0 +8092 0 +8093 0 +8094 0 +8095 0 +8096 0 +8097 0 +8098 1 +8099 0 +8100 0 +8101 0 +8102 0 +8103 0 +8104 0 +8105 1 +8106 0 +8107 0 +8108 0 +8109 0 +8110 0 +8111 0 +8112 0 +8113 0 +8114 0 +8115 1 +8116 0 +8117 0 +8118 0 +8119 0 +8120 0 +8121 0 +8122 0 +8123 0 +8124 0 +8125 1 +8126 0 +8127 0 +8128 0 +8129 0 +8130 0 +8131 0 +8132 0 +8133 0 +8134 1 +8135 0 +8136 0 +8137 0 +8138 0 +8139 0 +8140 0 +8141 0 +8142 0 +8143 0 +8144 0 +8145 1 +8146 0 +8147 0 +8148 0 +8149 0 +8150 0 +8151 0 +8152 0 +8153 0 +8154 0 +8155 0 +8156 1 +8157 0 +8158 0 +8159 0 +8160 0 +8161 0 +8162 0 +8163 0 +8164 0 +8165 0 +8166 1 +8167 0 +8168 0 +8169 0 +8170 0 +8171 0 +8172 0 +8173 0 +8174 0 +8175 0 +8176 1 +8177 0 +8178 0 +8179 0 +8180 0 +8181 0 +8182 0 +8183 0 +8184 0 +8185 0 +8186 1 +8187 0 +8188 0 +8189 0 +8190 0 +8191 0 +8192 0 +8193 0 +8194 0 +8195 0 +8196 0 +8197 1 +8198 0 +8199 0 +8200 0 +8201 0 +8202 0 +8203 0 +8204 0 +8205 0 +8206 0 +8207 1 +8208 0 +8209 0 +8210 0 +8211 0 +8212 0 +8213 0 +8214 0 +8215 0 +8216 1 +8217 0 +8218 0 +8219 0 +8220 0 +8221 0 +8222 0 +8223 0 +8224 0 +8225 1 +8226 0 +8227 0 +8228 0 +8229 0 +8230 0 +8231 0 +8232 0 +8233 0 +8234 0 +8235 1 +8236 0 +8237 0 +8238 0 +8239 0 +8240 0 +8241 0 +8242 0 +8243 0 +8244 1 +8245 0 +8246 0 +8247 0 +8248 0 +8249 0 +8250 0 +8251 0 +8252 0 +8253 0 +8254 1 +8255 0 +8256 0 +8257 0 +8258 0 +8259 0 +8260 0 +8261 0 +8262 0 +8263 0 +8264 0 +8265 1 +8266 0 +8267 0 +8268 0 +8269 0 +8270 0 +8271 0 +8272 0 +8273 0 +8274 0 +8275 1 +8276 0 +8277 0 +8278 0 +8279 0 +8280 0 +8281 0 +8282 0 +8283 0 +8284 0 +8285 0 +8286 1 +8287 0 +8288 0 +8289 0 +8290 0 +8291 0 +8292 0 +8293 0 +8294 0 +8295 0 +8296 1 +8297 0 +8298 0 +8299 0 +8300 0 +8301 0 +8302 0 +8303 0 +8304 1 +8305 0 +8306 0 +8307 0 +8308 0 +8309 0 +8310 0 +8311 0 +8312 0 +8313 0 +8314 1 +8315 0 +8316 0 +8317 0 +8318 0 +8319 0 +8320 0 +8321 0 +8322 0 +8323 0 +8324 1 +8325 0 +8326 0 +8327 0 +8328 0 +8329 0 +8330 0 +8331 0 +8332 0 +8333 0 +8334 0 +8335 0 +8336 0 +8337 0 +8338 0 +8339 0 +8340 0 +8341 0 +8342 1 +8343 0 +8344 0 +8345 0 +8346 0 +8347 0 +8348 0 +8349 0 +8350 0 +8351 1 +8352 0 +8353 0 +8354 0 +8355 0 +8356 0 +8357 0 +8358 0 +8359 0 +8360 0 +8361 1 +8362 0 +8363 0 +8364 0 +8365 0 +8366 0 +8367 0 +8368 0 +8369 0 +8370 0 +8371 1 +8372 0 +8373 0 +8374 0 +8375 0 +8376 0 +8377 0 +8378 0 +8379 0 +8380 1 +8381 0 +8382 0 +8383 0 +8384 0 +8385 0 +8386 0 +8387 0 +8388 0 +8389 1 +8390 0 +8391 0 +8392 0 +8393 0 +8394 0 +8395 0 +8396 0 +8397 0 +8398 0 +8399 1 +8400 0 +8401 0 +8402 0 +8403 0 +8404 0 +8405 0 +8406 0 +8407 0 +8408 0 +8409 1 +8410 0 +8411 0 +8412 0 +8413 0 +8414 0 +8415 0 +8416 0 +8417 0 +8418 0 +8419 1 +8420 0 +8421 0 +8422 0 +8423 0 +8424 0 +8425 0 +8426 0 +8427 0 +8428 0 +8429 0 +8430 1 +8431 0 +8432 0 +8433 0 +8434 0 +8435 0 +8436 0 +8437 0 +8438 1 +8439 0 +8440 0 +8441 0 +8442 0 +8443 0 +8444 0 +8445 0 +8446 0 +8447 1 +8448 0 +8449 0 +8450 0 +8451 0 +8452 0 +8453 0 +8454 0 +8455 0 +8456 0 +8457 1 +8458 0 +8459 0 +8460 0 +8461 0 +8462 0 +8463 0 +8464 0 +8465 0 +8466 0 +8467 1 +8468 0 +8469 0 +8470 0 +8471 0 +8472 0 +8473 0 +8474 0 +8475 0 +8476 0 +8477 1 +8478 0 +8479 0 +8480 0 +8481 0 +8482 0 +8483 0 +8484 0 +8485 0 +8486 1 +8487 0 +8488 0 +8489 0 +8490 0 +8491 0 +8492 0 +8493 0 +8494 0 +8495 0 +8496 0 +8497 0 +8498 0 +8499 0 +8500 0 +8501 0 +8502 0 +8503 0 +8504 0 +8505 0 +8506 1 +8507 0 +8508 0 +8509 0 +8510 0 +8511 0 +8512 0 +8513 0 +8514 0 +8515 0 +8516 0 +8517 0 +8518 0 +8519 0 +8520 0 +8521 0 +8522 0 +8523 1 +8524 0 +8525 0 +8526 0 +8527 0 +8528 0 +8529 0 +8530 0 +8531 0 +8532 1 +8533 0 +8534 0 +8535 0 +8536 0 +8537 0 +8538 0 +8539 0 +8540 0 +8541 1 +8542 0 +8543 0 +8544 0 +8545 0 +8546 0 +8547 0 +8548 0 +8549 1 +8550 0 +8551 0 +8552 0 +8553 0 +8554 0 +8555 0 +8556 0 +8557 0 +8558 0 +8559 1 +8560 0 +8561 0 +8562 0 +8563 0 +8564 0 +8565 0 +8566 0 +8567 0 +8568 1 +8569 0 +8570 0 +8571 0 +8572 0 +8573 0 +8574 0 +8575 0 +8576 0 +8577 1 +8578 0 +8579 0 +8580 0 +8581 0 +8582 0 +8583 0 +8584 0 +8585 0 +8586 1 +8587 0 +8588 0 +8589 0 +8590 0 +8591 0 +8592 0 +8593 0 +8594 0 +8595 0 +8596 1 +8597 0 +8598 0 +8599 0 +8600 0 +8601 0 +8602 0 +8603 0 +8604 0 +8605 0 +8606 1 +8607 0 +8608 0 +8609 0 +8610 0 +8611 0 +8612 0 +8613 0 +8614 0 +8615 0 +8616 1 +8617 0 +8618 0 +8619 0 +8620 0 +8621 0 +8622 0 +8623 0 +8624 0 +8625 1 +8626 0 +8627 0 +8628 0 +8629 0 +8630 0 +8631 0 +8632 0 +8633 1 +8634 0 +8635 0 +8636 0 +8637 0 +8638 0 +8639 0 +8640 0 +8641 0 +8642 0 +8643 1 +8644 0 +8645 0 +8646 0 +8647 0 +8648 0 +8649 0 +8650 0 +8651 1 +8652 0 +8653 0 +8654 0 +8655 0 +8656 0 +8657 0 +8658 0 +8659 0 +8660 1 +8661 0 +8662 0 +8663 0 +8664 0 +8665 0 +8666 0 +8667 0 +8668 0 +8669 1 +8670 0 +8671 0 +8672 0 +8673 0 +8674 0 +8675 0 +8676 0 +8677 1 +8678 0 +8679 0 +8680 0 +8681 0 +8682 0 +8683 0 +8684 0 +8685 0 +8686 1 +8687 0 +8688 0 +8689 0 +8690 0 +8691 0 +8692 0 +8693 0 +8694 0 +8695 0 +8696 1 +8697 0 +8698 0 +8699 0 +8700 0 +8701 0 +8702 0 +8703 0 +8704 0 +8705 1 +8706 0 +8707 0 +8708 0 +8709 0 +8710 0 +8711 0 +8712 0 +8713 0 +8714 0 +8715 1 +8716 0 +8717 0 +8718 0 +8719 0 +8720 0 +8721 0 +8722 0 +8723 0 +8724 0 +8725 1 +8726 0 +8727 0 +8728 0 +8729 0 +8730 0 +8731 0 +8732 0 +8733 0 +8734 0 +8735 1 +8736 0 +8737 0 +8738 0 +8739 0 +8740 0 +8741 0 +8742 0 +8743 0 +8744 0 +8745 1 +8746 0 +8747 0 +8748 0 +8749 0 +8750 0 +8751 0 +8752 0 +8753 0 +8754 0 +8755 1 +8756 0 +8757 0 +8758 0 +8759 0 +8760 0 +8761 0 +8762 0 +8763 1 +8764 0 +8765 0 +8766 0 +8767 0 +8768 0 +8769 0 +8770 1 +8771 0 +8772 0 +8773 0 +8774 0 +8775 0 +8776 0 +8777 0 +8778 0 +8779 0 +8780 1 +8781 0 +8782 0 +8783 0 +8784 0 +8785 0 +8786 0 +8787 0 +8788 0 +8789 1 +8790 0 +8791 0 +8792 0 +8793 0 +8794 0 +8795 0 +8796 0 +8797 0 +8798 1 +8799 0 +8800 0 +8801 0 +8802 0 +8803 0 +8804 0 +8805 0 +8806 0 +8807 3 +8808 0 +8809 0 +8810 1 +8811 0 +8812 0 +8813 0 +8814 0 +8815 1 +8816 0 +8817 0 +8818 0 +8819 0 +8820 1 +8821 0 +8822 0 +8823 0 +8824 1 +8825 0 +8826 0 +8827 0 +8828 0 +8829 0 +8830 1 +8831 0 +8832 0 +8833 0 +8834 0 +8835 0 +8836 0 +8837 1 +8838 0 +8839 0 +8840 0 +8841 0 +8842 0 +8843 0 +8844 0 +8845 1 +8846 0 +8847 0 +8848 0 +8849 0 +8850 0 +8851 0 +8852 0 +8853 0 +8854 0 +8855 1 +8856 0 +8857 0 +8858 0 +8859 0 +8860 0 +8861 0 +8862 0 +8863 0 +8864 0 +8865 1 +8866 0 +8867 0 +8868 0 +8869 0 +8870 0 +8871 0 +8872 1 +8873 0 +8874 0 +8875 0 +8876 0 +8877 0 +8878 0 +8879 0 +8880 1 +8881 0 +8882 0 +8883 0 +8884 0 +8885 0 +8886 0 +8887 0 +8888 1 +8889 0 +8890 0 +8891 0 +8892 0 +8893 0 +8894 0 +8895 0 +8896 0 +8897 0 +8898 0 +8899 0 +8900 0 +8901 0 +8902 0 +8903 0 +8904 0 +8905 1 +8906 0 +8907 0 +8908 0 +8909 0 +8910 0 +8911 0 +8912 1 +8913 0 +8914 0 +8915 0 +8916 0 +8917 0 +8918 0 +8919 0 +8920 1 +8921 0 +8922 0 +8923 0 +8924 0 +8925 0 +8926 0 +8927 0 +8928 0 +8929 1 +8930 0 +8931 0 +8932 0 +8933 0 +8934 0 +8935 0 +8936 0 +8937 0 +8938 0 +8939 1 +8940 0 +8941 0 +8942 0 +8943 0 +8944 0 +8945 0 +8946 0 +8947 0 +8948 0 +8949 1 +8950 0 +8951 0 +8952 0 +8953 0 +8954 0 +8955 0 +8956 0 +8957 0 +8958 0 +8959 1 +8960 0 +8961 0 +8962 0 +8963 0 +8964 0 +8965 0 +8966 0 +8967 0 +8968 0 +8969 1 +8970 0 +8971 0 +8972 0 +8973 0 +8974 0 +8975 0 +8976 0 +8977 0 +8978 1 +8979 0 +8980 0 +8981 0 +8982 0 +8983 0 +8984 0 +8985 0 +8986 0 +8987 1 +8988 0 +8989 0 +8990 0 +8991 0 +8992 0 +8993 0 +8994 0 +8995 0 +8996 0 +8997 1 +8998 0 +8999 0 +9000 0 +9001 0 +9002 0 +9003 0 +9004 0 +9005 0 +9006 1 +9007 0 +9008 0 +9009 0 +9010 0 +9011 0 +9012 0 +9013 0 +9014 1 +9015 0 +9016 0 +9017 0 +9018 0 +9019 0 +9020 0 +9021 0 +9022 1 +9023 0 +9024 0 +9025 0 +9026 0 +9027 0 +9028 0 +9029 0 +9030 1 +9031 0 +9032 0 +9033 0 +9034 0 +9035 0 +9036 0 +9037 0 +9038 1 +9039 0 +9040 0 +9041 0 +9042 0 +9043 0 +9044 0 +9045 0 +9046 0 +9047 1 +9048 0 +9049 0 +9050 0 +9051 0 +9052 0 +9053 0 +9054 0 +9055 1 +9056 0 +9057 0 +9058 0 +9059 0 +9060 0 +9061 0 +9062 0 +9063 1 +9064 0 +9065 0 +9066 0 +9067 0 +9068 0 +9069 0 +9070 0 +9071 0 +9072 0 +9073 1 +9074 0 +9075 0 +9076 0 +9077 0 +9078 0 +9079 0 +9080 0 +9081 0 +9082 0 +9083 0 +9084 0 +9085 0 +9086 0 +9087 0 +9088 0 +9089 0 +9090 0 +9091 0 +9092 1 +9093 0 +9094 0 +9095 0 +9096 0 +9097 0 +9098 0 +9099 0 +9100 1 +9101 0 +9102 0 +9103 0 +9104 0 +9105 0 +9106 0 +9107 0 +9108 1 +9109 0 +9110 0 +9111 0 +9112 0 +9113 0 +9114 0 +9115 0 +9116 0 +9117 1 +9118 0 +9119 0 +9120 0 +9121 0 +9122 0 +9123 0 +9124 0 +9125 0 +9126 1 +9127 0 +9128 0 +9129 0 +9130 0 +9131 0 +9132 0 +9133 0 +9134 0 +9135 1 +9136 0 +9137 0 +9138 0 +9139 0 +9140 0 +9141 0 +9142 0 +9143 1 +9144 0 +9145 0 +9146 0 +9147 0 +9148 0 +9149 0 +9150 0 +9151 0 +9152 1 +9153 0 +9154 0 +9155 0 +9156 0 +9157 0 +9158 0 +9159 0 +9160 0 +9161 1 +9162 0 +9163 0 +9164 0 +9165 0 +9166 0 +9167 0 +9168 0 +9169 1 +9170 0 +9171 0 +9172 0 +9173 0 +9174 0 +9175 0 +9176 0 +9177 0 +9178 1 +9179 0 +9180 0 +9181 0 +9182 0 +9183 0 +9184 0 +9185 0 +9186 0 +9187 0 +9188 1 +9189 0 +9190 0 +9191 0 +9192 0 +9193 0 +9194 0 +9195 0 +9196 0 +9197 1 +9198 0 +9199 0 +9200 0 +9201 0 +9202 0 +9203 0 +9204 0 +9205 0 +9206 0 +9207 0 +9208 0 +9209 0 +9210 0 +9211 0 +9212 0 +9213 0 +9214 0 +9215 0 +9216 0 +9217 0 +9218 0 +9219 0 +9220 0 +9221 1 +9222 0 +9223 0 +9224 0 +9225 0 +9226 0 +9227 0 +9228 1 +9229 0 +9230 0 +9231 0 +9232 0 +9233 0 +9234 0 +9235 0 +9236 0 +9237 1 +9238 0 +9239 0 +9240 0 +9241 0 +9242 0 +9243 0 +9244 0 +9245 0 +9246 1 +9247 0 +9248 0 +9249 0 +9250 0 +9251 0 +9252 0 +9253 0 +9254 0 +9255 1 +9256 0 +9257 0 +9258 0 +9259 0 +9260 0 +9261 1 +9262 0 +9263 0 +9264 0 +9265 0 +9266 0 +9267 0 +9268 0 +9269 0 +9270 0 +9271 0 +9272 0 +9273 0 +9274 0 +9275 0 +9276 1 +9277 0 +9278 0 +9279 0 +9280 0 +9281 0 +9282 0 +9283 0 +9284 0 +9285 0 +9286 0 +9287 0 +9288 0 +9289 0 +9290 1 +9291 0 +9292 0 +9293 0 +9294 0 +9295 0 +9296 0 +9297 0 +9298 0 +9299 0 +9300 1 +9301 0 +9302 0 +9303 0 +9304 0 +9305 0 +9306 0 +9307 0 +9308 1 +9309 0 +9310 0 +9311 0 +9312 0 +9313 0 +9314 0 +9315 0 +9316 1 +9317 0 +9318 0 +9319 0 +9320 0 +9321 0 +9322 0 +9323 1 +9324 0 +9325 0 +9326 0 +9327 0 +9328 0 +9329 0 +9330 0 +9331 1 +9332 0 +9333 0 +9334 0 +9335 0 +9336 0 +9337 0 +9338 1 +9339 0 +9340 0 +9341 0 +9342 0 +9343 0 +9344 0 +9345 1 +9346 0 +9347 0 +9348 0 +9349 0 +9350 0 +9351 0 +9352 0 +9353 0 +9354 0 +9355 1 +9356 0 +9357 0 +9358 0 +9359 0 +9360 0 +9361 0 +9362 0 +9363 1 +9364 0 +9365 0 +9366 0 +9367 0 +9368 0 +9369 0 +9370 1 +9371 0 +9372 0 +9373 0 +9374 0 +9375 0 +9376 0 +9377 0 +9378 1 +9379 0 +9380 0 +9381 0 +9382 0 +9383 0 +9384 0 +9385 0 +9386 0 +9387 0 +9388 0 +9389 0 +9390 0 +9391 0 +9392 0 +9393 0 +9394 0 +9395 1 +9396 0 +9397 0 +9398 0 +9399 0 +9400 0 +9401 0 +9402 0 +9403 1 +9404 0 +9405 0 +9406 0 +9407 0 +9408 0 +9409 0 +9410 0 +9411 0 +9412 1 +9413 0 +9414 0 +9415 0 +9416 0 +9417 0 +9418 0 +9419 0 +9420 1 +9421 0 +9422 0 +9423 0 +9424 0 +9425 0 +9426 0 +9427 0 +9428 0 +9429 1 +9430 0 +9431 0 +9432 0 +9433 0 +9434 0 +9435 0 +9436 0 +9437 0 +9438 0 +9439 1 +9440 0 +9441 0 +9442 0 +9443 0 +9444 0 +9445 0 +9446 0 +9447 0 +9448 0 +9449 1 +9450 0 +9451 0 +9452 0 +9453 0 +9454 0 +9455 0 +9456 0 +9457 1 +9458 0 +9459 0 +9460 0 +9461 0 +9462 0 +9463 0 +9464 1 +9465 0 +9466 0 +9467 0 +9468 0 +9469 0 +9470 0 +9471 0 +9472 0 +9473 1 +9474 0 +9475 0 +9476 0 +9477 0 +9478 0 +9479 0 +9480 0 +9481 1 +9482 0 +9483 0 +9484 0 +9485 0 +9486 0 +9487 0 +9488 1 +9489 0 +9490 0 +9491 0 +9492 0 +9493 0 +9494 0 +9495 0 +9496 0 +9497 1 +9498 0 +9499 0 +9500 0 +9501 0 +9502 0 +9503 0 +9504 0 +9505 0 +9506 0 +9507 0 +9508 0 +9509 0 +9510 0 +9511 0 +9512 0 +9513 0 +9514 1 +9515 0 +9516 0 +9517 0 +9518 0 +9519 0 +9520 0 +9521 0 +9522 1 +9523 0 +9524 0 +9525 0 +9526 0 +9527 0 +9528 0 +9529 0 +9530 1 +9531 0 +9532 0 +9533 0 +9534 0 +9535 0 +9536 0 +9537 0 +9538 1 +9539 0 +9540 0 +9541 0 +9542 0 +9543 0 +9544 0 +9545 0 +9546 0 +9547 1 +9548 0 +9549 0 +9550 0 +9551 0 +9552 0 +9553 0 +9554 0 +9555 1 +9556 0 +9557 0 +9558 0 +9559 0 +9560 0 +9561 0 +9562 0 +9563 1 +9564 0 +9565 0 +9566 0 +9567 0 +9568 0 +9569 0 +9570 0 +9571 0 +9572 1 +9573 0 +9574 0 +9575 0 +9576 0 +9577 0 +9578 0 +9579 0 +9580 1 +9581 0 +9582 0 +9583 0 +9584 0 +9585 0 +9586 0 +9587 0 +9588 0 +9589 1 +9590 0 +9591 0 +9592 0 +9593 0 +9594 0 +9595 0 +9596 0 +9597 0 +9598 0 +9599 0 +9600 0 +9601 0 +9602 0 +9603 0 +9604 0 +9605 0 +9606 0 +9607 0 +9608 1 +9609 0 +9610 0 +9611 0 +9612 0 +9613 0 +9614 0 +9615 1 +9616 0 +9617 0 +9618 0 +9619 0 +9620 0 +9621 0 +9622 1 +9623 0 +9624 0 +9625 0 +9626 0 +9627 0 +9628 0 +9629 0 +9630 1 +9631 0 +9632 0 +9633 0 +9634 0 +9635 0 +9636 0 +9637 0 +9638 0 +9639 1 +9640 0 +9641 0 +9642 0 +9643 0 +9644 0 +9645 0 +9646 0 +9647 0 +9648 1 +9649 0 +9650 0 +9651 0 +9652 0 +9653 0 +9654 0 +9655 0 +9656 1 +9657 0 +9658 0 +9659 0 +9660 0 +9661 0 +9662 0 +9663 1 +9664 0 +9665 0 +9666 0 +9667 0 +9668 0 +9669 0 +9670 0 +9671 0 +9672 0 +9673 1 +9674 0 +9675 0 +9676 0 +9677 0 +9678 0 +9679 0 +9680 0 +9681 1 +9682 0 +9683 0 +9684 0 +9685 0 +9686 0 +9687 0 +9688 0 +9689 1 +9690 0 +9691 0 +9692 0 +9693 0 +9694 0 +9695 0 +9696 1 +9697 0 +9698 0 +9699 0 +9700 0 +9701 0 +9702 0 +9703 0 +9704 1 +9705 0 +9706 0 +9707 0 +9708 0 +9709 0 +9710 0 +9711 0 +9712 1 +9713 0 +9714 0 +9715 0 +9716 0 +9717 0 +9718 0 +9719 0 +9720 0 +9721 0 +9722 1 +9723 0 +9724 0 +9725 0 +9726 0 +9727 0 +9728 0 +9729 0 +9730 0 +9731 1 +9732 0 +9733 0 +9734 0 +9735 0 +9736 0 +9737 0 +9738 0 +9739 0 +9740 1 +9741 0 +9742 0 +9743 0 +9744 0 +9745 0 +9746 0 +9747 0 +9748 0 +9749 1 +9750 0 +9751 0 +9752 0 +9753 0 +9754 0 +9755 0 +9756 1 +9757 0 +9758 0 +9759 0 +9760 0 +9761 0 +9762 0 +9763 0 +9764 0 +9765 0 +9766 0 +9767 0 +9768 0 +9769 0 +9770 0 +9771 0 +9772 0 +9773 1 +9774 0 +9775 0 +9776 0 +9777 0 +9778 0 +9779 0 +9780 1 +9781 0 +9782 0 +9783 0 +9784 0 +9785 0 +9786 0 +9787 0 +9788 1 +9789 0 +9790 0 +9791 0 +9792 0 +9793 0 +9794 0 +9795 0 +9796 0 +9797 0 +9798 0 +9799 0 +9800 0 +9801 0 +9802 0 +9803 1 +9804 0 +9805 0 +9806 0 +9807 0 +9808 0 +9809 0 +9810 0 +9811 0 +9812 1 +9813 0 +9814 0 +9815 0 +9816 0 +9817 0 +9818 0 +9819 0 +9820 1 +9821 0 +9822 0 +9823 0 +9824 0 +9825 0 +9826 0 +9827 0 +9828 0 +9829 1 +9830 0 +9831 0 +9832 0 +9833 0 +9834 0 +9835 0 +9836 0 +9837 0 +9838 1 +9839 0 +9840 0 +9841 0 +9842 0 +9843 0 +9844 0 +9845 0 +9846 0 +9847 0 +9848 1 +9849 0 +9850 0 +9851 0 +9852 0 +9853 0 +9854 4 +9855 0 +9856 0 +9857 1 +9858 0 +9859 0 +9860 0 +9861 0 +9862 1 +9863 0 +9864 0 +9865 0 +9866 0 +9867 0 +9868 1 +9869 0 +9870 0 +9871 0 +9872 0 +9873 1 +9874 0 +9875 0 +9876 0 +9877 0 +9878 1 +9879 0 +9880 0 +9881 0 +9882 0 +9883 0 +9884 0 +9885 0 +9886 1 +9887 0 +9888 0 +9889 0 +9890 0 +9891 0 +9892 0 +9893 0 +9894 0 +9895 1 +9896 0 +9897 0 +9898 0 +9899 0 +9900 0 +9901 0 +9902 0 +9903 0 +9904 1 +9905 0 +9906 0 +9907 0 +9908 0 +9909 0 +9910 0 +9911 0 +9912 0 +9913 0 +9914 0 +9915 0 +9916 0 +9917 0 +9918 0 +9919 0 +9920 0 +9921 0 +9922 0 +9923 0 +9924 1 +9925 0 +9926 0 +9927 0 +9928 0 +9929 0 +9930 0 +9931 0 +9932 0 +9933 0 +9934 1 +9935 0 +9936 0 +9937 0 +9938 0 +9939 0 +9940 0 +9941 0 +9942 0 +9943 0 +9944 1 +9945 0 +9946 0 +9947 0 +9948 0 +9949 0 +9950 0 +9951 0 +9952 0 +9953 0 +9954 1 +9955 0 +9956 0 +9957 0 +9958 0 +9959 0 +9960 0 +9961 0 +9962 0 +9963 1 +9964 0 +9965 0 +9966 0 +9967 0 +9968 0 +9969 0 +9970 0 +9971 0 +9972 1 +9973 0 +9974 0 +9975 0 +9976 0 +9977 0 +9978 0 +9979 0 +9980 0 +9981 0 +9982 0 +9983 1 +9984 0 +9985 0 +9986 0 +9987 0 +9988 0 +9989 0 +9990 0 +9991 0 +9992 0 +9993 1 +9994 0 +9995 0 +9996 0 +9997 0 +9998 0 +9999 0 +10000 0 +10001 0 +10002 0 +10003 0 +10004 1 +10005 0 +10006 0 +10007 0 +10008 0 +10009 0 +10010 0 +10011 0 +10012 0 +10013 1 +10014 0 +10015 0 +10016 0 +10017 0 +10018 0 +10019 0 +10020 0 +10021 0 +10022 0 +10023 1 +10024 0 +10025 0 +10026 0 +10027 0 +10028 0 +10029 0 +10030 0 +10031 1 +10032 0 +10033 0 +10034 0 +10035 0 +10036 0 +10037 0 +10038 0 +10039 0 +10040 0 +10041 1 +10042 0 +10043 0 +10044 0 +10045 0 +10046 0 +10047 0 +10048 0 +10049 0 +10050 0 +10051 1 +10052 0 +10053 0 +10054 0 +10055 0 +10056 0 +10057 0 +10058 0 +10059 0 +10060 1 +10061 0 +10062 0 +10063 0 +10064 0 +10065 0 +10066 0 +10067 0 +10068 0 +10069 1 +10070 0 +10071 0 +10072 0 +10073 0 +10074 0 +10075 0 +10076 0 +10077 0 +10078 1 +10079 0 +10080 0 +10081 0 +10082 0 +10083 0 +10084 0 +10085 0 +10086 0 +10087 1 +10088 0 +10089 0 +10090 0 +10091 0 +10092 0 +10093 0 +10094 0 +10095 0 +10096 0 +10097 1 +10098 0 +10099 0 +10100 0 +10101 0 +10102 0 +10103 0 +10104 0 +10105 0 +10106 0 +10107 0 +10108 1 +10109 0 +10110 0 +10111 0 +10112 0 +10113 0 +10114 0 +10115 0 +10116 0 +10117 0 +10118 1 +10119 0 +10120 0 +10121 0 +10122 0 +10123 0 +10124 0 +10125 0 +10126 0 +10127 1 +10128 0 +10129 0 +10130 0 +10131 0 +10132 0 +10133 0 +10134 0 +10135 0 +10136 0 +10137 1 +10138 0 +10139 0 +10140 0 +10141 0 +10142 0 +10143 0 +10144 0 +10145 0 +10146 0 +10147 1 +10148 0 +10149 0 +10150 0 +10151 0 +10152 0 +10153 0 +10154 0 +10155 0 +10156 0 +10157 1 +10158 0 +10159 0 +10160 0 +10161 0 +10162 0 +10163 0 +10164 0 +10165 0 +10166 0 +10167 1 +10168 0 +10169 0 +10170 0 +10171 0 +10172 0 +10173 0 +10174 0 +10175 0 +10176 1 +10177 0 +10178 0 +10179 0 +10180 0 +10181 0 +10182 0 +10183 0 +10184 0 +10185 1 +10186 0 +10187 0 +10188 0 +10189 0 +10190 0 +10191 0 +10192 0 +10193 1 +10194 0 +10195 0 +10196 0 +10197 0 +10198 0 +10199 0 +10200 0 +10201 1 +10202 0 +10203 0 +10204 0 +10205 0 +10206 0 +10207 0 +10208 0 +10209 0 +10210 0 +10211 1 +10212 0 +10213 0 +10214 0 +10215 0 +10216 0 +10217 0 +10218 0 +10219 0 +10220 1 +10221 0 +10222 0 +10223 0 +10224 0 +10225 0 +10226 0 +10227 0 +10228 0 +10229 0 +10230 1 +10231 0 +10232 0 +10233 0 +10234 0 +10235 0 +10236 0 +10237 0 +10238 0 +10239 0 +10240 1 +10241 0 +10242 0 +10243 0 +10244 0 +10245 0 +10246 0 +10247 0 +10248 0 +10249 0 +10250 1 +10251 0 +10252 0 +10253 0 +10254 0 +10255 0 +10256 0 +10257 0 +10258 0 +10259 0 +10260 1 +10261 0 +10262 0 +10263 0 +10264 1 +10265 0 +10266 0 +10267 0 +10268 0 +10269 0 +10270 1 +10271 0 +10272 0 +10273 0 +10274 0 +10275 0 +10276 0 +10277 0 +10278 1 +10279 0 +10280 0 +10281 0 +10282 0 +10283 0 +10284 0 +10285 0 +10286 1 +10287 0 +10288 0 +10289 0 +10290 0 +10291 0 +10292 0 +10293 0 +10294 0 +10295 0 +10296 1 +10297 0 +10298 0 +10299 0 +10300 0 +10301 0 +10302 0 +10303 0 +10304 0 +10305 1 +10306 0 +10307 0 +10308 0 +10309 0 +10310 0 +10311 0 +10312 0 +10313 0 +10314 1 +10315 0 +10316 0 +10317 0 +10318 0 +10319 0 +10320 0 +10321 0 +10322 0 +10323 1 +10324 0 +10325 0 +10326 0 +10327 0 +10328 0 +10329 0 +10330 0 +10331 0 +10332 0 +10333 1 +10334 0 +10335 0 +10336 0 +10337 0 +10338 0 +10339 0 +10340 0 +10341 0 +10342 0 +10343 0 +10344 0 +10345 0 +10346 0 +10347 0 +10348 0 +10349 0 +10350 0 +10351 1 +10352 0 +10353 0 +10354 0 +10355 0 +10356 0 +10357 0 +10358 0 +10359 0 +10360 1 +10361 0 +10362 0 +10363 0 +10364 0 +10365 0 +10366 0 +10367 0 +10368 0 +10369 0 +10370 1 +10371 0 +10372 0 +10373 0 +10374 0 +10375 0 +10376 0 +10377 0 +10378 0 +10379 0 +10380 1 +10381 0 +10382 0 +10383 0 +10384 0 +10385 0 +10386 0 +10387 1 +10388 0 +10389 0 +10390 0 +10391 0 +10392 0 +10393 0 +10394 0 +10395 1 +10396 0 +10397 0 +10398 0 +10399 0 +10400 0 +10401 0 +10402 0 +10403 0 +10404 1 +10405 0 +10406 0 +10407 0 +10408 0 +10409 0 +10410 0 +10411 0 +10412 0 +10413 0 +10414 1 +10415 0 +10416 0 +10417 0 +10418 0 +10419 0 +10420 0 +10421 0 +10422 0 +10423 1 +10424 0 +10425 0 +10426 0 +10427 0 +10428 0 +10429 0 +10430 0 +10431 0 +10432 0 +10433 1 +10434 0 +10435 0 +10436 0 +10437 0 +10438 0 +10439 0 +10440 0 +10441 0 +10442 0 +10443 1 +10444 0 +10445 0 +10446 0 +10447 0 +10448 0 +10449 0 +10450 0 +10451 0 +10452 1 +10453 0 +10454 0 +10455 0 +10456 0 +10457 0 +10458 0 +10459 0 +10460 1 +10461 0 +10462 0 +10463 0 +10464 0 +10465 0 +10466 0 +10467 0 +10468 0 +10469 1 +10470 0 +10471 0 +10472 0 +10473 0 +10474 0 +10475 0 +10476 0 +10477 0 +10478 0 +10479 1 +10480 0 +10481 0 +10482 0 +10483 0 +10484 0 +10485 0 +10486 0 +10487 0 +10488 0 +10489 1 +10490 0 +10491 0 +10492 0 +10493 0 +10494 0 +10495 0 +10496 0 +10497 0 +10498 1 +10499 0 +10500 0 +10501 0 +10502 0 +10503 0 +10504 0 +10505 0 +10506 1 +10507 0 +10508 0 +10509 0 +10510 0 +10511 0 +10512 0 +10513 0 +10514 0 +10515 0 +10516 0 +10517 1 +10518 0 +10519 0 +10520 0 +10521 0 +10522 0 +10523 0 +10524 0 +10525 0 +10526 0 +10527 1 +10528 0 +10529 0 +10530 0 +10531 0 +10532 0 +10533 0 +10534 0 +10535 0 +10536 1 +10537 0 +10538 0 +10539 0 +10540 0 +10541 0 +10542 0 +10543 0 +10544 0 +10545 1 +10546 0 +10547 0 +10548 0 +10549 0 +10550 0 +10551 0 +10552 0 +10553 0 +10554 0 +10555 1 +10556 0 +10557 0 +10558 0 +10559 0 +10560 0 +10561 0 +10562 0 +10563 0 +10564 0 +10565 0 +10566 1 +10567 0 +10568 0 +10569 0 +10570 0 +10571 0 +10572 0 +10573 0 +10574 0 +10575 0 +10576 0 +10577 0 +10578 0 +10579 0 +10580 0 +10581 0 +10582 0 +10583 0 +10584 0 +10585 0 +10586 0 +10587 1 +10588 0 +10589 0 +10590 0 +10591 0 +10592 0 +10593 0 +10594 0 +10595 0 +10596 0 +10597 0 +10598 1 +10599 0 +10600 0 +10601 0 +10602 0 +10603 0 +10604 0 +10605 0 +10606 0 +10607 0 +10608 0 +10609 1 +10610 0 +10611 0 +10612 0 +10613 0 +10614 0 +10615 0 +10616 0 +10617 1 +10618 0 +10619 0 +10620 0 +10621 0 +10622 0 +10623 0 +10624 0 +10625 1 +10626 0 +10627 0 +10628 0 +10629 0 +10630 0 +10631 0 +10632 0 +10633 0 +10634 1 +10635 0 +10636 0 +10637 0 +10638 0 +10639 0 +10640 0 +10641 0 +10642 0 +10643 0 +10644 1 +10645 0 +10646 0 +10647 0 +10648 0 +10649 0 +10650 0 +10651 0 +10652 0 +10653 1 +10654 0 +10655 0 +10656 0 +10657 0 +10658 0 +10659 0 +10660 0 +10661 1 +10662 0 +10663 0 +10664 0 +10665 0 +10666 0 +10667 0 +10668 0 +10669 0 +10670 0 +10671 1 +10672 0 +10673 0 +10674 0 +10675 0 +10676 0 +10677 0 +10678 0 +10679 0 +10680 0 +10681 1 +10682 0 +10683 0 +10684 0 +10685 0 +10686 0 +10687 0 +10688 0 +10689 0 +10690 0 +10691 0 +10692 0 +10693 0 +10694 0 +10695 0 +10696 0 +10697 0 +10698 0 +10699 0 +10700 0 +10701 1 +10702 0 +10703 0 +10704 0 +10705 0 +10706 0 +10707 0 +10708 0 +10709 0 +10710 0 +10711 1 +10712 0 +10713 0 +10714 0 +10715 0 +10716 0 +10717 0 +10718 0 +10719 0 +10720 0 +10721 1 +10722 0 +10723 0 +10724 0 +10725 0 +10726 0 +10727 0 +10728 0 +10729 0 +10730 1 +10731 0 +10732 0 +10733 0 +10734 0 +10735 0 +10736 0 +10737 0 +10738 0 +10739 0 +10740 1 +10741 0 +10742 0 +10743 0 +10744 0 +10745 0 +10746 0 +10747 0 +10748 0 +10749 1 +10750 0 +10751 0 +10752 0 +10753 0 +10754 0 +10755 0 +10756 0 +10757 0 +10758 0 +10759 1 +10760 0 +10761 0 +10762 0 +10763 0 +10764 0 +10765 0 +10766 0 +10767 0 +10768 0 +10769 0 +10770 1 +10771 0 +10772 0 +10773 0 +10774 0 +10775 0 +10776 0 +10777 0 +10778 0 +10779 0 +10780 1 +10781 0 +10782 0 +10783 0 +10784 0 +10785 0 +10786 0 +10787 0 +10788 0 +10789 0 +10790 1 +10791 0 +10792 0 +10793 0 +10794 0 +10795 0 +10796 0 +10797 0 +10798 0 +10799 0 +10800 1 +10801 0 +10802 0 +10803 0 +10804 0 +10805 0 +10806 0 +10807 0 +10808 0 +10809 0 +10810 0 +10811 0 +10812 0 +10813 0 +10814 0 +10815 0 +10816 0 +10817 0 +10818 0 +10819 0 +10820 1 +10821 0 +10822 0 +10823 0 +10824 0 +10825 0 +10826 0 +10827 0 +10828 0 +10829 0 +10830 0 +10831 1 +10832 0 +10833 0 +10834 0 +10835 0 +10836 0 +10837 0 +10838 0 +10839 0 +10840 1 +10841 0 +10842 0 +10843 0 +10844 0 +10845 0 +10846 0 +10847 0 +10848 0 +10849 0 +10850 0 +10851 0 +10852 0 +10853 0 +10854 0 +10855 0 +10856 0 +10857 0 +10858 0 +10859 0 +10860 1 +10861 0 +10862 0 +10863 0 +10864 0 +10865 0 +10866 0 +10867 0 +10868 0 +10869 1 +10870 0 +10871 0 +10872 0 +10873 0 +10874 0 +10875 0 +10876 0 +10877 0 +10878 0 +10879 0 +10880 1 +10881 0 +10882 0 +10883 0 +10884 0 +10885 0 +10886 0 +10887 0 +10888 0 +10889 0 +10890 1 +10891 0 +10892 0 +10893 0 +10894 0 +10895 0 +10896 0 +10897 0 +10898 0 +10899 0 +10900 1 +10901 0 +10902 0 +10903 0 +10904 0 +10905 0 +10906 0 +10907 0 +10908 0 +10909 0 +10910 0 +10911 1 +10912 0 +10913 0 +10914 0 +10915 0 +10916 0 +10917 0 +10918 0 +10919 0 +10920 0 +10921 1 +10922 0 +10923 0 +10924 0 +10925 0 +10926 0 +10927 0 +10928 0 +10929 0 +10930 0 +10931 1 +10932 0 +10933 0 +10934 0 +10935 0 +10936 0 +10937 0 +10938 0 +10939 0 +10940 1 +10941 0 +10942 0 +10943 0 +10944 0 +10945 0 +10946 0 +10947 0 +10948 0 +10949 1 +10950 0 +10951 0 +10952 0 +10953 0 +10954 0 +10955 0 +10956 0 +10957 0 +10958 1 +10959 0 +10960 0 +10961 0 +10962 0 +10963 0 +10964 0 +10965 0 +10966 0 +10967 0 +10968 1 +10969 0 +10970 0 +10971 0 +10972 0 +10973 0 +10974 0 +10975 0 +10976 0 +10977 0 +10978 1 +10979 0 +10980 0 +10981 0 +10982 0 +10983 0 +10984 0 +10985 0 +10986 0 +10987 0 +10988 0 +10989 1 +10990 0 +10991 0 +10992 0 +10993 0 +10994 0 +10995 0 +10996 0 +10997 0 +10998 0 +10999 0 +11000 1 \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..0c44ae7 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/README.md new file mode 100644 index 0000000..34c1189 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# readable-stream + +***Node-core streams for userland*** + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png)](https://nodei.co/npm/readable-stream/) + +This package is a mirror of the Streams2 and Streams3 implementations in Node-core. + +If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. + +**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. + +**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..b513d61 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +module.exports = Duplex; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} +/**/ + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; +}); + +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..895ca50 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..6307220 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,982 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events').EventEmitter; + +/**/ +if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +var Stream = require('stream'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var StringDecoder; + +util.inherits(Readable, Stream); + +function ReadableState(options, stream) { + options = options || {}; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + if (!(this instanceof Readable)) + return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); + + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } + + if (state.needReadable) + emitReadable(stream); + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + + + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; +}; + +// Don't raise the hwm > 128MB +var MAX_HWM = 0x800000; +function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; + + if (state.objectMode) + return n === 0 ? 0 : 1; + + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } + + if (n <= 0) + return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; + + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; + + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; + } + + if (state.length === 0) + endReadable(this); + + return ret; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; + + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); + + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; + + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + + +function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; + + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); +} + +function emitReadable_(stream) { + stream.emit('readable'); +} + + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(function() { + maybeReadMore_(stream, state); + }); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } + + function onend() { + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; + + + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); + + state.flowing = true; + process.nextTick(function() { + flow(src); + }); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function() { + var dest = this; + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; +} + +function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; + + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } + } + + while (state.pipesCount && null !== (chunk = src.read())) { + + if (state.pipesCount === 1) + write(state.pipes, 0, null); + else + forEach(state.pipes, write); + + src.emit('data', chunk); + + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; + } + + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; + + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; + } + + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; +} + +function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); + } +} + + +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; + + if (!dest) + dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); +}; + +Readable.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); +}; + +function emitDataEvents(stream, startPaused) { + var state = stream._readableState; + + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } + + var paused = startPaused || false; + var readable = false; + + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream.prototype.pipe; + stream.on = stream.addListener = Stream.prototype.on; + + stream.on('readable', function() { + readable = true; + + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); + + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); + + stream.pause = function() { + paused = true; + this.emit('pause'); + }; + + stream.resume = function() { + paused = false; + if (readable) + process.nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; + + // now make it start, just in case it hadn't already. + stream.emit('readable'); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + + + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted && state.calledRead) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..eb188df --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,210 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + + +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + + +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + var ts = this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); +} + +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + + +function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var rs = stream._readableState; + var ts = stream._transformState; + + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) + throw new Error('calling transform done when still transforming'); + + return stream.push(null); +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..4bdaa4f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,386 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. + +module.exports = Writable; + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Writable.WritableState = WritableState; + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Stream = require('stream'); + +util.inherits(Writable, Stream); + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; +} + +function WritableState(options, stream) { + options = options || {}; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.buffer = []; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; +} + +function Writable(options) { + var Duplex = require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + + +function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; +} + +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (typeof cb !== 'function') + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); + + return ret; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; + + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); + + return ret; +} + +function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + cb(er); + }); + else + cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); + + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, len, chunk, encoding, cb); + + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } + } + + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; +} + +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); +}; + + +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); +} + +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..9074e8e --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return Buffer.isBuffer(arg); +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 0000000..466dfdf --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,53 @@ +{ + "name": "core-util-is", + "version": "1.0.1", + "description": "The `util.is*` functions introduced in Node v0.12.", + "main": "lib/util.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", + "readmeFilename": "README.md", + "homepage": "https://github.com/isaacs/core-util-is", + "_id": "core-util-is@1.0.1", + "dist": { + "shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", + "tarball": "http://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" + }, + "_from": "core-util-is@>=1.0.0 <1.1.0", + "_npmVersion": "1.3.23", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js new file mode 100644 index 0000000..007fa10 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && objectToString(e) === '[object Error]'; +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return arg instanceof Buffer; +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# isarray + +`Array#isArray` for older browsers. + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module.exports) { + module.exports = {}; + module.client = module.component = true; + module.call(this, module.exports, require.relative(resolved), module); + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + var index = path + '/index.js'; + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (require.modules.hasOwnProperty(path)) return path; + } + + if (require.aliases.hasOwnProperty(index)) { + return require.aliases[index]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!require.modules.hasOwnProperty(from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return require.modules.hasOwnProperty(localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("isarray/index.js", function(exports, require, module){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +}); +require.alias("isarray/index.js", "isarray/index.js"); + diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 0000000..19228ab --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,53 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": {}, + "devDependencies": { + "tap": "*" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "_id": "isarray@0.0.1", + "dist": { + "shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "tarball": "http://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz" + }, + "_from": "isarray@0.0.1", + "_npmVersion": "1.2.18", + "_npmUser": { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + "maintainers": [ + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + } + ], + "directories": {}, + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "readme": "ERROR: No README data found!" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**string_decoder.js** (`require('string_decoder')`) from Node.js core + +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. + +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** + +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json new file mode 100644 index 0000000..0364d54 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json @@ -0,0 +1,54 @@ +{ + "name": "string_decoder", + "version": "0.10.31", + "description": "The string_decoder module from Node core", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "gitHead": "d46d4fd87cf1d06e031c23f1ba170ca7d4ade9a0", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_from": "string_decoder@>=0.10.0 <0.11.0", + "_npmVersion": "1.4.23", + "_npmUser": { + "name": "rvagg", + "email": "rod@vagg.org" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + }, + { + "name": "rvagg", + "email": "rod@vagg.org" + } + ], + "dist": { + "shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "tarball": "http://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/package.json new file mode 100644 index 0000000..2dc3a25 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/package.json @@ -0,0 +1,69 @@ +{ + "name": "readable-stream", + "version": "1.0.31", + "description": "Streams2, a user-land copy of the stream library from Node.js v0.10.x", + "main": "readable.js", + "dependencies": { + "core-util-is": "~1.0.0", + "isarray": "0.0.1", + "string_decoder": "~0.10.x", + "inherits": "~2.0.1" + }, + "devDependencies": { + "tap": "~0.2.6" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/readable-stream.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "homepage": "https://github.com/isaacs/readable-stream", + "_id": "readable-stream@1.0.31", + "_shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "_from": "readable-stream@1.0.31", + "_npmVersion": "1.4.9", + "_npmUser": { + "name": "rvagg", + "email": "rod@vagg.org" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + { + "name": "rvagg", + "email": "rod@vagg.org" + } + ], + "dist": { + "shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "tarball": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/readable.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..4d1ddfc --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/readable.js @@ -0,0 +1,6 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/transform.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/writable.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/util/retroImporter/node_modules/mongodb/package.json b/util/retroImporter/node_modules/mongodb/package.json new file mode 100644 index 0000000..9036dce --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/package.json @@ -0,0 +1,66 @@ +{ + "name": "mongodb", + "version": "2.0.45", + "description": "MongoDB legacy driver emulation layer on top of mongodb-core", + "main": "index.js", + "repository": { + "type": "git", + "url": "git@github.com:mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "legacy" + ], + "dependencies": { + "mongodb-core": "1.2.14", + "readable-stream": "1.0.31", + "es6-promise": "2.1.1" + }, + "devDependencies": { + "integra": "0.1.8", + "optimist": "0.6.1", + "bson": "~0.4", + "jsdoc": "3.3.0-beta3", + "semver": "4.1.0", + "rimraf": "2.2.6", + "gleak": "0.5.0", + "mongodb-version-manager": "^0.7.1", + "mongodb-tools": "~1.0", + "co": "4.5.4", + "bluebird": "2.9.27" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/mongodb/node-mongodb-native/issues" + }, + "scripts": { + "test": "node test/runner.js -t functional" + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "gitHead": "45d433baa92cb160f895d47911ee5776fbaad3be", + "_id": "mongodb@2.0.45", + "_shasum": "c63d42b918f19a53b32d4c64043f6a9f66c9aba5", + "_from": "mongodb@*", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "c63d42b918f19a53b32d4c64043f6a9f66c9aba5", + "tarball": "http://registry.npmjs.org/mongodb/-/mongodb-2.0.45.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-2.0.45.tgz" +} diff --git a/util/retroImporter/node_modules/mongodb/t.js b/util/retroImporter/node_modules/mongodb/t.js new file mode 100644 index 0000000..af73362 --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/t.js @@ -0,0 +1,73 @@ +var MongoClient = require('./').MongoClient + , assert = require('assert') + , cappedCollectionName = "capped_test"; + + +function capitalizeFirstLetter(string) { + return string.charAt(0).toUpperCase() + string.slice(1); +} + + function createTailedCursor(db, callback) { + var collection = db.collection(cappedCollectionName) + , cursor = collection.find({}, { tailable: true, awaitdata: true, numberOfRetries: Number.MAX_VALUE}) + , stream = cursor.stream() + , statusGetters = ['notified', 'closed', 'dead', 'killed']; + + console.log('After stream open'); + statusGetters.forEach(function (s) { + var getter = 'is' + capitalizeFirstLetter(s); + console.log("cursor " + getter + " => ", cursor[getter]()); + }); + + + stream.on('error', callback); + stream.on('end', callback.bind(null, 'end')); + stream.on('close', callback.bind(null, 'close')); + stream.on('readable', callback.bind(null, 'readable')); + stream.on('data', callback.bind(null, null, 'data')); + + console.log('After stream attach events'); + statusGetters.forEach(function (s) { + var getter = 'is' + capitalizeFirstLetter(s); + console.log("cursor " + getter + " => ", cursor[getter]()); + }); + } + + function cappedStreamEvent(err, evName, data) { + if (err) { + console.log("capped stream got error", err); + return; + } + + if (evName) { + console.log("capped stream got event", evName); + } + + if (data) { + console.log("capped stream got data", data); + } + } + + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + db.createCollection(cappedCollectionName, + { "capped": true, + "size": 100000, + "max": 5000 }, + function(err, collection) { + + assert.equal(null, err); + console.log("Created capped collection " + cappedCollectionName); + + createTailedCursor(db, cappedStreamEvent); + }); + + + //db.close(); +}); \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/t1.js b/util/retroImporter/node_modules/mongodb/t1.js new file mode 100644 index 0000000..392ed8e --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/t1.js @@ -0,0 +1,77 @@ +var MongoClient = require('./').MongoClient; + +MongoClient.connect('mongodb://localhost:27017/page-testing', function (err, db) { + collection = db.collection('test'); + + collection.insertMany([{a:1}, {a:2}], {w:1}, function (err, docs) { + if (err) { + console.log("ERROR"); + } + + collection.find().sort({'a': -1}).toArray(function(err, items) { + if (err) { + console.log("ERROR"); + } + console.log("Items: ", items); + }); + }); +}); +// var database = null; +// +// var MongoClient = require('./').MongoClient; +// +// function connect_to_mongo(callback) { +// if (database != null) { +// callback(null, database); +// } else { +// var connection = "mongodb://127.0.0.1:27017/test_db"; +// MongoClient.connect(connection, { +// server : { +// reconnectTries : 5, +// reconnectInterval: 1000, +// autoReconnect : true +// } +// }, function (err, db) { +// database = db; +// callback(err, db); +// }); +// } +// } +// +// function log(message) { +// console.log(new Date(), message); +// } +// +// var queryNumber = 0; +// +// function make_query(db) { +// var currentNumber = queryNumber; +// ++queryNumber; +// log("query " + currentNumber + ": started"); +// +// setTimeout(function() { +// make_query(db); +// }, 5000); +// +// var collection = db.collection('test_collection'); +// collection.findOne({}, +// function (err, result) { +// if (err != null) { +// log("query " + currentNumber + ": find one error: " + err.message); +// return; +// } +// log("query " + currentNumber + ": find one result: " + result); +// } +// ); +// } +// +// connect_to_mongo( +// function(err, db) { +// if (err != null) { +// log(err.message); +// return; +// } +// +// make_query(db); +// } +// ); diff --git a/util/retroImporter/node_modules/mongodb/wercker.yml b/util/retroImporter/node_modules/mongodb/wercker.yml new file mode 100644 index 0000000..b64845f --- /dev/null +++ b/util/retroImporter/node_modules/mongodb/wercker.yml @@ -0,0 +1,19 @@ +box: wercker/nodejs +services: + - wercker/mongodb@1.0.1 +# Build definition +build: + # The steps that will be executed on build + steps: + # A step that executes `npm install` command + - npm-install + # A step that executes `npm test` command + - npm-test + + # A custom script step, name value is used in the UI + # and the code value contains the command that get executed + - script: + name: echo nodejs information + code: | + echo "node version $(node -v) running" + echo "npm version $(npm -v) running" diff --git a/util/retroImporter/package.json b/util/retroImporter/package.json new file mode 100644 index 0000000..317d037 --- /dev/null +++ b/util/retroImporter/package.json @@ -0,0 +1,15 @@ +{ + "name": "retroimporter", + "version": "1.0.0", + "description": "", + "main": "retroImporter.js", + "dependencies": { + "mongodb": "^2.0.45" + }, + "devDependencies": {}, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC" +} diff --git a/util/retroImporter/retroImporter.js b/util/retroImporter/retroImporter.js new file mode 100644 index 0000000..8628b7d --- /dev/null +++ b/util/retroImporter/retroImporter.js @@ -0,0 +1,203 @@ +// Retrieve +var MongoClient = require('mongodb').MongoClient; +var util = require('util'); + +// Connect to the db +MongoClient.connect('mongodb://localhost:27017/query_composer_development', function(err, db) { + if(err) { return console.dir(err); } + + db.collection('queries', null, + function(err, queries) + { + if(err) { throw err; } + + //fetch the retro query excution + //**************************************************************************** + queries.find({title:'Retro-PDC-053'}).toArray( + function(err, retroPDC053Queries) + { + if(err) { throw err; } + + if(retroPDC053Queries.length != 1) + { + throw new Error('Not one and only one query with title for Retro-PDC-053'); + } + + var retroPDC053 = retroPDC053Queries[0]; + + if(retroPDC053.executions.length != 1) + { + throw new Error('Not one and only one execution for Retro-PDC-053'); + } + + retroPDC053.executions = retroPDC053.executions.sort( + function(a,b) + { + return a.time > b.time ? 1 : b.time > a.time ? -1 : 0; + } + ); + + var retroPDC053Execution = retroPDC053.executions[0]; + + //**************************************************************************** + + //fetch query executions + //**************************************************************************** + var pdc053Queries = queries.find({title:'PDC-053'}).toArray( + function(err, pdc053Queries) + { + if(err) { throw err; } + + if(pdc053Queries.length != 1) + { + throw new Error('Not one and only one query with title for PDC-053'); + } + + var pdc053 = pdc053Queries[0]; + + var pdc053Executions = pdc053.executions; + //**************************************************************************** + + //fetch retro retroResults + //**************************************************************************** + var retroResults = retroPDC053Execution.aggregate_result; + //**************************************************************************** + + //build simulated executions + //**************************************************************************** + var simulatedExecutions = {}; + + for( var key in retroResults) + { + if( !retroResults.hasOwnProperty(key)) + { + continue; + } + + var execution = JSON.parse(key); + + var date = execution.date/1000;//convert to seconds + var simulatedExecution; + + if( !simulatedExecutions[date] ) + { + var aggregate_result = {}; + var ar_key; + + if(execution.value === 'numerator') + { + ar_key = 'numerator_' + execution.pid; + aggregate_result[ar_key] = retroResults[key]; + } + else if(execution.value === 'denominator') + { + ar_key = 'denominator_' + execution.pid; + aggregate_result[ar_key] = retroResults[key]; + } + else { + throw new Error('key did not have value in ["numerator", "denominator"]'); + } + + simulatedExecution = {'_id':retroPDC053Execution._id, + 'aggregate_result':aggregate_result, + 'notification':null, + 'time':date + }; + + simulatedExecutions[date] = simulatedExecution; + } + else + { + simulatedExecution = simulatedExecutions[date]; + if(!simulatedExecution) + { + throw new Error('simulatedExecution evaluted to false'); + } + + console.log('execution.value: ' + execution.value); + console.log('aggresult: ' + util.inspect(simulatedExecution.aggregate_result)); + console.log('den_id: ' + simulatedExecution.aggregate_result['denominator_' + execution.pid]); + + if(execution.value === 'numerator' && + simulatedExecution.aggregate_result['denominator_' + execution.pid] !== undefined && + simulatedExecution.aggregate_result['denominator_' + execution.pid] !== null + ) + { + simulatedExecution.aggregate_result['numerator_' + execution.pid] = retroResults[key]; + } + else if(execution.value === 'denominator' && + simulatedExecution.aggregate_result['numerator_' + execution.pid] !== undefined && + simulatedExecution.aggregate_result['numerator_' + execution.pid] !== null ) + { + simulatedExecution.aggregate_result['denominator_' + execution.pid] = retroResults[key]; + } + else + { + throw new Error("no match for date: " + date); + } + + simulatedExecution.aggregate_result.simulated = true; + } + } + //**************************************************************************** + + //console.log("****Retro Execution****"); + //console.log(retroPDC053Execution); + + //console.log("****pdc053Executions****"); + //console.log(pdc053Executions); + + //add the simulated executions to the execution List + //**************************************************************************** + for( var se in simulatedExecutions) + { + if( !simulatedExecutions.hasOwnProperty(se)) + { + continue; + } + + pdc053Executions.push( simulatedExecutions[se] ); + } + //**************************************************************************** + + //update the query with the retro results + //**************************************************************************** + + queries.updateOne({title:'PDC-053'}, {$set:{executions:pdc053Executions}}, {upsert:true}, + function(err, result) + { + if(err) + { + throw new Error(err); + } + + queries.find({title:'PDC-053'}).toArray( + function(err, queries) + { + if(err) + { + throw new Error(err); + } + + if(queries.length != 1) + { + throw new Error('not one and only one query with title pdc-053'); + } + + var query = queries[0]; + + //console.log("****revised pdc053Executions****"); + console.log(query.executions); + } + ); + }); + + //**************************************************************************** + }); + + }); + } + ); + + console.log('done!'); +}); From 1445f1eeb457d438ef91419775277cefcf5a45cc Mon Sep 17 00:00:00 2001 From: Fieran Mason Date: Mon, 2 Nov 2015 17:13:15 +0000 Subject: [PATCH 06/10] generalized the retro importer --- .gitignore | 1 + util/retroImporter/retroImporter.js | 111 ++++++++++++++-------------- 2 files changed, 57 insertions(+), 55 deletions(-) diff --git a/.gitignore b/.gitignore index 98109f1..722beb4 100755 --- a/.gitignore +++ b/.gitignore @@ -13,3 +13,4 @@ spec/generated monitoring/nagios-config/ monitoring/nagios-nrpe-server-config/ generate_nagios3_config.sh~ +Gemfile.lock diff --git a/util/retroImporter/retroImporter.js b/util/retroImporter/retroImporter.js index 8628b7d..93d78c5 100644 --- a/util/retroImporter/retroImporter.js +++ b/util/retroImporter/retroImporter.js @@ -2,65 +2,85 @@ var MongoClient = require('mongodb').MongoClient; var util = require('util'); +var preconditions = true; + +if(process.env.QUERY_TITLE === null || process.env.QUERY_TITLE === undefined) +{ + console.log('ERROR: QUERY_TITLE environment variable not set.'); +} +else +{ + console.log('QUERY_TITLE: ' + process.env.QUERY_TITLE); +} + + +if(process.env.RETRO_QUERY_TITLE === null || process.env.RETRO_QUERY_TITLE === undefined) +{ + console.log('ERROR: RETRO_QUERY_TITLE environment variable not set.'); +} +else +{ + console.log('RETRO_QUERY_TITLE: ' + process.env.RETRO_QUERY_TITLE); +} // Connect to the db MongoClient.connect('mongodb://localhost:27017/query_composer_development', function(err, db) { if(err) { return console.dir(err); } db.collection('queries', null, - function(err, queries) + function(err, queriesCollection) { if(err) { throw err; } //fetch the retro query excution //**************************************************************************** - queries.find({title:'Retro-PDC-053'}).toArray( - function(err, retroPDC053Queries) + queriesCollection.find({title:process.env.RETRO_QUERY_TITLE}).toArray( + function(err, retroQueries) { if(err) { throw err; } - if(retroPDC053Queries.length != 1) + if(retroQueries.length != 1) { - throw new Error('Not one and only one query with title for Retro-PDC-053'); + throw new Error('Not one and only one retro query: ' + process.env.RETRO_QUERY_TITLE); } - var retroPDC053 = retroPDC053Queries[0]; + var retroQuery = retroQueries[0]; - if(retroPDC053.executions.length != 1) + if(retroQuery.executions.length != 1) { - throw new Error('Not one and only one execution for Retro-PDC-053'); + throw new Error('Not one and only one execution for retro query: ' + process.env.RETRO_QUERY_TITLE); } - retroPDC053.executions = retroPDC053.executions.sort( + retroQuery.executions = retroQuery.executions.sort( function(a,b) { return a.time > b.time ? 1 : b.time > a.time ? -1 : 0; } ); - var retroPDC053Execution = retroPDC053.executions[0]; + var retroQueryExecution = retroQuery.executions[0]; //**************************************************************************** //fetch query executions //**************************************************************************** - var pdc053Queries = queries.find({title:'PDC-053'}).toArray( - function(err, pdc053Queries) + var queries = queriesCollection.find({title:process.env.QUERY_TITLE}).toArray( + function(err, queries) { if(err) { throw err; } - if(pdc053Queries.length != 1) + if(queries.length != 1) { - throw new Error('Not one and only one query with title for PDC-053'); + throw new Error('Not one and only one query: ' + process.env.QUERY_TITLE); } - var pdc053 = pdc053Queries[0]; + var query = queries[0]; - var pdc053Executions = pdc053.executions; + var queryExecutions = query.executions; //**************************************************************************** //fetch retro retroResults //**************************************************************************** - var retroResults = retroPDC053Execution.aggregate_result; + var retroResults = retroQueryExecution.aggregate_result; //**************************************************************************** //build simulated executions @@ -98,7 +118,7 @@ MongoClient.connect('mongodb://localhost:27017/query_composer_development', func throw new Error('key did not have value in ["numerator", "denominator"]'); } - simulatedExecution = {'_id':retroPDC053Execution._id, + simulatedExecution = {'_id':retroQueryExecution._id, 'aggregate_result':aggregate_result, 'notification':null, 'time':date @@ -114,10 +134,6 @@ MongoClient.connect('mongodb://localhost:27017/query_composer_development', func throw new Error('simulatedExecution evaluted to false'); } - console.log('execution.value: ' + execution.value); - console.log('aggresult: ' + util.inspect(simulatedExecution.aggregate_result)); - console.log('den_id: ' + simulatedExecution.aggregate_result['denominator_' + execution.pid]); - if(execution.value === 'numerator' && simulatedExecution.aggregate_result['denominator_' + execution.pid] !== undefined && simulatedExecution.aggregate_result['denominator_' + execution.pid] !== null @@ -133,7 +149,7 @@ MongoClient.connect('mongodb://localhost:27017/query_composer_development', func } else { - throw new Error("no match for date: " + date); + throw new Error("ERROR: no match for date: " + date); } simulatedExecution.aggregate_result.simulated = true; @@ -141,12 +157,6 @@ MongoClient.connect('mongodb://localhost:27017/query_composer_development', func } //**************************************************************************** - //console.log("****Retro Execution****"); - //console.log(retroPDC053Execution); - - //console.log("****pdc053Executions****"); - //console.log(pdc053Executions); - //add the simulated executions to the execution List //**************************************************************************** for( var se in simulatedExecutions) @@ -155,41 +165,34 @@ MongoClient.connect('mongodb://localhost:27017/query_composer_development', func { continue; } - - pdc053Executions.push( simulatedExecutions[se] ); + + queryExecutions.push( simulatedExecutions[se] ); } //**************************************************************************** //update the query with the retro results //**************************************************************************** - - queries.updateOne({title:'PDC-053'}, {$set:{executions:pdc053Executions}}, {upsert:true}, + + queriesCollection.updateOne({title:process.env.QUERY_TITLE}, {$set:{executions:queryExecutions}}, {upsert:true}, function(err, result) { if(err) { throw new Error(err); } - - queries.find({title:'PDC-053'}).toArray( - function(err, queries) - { - if(err) - { - throw new Error(err); - } - - if(queries.length != 1) - { - throw new Error('not one and only one query with title pdc-053'); - } - - var query = queries[0]; - - //console.log("****revised pdc053Executions****"); - console.log(query.executions); - } - ); + + db.close( + function(err, result) + { + if(err) + { + console.log('ERROR: closing db - ' + error); + } + else + { + console.log('SUCCESS'); + } + }); }); //**************************************************************************** @@ -198,6 +201,4 @@ MongoClient.connect('mongodb://localhost:27017/query_composer_development', func }); } ); - - console.log('done!'); }); From 917790cc36a98d2a7ae69d2a6d585336c9ded851 Mon Sep 17 00:00:00 2001 From: Fieran Mason Date: Wed, 4 Nov 2015 16:45:37 +0000 Subject: [PATCH 07/10] added demographics importer for retrospective demogrphics queries --- .../demographicsImporter.js | 175 + .../node_modules/mongodb/HISTORY.md | 1218 ++ .../node_modules/mongodb/LICENSE | 201 + .../node_modules/mongodb/Makefile | 11 + .../node_modules/mongodb/README.md | 322 + .../node_modules/mongodb/c.js | 24 + .../node_modules/mongodb/conf.json | 69 + .../node_modules/mongodb/index.js | 47 + .../node_modules/mongodb/lib/admin.js | 581 + .../mongodb/lib/aggregation_cursor.js | 432 + .../node_modules/mongodb/lib/apm.js | 571 + .../node_modules/mongodb/lib/bulk/common.js | 393 + .../node_modules/mongodb/lib/bulk/ordered.js | 532 + .../mongodb/lib/bulk/unordered.js | 541 + .../node_modules/mongodb/lib/collection.js | 3128 +++++ .../mongodb/lib/command_cursor.js | 296 + .../node_modules/mongodb/lib/cursor.js | 1149 ++ .../node_modules/mongodb/lib/db.js | 1731 +++ .../node_modules/mongodb/lib/gridfs/chunk.js | 237 + .../mongodb/lib/gridfs/grid_store.js | 1919 +++ .../node_modules/mongodb/lib/metadata.js | 64 + .../node_modules/mongodb/lib/mongo_client.js | 463 + .../node_modules/mongodb/lib/mongos.js | 491 + .../mongodb/lib/read_preference.js | 104 + .../node_modules/mongodb/lib/replset.js | 555 + .../node_modules/mongodb/lib/server.js | 437 + .../node_modules/mongodb/lib/topology_base.js | 152 + .../node_modules/mongodb/lib/url_parser.js | 295 + .../node_modules/mongodb/lib/utils.js | 234 + .../node_modules/mongodb/load.js | 32 + .../node_modules/es6-promise/CHANGELOG.md | 9 + .../mongodb/node_modules/es6-promise/LICENSE | 19 + .../node_modules/es6-promise/README.md | 61 + .../es6-promise/dist/es6-promise.js | 957 ++ .../es6-promise/dist/es6-promise.min.js | 9 + .../es6-promise/dist/test/browserify.js | 11631 ++++++++++++++++ .../es6-promise/dist/test/es6-promise.js | 950 ++ .../es6-promise/dist/test/es6-promise.min.js | 1 + .../es6-promise/dist/test/index.html | 25 + .../es6-promise/dist/test/json3.js | 902 ++ .../es6-promise/dist/test/mocha.css | 270 + .../es6-promise/dist/test/mocha.js | 6095 ++++++++ .../es6-promise/dist/test/worker.js | 16 + .../es6-promise/lib/es6-promise.umd.js | 18 + .../es6-promise/lib/es6-promise/-internal.js | 250 + .../es6-promise/lib/es6-promise/asap.js | 111 + .../es6-promise/lib/es6-promise/enumerator.js | 113 + .../es6-promise/lib/es6-promise/polyfill.js | 26 + .../es6-promise/lib/es6-promise/promise.js | 408 + .../lib/es6-promise/promise/all.js | 52 + .../lib/es6-promise/promise/race.js | 104 + .../lib/es6-promise/promise/reject.js | 46 + .../lib/es6-promise/promise/resolve.js | 48 + .../es6-promise/lib/es6-promise/utils.js | 22 + .../node_modules/es6-promise/package.json | 88 + .../node_modules/mongodb-core/HISTORY.md | 246 + .../mongodb/node_modules/mongodb-core/LICENSE | 201 + .../node_modules/mongodb-core/Makefile | 11 + .../node_modules/mongodb-core/README.md | 225 + .../node_modules/mongodb-core/TESTING.md | 18 + .../node_modules/mongodb-core/conf.json | 60 + .../node_modules/mongodb-core/index.js | 18 + .../mongodb-core/lib/auth/gssapi.js | 244 + .../mongodb-core/lib/auth/mongocr.js | 160 + .../mongodb-core/lib/auth/plain.js | 150 + .../mongodb-core/lib/auth/scram.js | 317 + .../mongodb-core/lib/auth/sspi.js | 234 + .../mongodb-core/lib/auth/x509.js | 145 + .../mongodb-core/lib/connection/commands.js | 519 + .../mongodb-core/lib/connection/connection.js | 462 + .../mongodb-core/lib/connection/logger.js | 196 + .../mongodb-core/lib/connection/pool.js | 275 + .../mongodb-core/lib/connection/utils.js | 77 + .../node_modules/mongodb-core/lib/cursor.js | 756 + .../node_modules/mongodb-core/lib/error.js | 44 + .../mongodb-core/lib/tools/smoke_plugin.js | 59 + .../lib/topologies/command_result.js | 37 + .../mongodb-core/lib/topologies/mongos.js | 1000 ++ .../lib/topologies/read_preference.js | 106 + .../mongodb-core/lib/topologies/replset.js | 1333 ++ .../lib/topologies/replset_state.js | 483 + .../mongodb-core/lib/topologies/server.js | 1230 ++ .../mongodb-core/lib/topologies/session.js | 93 + .../lib/topologies/strategies/ping.js | 276 + .../lib/wireprotocol/2_4_support.js | 559 + .../lib/wireprotocol/2_6_support.js | 291 + .../lib/wireprotocol/3_2_support.js | 494 + .../mongodb-core/lib/wireprotocol/commands.js | 357 + .../mongodb-core/node_modules/bson/HISTORY | 113 + .../mongodb-core/node_modules/bson/LICENSE | 201 + .../mongodb-core/node_modules/bson/README.md | 69 + .../bson/alternate_parsers/bson.js | 1574 +++ .../bson/alternate_parsers/faster_bson.js | 429 + .../node_modules/bson/browser_build/bson.js | 4843 +++++++ .../bson/browser_build/package.json | 8 + .../node_modules/bson/lib/bson/binary.js | 344 + .../bson/lib/bson/binary_parser.js | 385 + .../node_modules/bson/lib/bson/bson.js | 323 + .../node_modules/bson/lib/bson/code.js | 24 + .../node_modules/bson/lib/bson/db_ref.js | 32 + .../node_modules/bson/lib/bson/double.js | 33 + .../bson/lib/bson/float_parser.js | 121 + .../node_modules/bson/lib/bson/index.js | 86 + .../node_modules/bson/lib/bson/long.js | 856 ++ .../node_modules/bson/lib/bson/map.js | 126 + .../node_modules/bson/lib/bson/max_key.js | 14 + .../node_modules/bson/lib/bson/min_key.js | 14 + .../node_modules/bson/lib/bson/objectid.js | 273 + .../bson/lib/bson/parser/calculate_size.js | 310 + .../bson/lib/bson/parser/deserializer.js | 544 + .../bson/lib/bson/parser/serializer.js | 909 ++ .../node_modules/bson/lib/bson/regexp.js | 30 + .../node_modules/bson/lib/bson/symbol.js | 47 + .../node_modules/bson/lib/bson/timestamp.js | 856 ++ .../node_modules/bson/package.json | 70 + .../node_modules/bson/tools/gleak.js | 21 + .../node_modules/kerberos/.travis.yml | 20 + .../node_modules/kerberos/LICENSE | 201 + .../node_modules/kerberos/README.md | 4 + .../node_modules/kerberos/binding.gyp | 46 + .../node_modules/kerberos/build/Makefile | 324 + .../Release/.deps/Release/kerberos.node.d | 1 + .../.deps/Release/obj.target/kerberos.node.d | 1 + .../obj.target/kerberos/lib/base64.o.d | 4 + .../obj.target/kerberos/lib/kerberos.o.d | 71 + .../kerberos/lib/kerberos_context.o.d | 70 + .../obj.target/kerberos/lib/kerberosgss.o.d | 16 + .../obj.target/kerberos/lib/worker.o.d | 57 + .../kerberos/build/Release/kerberos.node | Bin 0 -> 85259 bytes .../build/Release/obj.target/kerberos.node | Bin 0 -> 85259 bytes .../Release/obj.target/kerberos/lib/base64.o | Bin 0 -> 4176 bytes .../obj.target/kerberos/lib/kerberos.o | Bin 0 -> 86232 bytes .../kerberos/lib/kerberos_context.o | Bin 0 -> 31808 bytes .../obj.target/kerberos/lib/kerberosgss.o | Bin 0 -> 19608 bytes .../Release/obj.target/kerberos/lib/worker.o | Bin 0 -> 2720 bytes .../kerberos/build/binding.Makefile | 6 + .../node_modules/kerberos/build/config.gypi | 138 + .../kerberos/build/kerberos.target.mk | 151 + .../node_modules/kerberos/builderror.log | 25 + .../node_modules/kerberos/index.js | 6 + .../kerberos/lib/auth_processes/mongodb.js | 281 + .../node_modules/kerberos/lib/base64.c | 134 + .../node_modules/kerberos/lib/base64.h | 22 + .../node_modules/kerberos/lib/kerberos.cc | 893 ++ .../node_modules/kerberos/lib/kerberos.h | 50 + .../node_modules/kerberos/lib/kerberos.js | 164 + .../kerberos/lib/kerberos_context.cc | 134 + .../kerberos/lib/kerberos_context.h | 64 + .../node_modules/kerberos/lib/kerberosgss.c | 931 ++ .../node_modules/kerberos/lib/kerberosgss.h | 73 + .../node_modules/kerberos/lib/sspi.js | 15 + .../node_modules/kerberos/lib/win32/base64.c | 121 + .../node_modules/kerberos/lib/win32/base64.h | 18 + .../kerberos/lib/win32/kerberos.cc | 51 + .../kerberos/lib/win32/kerberos.h | 60 + .../kerberos/lib/win32/kerberos_sspi.c | 244 + .../kerberos/lib/win32/kerberos_sspi.h | 106 + .../node_modules/kerberos/lib/win32/worker.cc | 7 + .../node_modules/kerberos/lib/win32/worker.h | 38 + .../lib/win32/wrappers/security_buffer.cc | 101 + .../lib/win32/wrappers/security_buffer.h | 48 + .../lib/win32/wrappers/security_buffer.js | 12 + .../wrappers/security_buffer_descriptor.cc | 182 + .../wrappers/security_buffer_descriptor.h | 46 + .../wrappers/security_buffer_descriptor.js | 3 + .../lib/win32/wrappers/security_context.cc | 856 ++ .../lib/win32/wrappers/security_context.h | 74 + .../lib/win32/wrappers/security_context.js | 3 + .../win32/wrappers/security_credentials.cc | 348 + .../lib/win32/wrappers/security_credentials.h | 68 + .../win32/wrappers/security_credentials.js | 22 + .../node_modules/kerberos/lib/worker.cc | 7 + .../node_modules/kerberos/lib/worker.h | 38 + .../kerberos/node_modules/nan/.dntrc | 30 + .../kerberos/node_modules/nan/CHANGELOG.md | 374 + .../kerberos/node_modules/nan/LICENSE.md | 13 + .../kerberos/node_modules/nan/README.md | 367 + .../kerberos/node_modules/nan/appveyor.yml | 38 + .../kerberos/node_modules/nan/doc/.build.sh | 38 + .../node_modules/nan/doc/asyncworker.md | 97 + .../kerberos/node_modules/nan/doc/buffers.md | 54 + .../kerberos/node_modules/nan/doc/callback.md | 52 + .../node_modules/nan/doc/converters.md | 41 + .../kerberos/node_modules/nan/doc/errors.md | 226 + .../node_modules/nan/doc/maybe_types.md | 480 + .../kerberos/node_modules/nan/doc/methods.md | 624 + .../kerberos/node_modules/nan/doc/new.md | 141 + .../node_modules/nan/doc/node_misc.md | 114 + .../node_modules/nan/doc/persistent.md | 292 + .../kerberos/node_modules/nan/doc/scopes.md | 73 + .../kerberos/node_modules/nan/doc/script.md | 38 + .../node_modules/nan/doc/string_bytes.md | 62 + .../node_modules/nan/doc/v8_internals.md | 199 + .../kerberos/node_modules/nan/doc/v8_misc.md | 63 + .../kerberos/node_modules/nan/include_dirs.js | 1 + .../kerberos/node_modules/nan/nan.h | 2136 +++ .../kerberos/node_modules/nan/nan_callbacks.h | 88 + .../node_modules/nan/nan_callbacks_12_inl.h | 512 + .../nan/nan_callbacks_pre_12_inl.h | 506 + .../node_modules/nan/nan_converters.h | 64 + .../node_modules/nan/nan_converters_43_inl.h | 42 + .../nan/nan_converters_pre_43_inl.h | 42 + .../nan/nan_implementation_12_inl.h | 399 + .../nan/nan_implementation_pre_12_inl.h | 259 + .../node_modules/nan/nan_maybe_43_inl.h | 224 + .../node_modules/nan/nan_maybe_pre_43_inl.h | 295 + .../kerberos/node_modules/nan/nan_new.h | 332 + .../node_modules/nan/nan_object_wrap.h | 155 + .../node_modules/nan/nan_persistent_12_inl.h | 129 + .../nan/nan_persistent_pre_12_inl.h | 238 + .../node_modules/nan/nan_string_bytes.h | 305 + .../kerberos/node_modules/nan/nan_weak.h | 422 + .../kerberos/node_modules/nan/package.json | 92 + .../kerberos/node_modules/nan/tools/1to2.js | 412 + .../kerberos/node_modules/nan/tools/README.md | 14 + .../node_modules/nan/tools/package.json | 19 + .../node_modules/kerberos/package.json | 55 + .../kerberos/test/kerberos_tests.js | 34 + .../kerberos/test/kerberos_win32_test.js | 15 + .../win32/security_buffer_descriptor_tests.js | 41 + .../test/win32/security_buffer_tests.js | 22 + .../test/win32/security_credentials_tests.js | 55 + .../node_modules/mongodb-core/package.json | 66 + .../simple_2_document_limit_toArray.dat | 11000 +++++++++++++++ .../node_modules/readable-stream/.npmignore | 5 + .../node_modules/readable-stream/LICENSE | 27 + .../node_modules/readable-stream/README.md | 15 + .../node_modules/readable-stream/duplex.js | 1 + .../readable-stream/lib/_stream_duplex.js | 89 + .../lib/_stream_passthrough.js | 46 + .../readable-stream/lib/_stream_readable.js | 982 ++ .../readable-stream/lib/_stream_transform.js | 210 + .../readable-stream/lib/_stream_writable.js | 386 + .../node_modules/core-util-is/README.md | 3 + .../node_modules/core-util-is/float.patch | 604 + .../node_modules/core-util-is/lib/util.js | 107 + .../node_modules/core-util-is/package.json | 53 + .../node_modules/core-util-is/util.js | 106 + .../node_modules/inherits/LICENSE | 16 + .../node_modules/inherits/README.md | 42 + .../node_modules/inherits/inherits.js | 1 + .../node_modules/inherits/inherits_browser.js | 23 + .../node_modules/inherits/package.json | 50 + .../node_modules/inherits/test.js | 25 + .../node_modules/isarray/README.md | 54 + .../node_modules/isarray/build/build.js | 209 + .../node_modules/isarray/component.json | 19 + .../node_modules/isarray/index.js | 3 + .../node_modules/isarray/package.json | 53 + .../node_modules/string_decoder/.npmignore | 2 + .../node_modules/string_decoder/LICENSE | 20 + .../node_modules/string_decoder/README.md | 7 + .../node_modules/string_decoder/index.js | 221 + .../node_modules/string_decoder/package.json | 54 + .../node_modules/readable-stream/package.json | 69 + .../readable-stream/passthrough.js | 1 + .../node_modules/readable-stream/readable.js | 6 + .../node_modules/readable-stream/transform.js | 1 + .../node_modules/readable-stream/writable.js | 1 + .../node_modules/mongodb/package.json | 66 + .../node_modules/mongodb/t.js | 73 + .../node_modules/mongodb/t1.js | 77 + .../node_modules/mongodb/wercker.yml | 19 + util/demographicsImporter/package.json | 15 + 264 files changed, 93472 insertions(+) create mode 100644 util/demographicsImporter/demographicsImporter.js create mode 100644 util/demographicsImporter/node_modules/mongodb/HISTORY.md create mode 100644 util/demographicsImporter/node_modules/mongodb/LICENSE create mode 100644 util/demographicsImporter/node_modules/mongodb/Makefile create mode 100644 util/demographicsImporter/node_modules/mongodb/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/c.js create mode 100644 util/demographicsImporter/node_modules/mongodb/conf.json create mode 100644 util/demographicsImporter/node_modules/mongodb/index.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/admin.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/aggregation_cursor.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/apm.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/bulk/common.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/bulk/ordered.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/bulk/unordered.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/collection.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/command_cursor.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/cursor.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/db.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/gridfs/chunk.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/gridfs/grid_store.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/metadata.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/mongo_client.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/mongos.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/read_preference.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/replset.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/server.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/topology_base.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/url_parser.js create mode 100644 util/demographicsImporter/node_modules/mongodb/lib/utils.js create mode 100644 util/demographicsImporter/node_modules/mongodb/load.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/browserify.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/index.html create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/index.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Makefile create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d create mode 100755 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node create mode 100755 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos.node create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml create mode 100755 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/asyncworker.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/buffers.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/callback.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/converters.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/errors.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/maybe_types.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/methods.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/new.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/node_misc.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/persistent.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/scopes.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/script.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/string_bytes.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/v8_internals.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/v8_misc.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/include_dirs.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks_12_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks_pre_12_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters_43_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters_pre_43_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_maybe_43_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_maybe_pre_43_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_new.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_object_wrap.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_persistent_12_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_persistent_pre_12_inl.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_string_bytes.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_weak.h create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/package.json create mode 100755 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/1to2.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/readable.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/transform.js create mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/writable.js create mode 100644 util/demographicsImporter/node_modules/mongodb/package.json create mode 100644 util/demographicsImporter/node_modules/mongodb/t.js create mode 100644 util/demographicsImporter/node_modules/mongodb/t1.js create mode 100644 util/demographicsImporter/node_modules/mongodb/wercker.yml create mode 100644 util/demographicsImporter/package.json diff --git a/util/demographicsImporter/demographicsImporter.js b/util/demographicsImporter/demographicsImporter.js new file mode 100644 index 0000000..086b3f7 --- /dev/null +++ b/util/demographicsImporter/demographicsImporter.js @@ -0,0 +1,175 @@ +// Retrieve +var MongoClient = require('mongodb').MongoClient; +var util = require('util'); + +var preconditions = true; + +if(process.env.QUERY_TITLE === null || process.env.QUERY_TITLE === undefined) +{ + console.log('ERROR: QUERY_TITLE environment variable not set.'); +} +else +{ + console.log('QUERY_TITLE: ' + process.env.QUERY_TITLE); +} + + +if(process.env.RETRO_QUERY_TITLE === null || process.env.RETRO_QUERY_TITLE === undefined) +{ + console.log('ERROR: RETRO_QUERY_TITLE environment variable not set.'); +} +else +{ + console.log('RETRO_QUERY_TITLE: ' + process.env.RETRO_QUERY_TITLE); +} +// Connect to the db +MongoClient.connect('mongodb://localhost:27017/query_composer_development', function(err, db) { + if(err) { return console.dir(err); } + + db.collection('queries', null, + function(err, queriesCollection) + { + if(err) { throw err; } + + //fetch the retro query excution + //**************************************************************************** + queriesCollection.find({title:process.env.RETRO_QUERY_TITLE}).toArray( + function(err, retroQueries) + { + if(err) { throw err; } + + if(retroQueries.length != 1) + { + throw new Error('Not one and only one retro query: ' + process.env.RETRO_QUERY_TITLE); + } + + var retroQuery = retroQueries[0]; + + if(retroQuery.executions.length != 1) + { + throw new Error('Not one and only one execution for retro query: ' + process.env.RETRO_QUERY_TITLE); + } + + retroQuery.executions = retroQuery.executions.sort( + function(a,b) + { + return a.time > b.time ? 1 : b.time > a.time ? -1 : 0; + } + ); + + var retroQueryExecution = retroQuery.executions[0]; + + //**************************************************************************** + + //fetch query executions + //**************************************************************************** + var queries = queriesCollection.find({title:process.env.QUERY_TITLE}).toArray( + function(err, queries) + { + if(err) { throw err; } + + if(queries.length != 1) + { + throw new Error('Not one and only one query: ' + process.env.QUERY_TITLE); + } + + var query = queries[0]; + + var queryExecutions = query.executions; + //**************************************************************************** + + //fetch retro retroResults + //**************************************************************************** + var retroResults = retroQueryExecution.aggregate_result; + //**************************************************************************** + + //build simulated executions + //**************************************************************************** + var simulatedExecutions = {}; + + for( var key in retroResults) + { + if( !retroResults.hasOwnProperty(key)) + { + continue; + } + + var execution = JSON.parse(key); + + var date = execution.date/1000;//leave in milliseconds + var simulatedExecution; + + if(!execution.gender || !execution.age || !execution.pid || !execution.date) + { + throw new Error('Error: Missing field'); + } + + var ar_key = execution.gender + '_' + + execution.age + '_' + + execution.pid; + + if(!simulatedExecutions[date]) + { + var aggregate_result = {}; + aggregate_result[ar_key] = retroResults[key]; + simulatedExecution = {'_id':retroQueryExecution._id, + 'aggregate_result':aggregate_result, + 'notification':null, + 'time':date, + 'simulated':true + }; + simulatedExecutions[date] = simulatedExecution; + } + else + { + simulatedExecution = simulatedExecutions[date]; + simulatedExecution.aggregate_result[ar_key] = retroResults[key]; + } + } + //**************************************************************************** + + //add the simulated executions to the execution List + //**************************************************************************** + for( var se in simulatedExecutions) + { + if( !simulatedExecutions.hasOwnProperty(se)) + { + continue; + } + + queryExecutions.push( simulatedExecutions[se] ); + } + //**************************************************************************** + + //update the query with the retro results + //**************************************************************************** + + queriesCollection.updateOne({title:process.env.QUERY_TITLE}, {$set:{executions:queryExecutions}}, {upsert:true}, + function(err, result) + { + if(err) + { + throw new Error(err); + } + + db.close( + function(err, result) + { + if(err) + { + console.log('ERROR: closing db - ' + error); + } + else + { + console.log('SUCCESS'); + } + }); + }); + + //**************************************************************************** + }); + + }); + } + ); +}); diff --git a/util/demographicsImporter/node_modules/mongodb/HISTORY.md b/util/demographicsImporter/node_modules/mongodb/HISTORY.md new file mode 100644 index 0000000..4d8fd75 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/HISTORY.md @@ -0,0 +1,1218 @@ +2.0.45 09-30-2015 +----------------- +* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. + +2.0.44 09-28-2015 +----------------- +* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. +* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. +* Updated mongodb-core to 1.2.14. +* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. +* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) +* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. +* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. +* NODE-572 Remove examples that use the second parameter to `find()`. + +2.0.43 09-14-2015 +----------------- +* Propagate timeout event correctly to db instances. +* Application Monitoring API (APM) implemented. +* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. +* Updated mongodb-core to 1.2.12. +* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. +* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) +* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) +* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) + +2.0.42 08-18-2015 +----------------- +* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. + +2.0.41 08-14-2015 +----------------- +* Added missing Mongos.prototype.parserType function. +* Updated mongodb-core to 1.2.10. + +2.0.40 07-14-2015 +----------------- +* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. +* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +* NODE-518 connectTimeoutMS is doubled in 2.0.39. +* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). +* NODE-526 Unique index not throwing duplicate key error. +* NODE-528 Ignore undefined fields in Collection.find(). +* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. + +2.0.39 07-14-2015 +----------------- +* Updated mongodb-core to 1.2.6 for NODE-505. + +2.0.38 07-14-2015 +----------------- +* NODE-505 Query fails to find records that have a 'result' property with an array value. + +2.0.37 07-14-2015 +----------------- +* NODE-504 Collection * Default options when using promiseLibrary. +* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. +* Updated mongodb-core to 1.2.5 to fix NODE-492. + +2.0.36 07-07-2015 +----------------- +* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). +* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. + +2.0.35 06-17-2015 +----------------- +* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. + +2.0.34 06-17-2015 +----------------- +* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. +* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. +* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +2.0.33 05-20-2015 +----------------- +* Bumped mongodb-core to 1.1.32. + +2.0.32 05-19-2015 +----------------- +* NODE-463 db.close immediately executes its callback. +* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). +* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. + +2.0.31 05-08-2015 +----------------- +* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. + +2.0.30 05-07-2015 +----------------- +* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. + +2.0.29 05-07-2015 +----------------- +* NODE-444 Possible memory leak, too many listeners added. +* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. +* Bumped mongodb-core to 1.1.26. + +2.0.28 04-24-2015 +----------------- +* Bumped mongodb-core to 1.1.25 +* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. +* NODE-430 Cursor.count() opts argument masked by var opts = {} +* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. +* NODE-438 replaceOne is not returning the result.ops property as described in the docs. +* NODE-433 _read, pipe and write all open gridstore automatically if not open. +* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. +* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. +* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). +* Minor fix in GridStore.exists for dealing with regular expressions searches. + +2.0.27 04-07-2015 +----------------- +* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. + +2.0.26 04-07-2015 +----------------- +* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. +* NODE-408 Expose GridStore.currentChunk.chunkNumber. + +2.0.25 03-26-2015 +----------------- +* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. + +2.0.24 03-24-2015 +----------------- +* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. +* Upgraded mongodb-core to 1.1.20. + +2.0.23 2015-03-21 +----------------- +* NODE-380 Correctly return MongoError from toError method. +* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. +* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. +* Upgraded mongodb-core to 1.1.19. + +2.0.22 2015-03-16 +----------------- +* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. +* Upgraded mongodb-core to 1.1.17. + +2.0.21 2015-03-06 +----------------- +* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. + +2.0.20 2015-03-04 +----------------- +* Updated mongodb-core 1.1.15 to relax pickserver method. + +2.0.19 2015-03-03 +----------------- +* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) +* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) +* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) + +2.0.18 2015-02-27 +----------------- +* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. + +2.0.17 2015-02-27 +----------------- +* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. +* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. + +2.0.16 2015-02-16 +----------------- +* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. +* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. +* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) + +2.0.15 2015-02-02 +----------------- +* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. +* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. +* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. +* Added ~1.0 mongodb-tools module for test running. +* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +2.0.14 2015-01-21 +----------------- +* Fixed some MongoClient.connect options pass through issues and added test coverage. +* Bumped mongodb-core to 1.1.9 including fixes for io.js + +2.0.13 2015-01-09 +----------------- +* Bumped mongodb-core to 1.1.8. +* Optimized query path for performance, moving Object.defineProperty outside of constructors. + +2.0.12 2014-12-22 +----------------- +* Minor fixes to listCollections to ensure correct querying of a collection when using a string. + +2.0.11 2014-12-19 +----------------- +* listCollections filters out index namespaces on < 2.8 correctly +* Bumped mongo-client to 1.1.7 + +2.0.10 2014-12-18 +----------------- +* NODE-328 fixed db.open return when no callback available issue and added test. +* NODE-327 Refactored listCollections to return cursor to support 2.8. +* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. +* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. +* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) +* Bumped mongo-client to 1.1.6 + +2.0.9 2014-12-01 +---------------- +* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. +* All classes are now strict (Issue #1233) +* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. +* Fixed recursion issues in debug logging due to JSON.stringify() +* Documentation fixes (Issue #1232, https://github.com/wsmoak) +* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) + +2.0.8 2014-11-28 +---------------- +* NODE-322 Finished up prototype refactoring of Db class. +* NODE-322 Exposed Cursor in index.js for New Relic. + +2.0.7 2014-11-20 +---------------- +* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. +* NODE-318 collection.update error while setting a function with serializeFunctions option. +* Documentation fixes. + +2.0.6 2014-11-14 +---------------- +* Refactored code to be prototype based instead of privileged methods. +* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. +* Implemented missing aspects of the CRUD specification. +* Fixed documentation issues. +* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) +* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) + +2.0.5 2014-10-29 +---------------- +* Minor fixes to documentation and generation of documentation. +* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. + +2.0.4 2014-10-23 +---------------- +* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) +* Made each rewind on each call allowing for re-using the cursor. +* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. +* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. + +2.0.3 2014-10-14 +---------------- +* NODE-297 Aggregate Broken for case of pipeline with no options. + +2.0.2 2014-10-08 +---------------- +* Bumped mongodb-core to 1.0.2. +* Fixed bson module dependency issue by relying on the mongodb-core one. +* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) + +2.0.1 2014-10-07 +---------------- +* Dependency fix + +2.0.0 2014-10-07 +---------------- +* First release of 2.0 driver + +2.0.0-alpha2 2014-10-02 +----------------------- +* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) +* Cluster Management Spec compatible. + +2.0.0-alpha1 2014-09-08 +----------------------- +* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode +* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package +* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node +* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) + * Might break some application +* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove +* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) +* Removed Grid class +* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data + + seek will fail if attempt to use with w or w+ + + write will fail if attempted with w+ or r + + w+ only works for updating metadata on a file +* Cursor toArray and each resets and re-runs the cursor +* FindAndModify returns whole result document instead of just value +* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find +* Removed db.dereference method +* Removed db.cursorInfo method +* Removed db.stats method +* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections +* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. +* Added db.listCollections to replace several methods above + +1.4.10 2014-09-04 +----------------- +* Fixed BSON and Kerberos compilation issues +* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series +* Fixed Kerberos and bumped to 0.0.4 + +1.4.9 2014-08-26 +---------------- +* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) +* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) +* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) +* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) +* NODE-240 Operations on SSL connection hang on node 0.11.x +* NODE-235 writeResult is not being passed on when error occurs in insert +* NODE-229 Allow count to work with query hints +* NODE-233 collection.save() does not support fullResult +* NODE-244 Should parseError also emit a `disconnected` event? +* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. +* NODE-248 Crash with X509 auth +* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks +* Bumped BSON parser to 0.2.12 + + +1.4.8 2014-08-01 +---------------- +* NODE-205 correctly emit authenticate event +* NODE-210 ensure no undefined connection error when checking server state +* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones +* NODE-220 don't throw error if ensureIndex errors out in Gridstore +* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes +* Fixed test running filters +* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) +* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) +* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) +* Fixed parsing issue for w:0 in url parser when in connection string +* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) + +1.4.7 2014-06-18 +---------------- +* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) +* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) + +1.4.6 2014-06-12 +---------------- +* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) +* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) +* Added missing type check before calling optional callback function (Issue #1180) + +1.4.5 2014-05-21 +---------------- +* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. +* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. +* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) + +1.4.4 2014-05-13 +---------------- +* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID +* Removed leaking global variable (Issue #1174, https://github.com/dainis) +* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) +* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) + +1.4.3 2014-05-01 +---------------- +* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) +* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) +* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) +* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) +* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) +* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) + +1.4.2 2014-04-15 +---------------- +* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 +* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) +* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) +* Fixed global variable leak (Issue #1160, https://github.com/vaseker) + +1.4.1 2014-04-09 +---------------- +* Correctly emit joined event when primary change +* Add _id to documents correctly when using bulk operations + +1.4.0 2014-04-03 +---------------- +* All node exceptions will no longer be caught if on('error') is defined +* Added X509 auth support +* Fix for MongoClient connection timeout issue (NODE-97) +* Pass through error messages from parseError instead of just text (Issue #1125) +* Close db connection on error (Issue #1128, https://github.com/benighted) +* Fixed documentation generation +* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) +* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 +* Insert/Update/Remove using new write commands when available +* Added support for new roles based API's in 2.6 for addUser/removeUser +* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries +* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes +* Support for OP_LOG_REPLAY flag (NODE-94) +* Fixes for SSL HA ping and discovery. +* Uses createIndexes if available for ensureIndex/createIndex +* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors +* Made CommandCursor behave as Readable stream. +* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. +* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. +* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) +* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. +* Refactored commands to all go through command function ensuring consistent command execution. +* Fixed issues where readPreferences where not correctly passed to mongos. +* Catch error == null and make err detection more prominent (NODE-130) +* Allow reads from arbiter for single server connection (NODE-117) +* Handle error coming back with no documents (NODE-130) +* Correctly use close parameter in Gridstore.write() (NODE-125) +* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) +* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) +* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) +* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) +* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) +* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) +* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) +* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) +* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) +* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) +* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) + +1.3.19 2013-08-21 +----------------- +* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. +* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) +* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) + +1.3.18 2013-08-10 +----------------- +* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) +* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. + +1.3.17 2013-08-07 +----------------- +* Ignore return commands that have no registered callback +* Made collection.count not use the db.command function +* Fix throw exception on ping command (Issue #1055) + +1.3.16 2013-08-02 +----------------- +* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) +* Bug in unlink mulit filename (Issue #1054) + +1.3.15 2013-08-01 +----------------- +* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time + +1.3.14 2013-08-01 +----------------- +* Fixed issue with checkKeys where it would error on X.X + +1.3.13 2013-07-31 +----------------- +* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) +* BSON size checking now done pre serialization (Issue #1037) +* Added isConnected returns false when no connection Pool exists (Issue #1043) +* Unified command handling to ensure same handling (Issue #1041, #1042) +* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) +* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. +* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. +* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. +* Fixed issue with Kerberos authentication on Windows for re-authentication. +* Fixed Mongos failover behavior to correctly throw out old servers. +* Ensure stored queries/write ops are executed correctly after connection timeout +* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. + +1.3.12 2013-07-19 +----------------- +* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) +* Fixed bug with callback third parameter on some commands (Issue #1033) +* Fixed possible issue where killcursor command might leave hanging functions +* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers +* Throw error if dbName or collection name contains null character (at command level and at collection level) +* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) + +1.3.11 2013-07-04 +----------------- +* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) +* Add driver version to export (Issue #1021, https://github.com/aheckmann) +* Add text to readpreference obedient commands (Issue #1019) +* Drivers should check the query failure bit even on getmore response (Issue #1018) +* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) +* Support SASL PLAIN authentication (Issue #1009) +* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) +* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) +* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) + +1.3.10 2013-06-17 +----------------- +* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) +* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) +* Introduced write and read concerns for GridFS (Issue #996) +* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) +* Fixed issue with pool size on replicaset connections (Issue #1000) +* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) + +1.3.9 2013-06-05 +---------------- +* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. + +1.3.8 2013-05-31 +---------------- +* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) +* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) +* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. + +1.3.7 2013-05-29 +---------------- +* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) +* Updated Bson to 0.1.9 to fix ARM support (Issue #985) + +1.3.6 2013-05-21 +---------------- +* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) +* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) + +1.3.5 2013-05-14 +---------------- +* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. + +1.3.4 2013-05-14 +---------------- +* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) +* Fixed bug when passing a named index hint (Issue #974) + +1.3.3 2013-05-09 +---------------- +* Fixed auto-reconnect issue with single server instance. + +1.3.2 2013-05-08 +---------------- +* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. + +1.3.1 2013-05-06 +---------------- +* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly +* Applied auth before server instance is set as connected when single server connection +* Throw error if array of documents passed to save method + +1.3.0 2013-04-25 +---------------- +* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. +* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) +* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) +* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) +* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition +* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) + +1.2.14 2013-03-14 +----------------- +* Refactored test suite to speed up running of replicaset tests +* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) +* Corrected a slaveOk setting issue (Issue #906, #905) +* Fixed HA issue where ping's would not go to correct server on HA server connection failure. +* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream +* Fixed race condition in Cursor stream (NODE-31) +* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 +* Added support for maxMessageSizeBytes if available (DRIVERS-1) +* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) +* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) + +1.2.13 2013-02-22 +----------------- +* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) +* Fixed missing MongoErrors on some cursor methods (Issue #882) +* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) +* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) +* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) + +1.2.12 2013-02-13 +----------------- +* Added limit/skip options to Collection.count (Issue #870) +* Added applySkipLimit option to Cursor.count (Issue #870) +* Enabled ping strategy as default for Replicaset if none specified (Issue #876) +* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) + +1.2.11 2013-01-29 +----------------- +* Added fixes for handling type 2 binary due to PHP driver (Issue #864) +* Moved callBackStore to Base class to have single unified store (Issue #866) +* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead + +1.2.10 2013-01-25 +----------------- +* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. +* Only open a new HA socket when previous one dead (Issue #859, #857) +* Minor fixes + +1.2.9 2013-01-15 +---------------- +* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) +* Connection string with no db specified should default to admin db (Issue #848) +* Support port passed as string to Server class (Issue #844) +* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) +* Included toError wrapper code moved to utils.js file (Issue #839, #840) +* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% + +1.2.8 2013-01-07 +---------------- +* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) +* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) +* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) +* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) +* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) +* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) +* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) +* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) + +1.2.7 2012-12-23 +---------------- +* Rolled back batches as they hang in certain situations +* Fixes for NODE-25, keep reading from secondaries when primary goes down + +1.2.6 2012-12-21 +---------------- +* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) +* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) +* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) +* Cursor readPreference bug for non-supported read preferences (Issue #817) + +1.2.5 2012-12-12 +---------------- +* Fixed ssl regression, added more test coverage (Issue #800) +* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) + +1.2.4 2012-12-11 +---------------- +* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. + +1.2.3 2012-12-10 +---------------- +* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) +* Fixed seek issue in gridstore when using stream (Issue #790) + +1.2.2 2012-12-03 +---------------- +* Fix for journal write concern not correctly being passed under some circumstances. +* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). + +1.2.1 2012-11-30 +---------------- +* Fix for double callback on insert with w:0 specified (Issue #783) +* Small cleanup of urlparser. + +1.2.0 2012-11-27 +---------------- +* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) +* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) +* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) +* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) +* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) +* Force correct setting of read_secondary based on the read preference (Issue #741) +* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) +* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type +* Mongos connection with auth not working (Issue #737) +* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") +* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db + * open/close/db/connect methods implemented +* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. +* Fixed a bug with aggregation helper not properly accepting readPreference + +1.1.11 2012-10-10 +----------------- +* Removed strict mode and introduced normal handling of safe at DB level. + +1.1.10 2012-10-08 +----------------- +* fix Admin.serverStatus (Issue #723, https://github.com/Contra) +* logging on connection open/close(Issue #721, https://github.com/asiletto) +* more fixes for windows bson install (Issue #724) + +1.1.9 2012-10-05 +---------------- +* Updated bson to 0.1.5 to fix build problem on sunos/windows. + +1.1.8 2012-10-01 +---------------- +* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) +* Cleanup of non-closing connections (Issue #706) +* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) +* Set keepalive on as default, override if not needed +* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) +* Added domain socket support new Server("/tmp/mongodb.sock") style + +1.1.7 2012-09-10 +---------------- +* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) +* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) +* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) +* Proper stopping of strategy on replicaset stop +* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) +* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) + +1.1.6 2012-09-01 +---------------- +* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) +* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) + +1.1.5 2012-08-29 +---------------- +* Fix for eval on replicaset Issue #684 +* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) +* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) +* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X +* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes +* Added exhaust option for find for feature completion (not recommended for normal use) +* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval +* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) + +1.1.4 2012-08-12 +---------------- +* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. +* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. +* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). +* Fix gridfs readstream (Issue #607, https://github.com/tedeh). +* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). +* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). +* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). +* Cleanup map reduce (Issue #614, https://github.com/aheckmann). +* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). +* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. +* Date identification handled correctly in bson js parser when running in vm context. +* Documentation updates +* GridStore filename not set on read (Issue #621) +* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls +* Added support for awaitdata for tailable cursors (Issue #624) +* Implementing read preference setting at collection and cursor level + * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) + * db.collection("some", {readPreference:Server.SECONDARY}) +* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. + * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to +* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) +* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 +* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) +* Fixed auth to work better when multiple connections are involved. +* Default connection pool size increased to 5 connections. +* Fixes for the ReadStream class to work properly with 0.8 of Node.js +* Added explain function support to aggregation helper +* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js +* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required +* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) +* Fixed Always emit db events (Issue #657) +* Close event not correctly resets DB openCalled variable to allow reconnect +* Added open event on connection established for replicaset, mongos and server +* Much faster BSON C++ parser thanks to Lucasfilm Singapore. +* Refactoring of replicaset connection logic to simplify the code. +* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) +* Minor optimization for findAndModify when not using j,w or fsync for safe + +1.0.2 2012-05-15 +---------------- +* Reconnect functionality for replicaset fix for mongodb 2.0.5 + +1.0.1 2012-05-12 +---------------- +* Passing back getLastError object as 3rd parameter on findAndModify command. +* Fixed a bunch of performance regressions in objectId and cursor. +* Fixed issue #600 allowing for single document delete to be passed in remove command. + +1.0.0 2012-04-25 +---------------- +* Fixes to handling of failover on server error +* Only emits error messages if there are error listeners to avoid uncaught events +* Server.isConnected using the server state variable not the connection pool state + +0.9.9.8 2012-04-12 +------------------ +* _id=0 is being turned into an ObjectID (Issue #551) +* fix for error in GridStore write method (Issue #559) +* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) +* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) +* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) +* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) +* Connection pools handles closing themselves down and clearing the state +* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) +* Returning update status document at the end of the callback for updates, (Issue #569) +* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) + +0.9.9.7 2012-03-16 +------------------ +* Stats not returned from map reduce with inline results (Issue #542) +* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) +* Streaming large files from GridFS causes truncation (Issue #540) +* Make callback type checks agnostic to V8 context boundaries (Issue #545) +* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback +* Db.open throws if the application attemps to call open again without calling close first + +0.9.9.6 2012-03-12 +------------------ +* BSON parser is externalized in it's own repository, currently using git master +* Fixes for Replicaset connectivity issue (Issue #537) +* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) +* Removed SimpleEmitter and replaced with standard EventEmitter +* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) + +0.9.9.5 2012-03-07 +------------------ +* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) +* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) +* Fixed memory leak in C++ bson parser (Issue #526) +* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) +* Cannot save files with the same file name to GridFS (Issue #531) + +0.9.9.4 2012-02-26 +------------------ +* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) + +0.9.9.3 2012-02-23 +------------------ +* document: save callback arguments are both undefined, (Issue #518) +* Native BSON parser install error with npm, (Issue #517) + +0.9.9.2 2012-02-17 +------------------ +* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. +* Added wrap error around db.dropDatabase to catch all errors (Issue #512) +* Added aggregate helper to collection, only for MongoDB >= 2.1 + +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + +0.9.9 2012-02-13 +---------------- +* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. +* Db.close(true) now makes connection unusable as it's been force closed by app. +* Fixed mapReduce and group functions to correctly send slaveOk on queries. +* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). +* A fix for connection error handling when using the SSL on MongoDB. + +0.9.8-7 2012-02-06 +------------------ +* Simplified findOne to use the find command instead of the custom code (Issue #498). +* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). + +0.9.8-6 2012-02-04 +------------------ +* Removed the check for replicaset change code as it will never work with node.js. + +0.9.8-5 2012-02-02 +------------------ +* Added geoNear command to Collection. +* Added geoHaystackSearch command to Collection. +* Added indexes command to collection to retrieve the indexes on a Collection. +* Added stats command to collection to retrieve the statistics on a Collection. +* Added listDatabases command to admin object to allow retrieval of all available dbs. +* Changed createCreateIndexCommand to work better with options. +* Fixed dereference method on Db class to correctly dereference Db reference objects. +* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. +* Removed writeBuffer method from gridstore, write handles switching automatically now. +* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. +* Moved Long class to bson directory. + +0.9.8-4 2012-01-28 +------------------ +* Added reIndex command to collection and db level. +* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. +* Added dropDups and v option to createIndex and ensureIndex. +* Added isCapped method to Collection. +* Added indexExists method to Collection. +* Added findAndRemove method to Collection. +* Fixed bug for replicaset connection when no active servers in the set. +* Fixed bug for replicaset connections when errors occur during connection. +* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. + +0.9.8-3 2012-01-21 +------------------ +* Workaround for issue with Object.defineProperty (Issue #484) +* ObjectID generation with date does not set rest of fields to zero (Issue #482) + +0.9.8-2 2012-01-20 +------------------ +* Fixed a missing this in the ReplSetServers constructor. + +0.9.8-1 2012-01-17 +------------------ +* FindAndModify bug fix for duplicate errors (Issue #481) + +0.9.8 2012-01-17 +---------------- +* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. + * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) +* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh +* Removed duplicate code for formattedOrderClause and moved to utils module +* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members +* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations +* Correct handling of illegal BSON messages during deserialization +* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) +* Correctly update existing user password when using addUser (Issue #470) + +0.9.7.3-5 2012-01-04 +-------------------- +* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' +* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors + +0.9.7.3-4 2012-01-04 +-------------------- +* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) +* Sanity checks for GridFS performance with benchmark added + +0.9.7.3-3 2012-01-04 +-------------------- +* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux +* BSON bug fixes for performance + +0.9.7.3-2 2012-01-02 +-------------------- +* Fixed up documentation to reflect the preferred way of instantiating bson types +* GC bug fix for JS bson parser to avoid stop-and-go GC collection + +0.9.7.3-1 2012-01-02 +-------------------- +* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously + +0.9.7.3 2011-12-30 +-------------------- +* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes +* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) +* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 +* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) +* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) + +0.9.7.2-5 2011-12-22 +-------------------- +* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann + +0.9.7.2-4 2011-12-21 +-------------------- +* Refactoring of callback code to work around performance regression on linux +* Fixed group function to correctly use the command mode as default + +0.9.7.2-3 2011-12-18 +-------------------- +* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). +* Allow for force send query to primary, pass option (read:'primary') on find command. + * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` + +0.9.7.2-2 2011-12-16 +-------------------- +* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) + +0.9.7.2-1 2011-12-16 +-------------------- +* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) +* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver +* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents + +0.9.7.2 2011-12-15 +------------------ +* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) + * pass in the ssl:true option to the server or replicaset server config to enable + * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). +* Added getTimestamp() method to objectID that returns a date object +* Added finalize function to collection.group + * function group (keys, condition, initial, reduce, finalize, command, callback) +* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. + * reaperInterval, set interval for reaper (default 10000 miliseconds) + * reaperTimeout, set timeout for calls (default 30000 miliseconds) + * reaper, enable/disable reaper (default false) +* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb +* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close +* EnsureIndex command can be executed without a callback (Issue #438) +* Eval function no accepts options including nolock (Issue #432) + * eval(code, parameters, options, callback) (where options = {nolock:true}) + +0.9.7.1-4 2011-11-27 +-------------------- +* Replaced install.sh with install.js to install correctly on all supported os's + +0.9.7.1-3 2011-11-27 +-------------------- +* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch + +0.9.7.1-2 2011-11-27 +-------------------- +* Set statistical selection strategy as default for secondary choice. + +0.9.7.1-1 2011-11-27 +-------------------- +* Better handling of single server reconnect (fixes some bugs) +* Better test coverage of single server failure +* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect + +0.9.7.1 2011-11-24 +------------------ +* Better handling of dead server for single server instances +* FindOne and find treats selector == null as {}, Issue #403 +* Possible to pass in a strategy for the replicaset to pick secondary reader node + * parameter strategy + * ping (default), pings the servers and picks the one with the lowest ping time + * statistical, measures each request and pick the one with the lowest mean and std deviation +* Set replicaset read preference replicaset.setReadPreference() + * Server.READ_PRIMARY (use primary server for reads) + * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) + * tags, {object of tags} +* Added replay of commands issued to a closed connection when the connection is re-established +* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) +* Moved reaper to db.open instead of constructor (Issue #406) +* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions + * timeout = set seconds before connection times out (default 0) + * noDelay = Disables the Nagle algorithm (default true) + * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) + * encoding = ['ascii', 'utf8', or 'base64'] (default null) +* Fixes for handling of errors during shutdown off a socket connection +* Correctly applies socket options including timeout +* Cleanup of test management code to close connections correctly +* Handle parser errors better, closing down the connection and emitting an error +* Correctly emit errors from server.js only wrapping errors that are strings + +0.9.7 2011-11-10 +---------------- +* Added priority setting to replicaset manager +* Added correct handling of passive servers in replicaset +* Reworked socket code for simpler clearer handling +* Correct handling of connections in test helpers +* Added control of retries on failure + * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance +* Added reaper that will timeout and cleanup queries that never return + * control with parameters reaperInterval and reaperTimeout when creating a db instance +* Refactored test helper classes for replicaset tests +* Allows raw (no bson parser mode for insert, update, remove, find and findOne) + * control raw mode passing in option raw:true on the commands + * will return buffers with the binary bson objects +* Fixed memory leak in cursor.toArray +* Fixed bug in command creation for mongodb server with wrong scope of call +* Added db(dbName) method to db.js to allow for reuse of connections against other databases +* Serialization of functions in an object is off by default, override with parameter + * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify +* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) +* FindOne and find now share same code execution and will work in the same manner, Issue #399 +* Fix for tailable cursors, Issue #384 +* Fix for Cursor rewind broken, Issue #389 +* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) +* Updated documentation on https://github.com/christkv/node-mongodb-native +* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data + +0.9.6-22 2011-10-15 +------------------- +* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 +* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 + +0.9.6-21 2011-10-05 +------------------- +* Reworked reconnect code to work correctly +* Handling errors in different parts of the code to ensure that it does not lock the connection +* Consistent error handling for Object.createFromHexString for JS and C++ + +0.9.6-20 2011-10-04 +------------------- +* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc +* Reworked bson.cc to throw error when trying to serialize js bson types +* Added MinKey, MaxKey and Double support for JS and C++ parser +* Reworked socket handling code to emit errors on unparsable messages +* Added logger option for Db class, lets you pass in a function in the shape + { + log : function(message, object) {}, + error : function(errorMessage, errorObject) {}, + debug : function(debugMessage, object) {}, + } + + Usage is new Db(new Server(..), {logger: loggerInstance}) + +0.9.6-19 2011-09-29 +------------------- +* Fixing compatibility issues between C++ bson parser and js parser +* Added Symbol support to C++ parser +* Fixed socket handling bug for seldom misaligned message from mongodb +* Correctly handles serialization of functions using the C++ bson parser + +0.9.6-18 2011-09-22 +------------------- +* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 + +0.9.6-17 2011-09-21 +------------------- +* Fixed broken exception test causing bamboo to hang +* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 + +0.9.6-16 2011-09-14 +------------------- +* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. +* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 + +0.9.6-15 2011-09-09 +------------------- +* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 +* Fixed authentication issue with secondary servers in Replicaset, Issue #334 +* Duplicate replica-set servers when omitting port, Issue #341 +* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 +* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks + +0.9.6-14 2011-09-05 +------------------- +* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 +* Minor doc fixes +* Some more cursor sort tests added, Issue #333 +* Fixes to work with 0.5.X branch +* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 +* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 +* Implement correct safe/strict mode for findAndModify. + +0.9.6-13 2011-08-24 +------------------- +* Db names correctly error checked for illegal characters + +0.9.6-12 2011-08-24 +------------------- +* Nasty bug in GridFS if you changed the default chunk size +* Fixed error handling bug in findOne + +0.9.6-11 2011-08-23 +------------------- +* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) +* Fixes for memory leaks when using buffers and C++ parser +* Fixes to make tests pass on 0.5.X +* Cleanup of bson.js to remove duplicated code paths +* Fix for errors occurring in ensureIndex, Issue #326 +* Removing require.paths to make tests work with the 0.5.X branch + +0.9.6-10 2011-08-11 +------------------- +* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 +* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 +* Implementing fixes for mongodb 1.9.1 and higher to make tests pass +* Admin validateCollection now takes an options argument for you to pass in full option +* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 +* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 + +0.9.6-9 +------- +* Bug fix for bson parsing the key '':'' correctly without crashing + +0.9.6-8 +------- +* Changed to using node.js crypto library MD5 digest +* Connect method support documented mongodb: syntax by (https://github.com/sethml) +* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 +* Code object without scope serializing to correct BSON type +* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 +* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) +* Fixed C++ parser to reflect JS parser handling of long deserialization +* Bson small optimizations + +0.9.6-7 2011-07-13 +------------------ +* JS Bson deserialization bug #287 + +0.9.6-6 2011-07-12 +------------------ +* FindAndModify not returning error message as other methods Issue #277 +* Added test coverage for $push, $pushAll and $inc atomic operations +* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 +* Fixed terrible deserialization bug in js bson code #285 +* Fix by andrewjstone to avoid throwing errors when this.primary not defined + +0.9.6-5 2011-07-06 +------------------ +* Rewritten BSON js parser now faster than the C parser on my core2duo laptop +* Added option full to indexInformation to get all index info Issue #265 +* Passing in ObjectID for new Gridstore works correctly Issue #272 + +0.9.6-4 2011-07-01 +------------------ +* Added test and bug fix for insert/update/remove without callback supplied + +0.9.6-3 2011-07-01 +------------------ +* Added simple grid class called Grid with put, get, delete methods +* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly +* Automatic handling of buffers when using write method on GridStore +* GridStore now accepts a ObjectID instead of file name for write and read methods +* GridStore.list accepts id option to return of file ids instead of filenames +* GridStore close method returns document for the file allowing user to reference _id field + +0.9.6-2 2011-06-30 +------------------ +* Fixes for reconnect logic for server object (replays auth correctly) +* More testcases for auth +* Fixes in error handling for replicaset +* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout +* Fixed slaveOk bug for findOne method +* Implemented auth support for replicaset and test cases +* Fixed error when not passing in rs_name + +0.9.6-1 2011-06-25 +------------------ +* Fixes for test to run properly using c++ bson parser +* Fixes for dbref in native parser (correctly handles ref without db component) +* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) +* Fixes for timestamp in js bson parser (distinct timestamp type now) + +0.9.6 2011-06-21 +---------------- +* Worked around npm version handling bug +* Race condition fix for cygwin (https://github.com/vincentcr) + +0.9.5-1 2011-06-21 +------------------ +* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems +* Fixed driver strict mode issue + +0.9.5 2011-06-20 +---------------- +* Replicaset support (failover and reading from secondary servers) +* Removed ServerPair and ServerCluster +* Added connection pool functionality +* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences +* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} + +0.6.8 +----- +* Removed multiple message concept from bson +* Changed db.open(db) to be db.open(err, db) + +0.1 2010-01-30 +-------------- +* Initial release support of driver using native node.js interface +* Supports gridfs specification +* Supports admin functionality diff --git a/util/demographicsImporter/node_modules/mongodb/LICENSE b/util/demographicsImporter/node_modules/mongodb/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/Makefile b/util/demographicsImporter/node_modules/mongodb/Makefile new file mode 100644 index 0000000..36e1202 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/util/demographicsImporter/node_modules/mongodb/README.md b/util/demographicsImporter/node_modules/mongodb/README.md new file mode 100644 index 0000000..2828713 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/README.md @@ -0,0 +1,322 @@ +[![NPM](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![NPM](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) + +[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.png)](http://travis-ci.org/mongodb/node-mongodb-native) + +[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +# Description + +The MongoDB driver is the high level part of the 2.0 or higher MongoDB driver and is meant for end users. + +## MongoDB Node.JS Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| api-doc | http://mongodb.github.io/node-mongodb-native/2.0/api/ | +| source | https://github.com/mongodb/node-mongodb-native | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login . +- Navigate to the NODE project . +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +QuickStart +========== +The quick start guide will show you how to setup a simple application using node.js and MongoDB. Its scope is only how to set up the driver and perform the simple crud operations. For more in depth coverage we encourage reading the tutorials. + +Create the package.json file +---------------------------- +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Enter the following command and answer the questions to create the initial structure for your new project + +``` +npm init +``` + +Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init` + +``` +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb": "~2.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +Connecting to MongoDB +--------------------- +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server and the database **myproject**. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + db.close(); +}); +``` + +Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console. + +Let's Add some code to show the different CRUD operations available. + +Inserting a Document +-------------------- +Let's create a function that will insert some documents for us. + +```js +var insertDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.insert([ + {a : 1}, {a : 2}, {a : 3} + ], function(err, result) { + assert.equal(err, null); + assert.equal(3, result.result.n); + assert.equal(3, result.ops.length); + console.log("Inserted 3 documents into the document collection"); + callback(result); + }); +} +``` + +The insert command will return a results object that contains several fields that might be useful. + +* **result** Contains the result document from MongoDB +* **ops** Contains the documents inserted with added **_id** fields +* **connection** Contains the connection used to perform the insert + +Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + db.close(); + }); +}); +``` + +We can now run the update **app.js** file. + +``` +node app.js +``` + +You should see the following output after running the **app.js** file. + +``` +Connected correctly to server +Inserted 3 documents into the document collection +``` + +Updating a document +------------------- +Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**. + +```js +var updateDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Update document where a is 2, set b equal to 1 + collection.update({ a : 2 } + , { $set: { b : 1 } }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Updated the document with the field a equal to 2"); + callback(result); + }); +} +``` + +The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + db.close(); + }); + }); +}); +``` + +Remove a document +----------------- +Next lets remove the document where the field **a** equals to **3**. + +```js +var removeDocument = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Insert some documents + collection.remove({ a : 3 }, function(err, result) { + assert.equal(err, null); + assert.equal(1, result.result.n); + console.log("Removed the document with the field a equal to 3"); + callback(result); + }); +} +``` + +This will remove the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient.connect** callback function. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + db.close(); + }); + }); + }); +}); +``` + +Finally let's retrieve all the documents using a simple find. + +Find All Documents +------------------ +We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query. + +```js +var findDocuments = function(db, callback) { + // Get the documents collection + var collection = db.collection('documents'); + // Find some documents + collection.find({}).toArray(function(err, docs) { + assert.equal(err, null); + assert.equal(2, docs.length); + console.log("Found the following records"); + console.dir(docs); + callback(docs); + }); +} +``` + +This query will return all the documents in the **documents** collection. Since we removed a document the total documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback. + +```js +var MongoClient = require('mongodb').MongoClient + , assert = require('assert'); + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + insertDocuments(db, function() { + updateDocument(db, function() { + removeDocument(db, function() { + findDocuments(db, function() { + db.close(); + }); + }); + }); + }); +}); +``` + +This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest. + +## Next Steps + + * [MongoDB Documentation](http://mongodb.org/) + * [Read about Schemas](http://learnmongodbthehardway.com/) + * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) diff --git a/util/demographicsImporter/node_modules/mongodb/c.js b/util/demographicsImporter/node_modules/mongodb/c.js new file mode 100644 index 0000000..5b6bc1e --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/c.js @@ -0,0 +1,24 @@ +var MongoClient = require('./').MongoClient; + +var index = 0; + +MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { + setInterval(function() { + db = db.db("index" + index, {noListener:true}); + var collection = db.collection("index" + index); + collection.insert({a:index}) + }, 1); +}); + +// var Server = require('./').Server, +// Db = require('./').Db, +// ReadPreference = require('./').ReadPreference; +// +// new Db('test', new Server('localhost', 31001), {readPreference: ReadPreference.SECONDARY}).open(function(err, db) { +// +// db.collection('test').find().toArray(function(err, docs) { +// console.dir(err) +// console.dir(docs) +// db.close(); +// }); +// }); diff --git a/util/demographicsImporter/node_modules/mongodb/conf.json b/util/demographicsImporter/node_modules/mongodb/conf.json new file mode 100644 index 0000000..15f3021 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/conf.json @@ -0,0 +1,69 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/functional/operation_example_tests.js", + "test/functional/operation_promises_example_tests.js", + "test/functional/operation_generators_example_tests.js", + "test/functional/authentication_tests.js", + "lib/admin.js", + "lib/collection.js", + "lib/cursor.js", + "lib/aggregation_cursor.js", + "lib/command_cursor.js", + "lib/db.js", + "lib/mongo_client.js", + "lib/mongos.js", + "lib/read_preference.js", + "lib/replset.js", + "lib/server.js", + "lib/bulk/common.js", + "lib/bulk/ordered.js", + "lib/bulk/unordered.js", + "lib/gridfs/grid_store.js", + "node_modules/mongodb-core/lib/error.js", + "node_modules/mongodb-core/lib/connection/logger.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} diff --git a/util/demographicsImporter/node_modules/mongodb/index.js b/util/demographicsImporter/node_modules/mongodb/index.js new file mode 100644 index 0000000..df24555 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/index.js @@ -0,0 +1,47 @@ +// Core module +var core = require('mongodb-core'), + Instrumentation = require('./lib/apm'); + +// Set up the connect function +var connect = require('./lib/mongo_client').connect; + +// Expose error class +connect.MongoError = core.MongoError; + +// Actual driver classes exported +connect.MongoClient = require('./lib/mongo_client'); +connect.Db = require('./lib/db'); +connect.Collection = require('./lib/collection'); +connect.Server = require('./lib/server'); +connect.ReplSet = require('./lib/replset'); +connect.Mongos = require('./lib/mongos'); +connect.ReadPreference = require('./lib/read_preference'); +connect.GridStore = require('./lib/gridfs/grid_store'); +connect.Chunk = require('./lib/gridfs/chunk'); +connect.Logger = core.Logger; +connect.Cursor = require('./lib/cursor'); + +// BSON types exported +connect.Binary = core.BSON.Binary; +connect.Code = core.BSON.Code; +connect.DBRef = core.BSON.DBRef; +connect.Double = core.BSON.Double; +connect.Long = core.BSON.Long; +connect.MinKey = core.BSON.MinKey; +connect.MaxKey = core.BSON.MaxKey; +connect.ObjectID = core.BSON.ObjectID; +connect.ObjectId = core.BSON.ObjectID; +connect.Symbol = core.BSON.Symbol; +connect.Timestamp = core.BSON.Timestamp; + +// Add connect method +connect.connect = connect; + +// Set up the instrumentation method +connect.instrument = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + return new Instrumentation(core, options, callback); +} + +// Set our exports to be the connect function +module.exports = connect; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/admin.js b/util/demographicsImporter/node_modules/mongodb/lib/admin.js new file mode 100644 index 0000000..1f89512 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/admin.js @@ -0,0 +1,581 @@ +"use strict"; + +var toError = require('./utils').toError, + Define = require('./metadata'), + shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Admin** class is an internal class that allows convenient access to + * the admin functionality and commands for MongoDB. + * + * **ADMIN Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Use the admin database for the operation + * var adminDb = db.admin(); + * + * // List all the available databases + * adminDb.listDatabases(function(err, dbs) { + * test.equal(null, err); + * test.ok(dbs.databases.length > 0); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {Admin} a collection instance. + */ +var Admin = function(db, topology, promiseLibrary) { + if(!(this instanceof Admin)) return new Admin(db, topology); + var self = this; + + // Internal state + this.s = { + db: db + , topology: topology + , promiseLibrary: promiseLibrary + } +} + +var define = Admin.define = new Define('Admin', Admin, false); + +/** + * The callback format for results + * @callback Admin~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.command = function(command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand(command, options, function(err, doc) { + return callback != null ? callback(err, doc) : null; + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand(command, options, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.buildInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.serverInfo(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.serverInfo(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('buildInfo', {callback: true, promise:true}); + +/** + * Retrieve the server information for the current + * instance of the db client + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverInfo = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err != null) return callback(err, null); + callback(null, doc); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { + if(err) return reject(err); + resolve(doc); + }); + }); +} + +define.classMethod('serverInfo', {callback: true, promise:true}); + +/** + * Retrieve this db's server status. + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.serverStatus = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return serverStatus(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + serverStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var serverStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { + if(err == null && doc.ok === 1) { + callback(null, doc); + } else { + if(err) return callback(err, false); + return callback(toError(doc), false); + } + }); +} + +define.classMethod('serverStatus', {callback: true, promise:true}); + +/** + * Retrieve the current profiling Level for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingLevel = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingLevel(self, callback) + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingLevel(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingLevel = function(self, callback) { + self.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) { + doc = doc; + + if(err == null && doc.ok === 1) { + var was = doc.was; + if(was == 0) return callback(null, "off"); + if(was == 1) return callback(null, "slow_only"); + if(was == 2) return callback(null, "all"); + return callback(new Error("Error: illegal profiling level value " + was), null); + } else { + err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + } + }); +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Ping the MongoDB server and retrieve results + * + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.ping = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({ping: 1}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({ping: 1}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('ping', {callback: true, promise:true}); + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.authenticate = function(username, password, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options); + options.authdb = 'admin'; + + // Execute using callback + if(typeof callback == 'function') return this.s.db.authenticate(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.authenticate(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.logout = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return this.s.db.logout({authdb: 'admin'}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.logout({authdb: 'admin'}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +// Get write concern +var writeConcern = function(options, db) { + options = shallowClone(options); + + // If options already contain write concerns return it + if(options.w || options.wtimeout || options.j || options.fsync) { + return options; + } + + // Set db write concern if available + if(db.writeConcern) { + if(options.w) options.w = db.writeConcern.w; + if(options.wtimeout) options.wtimeout = db.writeConcern.wtimeout; + if(options.j) options.j = db.writeConcern.j; + if(options.fsync) options.fsync = db.writeConcern.fsync; + } + + // Return modified options + return options; +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.addUser = function(username, password, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name to admin + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.addUser(username, password, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.addUser(username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('addUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {Admin~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + // Get the options + options = writeConcern(options, self.s.db) + // Set the db name + options.dbName = 'admin'; + + // Execute using callback + if(typeof callback == 'function') + return self.s.db.removeUser(username, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.removeUser(username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Set the current profiling level of MongoDB + * + * @param {string} level The new profiling level (off, slow_only, all). + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.setProfilingLevel = function(level, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return setProfilingLevel(self, level, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + setProfilingLevel(self, level, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var setProfilingLevel = function(self, level, callback) { + var command = {}; + var profile = 0; + + if(level == "off") { + profile = 0; + } else if(level == "slow_only") { + profile = 1; + } else if(level == "all") { + profile = 2; + } else { + return callback(new Error("Error: illegal profiling level value " + level)); + } + + // Set up the profile number + command['profile'] = profile; + + self.s.db.executeDbAdminCommand(command, function(err, doc) { + doc = doc; + + if(err == null && doc.ok === 1) + return callback(null, level); + return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); + }); +} + +define.classMethod('setProfilingLevel', {callback: true, promise:true}); + +/** + * Retrive the current profiling information for MongoDB + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.profilingInfo = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return profilingInfo(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + profilingInfo(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var profilingInfo = function(self, callback) { + try { + self.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback); + } catch (err) { + return callback(err, null); + } +} + +define.classMethod('profilingLevel', {callback: true, promise:true}); + +/** + * Validate an existing collection + * + * @param {string} collectionName The name of the collection to validate. + * @param {object} [options=null] Optional settings. + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.validateCollection = function(collectionName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') + return validateCollection(self, collectionName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + validateCollection(self, collectionName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var validateCollection = function(self, collectionName, options, callback) { + var command = {validate: collectionName}; + var keys = Object.keys(options); + + // Decorate command with extra options + for(var i = 0; i < keys.length; i++) { + if(options.hasOwnProperty(keys[i])) { + command[keys[i]] = options[keys[i]]; + } + } + + self.s.db.command(command, function(err, doc) { + if(err != null) return callback(err, null); + + if(doc.ok === 0) + return callback(new Error("Error with validate command"), null); + if(doc.result != null && doc.result.constructor != String) + return callback(new Error("Error with validation data"), null); + if(doc.result != null && doc.result.match(/exception|corrupt/) != null) + return callback(new Error("Error: invalid collection " + collectionName), null); + if(doc.valid != null && !doc.valid) + return callback(new Error("Error: invalid collection " + collectionName), null); + + return callback(null, doc); + }); +} + +define.classMethod('validateCollection', {callback: true, promise:true}); + +/** + * List the available databases + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.listDatabases = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return self.s.db.executeDbAdminCommand({listDatabases:1}, {}, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('listDatabases', {callback: true, promise:true}); + +/** + * Get ReplicaSet status + * + * @param {Admin~resultCallback} [callback] The command result callback. + * @return {Promise} returns Promise if no callback passed + */ +Admin.prototype.replSetGetStatus = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return replSetGetStatus(self, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replSetGetStatus(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var replSetGetStatus = function(self, callback) { + self.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { + if(err == null && doc.ok === 1) + return callback(null, doc); + if(err) return callback(err, false); + callback(toError(doc), false); + }); +} + +define.classMethod('replSetGetStatus', {callback: true, promise:true}); + +module.exports = Admin; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/aggregation_cursor.js b/util/demographicsImporter/node_modules/mongodb/lib/aggregation_cursor.js new file mode 100644 index 0000000..3663229 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/aggregation_cursor.js @@ -0,0 +1,432 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **AGGREGATIONCURSOR Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * // Show that duplicate records got dropped + * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class AggregationCursor + * @extends external:Readable + * @fires AggregationCursor#data + * @fires AggregationCursor#end + * @fires AggregationCursor#close + * @fires AggregationCursor#readable + * @return {AggregationCursor} an AggregationCursor instance. + */ +var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = AggregationCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * AggregationCursor stream data event, fired for each document in the cursor. + * + * @event AggregationCursor#data + * @type {object} + */ + +/** + * AggregationCursor stream end event + * + * @event AggregationCursor#end + * @type {null} + */ + +/** + * AggregationCursor stream close event + * + * @event AggregationCursor#close + * @type {null} + */ + +/** + * AggregationCursor stream readable event + * + * @event AggregationCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(AggregationCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' + , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified']; + +// Extend the Cursor +for(var name in CoreCursor.prototype) { + AggregationCursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {AggregationCursor} + */ +AggregationCursor.prototype.batchSize = function(value) { + if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true }); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", drvier:true }); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a geoNear stage to the aggregation pipeline + * @method + * @param {object} document The geoNear stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.geoNear = function(document) { + this.s.cmd.pipeline.push({$geoNear: document}); + return this; +} + +define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a group stage to the aggregation pipeline + * @method + * @param {object} document The group stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.group = function(document) { + this.s.cmd.pipeline.push({$group: document}); + return this; +} + +define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a limit stage to the aggregation pipeline + * @method + * @param {number} value The state limit value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.limit = function(value) { + this.s.cmd.pipeline.push({$limit: value}); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a match stage to the aggregation pipeline + * @method + * @param {object} document The match stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.match = function(document) { + this.s.cmd.pipeline.push({$match: document}); + return this; +} + +define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a out stage to the aggregation pipeline + * @method + * @param {number} destination The destination name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.out = function(destination) { + this.s.cmd.pipeline.push({$out: destination}); + return this; +} + +define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a project stage to the aggregation pipeline + * @method + * @param {object} document The project stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.project = function(document) { + this.s.cmd.pipeline.push({$project: document}); + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a redact stage to the aggregation pipeline + * @method + * @param {object} document The redact stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.redact = function(document) { + this.s.cmd.pipeline.push({$redact: document}); + return this; +} + +define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a skip stage to the aggregation pipeline + * @method + * @param {number} value The state skip value. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.skip = function(value) { + this.s.cmd.pipeline.push({$skip: value}); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a sort stage to the aggregation pipeline + * @method + * @param {object} document The sort stage document. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.sort = function(document) { + this.s.cmd.pipeline.push({$sort: document}); + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]}); + +/** + * Add a unwind stage to the aggregation pipeline + * @method + * @param {number} field The unwind field name. + * @return {AggregationCursor} + */ +AggregationCursor.prototype.unwind = function(field) { + this.s.cmd.pipeline.push({$unwind: field}); + return this; +} + +define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]}); + +AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function AggregationCursor.prototype.next + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method AggregationCursor.prototype.toArray + * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback AggregationCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method AggregationCursor.prototype.each + * @param {AggregationCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a AggregationCursor command and emitting close. + * @method AggregationCursor.prototype.close + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method AggregationCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Execute the explain for the cursor + * @method AggregationCursor.prototype.explain + * @param {AggregationCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Clone the cursor + * @function AggregationCursor.prototype.clone + * @return {AggregationCursor} + */ + +/** + * Resets the cursor + * @function AggregationCursor.prototype.rewind + * @return {AggregationCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback AggregationCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback AggregationCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method AggregationCursor.prototype.forEach + * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. + * @param {AggregationCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +AggregationCursor.INIT = 0; +AggregationCursor.OPEN = 1; +AggregationCursor.CLOSED = 2; + +module.exports = AggregationCursor; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/apm.js b/util/demographicsImporter/node_modules/mongodb/lib/apm.js new file mode 100644 index 0000000..aba5b86 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/apm.js @@ -0,0 +1,571 @@ +var EventEmitter = require('events').EventEmitter, + inherits = require('util').inherits; + +// Get prototypes +var AggregationCursor = require('./aggregation_cursor'), + CommandCursor = require('./command_cursor'), + OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation, + UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation, + GridStore = require('./gridfs/grid_store'), + Server = require('./server'), + ReplSet = require('./replset'), + Mongos = require('./mongos'), + Cursor = require('./cursor'), + Collection = require('./collection'), + Db = require('./db'), + Admin = require('./admin'); + +var basicOperationIdGenerator = { + operationId: 1, + + next: function() { + return this.operationId++; + } +} + +var basicTimestampGenerator = { + current: function() { + return new Date().getTime(); + }, + + duration: function(start, end) { + return end - start; + } +} + +var senstiveCommands = ['authenticate', 'saslStart', 'saslContinue', 'getnonce', + 'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb']; + +var Instrumentation = function(core, options, callback) { + options = options || {}; + + // Optional id generators + var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator; + // Optional timestamp generator + var timestampGenerator = options.timestampGenerator || basicTimestampGenerator; + // Extend with event emitter functionality + EventEmitter.call(this); + + // Contains all the instrumentation overloads + this.overloads = []; + + // --------------------------------------------------------- + // + // Instrument prototype + // + // --------------------------------------------------------- + + var instrumentPrototype = function(callback) { + var instrumentations = [] + + // Classes to support + var classes = [GridStore, OrderedBulkOperation, UnorderedBulkOperation, + CommandCursor, AggregationCursor, Cursor, Collection, Db]; + + // Add instrumentations to the available list + for(var i = 0; i < classes.length; i++) { + if(classes[i].define) { + instrumentations.push(classes[i].define.generate()); + } + } + + // Return the list of instrumentation points + callback(null, instrumentations); + } + + // Did the user want to instrument the prototype + if(typeof callback == 'function') { + instrumentPrototype(callback); + } + + // --------------------------------------------------------- + // + // Server + // + // --------------------------------------------------------- + + // Reference + var self = this; + // Names of methods we need to wrap + var methods = ['command', 'insert', 'update', 'remove']; + // Prototype + var proto = core.Server.prototype; + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var requestId = core.Query.nextRequestId(); + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + var ns = args[0]; + var commandObj = args[1]; + var options = args[2] || {}; + var keys = Object.keys(commandObj); + var commandName = keys[0]; + var db = ns.split('.')[0]; + + // Do we have a legacy insert/update/remove command + if(x == 'insert' && !this.lastIsMaster().maxWireVersion) { + commandName = 'insert'; + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + insert: col, documents: commandObj + } + + if(options.writeConcern) commandObj.writeConcern = options.writeConcern; + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'update' && !this.lastIsMaster().maxWireVersion) { + commandName = 'update'; + + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + update: col, updates: commandObj + } + + if(options.writeConcern) commandObj.writeConcern = options.writeConcern; + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'remove' && !this.lastIsMaster().maxWireVersion) { + commandName = 'delete'; + + // Get the collection + var col = ns.split('.'); + col.shift(); + col = col.join('.'); + + // Re-write the command + commandObj = { + delete: col, deletes: commandObj + } + + if(options.writeConcern) commandObj.writeConcern = options.writeConcern; + commandObj.ordered = options.ordered != undefined ? options.ordered : true; + } else if(x == 'insert' || x == 'update' || x == 'remove' && this.lastIsMaster().maxWireVersion >= 2) { + // Skip the insert/update/remove commands as they are executed as actual write commands in 2.6 or higher + return func.apply(this, args); + } + + // Get the callback + var callback = args.pop(); + // Set current callback operation id from the current context or create + // a new one + var ourOpId = callback.operationId || operationIdGenerator.next(); + + // Get a connection reference for this server instance + var connection = this.s.pool.get() + + // Emit the start event for the command + var command = { + // Returns the command. + command: commandObj, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: ourOpId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connection + }; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.commandObj = {}; + command.commandObj[commandName] = true; + } + + // Emit the started event + self.emit('started', command) + + // Start time + var startTime = timestampGenerator.current(); + + // Push our handler callback + args.push(function(err, r) { + var endTime = timestampGenerator.current(); + var command = { + duration: timestampGenerator.duration(startTime, endTime), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: connection + }; + + // If we have an error + if(err || (r.result.ok == 0)) { + command.failure = err || r.result.writeErrors || r.result; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.failure = {}; + } + + self.emit('failed', command); + } else { + command.reply = r; + + // Filter out any sensitive commands + if(senstiveCommands.indexOf(commandName.toLowerCase())) { + command.reply = {}; + } + + self.emit('succeeded', command); + } + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } + }); + + // --------------------------------------------------------- + // + // Bulk Operations + // + // --------------------------------------------------------- + + // Inject ourselves into the Bulk methods + var methods = ['execute']; + var prototypes = [ + require('./bulk/ordered').Bulk.prototype, + require('./bulk/unordered').Bulk.prototype + ] + + prototypes.forEach(function(proto) { + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var bulk = this; + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + // Set an operation Id on the bulk object + this.operationId = operationIdGenerator.next(); + + // Get the callback + var callback = args.pop(); + // If we have a callback use this + if(typeof callback == 'function') { + args.push(function(err, r) { + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + return func.apply(this, args); + } + } + }); + }); + + // --------------------------------------------------------- + // + // Cursor + // + // --------------------------------------------------------- + + // Inject ourselves into the Cursor methods + var methods = ['_find', '_getmore', '_killcursor']; + var prototypes = [ + require('./cursor').prototype, + require('./command_cursor').prototype, + require('./aggregation_cursor').prototype + ] + + // Command name translation + var commandTranslation = { + '_find': 'find', '_getmore': 'getMore', '_killcursor': 'killCursors', '_explain': 'explain' + } + + prototypes.forEach(function(proto) { + + // Core server method we are going to wrap + methods.forEach(function(x) { + var func = proto[x]; + + // Add to overloaded methods + self.overloads.push({proto: proto, name:x, func:func}); + + // The actual prototype + proto[x] = function() { + var cursor = this; + var requestId = core.Query.nextRequestId(); + var ourOpId = operationIdGenerator.next(); + var parts = this.ns.split('.'); + var db = parts[0]; + + // Get the collection + parts.shift(); + var collection = parts.join('.'); + + // Set the command + var command = this.query; + var cmd = this.s.cmd; + + // If we have a find method, set the operationId on the cursor + if(x == '_find') { + cursor.operationId = ourOpId; + } + + // Do we have a find command rewrite it + if(cmd.find) { + command = { + find: collection, filter: cmd.query + } + + if(cmd.sort) command.sort = cmd.sort; + if(cmd.fields) command.projection = cmd.fields; + if(cmd.limit && cmd.limit < 0) { + command.limit = Math.abs(cmd.limit); + command.singleBatch = true; + } else if(cmd.limit) { + command.limit = Math.abs(cmd.limit); + } + + // Options + if(cmd.skip) command.skip = cmd.skip; + if(cmd.hint) command.hint = cmd.hint; + if(cmd.batchSize) command.batchSize = cmd.batchSize; + if(cmd.returnKey) command.returnKey = cmd.returnKey; + if(cmd.comment) command.comment = cmd.comment; + if(cmd.min) command.min = cmd.min; + if(cmd.max) command.max = cmd.max; + if(cmd.maxScan) command.maxScan = cmd.maxScan; + if(cmd.readPreference) command['$readPreference'] = cmd.readPreference; + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + + // Flags + if(cmd.awaitData) command.awaitData = cmd.awaitData; + if(cmd.snapshot) command.snapshot = cmd.snapshot; + if(cmd.tailable) command.tailable = cmd.tailable; + if(cmd.oplogReplay) command.oplogReplay = cmd.oplogReplay; + if(cmd.noCursorTimeout) command.noCursorTimeout = cmd.noCursorTimeout; + if(cmd.partial) command.partial = cmd.partial; + if(cmd.showDiskLoc) command.showRecordId = cmd.showDiskLoc; + + // Read Concern + if(cmd.readConcern) command.readConcern = cmd.readConcern; + + // Override method + if(cmd.explain) command.explain = cmd.explain; + if(cmd.exhaust) command.exhaust = cmd.exhaust; + + // If we have a explain flag + if(cmd.explain) { + // Create fake explain command + command = { + explain: command, + verbosity: 'allPlansExecution' + } + + // Set readConcern on the command if available + if(cmd.readConcern) command.readConcern = cmd.readConcern + + // Set up the _explain name for the command + x = '_explain'; + } + } else if(x == '_getmore') { + command = { + getMore: this.cursorState.cursorId, + collection: collection, + batchSize: cmd.batchSize + } + + if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; + } else if(x == '_killcursors') { + command = { + killCursors: collection, + cursors: [this.cursorState.cursorId] + } + } else { + command = cmd; + } + + // Set up the connection + var connectionId = null; + + // Set local connection + if(this.connection) connectionId = this.connection; + if(!connectionId && this.server && this.server.getConnection) connectionId = this.server.getConnection(); + + // Get the command Name + var commandName = x == '_find' ? Object.keys(command)[0] : commandTranslation[x]; + + // Emit the start event for the command + var command = { + // Returns the command. + command: command, + // Returns the database name. + databaseName: db, + // Returns the command name. + commandName: commandName, + // Returns the driver generated request id. + requestId: requestId, + // Returns the driver generated operation id. + // This is used to link events together such as bulk write operations. OPTIONAL. + operationId: this.operationId, + // Returns the connection id for the command. For languages that do not have this, + // this MUST return the driver equivalent which MUST include the server address and port. + // The name of this field is flexible to match the object that is returned from the driver. + connectionId: connectionId + }; + + // Get the aruments + var args = Array.prototype.slice.call(arguments, 0); + + // Get the callback + var callback = args.pop(); + + // We do not have a callback but a Promise + if(typeof callback == 'function' || command.commandName == 'killCursors') { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + + // Emit succeeded event with killcursor if we have a legacy protocol + if(command.commandName == 'killCursors' + && this.server.lastIsMaster() + && this.server.lastIsMaster().maxWireVersion < 4) { + // Emit the succeeded command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: [{ok:1}] + }; + + // Emit the command + return self.emit('succeeded', command) + } + + // Add our callback handler + args.push(function(err, r) { + + if(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + } else { + // cursor id is zero, we can issue success command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: cursor.cursorState.documents + }; + + // Emit the command + self.emit('succeeded', command) + } + + // Return + if(!callback) return; + + // Return to caller + callback(err, r); + }); + + // Apply the call + func.apply(this, args); + } else { + // Assume promise, push back the missing value + args.push(callback); + // Get the promise + var promise = func.apply(this, args); + // Return a new promise + return new cursor.s.promiseLibrary(function(resolve, reject) { + var startTime = timestampGenerator.current(); + // Emit the started event + self.emit('started', command) + // Execute the function + promise.then(function(r) { + // cursor id is zero, we can issue success command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: cursor.operationId, + connectionId: cursor.server.getConnection(), + reply: cursor.cursorState.documents + }; + + // Emit the command + self.emit('succeeded', command) + }).catch(function(err) { + // Command + var command = { + duration: timestampGenerator.duration(startTime, timestampGenerator.current()), + commandName: commandName, + requestId: requestId, + operationId: ourOpId, + connectionId: cursor.server.getConnection(), + failure: err }; + + // Emit the command + self.emit('failed', command) + // reject the promise + reject(err); + }); + }); + } + } + }); + }); +} + +inherits(Instrumentation, EventEmitter); + +Instrumentation.prototype.uninstrument = function() { + for(var i = 0; i < this.overloads.length; i++) { + var obj = this.overloads[i]; + obj.proto[obj.name] = obj.func; + } + + // Remove all listeners + this.removeAllListeners('started'); + this.removeAllListeners('succeeded'); + this.removeAllListeners('failed'); +} + +module.exports = Instrumentation; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/lib/bulk/common.js b/util/demographicsImporter/node_modules/mongodb/lib/bulk/common.js new file mode 100644 index 0000000..7ec023e --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/bulk/common.js @@ -0,0 +1,393 @@ +"use strict"; + +var utils = require('../utils'); + +// Error codes +var UNKNOWN_ERROR = 8; +var INVALID_BSON_ERROR = 22; +var WRITE_CONCERN_ERROR = 64; +var MULTIPLE_ERROR = 65; + +// Insert types +var INSERT = 1; +var UPDATE = 2; +var REMOVE = 3 + + +// Get write concern +var writeConcern = function(target, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + target.writeConcern = options; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } + + return target +} + +/** + * Helper function to define properties + * @ignore + */ +var defineReadOnlyProperty = function(self, name, value) { + Object.defineProperty(self, name, { + enumerable: true + , get: function() { + return value; + } + }); +} + +/** + * Keeps the state of a unordered batch so we can rewrite the results + * correctly after command execution + * @ignore + */ +var Batch = function(batchType, originalZeroIndex) { + this.originalZeroIndex = originalZeroIndex; + this.currentIndex = 0; + this.originalIndexes = []; + this.batchType = batchType; + this.operations = []; + this.size = 0; + this.sizeBytes = 0; +} + +/** + * Wraps a legacy operation so we can correctly rewrite it's error + * @ignore + */ +var LegacyOp = function(batchType, operation, index) { + this.batchType = batchType; + this.index = index; + this.operation = operation; +} + +/** + * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {boolean} ok Did bulk operation correctly execute + * @property {number} nInserted number of inserted documents + * @property {number} nUpdated number of documents updated logically + * @property {number} nUpserted Number of upserted documents + * @property {number} nModified Number of documents updated physically on disk + * @property {number} nRemoved Number of removed documents + * @return {BulkWriteResult} a BulkWriteResult instance + */ +var BulkWriteResult = function(bulkResult) { + defineReadOnlyProperty(this, "ok", bulkResult.ok); + defineReadOnlyProperty(this, "nInserted", bulkResult.nInserted); + defineReadOnlyProperty(this, "nUpserted", bulkResult.nUpserted); + defineReadOnlyProperty(this, "nMatched", bulkResult.nMatched); + defineReadOnlyProperty(this, "nModified", bulkResult.nModified); + defineReadOnlyProperty(this, "nRemoved", bulkResult.nRemoved); + + /** + * Return an array of inserted ids + * + * @return {object[]} + */ + this.getInsertedIds = function() { + return bulkResult.insertedIds; + } + + /** + * Return an array of upserted ids + * + * @return {object[]} + */ + this.getUpsertedIds = function() { + return bulkResult.upserted; + } + + /** + * Return the upserted id at position x + * + * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index + * @return {object} + */ + this.getUpsertedIdAt = function(index) { + return bulkResult.upserted[index]; + } + + /** + * Return raw internal result + * + * @return {object} + */ + this.getRawResponse = function() { + return bulkResult; + } + + /** + * Returns true if the bulk operation contains a write error + * + * @return {boolean} + */ + this.hasWriteErrors = function() { + return bulkResult.writeErrors.length > 0; + } + + /** + * Returns the number of write errors off the bulk operation + * + * @return {number} + */ + this.getWriteErrorCount = function() { + return bulkResult.writeErrors.length; + } + + /** + * Returns a specific write error object + * + * @return {WriteError} + */ + this.getWriteErrorAt = function(index) { + if(index < bulkResult.writeErrors.length) { + return bulkResult.writeErrors[index]; + } + return null; + } + + /** + * Retrieve all write errors + * + * @return {object[]} + */ + this.getWriteErrors = function() { + return bulkResult.writeErrors; + } + + /** + * Retrieve lastOp if available + * + * @return {object} + */ + this.getLastOp = function() { + return bulkResult.lastOp; + } + + /** + * Retrieve the write concern error if any + * + * @return {WriteConcernError} + */ + this.getWriteConcernError = function() { + if(bulkResult.writeConcernErrors.length == 0) { + return null; + } else if(bulkResult.writeConcernErrors.length == 1) { + // Return the error + return bulkResult.writeConcernErrors[0]; + } else { + + // Combine the errors + var errmsg = ""; + for(var i = 0; i < bulkResult.writeConcernErrors.length; i++) { + var err = bulkResult.writeConcernErrors[i]; + errmsg = errmsg + err.errmsg; + + // TODO: Something better + if(i == 0) errmsg = errmsg + " and "; + } + + return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_ERROR }); + } + } + + this.toJSON = function() { + return bulkResult; + } + + this.toString = function() { + return "BulkWriteResult(" + this.toJSON(bulkResult) + ")"; + } + + this.isOk = function() { + return bulkResult.ok == 1; + } +} + +/** + * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +var WriteConcernError = function(err) { + if(!(this instanceof WriteConcernError)) return new WriteConcernError(err); + + // Define properties + defineReadOnlyProperty(this, "code", err.code); + defineReadOnlyProperty(this, "errmsg", err.errmsg); + + this.toJSON = function() { + return {code: err.code, errmsg: err.errmsg}; + } + + this.toString = function() { + return "WriteConcernError(" + err.errmsg + ")"; + } +} + +/** + * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @property {number} code Write concern error code. + * @property {number} index Write concern error original bulk operation index. + * @property {string} errmsg Write concern error message. + * @return {WriteConcernError} a WriteConcernError instance + */ +var WriteError = function(err) { + if(!(this instanceof WriteError)) return new WriteError(err); + + // Define properties + defineReadOnlyProperty(this, "code", err.code); + defineReadOnlyProperty(this, "index", err.index); + defineReadOnlyProperty(this, "errmsg", err.errmsg); + + // + // Define access methods + this.getOperation = function() { + return err.op; + } + + this.toJSON = function() { + return {code: err.code, index: err.index, errmsg: err.errmsg, op: err.op}; + } + + this.toString = function() { + return "WriteError(" + JSON.stringify(this.toJSON()) + ")"; + } +} + +/** + * Merges results into shared data structure + * @ignore + */ +var mergeBatchResults = function(ordered, batch, bulkResult, err, result) { + // If we have an error set the result to be the err object + if(err) { + result = err; + } else if(result && result.result) { + result = result.result; + } else if(result == null) { + return; + } + + // Do we have a top level error stop processing and return + if(result.ok == 0 && bulkResult.ok == 1) { + bulkResult.ok = 0; + // bulkResult.error = utils.toError(result); + var writeError = { + index: 0 + , code: result.code || 0 + , errmsg: result.message + , op: batch.operations[0] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + return; + } else if(result.ok == 0 && bulkResult.ok == 0) { + return; + } + + // Add lastop if available + if(result.lastOp) { + bulkResult.lastOp = result.lastOp; + } + + // If we have an insert Batch type + if(batch.batchType == INSERT && result.n) { + bulkResult.nInserted = bulkResult.nInserted + result.n; + } + + // If we have an insert Batch type + if(batch.batchType == REMOVE && result.n) { + bulkResult.nRemoved = bulkResult.nRemoved + result.n; + } + + var nUpserted = 0; + + // We have an array of upserted values, we need to rewrite the indexes + if(Array.isArray(result.upserted)) { + nUpserted = result.upserted.length; + + for(var i = 0; i < result.upserted.length; i++) { + bulkResult.upserted.push({ + index: result.upserted[i].index + batch.originalZeroIndex + , _id: result.upserted[i]._id + }); + } + } else if(result.upserted) { + + nUpserted = 1; + + bulkResult.upserted.push({ + index: batch.originalZeroIndex + , _id: result.upserted + }); + } + + // If we have an update Batch type + if(batch.batchType == UPDATE && result.n) { + var nModified = result.nModified; + bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; + bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); + + if(typeof nModified == 'number') { + bulkResult.nModified = bulkResult.nModified + nModified; + } else { + bulkResult.nModified = null; + } + } + + if(Array.isArray(result.writeErrors)) { + for(var i = 0; i < result.writeErrors.length; i++) { + + var writeError = { + index: batch.originalZeroIndex + result.writeErrors[i].index + , code: result.writeErrors[i].code + , errmsg: result.writeErrors[i].errmsg + , op: batch.operations[result.writeErrors[i].index] + }; + + bulkResult.writeErrors.push(new WriteError(writeError)); + } + } + + if(result.writeConcernError) { + bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); + } +} + +// +// Clone the options +var cloneOptions = function(options) { + var clone = {}; + var keys = Object.keys(options); + for(var i = 0; i < keys.length; i++) { + clone[keys[i]] = options[keys[i]]; + } + + return clone; +} + +// Exports symbols +exports.BulkWriteResult = BulkWriteResult; +exports.WriteError = WriteError; +exports.Batch = Batch; +exports.LegacyOp = LegacyOp; +exports.mergeBatchResults = mergeBatchResults; +exports.cloneOptions = cloneOptions; +exports.writeConcern = writeConcern; +exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR; +exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR; +exports.MULTIPLE_ERROR = MULTIPLE_ERROR; +exports.UNKNOWN_ERROR = UNKNOWN_ERROR; +exports.INSERT = INSERT; +exports.UPDATE = UPDATE; +exports.REMOVE = REMOVE; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/bulk/ordered.js b/util/demographicsImporter/node_modules/mongodb/lib/bulk/ordered.js new file mode 100644 index 0000000..319a030 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/bulk/ordered.js @@ -0,0 +1,532 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Define = require('../metadata') + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. + */ +var FindOperatorsOrdered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +FindOperatorsOrdered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.deleteOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +FindOperatorsOrdered.prototype.delete = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// Backward compatibility +FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; + +// Add to internal list of documents +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Reset the current size trackers + _self.s.currentBatchSize = 0; + _self.s.currentBatchSizeBytes = 0; + } else { + // Update current batch size + _self.s.currentBatchSize = _self.s.currentBatchSize + 1; + _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; + } + + if(docType == common.INSERT) { + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentBatch.operations.push(document) + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Return self + return _self; +} + +/** + * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {OrderedBulkOperation} a OrderedBulkOperation instance. + */ +function OrderedBulkOperation(topology, collection, options) { + options = options == null ? {} : options; + // TODO Bring from driver information in isMaster + var self = this; + var executed = false; + + // Current item + var currentOp = null; + + // Handle to the bson serializer, used to calculate running sizes + var bson = topology.bson; + + // Namespace for the operation + var namespace = collection.collectionName; + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; + var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; + + // Get the capabilities + var capabilities = topology.capabilities(); + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Current batch + var currentBatch = null; + var currentIndex = 0; + var currentBatchSize = 0; + var currentBatchSizeBytes = 0; + var batches = []; + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentBatch: null + , currentIndex: 0 + , currentBatchSize: 0 + , currentBatchSizeBytes: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Capabilities + , capabilities: capabilities + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Fundamental error + , err: null + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = OrderedBulkOperation.define = new Define('OrderedBulkOperation', OrderedBulkOperation, false); + +OrderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + if(op[key].upsert) operation.upsert = true; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {OrderedBulkOperation} + */ +OrderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsOrdered} + */ +OrderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsOrdered(this); +} + +Object.defineProperty(OrderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +// +// Execute next write command in a chain +var executeCommands = function(self, callback) { + if(self.s.batches.length == 0) { + return callback(null, new BulkWriteResult(self.s.bulkResult)); + } + + // Ordered execution of the command + var batch = self.s.batches.shift(); + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return callback(err); + } + + // If we have and error + if(err) err.ok = 0; + // Merge the results together + var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); + if(mergeResult != null) { + return callback(null, new BulkWriteResult(self.s.bulkResult)); + } + + // If we are ordered and have errors and they are + // not all replication errors terminate the operation + if(self.s.bulkResult.writeErrors.length > 0) { + return callback(toError(self.s.bulkResult.writeErrors[0]), new BulkWriteResult(self.s.bulkResult)); + } + + // Execute the next command in line + executeCommands(self, callback); + } + + var finalOptions = {ordered: true} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Serialize functions + if(self.s.options.ignoreUndefined) { + finalOptions.ignoreUndefined = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +/** + * The callback format for results + * @callback OrderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {OrderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw new toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentBatch) this.s.batches.push(this.s.currentBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') { + return executeCommands(this, callback); + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommands(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeOrderedBulkOp = function(topology, collection, options) { + return new OrderedBulkOperation(topology, collection, options); +} + +initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; +module.exports = initializeOrderedBulkOp; +module.exports.Bulk = OrderedBulkOperation; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/bulk/unordered.js b/util/demographicsImporter/node_modules/mongodb/lib/bulk/unordered.js new file mode 100644 index 0000000..ca45b96 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/bulk/unordered.js @@ -0,0 +1,541 @@ +"use strict"; + +var common = require('./common') + , utils = require('../utils') + , toError = require('../utils').toError + , f = require('util').format + , shallowClone = utils.shallowClone + , WriteError = common.WriteError + , BulkWriteResult = common.BulkWriteResult + , LegacyOp = common.LegacyOp + , ObjectID = require('mongodb-core').BSON.ObjectID + , Define = require('../metadata') + , Batch = common.Batch + , mergeBatchResults = common.mergeBatchResults; + +/** + * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {number} length Get the number of operations in the bulk. + * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. + */ +var FindOperatorsUnordered = function(self) { + this.s = self.s; +} + +/** + * Add a single update document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.update = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: true + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a single update one document to the bulk operation + * + * @method + * @param {object} doc update operations + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { + // Perform upsert + var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; + + // Establish the update command + var document = { + q: this.s.currentOp.selector + , u: updateDocument + , multi: false + , upsert: upsert + } + + // Clear out current Op + this.s.currentOp = null; + // Add the update document to the list + return addToOperationsList(this, common.UPDATE, document); +} + +/** + * Add a replace one operation to the bulk operation + * + * @method + * @param {object} doc the new document to replace the existing one with + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { + this.updateOne(updateDocument); +} + +/** + * Upsert modifier for update bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.upsert = function() { + this.s.currentOp.upsert = true; + return this; +} + +/** + * Add a remove one operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.removeOne = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 1 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +/** + * Add a remove operation to the bulk operation + * + * @method + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +FindOperatorsUnordered.prototype.remove = function() { + // Establish the update command + var document = { + q: this.s.currentOp.selector + , limit: 0 + } + + // Clear out current Op + this.s.currentOp = null; + // Add the remove document to the list + return addToOperationsList(this, common.REMOVE, document); +} + +// +// Add to the operations list +// +var addToOperationsList = function(_self, docType, document) { + // Get the bsonSize + var bsonSize = _self.s.bson.calculateObjectSize(document, false); + // Throw error if the doc is bigger than the max BSON size + if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); + // Holds the current batch + _self.s.currentBatch = null; + // Get the right type of batch + if(docType == common.INSERT) { + _self.s.currentBatch = _self.s.currentInsertBatch; + } else if(docType == common.UPDATE) { + _self.s.currentBatch = _self.s.currentUpdateBatch; + } else if(docType == common.REMOVE) { + _self.s.currentBatch = _self.s.currentRemoveBatch; + } + + // Create a new batch object if we don't have a current one + if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + + // Check if we need to create a new batch + if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize) + || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes) + || (_self.s.currentBatch.batchType != docType)) { + // Save the batch to the execution stack + _self.s.batches.push(_self.s.currentBatch); + + // Create a new batch + _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); + } + + // We have an array of documents + if(Array.isArray(document)) { + throw toError("operation passed in cannot be an Array"); + } else { + _self.s.currentBatch.operations.push(document); + _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); + _self.s.currentIndex = _self.s.currentIndex + 1; + } + + // Save back the current Batch to the right type + if(docType == common.INSERT) { + _self.s.currentInsertBatch = _self.s.currentBatch; + _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); + } else if(docType == common.UPDATE) { + _self.s.currentUpdateBatch = _self.s.currentBatch; + } else if(docType == common.REMOVE) { + _self.s.currentRemoveBatch = _self.s.currentBatch; + } + + // Update current batch size + _self.s.currentBatch.size = _self.s.currentBatch.size + 1; + _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; + + // Return self + return _self; +} + +/** + * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. + */ +var UnorderedBulkOperation = function(topology, collection, options) { + options = options == null ? {} : options; + + // Contains reference to self + var self = this; + // Get the namesspace for the write operations + var namespace = collection.collectionName; + // Used to mark operation as executed + var executed = false; + + // Current item + // var currentBatch = null; + var currentOp = null; + var currentIndex = 0; + var batches = []; + + // The current Batches for the different operations + var currentInsertBatch = null; + var currentUpdateBatch = null; + var currentRemoveBatch = null; + + // Handle to the bson serializer, used to calculate running sizes + var bson = topology.bson; + + // Get the capabilities + var capabilities = topology.capabilities(); + + // Set max byte size + var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; + var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; + + // Get the write concern + var writeConcern = common.writeConcern(shallowClone(options), collection, options); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Final results + var bulkResult = { + ok: 1 + , writeErrors: [] + , writeConcernErrors: [] + , insertedIds: [] + , nInserted: 0 + , nUpserted: 0 + , nMatched: 0 + , nModified: 0 + , nRemoved: 0 + , upserted: [] + }; + + // Internal state + this.s = { + // Final result + bulkResult: bulkResult + // Current batch state + , currentInsertBatch: null + , currentUpdateBatch: null + , currentRemoveBatch: null + , currentBatch: null + , currentIndex: 0 + , batches: [] + // Write concern + , writeConcern: writeConcern + // Capabilities + , capabilities: capabilities + // Max batch size options + , maxBatchSizeBytes: maxBatchSizeBytes + , maxWriteBatchSize: maxWriteBatchSize + // Namespace + , namespace: namespace + // BSON + , bson: bson + // Topology + , topology: topology + // Options + , options: options + // Current operation + , currentOp: currentOp + // Executed + , executed: executed + // Collection + , collection: collection + // Promise Library + , promiseLibrary: promiseLibrary + // Bypass validation + , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false + } +} + +var define = UnorderedBulkOperation.define = new Define('UnorderedBulkOperation', UnorderedBulkOperation, false); + +/** + * Add a single insert document to the bulk operation + * + * @param {object} doc the document to insert + * @throws {MongoError} + * @return {UnorderedBulkOperation} + */ +UnorderedBulkOperation.prototype.insert = function(document) { + if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, document); +} + +/** + * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne + * + * @method + * @param {object} selector The selector for the bulk operation. + * @throws {MongoError} + * @return {FindOperatorsUnordered} + */ +UnorderedBulkOperation.prototype.find = function(selector) { + if (!selector) { + throw toError("Bulk find operation must specify a selector"); + } + + // Save a current selector + this.s.currentOp = { + selector: selector + } + + return new FindOperatorsUnordered(this); +} + +Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { + enumerable: true, + get: function() { + return this.s.currentIndex; + } +}); + +UnorderedBulkOperation.prototype.raw = function(op) { + var key = Object.keys(op)[0]; + + // Set up the force server object id + var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' + ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; + + // Update operations + if((op.updateOne && op.updateOne.q) + || (op.updateMany && op.updateMany.q) + || (op.replaceOne && op.replaceOne.q)) { + op[key].multi = op.updateOne || op.replaceOne ? false : true; + return addToOperationsList(this, common.UPDATE, op[key]); + } + + // Crud spec update format + if(op.updateOne || op.updateMany || op.replaceOne) { + var multi = op.updateOne || op.replaceOne ? false : true; + var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} + if(op[key].upsert) operation.upsert = true; + return addToOperationsList(this, common.UPDATE, operation); + } + + // Remove operations + if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { + op[key].limit = op.removeOne ? 1 : 0; + return addToOperationsList(this, common.REMOVE, op[key]); + } + + // Crud spec delete operations, less efficient + if(op.deleteOne || op.deleteMany) { + var limit = op.deleteOne ? 1 : 0; + var operation = {q: op[key].filter, limit: limit} + return addToOperationsList(this, common.REMOVE, operation); + } + + // Insert operations + if(op.insertOne && op.insertOne.document == null) { + if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne); + } else if(op.insertOne && op.insertOne.document) { + if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); + return addToOperationsList(this, common.INSERT, op.insertOne.document); + } + + if(op.insertMany) { + for(var i = 0; i < op.insertMany.length; i++) { + if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); + addToOperationsList(this, common.INSERT, op.insertMany[i]); + } + + return; + } + + // No valid type of operation + throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); +} + +// +// Execute the command +var executeBatch = function(self, batch, callback) { + var finalOptions = {ordered: false} + if(self.s.writeConcern != null) { + finalOptions.writeConcern = self.s.writeConcern; + } + + var resultHandler = function(err, result) { + // Error is a driver related error not a bulk op error, terminate + if(err && err.driver || err && err.message) { + return callback(err); + } + + // If we have and error + if(err) err.ok = 0; + callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); + } + + // Set an operationIf if provided + if(self.operationId) { + resultHandler.operationId = self.operationId; + } + + // Serialize functions + if(self.s.options.serializeFunctions) { + finalOptions.serializeFunctions = true + } + + // Is the bypassDocumentValidation options specific + if(self.s.bypassDocumentValidation == true) { + finalOptions.bypassDocumentValidation = true; + } + + try { + if(batch.batchType == common.INSERT) { + self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.UPDATE) { + self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } else if(batch.batchType == common.REMOVE) { + self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); + } + } catch(err) { + // Force top level error + err.ok = 0; + // Merge top level error and return + callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); + } +} + +// +// Execute all the commands +var executeBatches = function(self, callback) { + var numberOfCommandsToExecute = self.s.batches.length; + var error = null; + // Execute over all the batches + for(var i = 0; i < self.s.batches.length; i++) { + executeBatch(self, self.s.batches[i], function(err, result) { + // Driver layer error capture it + if(err) error = err; + // Count down the number of commands left to execute + numberOfCommandsToExecute = numberOfCommandsToExecute - 1; + + // Execute + if(numberOfCommandsToExecute == 0) { + // Driver level error + if(error) return callback(error); + // Treat write errors + var error = self.s.bulkResult.writeErrors.length > 0 ? toError(self.s.bulkResult.writeErrors[0]) : null; + callback(error, new BulkWriteResult(self.s.bulkResult)); + } + }); + } +} + +/** + * The callback format for results + * @callback UnorderedBulkOperation~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {BulkWriteResult} result The bulk write result. + */ + +/** + * Execute the ordered bulk operation + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) { + var self = this; + if(this.s.executed) throw toError("batch cannot be re-executed"); + if(typeof _writeConcern == 'function') { + callback = _writeConcern; + } else { + this.s.writeConcern = _writeConcern; + } + + // If we have current batch + if(this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); + if(this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); + if(this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); + + // If we have no operations in the bulk raise an error + if(this.s.batches.length == 0) { + throw toError("Invalid Operation, No operations in bulk"); + } + + // Execute using callback + if(typeof callback == 'function') return executeBatches(this, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeBatches(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('execute', {callback: true, promise:false}); + +/** + * Returns an unordered batch object + * @ignore + */ +var initializeUnorderedBulkOp = function(topology, collection, options) { + return new UnorderedBulkOperation(topology, collection, options); +} + +initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; +module.exports = initializeUnorderedBulkOp; +module.exports.Bulk = UnorderedBulkOperation; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/collection.js b/util/demographicsImporter/node_modules/mongodb/lib/collection.js new file mode 100644 index 0000000..5ae1ebc --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/collection.js @@ -0,0 +1,3128 @@ +"use strict"; + +var checkCollectionName = require('./utils').checkCollectionName + , ObjectID = require('mongodb-core').BSON.ObjectID + , Long = require('mongodb-core').BSON.Long + , Code = require('mongodb-core').BSON.Code + , f = require('util').format + , AggregationCursor = require('./aggregation_cursor') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone + , isObject = require('./utils').isObject + , toError = require('./utils').toError + , normalizeHintField = require('./utils').normalizeHintField + , handleCallback = require('./utils').handleCallback + , decorateCommand = require('./utils').decorateCommand + , formattedOrderClause = require('./utils').formattedOrderClause + , ReadPreference = require('./read_preference') + , CoreReadPreference = require('mongodb-core').ReadPreference + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Cursor = require('./cursor') + , unordered = require('./bulk/unordered') + , ordered = require('./bulk/ordered'); + +/** + * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection + * allowing for insert/update/remove/find and other command operation on that MongoDB collection. + * + * **COLLECTION Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + */ + +/** + * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) + * @class + * @property {string} collectionName Get the collection name. + * @property {string} namespace Get the full collection namespace. + * @property {object} writeConcern The current write concern values. + * @property {object} readConcern The current read concern values. + * @property {object} hint Get current index hint for collection. + * @return {Collection} a Collection instance. + */ +var Collection = function(db, topology, dbName, name, pkFactory, options) { + checkCollectionName(name); + var self = this; + // Unpack variables + var internalHint = null; + var opts = options != null && ('object' === typeof options) ? options : {}; + var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; + var serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; + var raw = options == null || options.raw == null ? db.raw : options.raw; + var readPreference = null; + var collectionHint = null; + var namespace = f("%s.%s", dbName, name); + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Assign the right collection level readPreference + if(options && options.readPreference) { + readPreference = options.readPreference; + } else if(db.options.readPreference) { + readPreference = db.options.readPreference; + } + + // Set custom primary key factory if provided + pkFactory = pkFactory == null + ? ObjectID + : pkFactory; + + // Internal state + this.s = { + // Set custom primary key factory if provided + pkFactory: pkFactory + // Db + , db: db + // Topology + , topology: topology + // dbName + , dbName: dbName + // Options + , options: options + // Namespace + , namespace: namespace + // Read preference + , readPreference: readPreference + // Raw + , raw: raw + // SlaveOK + , slaveOk: slaveOk + // Serialize functions + , serializeFunctions: serializeFunctions + // internalHint + , internalHint: internalHint + // collectionHint + , collectionHint: collectionHint + // Name + , name: name + // Promise library + , promiseLibrary: promiseLibrary + // Read Concern + , readConcern: options.readConcern + } +} + +var define = Collection.define = new Define('Collection', Collection, false); + +Object.defineProperty(Collection.prototype, 'collectionName', { + enumerable: true, get: function() { return this.s.name; } +}); + +Object.defineProperty(Collection.prototype, 'namespace', { + enumerable: true, get: function() { return this.s.namespace; } +}); + +Object.defineProperty(Collection.prototype, 'readConcern', { + enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; } +}); + +Object.defineProperty(Collection.prototype, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(this.s.options.w != null) ops.w = this.s.options.w; + if(this.s.options.j != null) ops.j = this.s.options.j; + if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; + if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; + return ops; + } +}); + +/** + * @ignore + */ +Object.defineProperty(Collection.prototype, "hint", { + enumerable: true + , get: function () { return this.s.collectionHint; } + , set: function (v) { this.s.collectionHint = normalizeHintField(v); } +}); + +/** + * Creates a cursor for a query that can be used to iterate over results from MongoDB + * @method + * @param {object} query The cursor query object. + * @throws {MongoError} + * @return {Cursor} + */ +Collection.prototype.find = function() { + var options + , args = Array.prototype.slice.call(arguments, 0) + , has_callback = typeof args[args.length - 1] === 'function' + , has_weird_callback = typeof args[0] === 'function' + , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) + , len = args.length + , selector = len >= 1 ? args[0] : {} + , fields = len >= 2 ? args[1] : undefined; + + if(len === 1 && has_weird_callback) { + // backwards compat for callback?, options case + selector = {}; + options = args[0]; + } + + if(len === 2 && fields !== undefined && !Array.isArray(fields)) { + var fieldKeys = Object.keys(fields); + var is_option = false; + + for(var i = 0; i < fieldKeys.length; i++) { + if(testForFields[fieldKeys[i]] != null) { + is_option = true; + break; + } + } + + if(is_option) { + options = fields; + fields = undefined; + } else { + options = {}; + } + } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { + var newFields = {}; + // Rewrite the array + for(var i = 0; i < fields.length; i++) { + newFields[fields[i]] = 1; + } + // Set the fields + fields = newFields; + } + + if(3 === len) { + options = args[2]; + } + + // Ensure selector is not null + selector = selector == null ? {} : selector; + // Validate correctness off the selector + var object = selector; + if(Buffer.isBuffer(object)) { + var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; + if(object_size != object.length) { + var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); + error.name = 'MongoError'; + throw error; + } + } + + // Validate correctness of the field selector + var object = fields; + if(Buffer.isBuffer(object)) { + var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; + if(object_size != object.length) { + var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); + error.name = 'MongoError'; + throw error; + } + } + + // Check special case where we are using an objectId + if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) { + selector = {_id:selector}; + } + + // If it's a serialized fields field we need to just let it through + // user be warned it better be good + if(options && options.fields && !(Buffer.isBuffer(options.fields))) { + fields = {}; + + if(Array.isArray(options.fields)) { + if(!options.fields.length) { + fields['_id'] = 1; + } else { + for (var i = 0, l = options.fields.length; i < l; i++) { + fields[options.fields[i]] = 1; + } + } + } else { + fields = options.fields; + } + } + + if (!options) options = {}; + + var newOptions = {}; + // Make a shallow copy of options + for (var key in options) { + newOptions[key] = options[key]; + } + + // Unpack options + newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; + newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; + newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.s.raw; + newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; + newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; + // // If we have overridden slaveOk otherwise use the default db setting + newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; + + // Add read preference if needed + newOptions = getReadPreference(this, newOptions, this.s.db, this); + // Set slave ok to true if read preference different from primary + if(newOptions.readPreference != null + && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) { + newOptions.slaveOk = true; + } + + // Ensure the query is an object + if(selector != null && typeof selector != 'object') { + throw MongoError.create({message: "query selector must be an object", driver:true }); + } + + // Build the find command + var findCommand = { + find: this.s.namespace + , limit: newOptions.limit + , skip: newOptions.skip + , query: selector + } + + // Ensure we use the right await data option + if(typeof newOptions.awaitdata == 'boolean') { + newOptions.awaitData = newOptions.awaitdata + }; + + // Translate to new command option noCursorTimeout + if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout; + + // Merge in options to command + for(var name in newOptions) { + if(newOptions[name] != null) findCommand[name] = newOptions[name]; + } + + // Format the fields + var formatFields = function(fields) { + var object = {}; + if(Array.isArray(fields)) { + for(var i = 0; i < fields.length; i++) { + if(Array.isArray(fields[i])) { + object[fields[i][0]] = fields[i][1]; + } else { + object[fields[i][0]] = 1; + } + } + } else { + object = fields; + } + + return object; + } + + // Special treatment for the fields selector + if(fields) findCommand.fields = formatFields(fields); + + // Add db object to the new options + newOptions.db = this.s.db; + + // Add the promise library + newOptions.promiseLibrary = this.s.promiseLibrary; + + // Set raw if available at collection level + if(newOptions.raw == null && this.s.raw) newOptions.raw = this.s.raw; + + // Sort options + if(findCommand.sort) + findCommand.sort = formattedOrderClause(findCommand.sort); + + // Set the readConcern + if(this.s.readConcern) { + findCommand.readConcern = this.s.readConcern; + } + + // Create the cursor + if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions)); + return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); +} + +define.classMethod('find', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Inserts a single document into MongoDB. + * @method + * @param {object} doc Document to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertOne = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + if(Array.isArray(doc)) return callback(MongoError.create({message: 'doc parameter must be an object', driver:true })); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return insertOne(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + insertOne(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var insertOne = function(self, doc, options, callback) { + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + // Workaround for pre 2.6 servers + if(r == null) return callback(null, {result: {ok:1}}); + // Add values to top level to ensure crud spec compatibility + r.insertedCount = r.result.n; + r.insertedId = doc._id; + if(callback) callback(null, r); + }); +} + +var mapInserManyResults = function(docs, r) { + var ids = r.getInsertedIds(); + var keys = Object.keys(ids); + var finalIds = new Array(keys); + + for(var i = 0; i < keys.length; i++) { + if(ids[keys[i]]._id) { + finalIds[ids[keys[i]].index] = ids[keys[i]]._id; + } + } + + return { + result: {ok: 1, n: r.insertedCount}, + ops: docs, + insertedCount: r.insertedCount, + insertedIds: finalIds + } +} + +define.classMethod('insertOne', {callback: true, promise:true}); + +/** + * Inserts an array of documents into MongoDB. + * @method + * @param {object[]} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.insertMany = function(docs, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + if(!Array.isArray(docs)) return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); + + // Get the write concern options + if(typeof options.checkKeys != 'boolean') { + options.checkKeys = true; + } + + // If keep going set unordered + options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Do we want to force the server to assign the _id key + if(forceServerObjectId !== true) { + // Add _id if not specified + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // Generate the bulk write operations + var operations = [{ + insertMany: docs + }]; + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) { + if(err) return callback(err, r); + callback(null, mapInserManyResults(docs, r)); + }); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err) return reject(err); + resolve(mapInserManyResults(docs, r)); + }); + }); +} + +define.classMethod('insertMany', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~BulkWriteOpResult + * @property {number} insertedCount Number of documents inserted. + * @property {number} matchedCount Number of documents matched for update. + * @property {number} modifiedCount Number of documents modified. + * @property {number} deletedCount Number of documents deleted. + * @property {number} upsertedCount Number of documents upserted. + * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation + * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~bulkWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Perform a bulkWrite operation without a fluent API + * + * Legal operation types are + * + * { insertOne: { document: { a: 1 } } } + * + * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } + * + * { deleteOne: { filter: {c:1} } } + * + * { deleteMany: { filter: {c:1} } } + * + * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} + * + * @method + * @param {object[]} operations Bulk operations to perform. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~bulkWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.bulkWrite = function(operations, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:true}; + + if(!Array.isArray(operations)) { + throw MongoError.create({message: "operations must be an array of documents", driver:true }); + } + + // Execute using callback + if(typeof callback == 'function') return bulkWrite(self, operations, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + bulkWrite(self, operations, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var bulkWrite = function(self, operations, options, callback) { + // Add ignoreUndfined + if(self.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = self.s.options.ignoreUndefined; + } + + // Create the bulk operation + var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options); + + // for each op go through and add to the bulk + for(var i = 0; i < operations.length; i++) { + bulk.raw(operations[i]); + } + + // Final options for write concern + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; + + // Execute the bulk + bulk.execute(writeCon, function(err, r) { + // We have connection level error + if(!r && err) return callback(err, null); + // We have single error + if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) { + return callback(toError(r.getWriteErrorAt(0)), r); + } + + // if(err) return callback(err); + r.insertedCount = r.nInserted; + r.matchedCount = r.nMatched; + r.modifiedCount = r.nModified || 0; + r.deletedCount = r.nRemoved; + r.upsertedCount = r.getUpsertedIds().length; + r.upsertedIds = {}; + r.insertedIds = {}; + + // Update the n + r.n = r.insertedCount; + + // Inserted documents + var inserted = r.getInsertedIds(); + // Map inserted ids + for(var i = 0; i < inserted.length; i++) { + r.insertedIds[inserted[i].index] = inserted[i]._id; + } + + // Upserted documents + var upserted = r.getUpsertedIds(); + // Map upserted ids + for(var i = 0; i < upserted.length; i++) { + r.upsertedIds[upserted[i].index] = upserted[i]._id; + } + + // Check if we have write errors + if(r.hasWriteErrors()) { + // Get all the errors + var errors = r.getWriteErrors(); + // Return the MongoError object + return callback(toError({ + message: 'write operation failed', code: errors[0].code, writeErrors: errors + }), r); + } + + // Check if we have a writeConcern error + if(r.getWriteConcernError()) { + // Return the MongoError object + return callback(toError(r.getWriteConcernError()), r); + } + + // Return the results + callback(null, r); + }); +} + +var insertDocuments = function(self, docs, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Ensure we are operating on an array op docs + docs = Array.isArray(docs) ? docs : [docs]; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true; + + // If keep going set unordered + if(finalOptions.keepGoing == true) finalOptions.ordered = false; + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Set up the force server object id + var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' + ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; + + // Add _id if not specified + if(forceServerObjectId !== true){ + for(var i = 0; i < docs.length; i++) { + if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); + } + } + + // File inserts + self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Add docs to the list + result.ops = docs; + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('bulkWrite', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~WriteOpResult + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {object} connection The connection object used for the operation. + * @property {object} result The command result object. + */ + +/** + * The callback format for inserts + * @callback Collection~writeOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * @typedef {Object} Collection~insertWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * @typedef {Object} Collection~insertOneWriteOpResult + * @property {Number} insertedCount The total amount of documents inserted. + * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany + * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. + * @property {object} connection The connection object used for the operation. + * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents inserted. + */ + +/** + * The callback format for inserts + * @callback Collection~insertWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * The callback format for inserts + * @callback Collection~insertOneWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Inserts a single document or a an array of documents into MongoDB. + * @method + * @param {(object|object[])} docs Documents to insert. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~insertWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated Use insertOne, insertMany or bulkWrite + */ +Collection.prototype.insert = function(docs, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {ordered:false}; + docs = !Array.isArray(docs) ? [docs] : docs; + + if(options.keepGoing == true) { + options.ordered = false; + } + + return this.insertMany(docs, options, callback); +} + +define.classMethod('insert', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~updateWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents scanned. + * @property {Number} result.nModified The total count of documents modified. + * @property {Object} connection The connection object used for the operation. + * @property {Number} matchedCount The number of documents that matched the filter. + * @property {Number} modifiedCount The number of documents that were modified. + * @property {Number} upsertedCount The number of documents upserted. + * @property {Object} upsertedId The upserted id. + * @property {ObjectId} upsertedId._id The upserted _id returned from the server. + */ + +/** + * The callback format for inserts + * @callback Collection~updateWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Update a single document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateOne = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateOne(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateOne(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateOne = function(self, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateOne', {callback: true, promise:true}); + +/** + * Replace a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} doc The Document that replaces the matching document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.replaceOne = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return replaceOne(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + replaceOne(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var replaceOne = function(self, filter, update, options, callback) { + // Set single document update + options.multi = false; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + r.ops = [update]; + if(callback) callback(null, r); + }); +} + +define.classMethod('replaceOne', {callback: true, promise:true}); + +/** + * Update multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the document to update + * @param {object} update The update operations to be applied to the document + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~updateWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.updateMany = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = shallowClone(options) + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateMany(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateMany(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var updateMany = function(self, filter, update, options, callback) { + // Set single document update + options.multi = true; + // Execute update + updateDocuments(self, filter, update, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.matchedCount = r.result.n; + r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; + r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; + r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; + if(callback) callback(null, r); + }); +} + +define.classMethod('updateMany', {callback: true, promise:true}); + +var updateDocuments = function(self, selector, document, options, callback) { + if('function' === typeof options) callback = options, options = null; + if(options == null) options = {}; + if(!('function' === typeof callback)) callback = null; + + // If we are not providing a selector or document throw + if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object")); + if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object")); + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // Do we return the actual result document + // Either use override on the function, or go back to default on either the collection + // level or db + finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; + + // Execute the operation + var op = {q: selector, u: document}; + if(options.upsert) op.upsert = true; + if(options.multi) op.multi = true; + + // Update options + self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +/** + * Updates documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} document The update document. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.upsert=false] Update operation is an upsert. + * @param {boolean} [options.multi=false] Update one/all documents with operation. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + * @deprecated use updateOne, updateMany or bulkWrite + */ +Collection.prototype.update = function(selector, document, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + updateDocuments(self, selector, document, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('update', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~deleteWriteOpResult + * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. + * @property {Number} result.ok Is 1 if the command executed correctly. + * @property {Number} result.n The total count of documents deleted. + * @property {Object} connection The connection object used for the operation. + * @property {Number} deletedCount The number of documents deleted. + */ + +/** + * The callback format for inserts + * @callback Collection~deleteWriteOpCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Delete a document on MongoDB + * @method + * @param {object} filter The Filter used to select the document to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteOne = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteOne(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteOne(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteOne = function(self, filter, options, callback) { + options.single = true; + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +define.classMethod('deleteOne', {callback: true, promise:true}); + +Collection.prototype.removeOne = Collection.prototype.deleteOne; + +define.classMethod('removeOne', {callback: true, promise:true}); + +/** + * Delete multiple documents on MongoDB + * @method + * @param {object} filter The Filter used to select the documents to remove + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~deleteWriteOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.deleteMany = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + var options = shallowClone(options); + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return deleteMany(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + deleteMany(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var deleteMany = function(self, filter, options, callback) { + options.single = false; + removeDocuments(self, filter, options, function(err, r) { + if(callback == null) return; + if(err && callback) return callback(err); + if(r == null) return callback(null, {result: {ok:1}}); + r.deletedCount = r.result.n; + if(callback) callback(null, r); + }); +} + +var removeDocuments = function(self, selector, options, callback) { + if(typeof options == 'function') { + callback = options, options = {}; + } else if (typeof selector === 'function') { + callback = selector; + options = {}; + selector = {}; + } + + // Create an empty options object if the provided one is null + options = options || {}; + + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + + // If selector is null set empty + if(selector == null) selector = {}; + + // Build the op + var op = {q: selector, limit: 0}; + if(options.single) op.limit = 1; + + // Execute the remove + self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, null, null); + if(result.result.code) return handleCallback(callback, toError(result.result)); + if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); + // Return the results + handleCallback(callback, null, result); + }); +} + +define.classMethod('deleteMany', {callback: true, promise:true}); + +Collection.prototype.removeMany = Collection.prototype.deleteMany; + +define.classMethod('removeMany', {callback: true, promise:true}); + +/** + * Remove documents. + * @method + * @param {object} selector The selector for the update operation. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.single=false] Removes the first document found. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use deleteOne, deleteMany or bulkWrite + */ +Collection.prototype.remove = function(selector, options, callback) { + var self = this; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return removeDocuments(self, selector, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeDocuments(self, selector, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('remove', {callback: true, promise:true}); + +/** + * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic + * operators and update instead for more efficient operations. + * @method + * @param {object} doc Document to save + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~writeOpCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use insertOne, insertMany, updateOne or updateMany + */ +Collection.prototype.save = function(doc, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Add ignoreUndfined + if(this.s.options.ignoreUndefined) { + options = shallowClone(options); + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute using callback + if(typeof callback == 'function') return save(self, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + save(self, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var save = function(self, doc, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); + // Establish if we need to perform an insert or update + if(doc._id != null) { + finalOptions.upsert = true; + return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback); + } + + // Insert the document + insertDocuments(self, [doc], options, function(err, r) { + if(callback == null) return; + if(doc == null) return handleCallback(callback, null, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, r); + }); +} + +define.classMethod('save', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +/** + * Fetches the first document that matches the query + * @method + * @param {object} query Query for find Operation + * @param {object} [options=null] Optional settings. + * @param {number} [options.limit=0] Sets the limit of documents returned in the query. + * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. + * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} + * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). + * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} + * @param {boolean} [options.explain=false] Explain the query instead of returning the data. + * @param {boolean} [options.snapshot=false] Snapshot query. + * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. + * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. + * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {boolean} [options.returnKey=false] Only return the index key. + * @param {number} [options.maxScan=null] Limit the number of items to scan. + * @param {number} [options.min=null] Set index bounds. + * @param {number} [options.max=null] Set index bounds. + * @param {boolean} [options.showDiskLoc=false] Show disk location of results. + * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use find().limit(1).next(function(err, doc){}) + */ +Collection.prototype.findOne = function() { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + var callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + + // Execute using callback + if(typeof callback == 'function') return findOne(self, args, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findOne(self, args, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOne = function(self, args, callback) { + var cursor = self.find.apply(self, args).limit(-1).batchSize(1); + // Return the item + cursor.next(function(err, item) { + if(err != null) return handleCallback(callback, toError(err), null); + handleCallback(callback, null, item); + }); +} + +define.classMethod('findOne', {callback: true, promise:true}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Collection~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Rename the collection. + * + * @method + * @param {string} newName New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Collection~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.rename = function(newName, opt, callback) { + var self = this; + if(typeof opt == 'function') callback = opt, opt = {}; + opt = opt || {}; + + // Execute using callback + if(typeof callback == 'function') return rename(self, newName, opt, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + rename(self, newName, opt, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var rename = function(self, newName, opt, callback) { + // Check the collection name + checkCollectionName(newName); + // Build the command + var renameCollection = f("%s.%s", self.s.dbName, self.s.name); + var toCollection = f("%s.%s", self.s.dbName, newName); + var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false; + var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; + + // Execute against admin + self.s.db.admin().command(cmd, opt, function(err, doc) { + if(err) return handleCallback(callback, err, null); + // We have an error + if(doc.errmsg) return handleCallback(callback, toError(doc), null); + try { + return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options)); + } catch(err) { + return handleCallback(callback, toError(err), null); + } + }); +} + +define.classMethod('rename', {callback: true, promise:true}); + +/** + * Drop the collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.drop = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, callback); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.s.db.dropCollection(self.s.name, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('drop', {callback: true, promise:true}); + +/** + * Returns the options of the collection. + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.options = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return options(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var options = function(self, callback) { + self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) { + if(err) return handleCallback(callback, err); + if(collections.length == 0) { + return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true })); + } + + handleCallback(callback, err, collections[0].options || null); + }); +} + +define.classMethod('options', {callback: true, promise:true}); + +/** + * Returns if the collection is a capped collection + * + * @method + * @param {Collection~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.isCapped = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return isCapped(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + isCapped(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var isCapped = function(self, callback) { + self.options(function(err, document) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, document && document.capped); + }); +} + +define.classMethod('isCapped', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + + // Execute using callback + if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Creates multiple indexes in the collection, this method is only supported for + * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported + * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. + * @method + * @param {array} indexSpecs An array of index specifications to be created + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.createIndexes = function(indexSpecs, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndexes(self, indexSpecs, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var createIndexes = function(self, indexSpecs, callback) { + // Ensure we generate the correct name if the parameter is not set + for(var i = 0; i < indexSpecs.length; i++) { + if(indexSpecs[i].name == null) { + var keys = []; + + for(var name in indexSpecs[i].key) { + keys.push(f('%s_%s', name, indexSpecs[i].key[name])); + } + + // Set the name + indexSpecs[i].name = keys.join('_'); + } + } + + // Execute the index + self.s.db.command({ + createIndexes: self.s.name, indexes: indexSpecs + }, callback); +} + +define.classMethod('createIndexes', {callback: true, promise:true}); + +/** + * Drops an index from this collection. + * @method + * @param {string} indexName Name of the index to drop. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndex = function(indexName, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return dropIndex(self, indexName, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndex(self, indexName, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndex = function(self, indexName, options, callback) { + // Delete index command + var cmd = {'deleteIndexes':self.s.name, 'index':indexName}; + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(typeof callback != 'function') return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result); + }); +} + +define.classMethod('dropIndex', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.dropIndexes = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return dropIndexes(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + dropIndexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var dropIndexes = function(self, callback) { + self.dropIndex('*', function (err, result) { + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true); + }); +} + +define.classMethod('dropIndexes', {callback: true, promise:true}); + +/** + * Drops all indexes from this collection. + * @method + * @deprecated use dropIndexes + * @param {Collection~resultCallback} callback The command result callback + * @return {Promise} returns Promise if no [callback] passed + */ +Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; + +define.classMethod('dropAllIndexes', {callback: true, promise:true}); + +/** + * Reindex all indexes on the collection + * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.reIndex = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return reIndex(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + reIndex(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var reIndex = function(self, options, callback) { + // Reindex + var cmd = {'reIndex':self.s.name}; + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); +} + +define.classMethod('reIndex', {callback: true, promise:true}); + +/** + * Get the list of all indexes information for the collection. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @return {CommandCursor} + */ +Collection.prototype.listIndexes = function(options) { + options = options || {}; + // Clone the options + options = shallowClone(options); + // Set the CommandCursor constructor + options.cursorFactory = CommandCursor; + // Set the promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // We have a list collections command + if(this.s.db.serverConfig.capabilities().hasListIndexesCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listIndexes: this.s.name, cursor: cursor }; + // Execute the cursor + return this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); + } + + // Get the namespace + var ns = f('%s.system.indexes', this.s.dbName); + // Get the query + return this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options); +}; + +define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated use createIndexes instead + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var ensureIndex = function(self, fieldOrSpec, options, callback) { + self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +/** + * Checks if one or more indexes exist on the collection, fails on first non-existing index + * @method + * @param {(string|array)} indexes One or more index names to check. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexExists = function(indexes, callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') return indexExists(self, indexes, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexExists(self, indexes, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexExists = function(self, indexes, callback) { + self.indexInformation(function(err, indexInformation) { + // If we have an error return + if(err != null) return handleCallback(callback, err, null); + // Let's check for the index names + if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); + // Check in list of indexes + for(var i = 0; i < indexes.length; i++) { + if(indexInformation[indexes[i]] == null) { + return handleCallback(callback, null, false); + } + } + + // All keys found return true + return handleCallback(callback, null, true); + }); +} + +define.classMethod('indexExists', {callback: true, promise:true}); + +/** + * Retrieves this collections index info. + * @method + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexInformation = function(options, callback) { + var self = this; + // Unpack calls + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return indexInformation(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexInformation = function(self, options, callback) { + self.s.db.indexInformation(self.s.name, options, callback); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Collection~countCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} result The count of documents that matched the query. + */ + +/** + * Count number of matching documents in the db to a query. + * @method + * @param {object} query The query for the count. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.limit=null] The limit of documents to count. + * @param {boolean} [options.skip=null] The number of documents to skip for the count. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~countCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.count = function(query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback); + + // Check if query is empty + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, query, options, callback) { + var skip = options.skip; + var limit = options.limit; + var hint = options.hint; + var maxTimeMS = options.maxTimeMS; + + // Final query + var cmd = { + 'count': self.s.name, 'query': query + , 'fields': null + }; + + // Add limit and skip if defined + if(typeof skip == 'number') cmd.skip = skip; + if(typeof limit == 'number') cmd.limit = limit; + if(hint) options.hint = hint; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.n); + }); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * The distinct command returns returns a list of distinct values for the given key across a collection. + * @method + * @param {string} key Field of the document to find distinct values for. + * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.distinct = function(key, query, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + var queryOption = args.length ? args.shift() || {} : {}; + var optionsOption = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback); + + // Ensure the query and options are set + query = query || {}; + options = options || {}; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + distinct(self, key, query, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var distinct = function(self, key, query, options, callback) { + // maxTimeMS option + var maxTimeMS = options.maxTimeMS; + + // Distinct command + var cmd = { + 'distinct': self.s.name, 'key': key, 'query': query + }; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + cmd.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.values); + }); +} + +define.classMethod('distinct', {callback: true, promise:true}); + +/** + * Retrieve all the indexes on the collection. + * @method + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.indexes = function(callback) { + var self = this; + // Execute using callback + if(typeof callback == 'function') return indexes(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexes(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var indexes = function(self, callback) { + self.s.db.indexInformation(self.s.name, {full:true}, callback); +} + +define.classMethod('indexes', {callback: true, promise:true}); + +/** + * Get all the collection statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Collection~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.stats = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return stats(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + stats(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var stats = function(self, options, callback) { + // Build command object + var commandObject = { + collStats:self.s.name + } + + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Execute the command + self.s.db.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +/** + * @typedef {Object} Collection~findAndModifyWriteOpResult + * @property {object} value Document returned from findAndModify command. + * @property {object} lastErrorObject The raw lastErrorObject returned from the command. + * @property {Number} ok Is 1 if the command executed correctly. + */ + +/** + * The callback format for inserts + * @callback Collection~findAndModifyCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. + */ + +/** + * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndDelete = function(filter, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndDelete(self, filter, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndDelete = function(self, filter, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['remove'] = true; + // Execute find and Modify + self.findAndModify( + filter + , options.sort + , null + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndDelete', {callback: true, promise:true}); + +/** + * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} replacement Document replacing the matching document. + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndReplace(self, filter, replacement, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndReplace = function(self, filter, replacement, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , replacement + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndReplace', {callback: true, promise:true}); + +/** + * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. + * + * @method + * @param {object} filter Document selection filter. + * @param {object} update Update operations to be performed on the document + * @param {object} [options=null] Optional settings. + * @param {object} [options.projection=null] Limits the fields to return for all matching documents. + * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. + * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. + * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. + * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. + * @param {Collection~findAndModifyCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // Execute using callback + if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findOneAndUpdate(self, filter, update, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findOneAndUpdate = function(self, filter, update, options, callback) { + // Final options + var finalOptions = shallowClone(options); + finalOptions['fields'] = options.projection; + finalOptions['update'] = true; + finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; + finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; + + // Execute findAndModify + self.findAndModify( + filter + , options.sort + , update + , finalOptions + , callback + ); +} + +define.classMethod('findOneAndUpdate', {callback: true, promise:true}); + +/** + * Find and update a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} doc The fields/vals to be updated. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.remove=false] Set to true to remove the object before returning. + * @param {boolean} [options.upsert=false] Perform an upsert operation. + * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. + * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead + */ +Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + doc = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Clone options + var options = shallowClone(options); + // Force read preference primary + options.readPreference = ReadPreference.PRIMARY; + + // Execute using callback + if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + options = options || {}; + + findAndModify(self, query, sort, doc, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndModify = function(self, query, sort, doc, options, callback) { + // Create findAndModify command object + var queryObject = { + 'findandmodify': self.s.name + , 'query': query + }; + + sort = formattedOrderClause(sort); + if(sort) { + queryObject.sort = sort; + } + + queryObject.new = options.new ? true : false; + queryObject.remove = options.remove ? true : false; + queryObject.upsert = options.upsert ? true : false; + + if(options.fields) { + queryObject.fields = options.fields; + } + + if(doc && !options.remove) { + queryObject.update = doc; + } + + // Either use override on the function, or go back to default on either the collection + // level or db + if(options['serializeFunctions'] != null) { + options['serializeFunctions'] = options['serializeFunctions']; + } else { + options['serializeFunctions'] = self.s.serializeFunctions; + } + + // No check on the documents + options.checkKeys = false; + + // Get the write concern settings + var finalOptions = writeConcern(options, self.s.db, self, options); + + // Decorate the findAndModify command with the write Concern + if(finalOptions.writeConcern) { + queryObject.writeConcern = finalOptions.writeConcern; + } + + // Have we specified bypassDocumentValidation + if(typeof finalOptions.bypassDocumentValidation == 'boolean') { + queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; + } + + // Execute the command + self.s.db.command(queryObject + , options, function(err, result) { + if(err) return handleCallback(callback, err, null); + return handleCallback(callback, null, result); + }); +} + +define.classMethod('findAndModify', {callback: true, promise:true}); + +/** + * Find and remove a document. + * @method + * @param {object} query Query object to locate the object to modify. + * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + * @deprecated use findOneAndDelete instead + */ +Collection.prototype.findAndRemove = function(query, sort, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + sort = args.length ? args.shift() || [] : []; + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + findAndRemove(self, query, sort, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var findAndRemove = function(self, query, sort, options, callback) { + // Add the remove option + options['remove'] = true; + // Execute the callback + self.findAndModify(query, sort, null, options, callback); +} + +define.classMethod('findAndRemove', {callback: true, promise:true}); + +/** + * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 + * @method + * @param {object} pipeline Array containing all the aggregation framework commands for the execution. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. + * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor + * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). + * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). + * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~resultCallback} callback The command result callback + * @return {(null|AggregationCursor)} + */ +Collection.prototype.aggregate = function(pipeline, options, callback) { + var self = this; + if(Array.isArray(pipeline)) { + // Set up callback if one is provided + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // If we have no options or callback we are doing + // a cursor based aggregation + if(options == null && callback == null) { + options = {}; + } + } else { + // Aggregation pipeline passed as arguments on the method + var args = Array.prototype.slice.call(arguments, 0); + // Get the callback + callback = args.pop(); + // Get the possible options object + var opts = args[args.length - 1]; + // If it contains any of the admissible options pop it of the args + options = opts && (opts.readPreference + || opts.explain || opts.cursor || opts.out + || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {}; + // Left over arguments is the pipeline + pipeline = args; + } + + // If out was specified + if(typeof options.out == 'string') { + pipeline.push({$out: options.out}); + } + + // Build the command + var command = { aggregate : this.s.name, pipeline : pipeline}; + + // If we have bypassDocumentValidation set + if(typeof options.bypassDocumentValidation == 'boolean') { + command.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Do we have a readConcern specified + if(this.s.readConcern) { + command.readConcern = this.s.readConcern; + } + + // If we have allowDiskUse defined + if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // If explain has been specified add it + if(options.explain) command.explain = options.explain; + + // Validate that cursor options is valid + if(options.cursor != null && typeof options.cursor != 'object') { + throw toError('cursor options must be an object'); + } + + // promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Set the AggregationCursor constructor + options.cursorFactory = AggregationCursor; + if(typeof callback != 'function') { + if(this.s.topology.capabilities().hasAggregationCursor) { + options.cursor = options.cursor || { batchSize : 1000 }; + command.cursor = options.cursor; + } + + // Allow disk usage command + if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse; + if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; + + // Execute the cursor + return this.s.topology.cursor(this.s.namespace, command, options); + } + + var cursor = null; + // We do not allow cursor + if(options.cursor) { + return this.s.topology.cursor(this.s.namespace, command, options); + } + + // Execute the command + this.s.db.command(command, options, function(err, result) { + if(err) { + handleCallback(callback, err); + } else if(result['err'] || result['errmsg']) { + handleCallback(callback, toError(result)); + } else if(typeof result == 'object' && result['serverPipeline']) { + handleCallback(callback, null, result['serverPipeline']); + } else if(typeof result == 'object' && result['stages']) { + handleCallback(callback, null, result['stages']); + } else { + handleCallback(callback, null, result.result); + } + }); +} + +define.classMethod('aggregate', {callback: true, promise:false}); + +/** + * The callback format for results + * @callback Collection~parallelCollectionScanCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. + */ + +/** + * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are + * no ordering guarantees for returned results. + * @method + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. + * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) + * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. + * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.parallelCollectionScan = function(options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {numCursors: 1}; + // Set number of cursors to 1 + options.numCursors = options.numCursors || 1; + options.batchSize = options.batchSize || 1000; + + // Ensure we have the right read preference inheritance + options = getReadPreference(this, options, this.s.db, this); + + // Add a promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Execute using callback + if(typeof callback == 'function') return parallelCollectionScan(self, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + parallelCollectionScan(self, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var parallelCollectionScan = function(self, options, callback) { + // Create command object + var commandObject = { + parallelCollectionScan: self.s.name + , numCursors: options.numCursors + } + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null); + + var cursors = []; + // Create command cursors for each item + for(var i = 0; i < result.cursors.length; i++) { + var rawId = result.cursors[i].cursor.id + // Convert cursorId to Long if needed + var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId; + + // Command cursor options + var cmd = { + batchSize: options.batchSize + , cursorId: cursorId + , items: result.cursors[i].cursor.firstBatch + } + + // Add a command cursor + cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); + } + + handleCallback(callback, null, cursors); + }); +} + +define.classMethod('parallelCollectionScan', {callback: true, promise:true}); + +/** + * Execute the geoNear command to search for items in the collection + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.num=null] Max number of results to return. + * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher) + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions. + * @param {object} [options.query=null] Filter the results by a query. + * @param {boolean} [options.spherical=false] Perform query using a spherical model. + * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X. + * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoNear = function(x, y, options, callback) { + var self = this; + var point = typeof(x) == 'object' && x + , args = Array.prototype.slice.call(arguments, point?1:2); + + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoNear(self, x, y, point, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoNear = function(self, x, y, point, options, callback) { + // Build command object + var commandObject = { + geoNear:self.s.name, + near: point || [x, y] + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Exclude readPreference and existing options to prevent user from + // shooting themselves in the foot + var exclude = { + readPreference: true, + geoNear: true, + near: true + }; + + // Filter out any excluded objects + commandObject = decorateCommand(commandObject, options, exclude); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) return handleCallback(callback, toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoNear', {callback: true, promise:true}); + +/** + * Execute a geo search using a geo haystack index on a collection. + * + * @method + * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. + * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. + * @param {object} [options.search=null] Filter the results by a query. + * @param {number} [options.limit=false] Max number of results to return. + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + options = args.length ? args.shift() || {} : {}; + + // Execute using callback + if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + geoHaystackSearch(self, x, y, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var geoHaystackSearch = function(self, x, y, options, callback) { + // Build command object + var commandObject = { + geoSearch: self.s.name, + near: [x, y] + } + + // Remove read preference from hash if it exists + commandObject = decorateCommand(commandObject, options, {readPreference: true}); + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + commandObject.readConcern = self.s.readConcern; + } + + // Execute the command + self.s.db.command(commandObject, options, function (err, res) { + if(err) return handleCallback(callback, err); + if(res.err || res.errmsg) handleCallback(callback, utils.toError(res)); + // should we only be returning res.results here? Not sure if the user + // should see the other return information + handleCallback(callback, null, res); + }); +} + +define.classMethod('geoHaystackSearch', {callback: true, promise:true}); + +/** + * Group function helper + * @ignore + */ +var groupFunction = function () { + var c = db[ns].find(condition); + var map = new Map(); + var reduce_function = reduce; + + while (c.hasNext()) { + var obj = c.next(); + var key = {}; + + for (var i = 0, len = keys.length; i < len; ++i) { + var k = keys[i]; + key[k] = obj[k]; + } + + var aggObj = map.get(key); + + if (aggObj == null) { + var newObj = Object.extend({}, key); + aggObj = Object.extend(newObj, initial); + map.put(key, aggObj); + } + + reduce_function(obj, aggObj); + } + + return { "result": map.values() }; +}.toString(); + +/** + * Run a group command across a collection + * + * @method + * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. + * @param {object} condition An optional condition that must be true for a row to be considered. + * @param {object} initial Initial value of the aggregation counter object. + * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated + * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. + * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Collection~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 3); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + // Fetch all commands + reduce = args.length ? args.shift() : null; + finalize = args.length ? args.shift() : null; + command = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Make sure we are backward compatible + if(!(typeof finalize == 'function')) { + command = finalize; + finalize = null; + } + + if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) { + keys = Object.keys(keys); + } + + if(typeof reduce === 'function') { + reduce = reduce.toString(); + } + + if(typeof finalize === 'function') { + finalize = finalize.toString(); + } + + // Set up the command as default + command = command == null ? true : command; + + // Execute using callback + if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) { + // Execute using the command + if(command) { + var reduceFunction = reduce instanceof Code + ? reduce + : new Code(reduce); + + var selector = { + group: { + 'ns': self.s.name + , '$reduce': reduceFunction + , 'cond': condition + , 'initial': initial + , 'out': "inline" + } + }; + + // if finalize is defined + if(finalize != null) selector.group['finalize'] = finalize; + // Set up group selector + if ('function' === typeof keys || keys instanceof Code) { + selector.group.$keyf = keys instanceof Code + ? keys + : new Code(keys); + } else { + var hash = {}; + keys.forEach(function (key) { + hash[key] = 1; + }); + selector.group.key = hash; + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // Do we have a readConcern specified + if(self.s.readConcern) { + selector.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(selector, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.retval); + }); + } else { + // Create execution scope + var scope = reduce != null && reduce instanceof Code + ? reduce.scope + : {}; + + scope.ns = self.s.name; + scope.keys = keys; + scope.condition = condition; + scope.initial = initial; + + // Pass in the function text to execute within mongodb. + var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); + + self.s.db.eval(new Code(groupfn, scope), function (err, results) { + if (err) return handleCallback(callback, err, null); + handleCallback(callback, null, results.result || results); + }); + } +} + +define.classMethod('group', {callback: true, promise:true}); + +/** + * Functions that are passed as scope args must + * be converted to Code instances. + * @ignore + */ +function processScope (scope) { + if(!isObject(scope)) { + return scope; + } + + var keys = Object.keys(scope); + var i = keys.length; + var key; + var new_scope = {}; + + while (i--) { + key = keys[i]; + if ('function' == typeof scope[key]) { + new_scope[key] = new Code(String(scope[key])); + } else { + new_scope[key] = processScope(scope[key]); + } + } + + return new_scope; +} + +/** + * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. + * + * @method + * @param {(function|string)} map The mapping function. + * @param {(function|string)} reduce The reduce function. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* + * @param {object} [options.query=null] Query filter object. + * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. + * @param {number} [options.limit=null] Number of objects to return from collection. + * @param {boolean} [options.keeptemp=false] Keep temporary data. + * @param {(function|string)} [options.finalize=null] Finalize function. + * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. + * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. + * @param {boolean} [options.verbose=false] Provide statistics on job execution time. + * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. + * @param {Collection~resultCallback} [callback] The command result callback + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Collection.prototype.mapReduce = function(map, reduce, options, callback) { + var self = this; + if('function' === typeof options) callback = options, options = {}; + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if(null == options.out) { + throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); + } + + if('function' === typeof map) { + map = map.toString(); + } + + if('function' === typeof reduce) { + reduce = reduce.toString(); + } + + if('function' === typeof options.finalize) { + options.finalize = options.finalize.toString(); + } + + // Execute using callback + if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + mapReduce(self, map, reduce, options, function(err, r, r1) { + if(err) return reject(err); + if(r instanceof Collection) return resolve(r); + resolve({results: r, stats: r1}); + }); + }); +} + +var mapReduce = function(self, map, reduce, options, callback) { + var mapCommandHash = { + mapreduce: self.s.name + , map: map + , reduce: reduce + }; + + // Add any other options passed in + for(var n in options) { + if('scope' == n) { + mapCommandHash[n] = processScope(options[n]); + } else { + mapCommandHash[n] = options[n]; + } + } + + // Ensure we have the right read preference inheritance + options = getReadPreference(self, options, self.s.db, self); + + // If we have a read preference and inline is not set as output fail hard + if((options.readPreference != false && options.readPreference != 'primary') + && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { + options.readPreference = 'primary'; + } + + // Is bypassDocumentValidation specified + if(typeof options.bypassDocumentValidation == 'boolean') { + mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Do we have a readConcern specified + if(self.s.readConcern) { + mapCommandHash.readConcern = self.s.readConcern; + } + + // Execute command + self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) { + if(err) return handleCallback(callback, err); + // Check if we have an error + if(1 != result.ok || result.err || result.errmsg) { + return handleCallback(callback, toError(result)); + } + + // Create statistics value + var stats = {}; + if(result.timeMillis) stats['processtime'] = result.timeMillis; + if(result.counts) stats['counts'] = result.counts; + if(result.timing) stats['timing'] = result.timing; + + // invoked with inline? + if(result.results) { + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, null, result.results); + } + + return handleCallback(callback, null, result.results, stats); + } + + // The returned collection + var collection = null; + + // If we have an object it's a different db + if(result.result != null && typeof result.result == 'object') { + var doc = result.result; + collection = self.s.db.db(doc.db).collection(doc.collection); + } else { + // Create a collection object that wraps the result collection + collection = self.s.db.collection(result.result) + } + + // If we wish for no verbosity + if(options['verbose'] == null || !options['verbose']) { + return handleCallback(callback, err, collection); + } + + // Return stats as third set of values + handleCallback(callback, err, collection, stats); + }); +} + +define.classMethod('mapReduce', {callback: true, promise:true}); + +/** + * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @return {UnorderedBulkOperation} + */ +Collection.prototype.initializeUnorderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return unordered(this.s.topology, this, options); +} + +define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]}); + +/** + * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {OrderedBulkOperation} callback The command result callback + * @return {null} + */ +Collection.prototype.initializeOrderedBulkOp = function(options) { + options = options || {}; + options.promiseLibrary = this.s.promiseLibrary; + return ordered(this.s.topology, this, options); +} + +define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]}); + +// Get write concern +var writeConcern = function(target, db, col, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w != null) opts.w = options.w; + if(options.wtimeout != null) opts.wtimeout = options.wtimeout; + if(options.j != null) opts.j = options.j; + if(options.fsync != null) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { + target.writeConcern = col.writeConcern; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Figure out the read preference +var getReadPreference = function(self, options, db, coll) { + var r = null + if(options.readPreference) { + r = options.readPreference + } else if(self.s.readPreference) { + r = self.s.readPreference + } else if(db.readPreference) { + r = db.readPreference; + } + + if(r instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else if(typeof r == 'string') { + options.readPreference = new CoreReadPreference(r); + } + + return options; +} + +var testForFields = { + limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 + , numberOfRetries: 1, awaitdata: 1, awaitData: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 + , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms: 1 +} + +module.exports = Collection; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/command_cursor.js b/util/demographicsImporter/node_modules/mongodb/lib/command_cursor.js new file mode 100644 index 0000000..37df593 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/command_cursor.js @@ -0,0 +1,296 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('./cursor') + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **CommandCursor** class is an internal class that embodies a + * generalized cursor based on a MongoDB command allowing for iteration over the + * results returned. It supports one by one document iteration, conversion to an + * array or can be iterated as a Node 0.10.X or higher stream + * + * **CommandCursor Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('listCollectionsExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // List the database collections available + * db.listCollections().toArray(function(err, items) { + * test.equal(null, err); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the browser. + * @external Readable + */ + +/** + * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class CommandCursor + * @extends external:Readable + * @fires CommandCursor#data + * @fires CommandCursor#end + * @fires CommandCursor#close + * @fires CommandCursor#readable + * @return {CommandCursor} an CommandCursor instance. + */ +var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = CommandCursor.INIT; + var streamOptions = {}; + + // MaxTimeMS + var maxTimeMS = null; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal state + this.s = { + // MaxTimeMS + maxTimeMS: maxTimeMS + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespae + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology Options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + } +} + +/** + * CommandCursor stream data event, fired for each document in the cursor. + * + * @event CommandCursor#data + * @type {object} + */ + +/** + * CommandCursor stream end event + * + * @event CommandCursor#end + * @type {null} + */ + +/** + * CommandCursor stream close event + * + * @event CommandCursor#close + * @type {null} + */ + +/** + * CommandCursor stream readable event + * + * @event CommandCursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(CommandCursor, Readable); + +// Set the methods to inherit from prototype +var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' + , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' + , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled']; + +// Only inherit the types we need +for(var i = 0; i < methodsToInherit.length; i++) { + CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; +} + +var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {CommandCursor} + */ +CommandCursor.prototype.batchSize = function(value) { + if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]}); + +/** + * Add a maxTimeMS stage to the aggregation pipeline + * @method + * @param {number} value The state maxTimeMS value. + * @return {CommandCursor} + */ +CommandCursor.prototype.maxTimeMS = function(value) { + if(this.s.topology.lastIsMaster().minWireVersion > 2) { + this.s.cmd.maxTimeMS = value; + } + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]}); + +CommandCursor.prototype.get = CommandCursor.prototype.toArray; + +define.classMethod('get', {callback: true, promise:false}); + +// Inherited methods +define.classMethod('toArray', {callback: true, promise:true}); +define.classMethod('each', {callback: true, promise:false}); +define.classMethod('forEach', {callback: true, promise:false}); +define.classMethod('next', {callback: true, promise:true}); +define.classMethod('close', {callback: true, promise:true}); +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); +define.classMethod('rewind', {callback: false, promise:false}); +define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); +define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @function CommandCursor.prototype.next + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. + * @method CommandCursor.prototype.toArray + * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ + +/** + * The callback format for results + * @callback CommandCursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null)} result The result object if the command was executed successfully. + */ + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method CommandCursor.prototype.each + * @param {CommandCursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method CommandCursor.prototype.close + * @param {CommandCursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ + +/** + * Is the cursor closed + * @method CommandCursor.prototype.isClosed + * @return {boolean} + */ + +/** + * Clone the cursor + * @function CommandCursor.prototype.clone + * @return {CommandCursor} + */ + +/** + * Resets the cursor + * @function CommandCursor.prototype.rewind + * @return {CommandCursor} + */ + +/** + * The callback format for the forEach iterator method + * @callback CommandCursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback CommandCursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/* + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method CommandCursor.prototype.forEach + * @param {CommandCursor~iteratorCallback} iterator The iteration callback. + * @param {CommandCursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ + +CommandCursor.INIT = 0; +CommandCursor.OPEN = 1; +CommandCursor.CLOSED = 2; + +module.exports = CommandCursor; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/cursor.js b/util/demographicsImporter/node_modules/mongodb/lib/cursor.js new file mode 100644 index 0000000..1a446a8 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/cursor.js @@ -0,0 +1,1149 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , toError = require('./utils').toError + , getSingleProperty = require('./utils').getSingleProperty + , formattedOrderClause = require('./utils').formattedOrderClause + , handleCallback = require('./utils').handleCallback + , Logger = require('mongodb-core').Logger + , EventEmitter = require('events').EventEmitter + , ReadPreference = require('./read_preference') + , MongoError = require('mongodb-core').MongoError + , Readable = require('stream').Readable || require('readable-stream').Readable + , Define = require('./metadata') + , CoreCursor = require('mongodb-core').Cursor + , Query = require('mongodb-core').Query + , CoreReadPreference = require('mongodb-core').ReadPreference; + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. It supports + * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X + * or higher stream + * + * **CURSORS Cannot directly be instantiated** + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Create a collection we want to drop later + * var col = db.collection('createIndexExample1'); + * // Insert a bunch of documents + * col.insert([{a:1, b:1} + * , {a:2, b:2}, {a:3, b:3} + * , {a:4, b:4}], {w:1}, function(err, result) { + * test.equal(null, err); + * + * // Show that duplicate records got dropped + * col.find({}).toArray(function(err, items) { + * test.equal(null, err); + * test.equal(4, items.length); + * db.close(); + * }); + * }); + * }); + */ + +/** + * Namespace provided by the mongodb-core and node.js + * @external CoreCursor + * @external Readable + */ + +// Flags allowed for cursor +var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; +var fields = ['numberOfRetries', 'tailableRetryInterval']; + +/** + * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) + * @class Cursor + * @extends external:CoreCursor + * @extends external:Readable + * @property {string} sortValue Cursor query sort setting. + * @property {boolean} timeout Is Cursor able to time out. + * @property {ReadPreference} readPreference Get cursor ReadPreference. + * @fires Cursor#data + * @fires Cursor#end + * @fires Cursor#close + * @fires Cursor#readable + * @return {Cursor} a Cursor instance. + * @example + * Cursor cursor options. + * + * collection.find({}).project({a:1}) // Create a projection of field a + * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 + * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 + * collection.find({}).filter({a:1}) // Set query on the cursor + * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries + * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable + * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay + * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout + * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData + * collection.find({}).addCursorFlag('exhaust', true) // Set cursor as exhaust + * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial + * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} + * collection.find({}).max(10) // Set the cursor maxScan + * collection.find({}).maxScan(10) // Set the cursor maxScan + * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS + * collection.find({}).min(100) // Set the cursor min + * collection.find({}).returnKey(10) // Set the cursor returnKey + * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference + * collection.find({}).showRecordId(true) // Set the cursor showRecordId + * collection.find({}).snapshot(true) // Set the cursor snapshot + * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query + * collection.find({}).hint('a_1') // Set the cursor hint + * + * All options are chainable, so one can do the following. + * + * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); + var self = this; + var state = Cursor.INIT; + var streamOptions = {}; + + // Tailable cursor options + var numberOfRetries = options.numberOfRetries || 5; + var tailableRetryInterval = options.tailableRetryInterval || 500; + var currentNumberOfRetries = numberOfRetries; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set up + Readable.call(this, {objectMode: true}); + + // Internal cursor state + this.s = { + // Tailable cursor options + numberOfRetries: numberOfRetries + , tailableRetryInterval: tailableRetryInterval + , currentNumberOfRetries: currentNumberOfRetries + // State + , state: state + // Stream options + , streamOptions: streamOptions + // BSON + , bson: bson + // Namespace + , ns: ns + // Command + , cmd: cmd + // Options + , options: options + // Topology + , topology: topology + // Topology options + , topologyOptions: topologyOptions + // Promise library + , promiseLibrary: promiseLibrary + // Current doc + , currentDoc: null + } + + // Legacy fields + this.timeout = self.s.options.noCursorTimeout == true; + this.sortValue = self.s.cmd.sort; + this.readPreference = self.s.options.readPreference; +} + +/** + * Cursor stream data event, fired for each document in the cursor. + * + * @event Cursor#data + * @type {object} + */ + +/** + * Cursor stream end event + * + * @event Cursor#end + * @type {null} + */ + +/** + * Cursor stream close event + * + * @event Cursor#close + * @type {null} + */ + +/** + * Cursor stream readable event + * + * @event Cursor#readable + * @type {null} + */ + +// Inherit from Readable +inherits(Cursor, Readable); + +// Map core cursor _next method so we can apply mapping +CoreCursor.prototype._next = CoreCursor.prototype.next; + +for(var name in CoreCursor.prototype) { + Cursor.prototype[name] = CoreCursor.prototype[name]; +} + +var define = Cursor.define = new Define('Cursor', Cursor, true); + +/** + * Check if there is any document still available in the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.hasNext = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + if(self.s.currentDoc){ + return callback(null, true); + } else { + return nextObject(self, function(err, doc) { + if(!doc) return callback(null, false); + self.s.currentDoc = doc; + callback(null, true); + }); + } + } + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + if(self.s.currentDoc){ + resolve(true); + } else { + nextObject(self, function(err, doc) { + if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false); + if(err) return reject(err); + if(!doc) return resolve(false); + self.s.currentDoc = doc; + resolve(true); + }); + } + }); +} + +define.classMethod('hasNext', {callback: true, promise:true}); + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.next = function(callback) { + var self = this; + + // Execute using callback + if(typeof callback == 'function') { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return callback(null, doc); + } + + // Return the next object + return nextObject(self, callback) + }; + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + // Return the currentDoc if someone called hasNext first + if(self.s.currentDoc) { + var doc = self.s.currentDoc; + self.s.currentDoc = null; + return resolve(doc); + } + + nextObject(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('next', {callback: true, promise:true}); + +/** + * Set the cursor query + * @method + * @param {object} filter The filter object used for the cursor. + * @return {Cursor} + */ +Cursor.prototype.filter = function(filter) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.query = filter; + return this; +} + +define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor maxScan + * @method + * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query + * @return {Cursor} + */ +Cursor.prototype.maxScan = function(maxScan) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxScan = maxScan; + return this; +} + +define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor hint + * @method + * @param {object} hint If specified, then the query system will only consider plans using the hinted index. + * @return {Cursor} + */ +Cursor.prototype.hint = function(hint) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.hint = hint; + return this; +} + +define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor min + * @method + * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.min = function(min) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.min = min; + return this; +} + +define.classMethod('min', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor max + * @method + * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. + * @return {Cursor} + */ +Cursor.prototype.max = function(max) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.max = max; + return this; +} + +define.classMethod('max', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor returnKey + * @method + * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms: + * @return {Cursor} + */ +Cursor.prototype.returnKey = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.returnKey = value; + return this; +} + +define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor showRecordId + * @method + * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. + * @return {Cursor} + */ +Cursor.prototype.showRecordId = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.showDiskLoc = value; + return this; +} + +define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the cursor snapshot + * @method + * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. + * @return {Cursor} + */ +Cursor.prototype.snapshot = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.snapshot = value; + return this; +} + +define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a node.js specific cursor option + * @method + * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. + * @param {object} value The field value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setCursorOption = function(field, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true }); + this.s[field] = value; + if(field == 'numberOfRetries') + this.s.currentNumberOfRetries = value; + return this; +} + +define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a cursor flag to the cursor + * @method + * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']. + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addCursorFlag = function(flag, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true }); + if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true}); + this.s.cmd[flag] = value; + return this; +} + +define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a query modifier to the cursor query + * @method + * @param {string} name The query modifier (must start with $, such as $orderby etc) + * @param {boolean} value The flag boolean value. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.addQueryModifier = function(name, value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true}); + // Strip of the $ + var field = name.substr(1); + // Set on the command + this.s.cmd[field] = value; + // Deal with the special case for sort + if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field]; + return this; +} + +define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Add a comment to the cursor query allowing for tracking the comment in the log. + * @method + * @param {string} value The comment attached to this query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.comment = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.comment = value; + return this; +} + +define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) + * @method + * @param {number} value Number of milliseconds to wait before aborting the query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.maxTimeMS = function(value) { + if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.maxTimeMS = value; + return this; +} + +define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]}); + +Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; + +define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets a field projection for the query. + * @method + * @param {object} value The field projection object. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.project = function(value) { + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + this.s.cmd.fields = value; + return this; +} + +define.classMethod('project', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Sets the sort order of the cursor query. + * @method + * @param {(string|array|object)} keyOrList The key or keys set for the sort. + * @param {number} [direction] The direction of the sorting (1 or -1). + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.sort = function(keyOrList, direction) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true}); + if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + var order = keyOrList; + + if(direction != null) { + order = [[keyOrList, direction]]; + } + + this.s.cmd.sort = order; + this.sortValue = order; + return this; +} + +define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the batch size for the cursor. + * @method + * @param {number} value The batchSize for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.batchSize = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true}); + if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); + this.s.cmd.batchSize = value; + this.setCursorBatchSize(value); + return this; +} + +define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the limit for the cursor. + * @method + * @param {number} value The limit for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.limit = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true}); + this.s.cmd.limit = value; + // this.cursorLimit = value; + this.setCursorLimit(value); + return this; +} + +define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Set the skip for the cursor. + * @method + * @param {number} value The skip for the cursor query. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.skip = function(value) { + if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true}); + if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); + if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true}); + this.s.cmd.skip = value; + this.setCursorSkip(value); + return this; +} + +define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {(object|null|boolean)} result The result object if the command was executed successfully. + */ + +/** + * Clone the cursor + * @function external:CoreCursor#clone + * @return {Cursor} + */ + +/** + * Resets the cursor + * @function external:CoreCursor#rewind + * @return {null} + */ + +/** + * Get the next available document from the cursor, returns null if no more documents are available. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @throws {MongoError} + * @deprecated + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.nextObject = Cursor.prototype.next; + +var nextObject = function(self, callback) { + if(self.s.state == Cursor.CLOSED || self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + if(self.s.state == Cursor.INIT && self.s.cmd.sort) { + try { + self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort); + } catch(err) { + return handleCallback(callback, err); + } + } + + // Get the next object + self._next(function(err, doc) { + if(err && err.tailable && self.s.currentNumberOfRetries == 0) return callback(err); + if(err && err.tailable && self.s.currentNumberOfRetries > 0) { + self.s.currentNumberOfRetries = self.s.currentNumberOfRetries - 1; + + return setTimeout(function() { + // Rewind the cursor only when it has not actually read any documents yet + if(self.cursorState.currentLimit == 0) self.rewind(); + // Read the next document, forcing a re-issue of query if no cursorId exists + self.nextObject(callback); + }, self.s.tailableRetryInterval); + } + + self.s.state = Cursor.OPEN; + if(err) return handleCallback(callback, err); + handleCallback(callback, null, doc); + }); +} + +define.classMethod('nextObject', {callback: true, promise:true}); + +// Trampoline emptying the number of retrieved items +// without incurring a nextTick operation +var loop = function(self, callback) { + // No more items we are done + if(self.bufferedCount() == 0) return; + // Get the next document + self._next(callback); + // Loop + return loop; +} + +Cursor.prototype.next = Cursor.prototype.nextObject; + +define.classMethod('next', {callback: true, promise:true}); + +/** + * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, + * not all of the elements will be iterated if this cursor had been previouly accessed. + * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike + * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements + * at any given time if batch size is specified. Otherwise, the caller is responsible + * for making sure that the entire result can fit the memory. + * @method + * @deprecated + * @param {Cursor~resultCallback} callback The result callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.each = function(callback) { + // Rewind cursor state + this.rewind(); + // Set current cursor to INIT + this.s.state = Cursor.INIT; + // Run the query + _each(this, callback); +}; + +define.classMethod('each', {callback: true, promise:false}); + +// Run the each loop +var _each = function(self, callback) { + if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true}); + if(self.isNotified()) return; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); + } + + if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN; + + // Define function to avoid global scope escape + var fn = null; + // Trampoline all the entries + if(self.bufferedCount() > 0) { + while(fn = loop(self, callback)) fn(self, callback); + _each(self, callback); + } else { + self.next(function(err, item) { + if(err) return handleCallback(callback, err); + if(item == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, null); + } + + if(handleCallback(callback, null, item) == false) return; + _each(self, callback); + }) + } +} + +/** + * The callback format for the forEach iterator method + * @callback Cursor~iteratorCallback + * @param {Object} doc An emitted document for the iterator + */ + +/** + * The callback error format for the forEach iterator method + * @callback Cursor~endCallback + * @param {MongoError} error An error instance representing the error during the execution. + */ + +/** + * Iterates over all the documents for this cursor using the iterator, callback pattern. + * @method + * @param {Cursor~iteratorCallback} iterator The iteration callback. + * @param {Cursor~endCallback} callback The end callback. + * @throws {MongoError} + * @return {null} + */ +Cursor.prototype.forEach = function(iterator, callback) { + this.each(function(err, doc){ + if(err) { callback(err); return false; } + if(doc != null) { iterator(doc); return true; } + if(doc == null && callback) { + var internalCallback = callback; + callback = null; + internalCallback(null); + return false; + } + }); +} + +define.classMethod('forEach', {callback: true, promise:false}); + +/** + * Set the ReadPreference for the cursor. + * @method + * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. + * @throws {MongoError} + * @return {Cursor} + */ +Cursor.prototype.setReadPreference = function(r) { + if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); + if(r instanceof ReadPreference) { + this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags); + } else { + this.s.options.readPreference = new CoreReadPreference(r); + } + + return this; +} + +define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]}); + +/** + * The callback format for results + * @callback Cursor~toArrayResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object[]} documents All the documents the satisfy the cursor. + */ + +/** + * Returns an array of documents. The caller is responsible for making sure that there + * is enough memory to store the results. Note that the array only contain partial + * results when this cursor had been previouly accessed. In that case, + * cursor.rewind() can be used to reset the cursor. + * @method + * @param {Cursor~toArrayResultCallback} [callback] The result callback. + * @throws {MongoError} + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.toArray = function(callback) { + var self = this; + if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true}); + + // Execute using callback + if(typeof callback == 'function') return toArray(self, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + toArray(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +var toArray = function(self, callback) { + var items = []; + + // Reset cursor + self.rewind(); + self.s.state = Cursor.INIT; + + // Fetch all the documents + var fetchDocs = function() { + self._next(function(err, doc) { + if(err) return handleCallback(callback, err); + if(doc == null) { + self.s.state = Cursor.CLOSED; + return handleCallback(callback, null, items); + } + + // Add doc to items + items.push(doc) + + // Get all buffered objects + if(self.bufferedCount() > 0) { + var docs = self.readBufferedDocuments(self.bufferedCount()) + + // Transform the doc if transform method added + if(self.s.transforms && typeof self.s.transforms.doc == 'function') { + docs = docs.map(self.s.transforms.doc); + } + + items = items.concat(docs); + } + + // Attempt a fetch + fetchDocs(); + }) + } + + fetchDocs(); +} + +define.classMethod('toArray', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Cursor~countResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} count The count of documents. + */ + +/** + * Get the count of documents for this cursor + * @method + * @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options. + * @param {object} [options=null] Optional settings. + * @param {number} [options.skip=null] The number of documents to skip. + * @param {number} [options.limit=null] The maximum amounts to count before aborting. + * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. + * @param {string} [options.hint=null] An index name hint for the query. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Cursor~countResultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.count = function(applySkipLimit, opts, callback) { + var self = this; + if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true}); + if(typeof opts == 'function') callback = opts, opts = {}; + opts = opts || {}; + + // Execute using callback + if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + count(self, applySkipLimit, opts, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var count = function(self, applySkipLimit, opts, callback) { + if(typeof applySkipLimit == 'function') { + callback = applySkipLimit; + applySkipLimit = true; + } + + if(applySkipLimit) { + if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip(); + if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit(); + } + + // Command + var delimiter = self.s.ns.indexOf('.'); + + var command = { + 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query + } + + if(typeof opts.maxTimeMS == 'number') { + command.maxTimeMS = opts.maxTimeMS; + } else if(typeof self.s.maxTimeMS == 'number') { + command.maxTimeMS = self.s.maxTimeMS; + } + + // Get a server + var server = self.s.topology.getServer(opts); + // Get a connection + var connection = self.s.topology.getConnection(opts); + // Get the callbacks + var callbacks = server.getCallbacks(); + + // Merge in any options + if(opts.skip) command.skip = opts.skip; + if(opts.limit) command.limit = opts.limit; + if(self.s.options.hint) command.hint = self.s.options.hint; + + // Build Query object + var query = new Query(self.s.bson, f("%s.$cmd", self.s.ns.substr(0, delimiter)), command, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false + }); + + // Set up callback + callbacks.register(query.requestId, function(err, result) { + if(err) return handleCallback(callback, err); + if(result.documents.length == 1 + && (result.documents[0].errmsg + || result.documents[0].err + || result.documents[0]['$err'])) { + return handleCallback(callback, MongoError.create(result.documents[0])); + } + handleCallback(callback, null, result.documents[0].n); + }); + + // Write the initial command out + connection.write(query.toBin()); +} + +define.classMethod('count', {callback: true, promise:true}); + +/** + * Close the cursor, sending a KillCursor command and emitting close. + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.close = function(callback) { + this.s.state = Cursor.CLOSED; + // Kill the cursor + this.kill(); + // Emit the close event for the cursor + this.emit('close'); + // Callback if provided + if(typeof callback == 'function') return handleCallback(callback, null, this); + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Map all documents using the provided function + * @method + * @param {function} [transform] The mapping transformation method. + * @return {null} + */ +Cursor.prototype.map = function(transform) { + this.cursorState.transforms = { doc: transform }; + return this; +} + +define.classMethod('map', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Is the cursor closed + * @method + * @return {boolean} + */ +Cursor.prototype.isClosed = function() { + return this.isDead(); +} + +define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); + +Cursor.prototype.destroy = function(err) { + this.pause(); + this.close(); + if(err) this.emit('error', err); +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Return a modified Readable stream including a possible transform method. + * @method + * @param {object} [options=null] Optional settings. + * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. + * @return {Cursor} + */ +Cursor.prototype.stream = function(options) { + this.s.streamOptions = options || {}; + return this; +} + +define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]}); + +/** + * Execute the explain for the cursor + * @method + * @param {Cursor~resultCallback} [callback] The result callback. + * @return {Promise} returns Promise if no callback passed + */ +Cursor.prototype.explain = function(callback) { + var self = this; + this.s.cmd.explain = true; + + // Execute using callback + if(typeof callback == 'function') return this._next(callback); + + // Return a Promise + return new this.s.promiseLibrary(function(resolve, reject) { + self._next(function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('explain', {callback: true, promise:true}); + +Cursor.prototype._read = function(n) { + var self = this; + if(self.s.state == Cursor.CLOSED || self.isDead()) { + return self.push(null); + } + + // Get the next item + self.nextObject(function(err, result) { + if(err) { + if(!self.isDead()) self.close(); + if(self.listeners('error') && self.listeners('error').length > 0) { + self.emit('error', err); + } + + // Emit end event + self.emit('end'); + return self.emit('finish'); + } + + // If we provided a transformation method + if(typeof self.s.streamOptions.transform == 'function' && result != null) { + return self.push(self.s.streamOptions.transform(result)); + } + + // If we provided a map function + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) { + return self.push(self.cursorState.transforms.doc(result)); + } + + // Return the result + self.push(result); + }); +} + +Object.defineProperty(Cursor.prototype, 'namespace', { + enumerable: true, + get: function() { + if (!this || !this.s) { + return null; + } + + // TODO: refactor this logic into core + var ns = this.s.ns || ''; + var firstDot = ns.indexOf('.'); + if (firstDot < 0) { + return { + database: this.s.ns, + collection: '' + }; + } + return { + database: ns.substr(0, firstDot), + collection: ns.substr(firstDot + 1) + }; + } +}); + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Readable#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Readable#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Readable#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Readable#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Readable#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Readable#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Readable#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Readable#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +Cursor.INIT = 0; +Cursor.OPEN = 1; +Cursor.CLOSED = 2; +Cursor.GET_MORE = 3; + +module.exports = Cursor; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/db.js b/util/demographicsImporter/node_modules/mongodb/lib/db.js new file mode 100644 index 0000000..6667297 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/db.js @@ -0,0 +1,1731 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , getSingleProperty = require('./utils').getSingleProperty + , shallowClone = require('./utils').shallowClone + , parseIndexOptions = require('./utils').parseIndexOptions + , debugOptions = require('./utils').debugOptions + , CommandCursor = require('./command_cursor') + , handleCallback = require('./utils').handleCallback + , toError = require('./utils').toError + , ReadPreference = require('./read_preference') + , f = require('util').format + , Admin = require('./admin') + , Code = require('mongodb-core').BSON.Code + , CoreReadPreference = require('mongodb-core').ReadPreference + , MongoError = require('mongodb-core').MongoError + , ObjectID = require('mongodb-core').ObjectID + , Define = require('./metadata') + , Logger = require('mongodb-core').Logger + , Collection = require('./collection') + , crypto = require('crypto'); + +var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId' + , 'serializeFunctions', 'raw', 'promoteLongs', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds' + , 'readPreference', 'pkFactory']; + +/** + * @fileOverview The **Db** class is a class that represents a MongoDB Database. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * var testDb = db.db('test'); + * db.close(); + * }); + */ + +/** + * Creates a new Db instance + * @class + * @param {string} databaseName The name of the database this instance represents. + * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.native_parser=true] Select C++ bson parser instead of JavaScript parser. + * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. + * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. + * @param {number} [options.numberOfRetries=5] Number of times a tailable cursor will re-poll when it gets nothing back. + * @param {number} [options.retryMiliSeconds=500] Number of milliseconds between retries. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. + * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database + * @property {string} databaseName The name of the database this instance represents. + * @property {object} options The options associated with the db instance. + * @property {boolean} native_parser The current value of the parameter native_parser. + * @property {boolean} slaveOk The current slaveOk value for the db instance. + * @property {object} writeConcern The current write concern values. + * @fires Db#close + * @fires Db#authenticated + * @fires Db#reconnect + * @fires Db#error + * @fires Db#timeout + * @fires Db#parseError + * @fires Db#fullsetup + * @return {Db} a Db instance. + */ +var Db = function(databaseName, topology, options) { + options = options || {}; + if(!(this instanceof Db)) return new Db(databaseName, topology, options); + EventEmitter.call(this); + var self = this; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Ensure we put the promiseLib in the options + options.promiseLibrary = promiseLibrary; + + // var self = this; // Internal state of the db object + this.s = { + // Database name + databaseName: databaseName + // DbCache + , dbCache: {} + // Children db's + , children: [] + // Topology + , topology: topology + // Options + , options: options + // Logger instance + , logger: Logger('Db', options) + // Get the bson parser + , bson: topology ? topology.bson : null + // Authsource if any + , authSource: options.authSource + // Unpack read preference + , readPreference: options.readPreference + // Set buffermaxEntries + , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1 + // Parent db (if chained) + , parentDb: options.parentDb || null + // Set up the primary key factory or fallback to ObjectID + , pkFactory: options.pkFactory || ObjectID + // Get native parser + , nativeParser: options.nativeParser || options.native_parser + // Promise library + , promiseLibrary: promiseLibrary + // No listener + , noListener: typeof options.noListener == 'boolean' ? options.noListener : false + // ReadConcern + , readConcern: options.readConcern + } + + // Ensure we have a valid db name + validateDatabaseName(self.s.databaseName); + + // If we have specified the type of parser + if(typeof self.s.nativeParser == 'boolean') { + if(self.s.nativeParser) { + topology.setBSONParserType("c++"); + } else { + topology.setBSONParserType("js"); + } + } + + // Add a read Only property + getSingleProperty(this, 'serverConfig', self.s.topology); + getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); + getSingleProperty(this, 'databaseName', self.s.databaseName); + + // Last ismaster + Object.defineProperty(this, 'options', { + enumerable:true, + get: function() { return self.s.options; } + }); + + // Last ismaster + Object.defineProperty(this, 'native_parser', { + enumerable:true, + get: function() { return self.s.topology.parserType() == 'c++'; } + }); + + // Last ismaster + Object.defineProperty(this, 'slaveOk', { + enumerable:true, + get: function() { + if(self.s.options.readPreference != null + && (self.s.options.readPreference != 'primary' || self.s.options.readPreference.mode != 'primary')) { + return true; + } + return false; + } + }); + + Object.defineProperty(this, 'writeConcern', { + enumerable:true, + get: function() { + var ops = {}; + if(self.s.options.w != null) ops.w = self.s.options.w; + if(self.s.options.j != null) ops.j = self.s.options.j; + if(self.s.options.fsync != null) ops.fsync = self.s.options.fsync; + if(self.s.options.wtimeout != null) ops.wtimeout = self.s.options.wtimeout; + return ops; + } + }); + + // This is a child db, do not register any listeners + if(options.parentDb) return; + if(this.s.noListener) return; + + // Add listeners + topology.on('error', createListener(self, 'error', self)); + topology.on('timeout', createListener(self, 'timeout', self)); + topology.on('close', createListener(self, 'close', self)); + topology.on('parseError', createListener(self, 'parseError', self)); + topology.once('open', createListener(self, 'open', self)); + topology.once('fullsetup', createListener(self, 'fullsetup', self)); + topology.once('all', createListener(self, 'all', self)); + topology.on('reconnect', createListener(self, 'reconnect', self)); +} + +inherits(Db, EventEmitter); + +var define = Db.define = new Define('Db', Db, false); + +/** + * The callback format for the Db.open method + * @callback Db~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The Db instance if the open method was successful. + */ + +// Internal method +var open = function(self, callback) { + self.s.topology.connect(self, self.s.options, function(err, topology) { + if(callback == null) return; + var internalCallback = callback; + callback == null; + + if(err) { + self.close(); + return internalCallback(err); + } + + internalCallback(null, self); + }); +} + +/** + * Open the database + * @method + * @param {Db~openCallback} [callback] Callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.open = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + open(self, function(err, db) { + if(err) return reject(err); + resolve(db); + }) + }); +} + +define.classMethod('open', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Db~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result object if the command was executed successfully. + */ + +var executeCommand = function(self, command, options, callback) { + var dbName = options.dbName || options.authdb || self.s.databaseName; + // If we have a readPreference set + if(options.readPreference == null && self.s.readPreference) { + options.readPreference = self.s.readPreference; + } + + // Convert the readPreference + if(options.readPreference && typeof options.readPreference == 'string') { + options.readPreference = new CoreReadPreference(options.readPreference); + } else if(options.readPreference instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(options.readPreference.mode + , options.readPreference.tags); + } + + // Debug information + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]' + , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)))); + + // Execute command + self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); +} + +/** + * Execute a command + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.command = function(command, options, callback) { + var self = this; + // Change the callback + if(typeof options == 'function') callback = options, options = {}; + // Clone the options + options = shallowClone(options); + + // Do we have a callback + if(typeof callback == 'function') return executeCommand(self, command, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + executeCommand(self, command, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('command', {callback: true, promise:true}); + +/** + * The callback format for results + * @callback Db~noResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {null} result Is not set to a value + */ + +/** + * Close the db and it's underlying connections + * @method + * @param {boolean} force Force close, emitting no events + * @param {Db~noResultCallback} [callback] The result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.close = function(force, callback) { + if(typeof force == 'function') callback = force, force = false; + this.s.topology.close(force); + var self = this; + + // Fire close event if any listeners + if(this.listeners('close').length > 0) { + this.emit('close'); + + // If it's the top level db emit close on all children + if(this.parentDb == null) { + // Fire close on all children + for(var i = 0; i < this.s.children.length; i++) { + this.s.children[i].emit('close'); + } + } + + // Remove listeners after emit + self.removeAllListeners('close'); + } + + // Close parent db if set + if(this.s.parentDb) this.s.parentDb.close(); + // Callback after next event loop tick + if(typeof callback == 'function') return process.nextTick(function() { + handleCallback(callback, null); + }) + + // Return dummy promise + return new this.s.promiseLibrary(function(resolve, reject) { + resolve(); + }); +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * Return the Admin db instance + * @method + * @return {Admin} return the new Admin db instance + */ +Db.prototype.admin = function() { + return new Admin(this, this.s.topology, this.s.promiseLibrary); +}; + +define.classMethod('admin', {callback: false, promise:false, returns: [Admin]}); + +/** + * The callback format for the collection method, must be used if strict is specified + * @callback Db~collectionResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection instance. + */ + +/** + * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can + * can use it without a callback in the following way. var collection = db.collection('mycollection'); + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) + * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) + * @param {Db~collectionResultCallback} callback The collection result callback + * @return {Collection} return the new Collection instance if not in strict mode + */ +Db.prototype.collection = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // If we have not set a collection level readConcern set the db level one + options.readConcern = options.readConcern || this.s.readConcern; + + // Do we have ignoreUndefined set + if(this.s.options.ignoreUndefined) { + options.ignoreUndefined = this.s.options.ignoreUndefined; + } + + // Execute + if(options == null || !options.strict) { + try { + var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options); + if(callback) callback(null, collection); + return collection; + } catch(err) { + if(callback) return callback(err); + throw err; + } + } + + // Strict mode + if(typeof callback != 'function') { + throw toError(f("A callback is required in strict mode. While getting collection %s.", name)); + } + + // Strict mode + this.listCollections({name:name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null); + + try { + return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + } catch(err) { + return handleCallback(callback, err, null); + } + }); +} + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +var createCollection = function(self, name, options, callback) { + // Get the write concern options + var finalOptions = writeConcern(shallowClone(options), self, options); + + // Check if we have the name + self.listCollections({name: name}).toArray(function(err, collections) { + if(err != null) return handleCallback(callback, err, null); + if(collections.length > 0 && finalOptions.strict) { + return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null); + } else if (collections.length > 0) { + try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); } + catch(err) { return handleCallback(callback, err); } + } + + // Create collection command + var cmd = {'create':name}; + + // Add all optional parameters + for(var n in options) { + if(options[n] != null && typeof options[n] != 'function') + cmd[n] = options[n]; + } + + // Execute command + self.command(cmd, finalOptions, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); + }); + }); +} + +/** + * Creates a collection on a server pre-allocating space, need to create f.ex capped collections. + * + * @method + * @param {string} name the collection name we wish to access. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. + * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. + * @param {boolean} [options.strict=false] Returns an error if the collection does not exist + * @param {boolean} [options.capped=false] Create a capped collection. + * @param {number} [options.size=null] The size of the capped collection in bytes. + * @param {number} [options.max=null] The maximum number of documents in the capped collection. + * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createCollection = function(name, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + name = args.length ? args.shift() : null; + options = args.length ? args.shift() || {} : {}; + + // Do we have a promisesLibrary + options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; + + // Check if the callback is in fact a string + if(typeof callback == 'string') name = callback; + + // Execute the fallback callback + if(typeof callback == 'function') return createCollection(self, name, options, callback); + return new this.s.promiseLibrary(function(resolve, reject) { + createCollection(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +} + +define.classMethod('createCollection', {callback: true, promise:true}); + +/** + * Get all the db statistics. + * + * @method + * @param {object} [options=null] Optional settings. + * @param {number} [options.scale=null] Divide the returned sizes by scale value. + * @param {Db~resultCallback} [callback] The collection result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.stats = function(options, callback) { + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Build command object + var commandObject = { dbStats:true }; + // Check if we have the scale value + if(options['scale'] != null) commandObject['scale'] = options['scale']; + // Execute the command + return this.command(commandObject, options, callback); +} + +define.classMethod('stats', {callback: true, promise:true}); + +// Transformation methods for cursor results +var listCollectionsTranforms = function(databaseName) { + var matching = f('%s.', databaseName); + + return { + doc: function(doc) { + var index = doc.name.indexOf(matching); + // Remove database name if available + if(doc.name && index == 0) { + doc.name = doc.name.substr(index + matching.length); + } + + return doc; + } + } +} + +/** + * Get the list of all collection information for the specified db. + * + * @method + * @param {object} filter Query to filter collections by + * @param {object} [options=null] Optional settings. + * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection + * @return {CommandCursor} + */ +Db.prototype.listCollections = function(filter, options) { + filter = filter || {}; + options = options || {}; + + // Shallow clone the object + options = shallowClone(options); + // Set the promise library + options.promiseLibrary = this.s.promiseLibrary; + + // We have a list collections command + if(this.serverConfig.capabilities().hasListCollectionsCommand) { + // Cursor options + var cursor = options.batchSize ? {batchSize: options.batchSize} : {} + // Build the command + var command = { listCollections : true, filter: filter, cursor: cursor }; + // Set the AggregationCursor constructor + options.cursorFactory = CommandCursor; + // Filter out the correct field values + options.transforms = listCollectionsTranforms(this.s.databaseName); + // Execute the cursor + return this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); + } + + // We cannot use the listCollectionsCommand + if(!this.serverConfig.capabilities().hasListCollectionsCommand) { + // If we have legacy mode and have not provided a full db name filter it + if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { + filter = shallowClone(filter); + filter.name = f('%s.%s', this.s.databaseName, filter.name); + } + } + + // No filter, filter by current database + if(filter == null) { + filter.name = f('/%s/', this.s.databaseName); + } + + // Rewrite the filter to use $and to filter out indexes + if(filter.name) { + filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]}; + } else { + filter = {name:/^((?!\$).)*$/}; + } + + // Return options + var options = {transforms: listCollectionsTranforms(this.s.databaseName)} + // Get the cursor + var cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, options); + // Set the passed in batch size if one was provided + if(options.batchSize) cursor = cursor.batchSize(options.batchSize); + // We have a fallback mode using legacy systems collections + return cursor; +}; + +define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]}); + +var evaluate = function(self, code, parameters, options, callback) { + var finalCode = code; + var finalParameters = []; + + // If not a code object translate to one + if(!(finalCode instanceof Code)) finalCode = new Code(finalCode); + // Ensure the parameters are correct + if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = [parameters]; + } else if(parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { + finalParameters = parameters; + } + + // Create execution selector + var cmd = {'$eval':finalCode, 'args':finalParameters}; + // Check if the nolock parameter is passed in + if(options['nolock']) { + cmd['nolock'] = options['nolock']; + } + + // Set primary read preference + options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY); + + // Execute the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result && result.ok == 1) return handleCallback(callback, null, result.retval); + if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null); + handleCallback(callback, err, result); + }); +} + +/** + * Evaluate JavaScript on the server + * + * @method + * @param {Code} code JavaScript to execute on server. + * @param {(object|array)} parameters The parameters for the call. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. + * @param {Db~resultCallback} [callback] The results callback + * @deprecated Eval is deprecated on MongoDB 3.2 and forward + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.eval = function(code, parameters, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + parameters = args.length ? args.shift() : parameters; + options = args.length ? args.shift() || {} : {}; + + // Check if the callback is in fact a string + if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback); + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + evaluate(self, code, parameters, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('eval', {callback: true, promise:true}); + +/** + * Rename a collection. + * + * @method + * @param {string} fromCollection Name of current collection to rename. + * @param {string} toCollection New name of of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. + * @param {Db~collectionResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + // Add return new collection + options.new_collection = true; + + // Check if the callback is in fact a string + if(typeof callback == 'function') { + return this.collection(fromCollection).rename(toCollection, options, callback); + } + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.collection(fromCollection).rename(toCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('renameCollection', {callback: true, promise:true}); + +/** + * Drop a collection from the database, removing it permanently. New accesses will create a new collection. + * + * @method + * @param {string} name Name of collection to drop + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropCollection = function(name, callback) { + var self = this; + + // Command to execute + var cmd = {'drop':name} + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { + if(err) return handleCallback(callback, err); + if(result.ok) return handleCallback(callback, null, true); + handleCallback(callback, null, false); + }); + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, self.s.options, function(err, result) { + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +}; + +define.classMethod('dropCollection', {callback: true, promise:true}); + +/** + * Drop a database. + * + * @method + * @param {Db~resultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.dropDatabase = function(callback) { + var self = this; + // Drop database command + var cmd = {'dropDatabase':1}; + + // Check if the callback is in fact a string + if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }); + + // Execute the command + return new this.s.promiseLibrary(function(resolve, reject) { + // Execute command + self.command(cmd, self.s.options, function(err, result) { + if(err) return reject(err); + if(result.ok) return resolve(true); + resolve(false); + }); + }); +} + +define.classMethod('dropDatabase', {callback: true, promise:true}); + +/** + * The callback format for the collections method. + * @callback Db~collectionsResultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection[]} collections An array of all the collections objects for the db instance. + */ +var collections = function(self, callback) { + // Let's get the collection names + self.listCollections().toArray(function(err, documents) { + if(err != null) return handleCallback(callback, err, null); + // Filter collections removing any illegal ones + documents = documents.filter(function(doc) { + return doc.name.indexOf('$') == -1; + }); + + // Return the collection objects + handleCallback(callback, null, documents.map(function(d) { + return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options); + })); + }); +} + +/** + * Fetch all collections for the current db. + * + * @method + * @param {Db~collectionsResultCallback} [callback] The results callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.collections = function(callback) { + var self = this; + + // Return the callback + if(typeof callback == 'function') return collections(self, callback); + // Return the promise + return new self.s.promiseLibrary(function(resolve, reject) { + collections(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('collections', {callback: true, promise:true}); + +/** + * Runs a command on the database as admin. + * @method + * @param {object} command The command hash + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.executeDbAdminCommand = function(selector, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + if(options.readPreference) { + options.readPreference = options.readPreference; + } + + // Return the callback + if(typeof callback == 'function') return self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + if(err) return handleCallback(callback, err); + handleCallback(callback, null, result.result); + }); + + // Return promise + return new self.s.promiseLibrary(function(resolve, reject) { + self.s.topology.command('admin.$cmd', selector, options, function(err, result) { + if(err) return reject(err); + resolve(result.result); + }); + }); +}; + +define.classMethod('executeDbAdminCommand', {callback: true, promise:true}); + +/** + * Creates an index on the db and collection collection. + * @method + * @param {string} name Name of the collection to create the index on. + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + options = typeof callback === 'function' ? options : callback; + options = options == null ? {} : options; + // Shallow clone the options + options = shallowClone(options); + // Run only against primary + options.readPreference = ReadPreference.PRIMARY; + + // If we have a callback fallback + if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback); + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + createIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var createIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Ensure we have a callback + if(finalOptions.writeConcern && typeof callback != 'function') { + throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true}); + } + + // Attempt to run using createIndexes command + createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { + if(err == null) return handleCallback(callback, err, result); + // Create command + var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); + // Set no key checking + finalOptions.checkKeys = false; + // Insert document + self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { + if(callback == null) return; + if(err) return handleCallback(callback, err); + if(result == null) return handleCallback(callback, null, null); + if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); + handleCallback(callback, null, doc.name); + }); + }); +} + +define.classMethod('createIndex', {callback: true, promise:true}); + +/** + * Ensures that an index exists, if it does not it creates it + * @method + * @deprecated since version 2.0 + * @param {string} name The index name + * @param {(string|object)} fieldOrSpec Defines the index. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.unique=false] Creates an unique index. + * @param {boolean} [options.sparse=false] Creates a sparse index. + * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. + * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value + * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. + * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. + * @param {number} [options.v=null] Specify the format version of the indexes. + * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + ensureIndex(self, name, fieldOrSpec, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var ensureIndex = function(self, name, fieldOrSpec, options, callback) { + // Get the write concern options + var finalOptions = writeConcern({}, self, options); + // Create command + var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); + var index_name = selector.name; + + // Default command options + var commandOptions = {}; + // Check if the index allready exists + self.indexInformation(name, finalOptions, function(err, indexInformation) { + if(err != null && err.code != 26) return handleCallback(callback, err, null); + // If the index does not exist, create it + if(indexInformation == null || !indexInformation[index_name]) { + self.createIndex(name, fieldOrSpec, options, callback); + } else { + if(typeof callback === 'function') return handleCallback(callback, null, index_name); + } + }); +} + +define.classMethod('ensureIndex', {callback: true, promise:true}); + +Db.prototype.addChild = function(db) { + if(this.s.parentDb) return this.s.parentDb.addChild(db); + this.s.children.push(db); +} + +/** + * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are + * related in a parent-child relationship to the original instance so that events are correctly emitted on child + * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. + * You can control these behaviors with the options noListener and returnNonCachedInstance. + * + * @method + * @param {string} name The name of the database we want to use. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. + * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created + * @return {Db} + */ +Db.prototype.db = function(dbName, options) { + options = options || {}; + // Copy the options and add out internal override of the not shared flag + for(var key in this.options) { + options[key] = this.options[key]; + } + + // Do we have the db in the cache already + if(this.s.dbCache[dbName] && options.returnNonCachedInstance !== true) { + return this.s.dbCache[dbName]; + } + + // Add current db as parentDb + if(options.noListener == null || options.noListener == false) { + options.parentDb = this; + } + + // Add promiseLibrary + options.promiseLibrary = this.s.promiseLibrary; + + // Return the db object + var db = new Db(dbName, this.s.topology, options) + + // Add as child + if(options.noListener == null || options.noListener == false) { + this.addChild(db); + } + + // Add the db to the cache + this.s.dbCache[dbName] = db; + // Return the database + return db; +}; + +define.classMethod('db', {callback: false, promise:false, returns: [Db]}); + +var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { + // Special case where there is no password ($external users) + if(typeof username == 'string' + && password != null && typeof password == 'object') { + options = password; + password = null; + } + + // Unpack all options + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Error out if we digestPassword set + if(options.digestPassword != null) { + throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."); + } + + // Get additional values + var customData = options.customData != null ? options.customData : {}; + var roles = Array.isArray(options.roles) ? options.roles : []; + var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; + + // If not roles defined print deprecated message + if(roles.length == 0) { + console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"); + } + + // Get the error options + var commandOptions = {writeCommand:true}; + if(options['dbName']) commandOptions.dbName = options['dbName']; + + // Add maxTimeMS to options if set + if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Check the db name and add roles if needed + if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) { + roles = ['root'] + } else if(!Array.isArray(options.roles)) { + roles = ['dbOwner'] + } + + // Build the command to execute + var command = { + createUser: username + , customData: customData + , roles: roles + , digestPassword:false + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // No password + if(typeof password == 'string') { + command.pwd = userPassword; + } + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, !result.ok ? toError(result) : null + , result.ok ? [{user: username, pwd: ''}] : null); + }) +} + +var addUser = function(self, username, password, options, callback) { + // Attempt to execute auth command + _executeAuthCreateUserCommand(self, username, password, options, function(err, r) { + // We need to perform the backward compatible insert operation + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var userPassword = md5.digest('hex'); + + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Check if we are inserting the first user + collection.count({}, function(err, count) { + // We got an error (f.ex not authorized) + if(err != null) return handleCallback(callback, err, null); + // Check if the user exists and update i + collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) { + // We got an error (f.ex not authorized) + if(err != null) return handleCallback(callback, err, null); + // Add command keys + finalOptions.upsert = true; + + // We have a user, let's update the password or upsert if not + collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err, results, full) { + if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]); + if(err) return handleCallback(callback, err, null) + handleCallback(callback, null, [{user:username, pwd:userPassword}]); + }); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, r); + }); +} + +/** + * Add a user to the database. + * @method + * @param {string} username The username. + * @param {string} password The password. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) + * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.addUser = function(username, password, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return addUser(self, username, password, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + addUser(self, username, password, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('addUser', {callback: true, promise:true}); + +var _executeAuthRemoveUserCommand = function(self, username, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + // Get the error options + var commandOptions = {writeCommand:true}; + if(options['dbName']) commandOptions.dbName = options['dbName']; + + // Get additional values + var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; + + // Add maxTimeMS to options if set + if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; + + // Build the command to execute + var command = { + dropUser: username + } + + // Apply write concern to command + command = writeConcern(command, self, options); + + // Force write using primary + commandOptions.readPreference = CoreReadPreference.primary; + + // Execute the command + self.command(command, commandOptions, function(err, result) { + if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000}); + if(err) return handleCallback(callback, err, null); + handleCallback(callback, null, result.ok ? true : false); + }) +} + +var removeUser = function(self, username, options, callback) { + // Attempt to execute command + _executeAuthRemoveUserCommand(self, username, options, function(err, result) { + if(err && err.code == -5000) { + var finalOptions = writeConcern(shallowClone(options), self, options); + // If we have another db set + var db = options.dbName ? self.db(options.dbName) : self; + + // Fetch a user collection + var collection = db.collection(Db.SYSTEM_USER_COLLECTION); + + // Locate the user + collection.findOne({user: username}, {}, function(err, user) { + if(user == null) return handleCallback(callback, err, false); + collection.remove({user: username}, finalOptions, function(err, result) { + handleCallback(callback, err, true); + }); + }); + + return; + } + + if(err) return handleCallback(callback, err); + handleCallback(callback, err, result); + }); +} + +define.classMethod('removeUser', {callback: true, promise:true}); + +/** + * Remove a user from a database + * @method + * @param {string} username The username. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.removeUser = function(username, options, callback) { + // Unpack the parameters + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // If we have a callback fallback + if(typeof callback == 'function') return removeUser(self, username, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + removeUser(self, username, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var authenticate = function(self, username, password, options, callback) { + // the default db to authenticate against is 'self' + // if authententicate is called from a retry context, it may be another one, like admin + var authdb = options.authdb ? options.authdb : options.dbName; + authdb = options.authSource ? options.authSource : authdb; + authdb = authdb ? authdb : self.databaseName; + + // Callback + var _callback = function(err, result) { + if(self.listeners('authenticated').length > 0) { + self.emit('authenticated', err, result); + } + + // Return to caller + handleCallback(callback, err, result); + } + + // authMechanism + var authMechanism = options.authMechanism || ''; + authMechanism = authMechanism.toUpperCase(); + + // If classic auth delegate to auth command + if(authMechanism == 'MONGODB-CR') { + self.s.topology.auth('mongocr', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'PLAIN') { + self.s.topology.auth('plain', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'MONGODB-X509') { + self.s.topology.auth('x509', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'SCRAM-SHA-1') { + self.s.topology.auth('scram-sha-1', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else if(authMechanism == 'GSSAPI') { + if(process.platform == 'win32') { + self.s.topology.auth('sspi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + self.s.topology.auth('gssapi', authdb, username, password, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } + } else if(authMechanism == 'DEFAULT') { + self.s.topology.auth('default', authdb, username, password, function(err, result) { + if(err) return handleCallback(callback, err, false); + _callback(null, true); + }); + } else { + handleCallback(callback, MongoError.create({message: f("authentication mechanism %s not supported", options.authMechanism), driver:true})); + } +} + +/** + * Authenticate a user against the server. + * @method + * @param {string} username The username. + * @param {string} [password] The password. + * @param {object} [options=null] Optional settings. + * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.authenticate = function(username, password, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + // Shallow copy the options + options = shallowClone(options); + + // Set default mechanism + if(!options.authMechanism) { + options.authMechanism = 'DEFAULT'; + } else if(options.authMechanism != 'GSSAPI' + && options.authMechanism != 'MONGODB-CR' + && options.authMechanism != 'MONGODB-X509' + && options.authMechanism != 'SCRAM-SHA-1' + && options.authMechanism != 'PLAIN') { + return handleCallback(callback, MongoError.create({message: "only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism", driver:true})); + } + + // If we have a callback fallback + if(typeof callback == 'function') return authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return callback(err, r); + callback(null, r); + }); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + authenticate(self, username, password, options, function(err, r) { + // Support failed auth method + if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; + // Reject error + if(err) return reject(err); + resolve(r); + }); + }); +}; + +define.classMethod('authenticate', {callback: true, promise:true}); + +/** + * Logout user from server, fire off on all connections and remove all auth info + * @method + * @param {object} [options=null] Optional settings. + * @param {string} [options.dbName=null] Logout against different database than current. + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.logout = function(options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() || {} : {}; + + // logout command + var cmd = {'logout':1}; + + // Add onAll to login to ensure all connection are logged out + options.onAll = true; + + // We authenticated against a different db use that + if(this.s.authSource) options.dbName = this.s.authSource; + + // Execute the command + if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, false); + handleCallback(callback, null, true) + }); + + // Return promise + return new this.s.promiseLibrary(function(resolve, reject) { + self.command(cmd, options, function(err, result) { + if(err) return reject(err); + resolve(true); + }); + }); +} + +define.classMethod('logout', {callback: true, promise:true}); + +// Figure out the read preference +var getReadPreference = function(options, db) { + if(options.readPreference) return options; + if(db.readPreference) options.readPreference = db.readPreference; + return options; +} + +/** + * Retrieves this collections index info. + * @method + * @param {string} name The name of the collection. + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.full=false] Returns the full raw index information. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {Db~resultCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +Db.prototype.indexInformation = function(name, options, callback) { + var self = this; + if(typeof options == 'function') callback = options, options = {}; + options = options || {}; + + // If we have a callback fallback + if(typeof callback == 'function') return indexInformation(self, name, options, callback); + + // Return a promise + return new this.s.promiseLibrary(function(resolve, reject) { + indexInformation(self, name, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }); + }); +}; + +var indexInformation = function(self, name, options, callback) { + // If we specified full information + var full = options['full'] == null ? false : options['full']; + + // Process all the results from the index command and collection + var processResults = function(indexes) { + // Contains all the information + var info = {}; + // Process all the indexes + for(var i = 0; i < indexes.length; i++) { + var index = indexes[i]; + // Let's unpack the object + info[index.name] = []; + for(var name in index.key) { + info[index.name].push([name, index.key[name]]); + } + } + + return info; + } + + // Get the list of indexes of the specified collection + self.collection(name).listIndexes().toArray(function(err, indexes) { + if(err) return callback(toError(err)); + if(!Array.isArray(indexes)) return handleCallback(callback, null, []); + if(full) return handleCallback(callback, null, indexes); + handleCallback(callback, null, processResults(indexes)); + }); +} + +define.classMethod('indexInformation', {callback: true, promise:true}); + +var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { + var indexParameters = parseIndexOptions(fieldOrSpec); + var fieldHash = indexParameters.fieldHash; + var keys = indexParameters.keys; + + // Generate the index name + var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; + var selector = { + 'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName + } + + // Ensure we have a correct finalUnique + var finalUnique = options == null || 'object' === typeof options ? false : options; + // Set up options + options = options == null || typeof options == 'boolean' ? {} : options; + + // Add all the options + var keysToOmit = Object.keys(selector); + for(var optionName in options) { + if(keysToOmit.indexOf(optionName) == -1) { + selector[optionName] = options[optionName]; + } + } + + if(selector['unique'] == null) selector['unique'] = finalUnique; + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete selector[removeKeys[i]]; + } + + // Return the command creation selector + return selector; +} + +var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { + // Build the index + var indexParameters = parseIndexOptions(fieldOrSpec); + // Generate the index name + var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; + // Set up the index + var indexes = [{ name: indexName, key: indexParameters.fieldHash }]; + // merge all the options + var keysToOmit = Object.keys(indexes[0]); + for(var optionName in options) { + if(keysToOmit.indexOf(optionName) == -1) { + indexes[0][optionName] = options[optionName]; + } + + // Remove any write concern operations + var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; + for(var i = 0; i < removeKeys.length; i++) { + delete indexes[0][removeKeys[i]]; + } + } + + // Create command + var cmd = {createIndexes: name, indexes: indexes}; + + // Apply write concern to command + cmd = writeConcern(cmd, self, options); + + // Build the command + self.command(cmd, options, function(err, result) { + if(err) return handleCallback(callback, err, null); + if(result.ok == 0) return handleCallback(callback, toError(result), null); + // Return the indexName for backward compatibility + handleCallback(callback, null, indexName); + }); +} + +// Validate the database name +var validateDatabaseName = function(databaseName) { + if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true}); + if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true}); + if(databaseName == '$external') return; + + var invalidChars = [" ", ".", "$", "/", "\\"]; + for(var i = 0; i < invalidChars.length; i++) { + if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true}); + } +} + +// Get write concern +var writeConcern = function(target, db, options) { + if(options.w != null || options.j != null || options.fsync != null) { + var opts = {}; + if(options.w) opts.w = options.w; + if(options.wtimeout) opts.wtimeout = options.wtimeout; + if(options.j) opts.j = options.j; + if(options.fsync) opts.fsync = options.fsync; + target.writeConcern = opts; + } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { + target.writeConcern = db.writeConcern; + } + + return target +} + +// Add listeners to topology +var createListener = function(self, e, object) { + var listener = function(err) { + if(e != 'error') { + object.emit(e, err, self); + + // Emit on all associated db's if available + for(var i = 0; i < self.s.children.length; i++) { + self.s.children[i].emit(e, err, self.s.children[i]); + } + } + } + return listener; +} + +/** + * Db close event + * + * Emitted after a socket closed against a single server or mongos proxy. + * + * @event Db#close + * @type {MongoError} + */ + +/** + * Db authenticated event + * + * Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated. + * + * @event Db#authenticated + * @type {object} + */ + +/** + * Db reconnect event + * + * * Server: Emitted when the driver has reconnected and re-authenticated. + * * ReplicaSet: N/A + * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. + * + * @event Db#reconnect + * @type {object} + */ + +/** + * Db error event + * + * Emitted after an error occurred against a single server or mongos proxy. + * + * @event Db#error + * @type {MongoError} + */ + +/** + * Db timeout event + * + * Emitted after a socket timeout occurred against a single server or mongos proxy. + * + * @event Db#timeout + * @type {MongoError} + */ + +/** + * Db parseError event + * + * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. + * + * @event Db#parseError + * @type {MongoError} + */ + +/** + * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. + * + * * Server: Emitted when the driver has connected to the single server and has authenticated. + * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. + * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. + * + * @event Db#fullsetup + * @type {Db} + */ + +// Constants +Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; +Db.SYSTEM_INDEX_COLLECTION = "system.indexes"; +Db.SYSTEM_PROFILE_COLLECTION = "system.profile"; +Db.SYSTEM_USER_COLLECTION = "system.users"; +Db.SYSTEM_COMMAND_COLLECTION = "$cmd"; +Db.SYSTEM_JS_COLLECTION = "system.js"; + +module.exports = Db; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/gridfs/chunk.js b/util/demographicsImporter/node_modules/mongodb/lib/gridfs/chunk.js new file mode 100644 index 0000000..d96095f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/gridfs/chunk.js @@ -0,0 +1,237 @@ +"use strict"; + +var Binary = require('mongodb-core').BSON.Binary, + ObjectID = require('mongodb-core').BSON.ObjectID; + +/** + * Class for representing a single chunk in GridFS. + * + * @class + * + * @param file {GridStore} The {@link GridStore} object holding this chunk. + * @param mongoObject {object} The mongo object representation of this chunk. + * + * @throws Error when the type of data field for {@link mongoObject} is not + * supported. Currently supported types for data field are instances of + * {@link String}, {@link Array}, {@link Binary} and {@link Binary} + * from the bson module + * + * @see Chunk#buildMongoObject + */ +var Chunk = function(file, mongoObject, writeConcern) { + if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); + + this.file = file; + var self = this; + var mongoObjectFinal = mongoObject == null ? {} : mongoObject; + this.writeConcern = writeConcern || {w:1}; + this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; + this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; + this.data = new Binary(); + + if(mongoObjectFinal.data == null) { + } else if(typeof mongoObjectFinal.data == "string") { + var buffer = new Buffer(mongoObjectFinal.data.length); + buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); + this.data = new Binary(buffer); + } else if(Array.isArray(mongoObjectFinal.data)) { + var buffer = new Buffer(mongoObjectFinal.data.length); + var data = mongoObjectFinal.data.join(''); + buffer.write(data, 0, data.length, 'binary'); + this.data = new Binary(buffer); + } else if(mongoObjectFinal.data._bsontype === 'Binary') { + this.data = mongoObjectFinal.data; + } else if(Buffer.isBuffer(mongoObjectFinal.data)) { + } else { + throw Error("Illegal chunk format"); + } + + // Update position + this.internalPosition = 0; +}; + +/** + * Writes a data to this object and advance the read/write head. + * + * @param data {string} the data to write + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.write = function(data, callback) { + this.data.write(data, this.internalPosition, data.length, 'binary'); + this.internalPosition = this.data.length(); + if(callback != null) return callback(null, this); + return this; +}; + +/** + * Reads data and advances the read/write head. + * + * @param length {number} The length of data to read. + * + * @return {string} The data read if the given length will not exceed the end of + * the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.read = function(length) { + // Default to full read if no index defined + length = length == null || length == 0 ? this.length() : length; + + if(this.length() - this.internalPosition + 1 >= length) { + var data = this.data.read(this.internalPosition, length); + this.internalPosition = this.internalPosition + length; + return data; + } else { + return ''; + } +}; + +Chunk.prototype.readSlice = function(length) { + if ((this.length() - this.internalPosition) >= length) { + var data = null; + if (this.data.buffer != null) { //Pure BSON + data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); + } else { //Native BSON + data = new Buffer(length); + length = this.data.readInto(data, this.internalPosition); + } + this.internalPosition = this.internalPosition + length; + return data; + } else { + return null; + } +}; + +/** + * Checks if the read/write head is at the end. + * + * @return {boolean} Whether the read/write head has reached the end of this + * chunk. + */ +Chunk.prototype.eof = function() { + return this.internalPosition == this.length() ? true : false; +}; + +/** + * Reads one character from the data of this chunk and advances the read/write + * head. + * + * @return {string} a single character data read if the the read/write head is + * not at the end of the chunk. Returns an empty String otherwise. + */ +Chunk.prototype.getc = function() { + return this.read(1); +}; + +/** + * Clears the contents of the data in this chunk and resets the read/write head + * to the initial position. + */ +Chunk.prototype.rewind = function() { + this.internalPosition = 0; + this.data = new Binary(); +}; + +/** + * Saves this chunk to the database. Also overwrites existing entries having the + * same id as this chunk. + * + * @param callback {function(*, GridStore)} This will be called after executing + * this method. The first parameter will contain null and the second one + * will contain a reference to this object. + */ +Chunk.prototype.save = function(options, callback) { + var self = this; + if(typeof options == 'function') { + callback = options; + options = {}; + } + + self.file.chunkCollection(function(err, collection) { + if(err) return callback(err); + + // Merge the options + var writeOptions = {}; + for(var name in options) writeOptions[name] = options[name]; + for(var name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; + + // collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) { + collection.remove({'_id':self.objectId}, writeOptions, function(err, result) { + if(err) return callback(err); + + if(self.data.length() > 0) { + self.buildMongoObject(function(mongoObject) { + var options = {forceServerObjectId:true}; + for(var name in self.writeConcern) { + options[name] = self.writeConcern[name]; + } + + collection.insert(mongoObject, writeOptions, function(err, collection) { + callback(err, self); + }); + }); + } else { + callback(null, self); + } + }); + }); +}; + +/** + * Creates a mongoDB object representation of this chunk. + * + * @param callback {function(Object)} This will be called after executing this + * method. The object will be passed to the first parameter and will have + * the structure: + * + *
    
    + *        {
    + *          '_id' : , // {number} id for this chunk
    + *          'files_id' : , // {number} foreign key to the file collection
    + *          'n' : , // {number} chunk number
    + *          'data' : , // {bson#Binary} the chunk data itself
    + *        }
    + *        
    + * + * @see MongoDB GridFS Chunk Object Structure + */ +Chunk.prototype.buildMongoObject = function(callback) { + var mongoObject = { + 'files_id': this.file.fileId, + 'n': this.chunkNumber, + 'data': this.data}; + // If we are saving using a specific ObjectId + if(this.objectId != null) mongoObject._id = this.objectId; + + callback(mongoObject); +}; + +/** + * @return {number} the length of the data + */ +Chunk.prototype.length = function() { + return this.data.length(); +}; + +/** + * The position of the read/write head + * @name position + * @lends Chunk# + * @field + */ +Object.defineProperty(Chunk.prototype, "position", { enumerable: true + , get: function () { + return this.internalPosition; + } + , set: function(value) { + this.internalPosition = value; + } +}); + +/** + * The default chunk size + * @constant + */ +Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; + +module.exports = Chunk; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/gridfs/grid_store.js b/util/demographicsImporter/node_modules/mongodb/lib/gridfs/grid_store.js new file mode 100644 index 0000000..62943bd --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/gridfs/grid_store.js @@ -0,0 +1,1919 @@ +"use strict"; + +/** + * @fileOverview GridFS is a tool for MongoDB to store files to the database. + * Because of the restrictions of the object size the database can hold, a + * facility to split a file into several chunks is needed. The {@link GridStore} + * class offers a simplified api to interact with files while managing the + * chunks of split files behind the scenes. More information about GridFS can be + * found here. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * GridStore = require('mongodb').GridStore, + * ObjectID = require('mongodb').ObjectID, + * test = require('assert'); + * + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * var gridStore = new GridStore(db, null, "w"); + * gridStore.open(function(err, gridStore) { + * gridStore.write("hello world!", function(err, gridStore) { + * gridStore.close(function(err, result) { + * + * // Let's read the file using object Id + * GridStore.read(db, result._id, function(err, data) { + * test.equal('hello world!', data); + * db.close(); + * test.done(); + * }); + * }); + * }); + * }); + * }); + */ +var Chunk = require('./chunk'), + ObjectID = require('mongodb-core').BSON.ObjectID, + ReadPreference = require('../read_preference'), + Buffer = require('buffer').Buffer, + Collection = require('../collection'), + fs = require('fs'), + timers = require('timers'), + f = require('util').format, + util = require('util'), + Define = require('../metadata'), + MongoError = require('mongodb-core').MongoError, + inherits = util.inherits, + Duplex = require('stream').Duplex || require('readable-stream').Duplex; + +var REFERENCE_BY_FILENAME = 0, + REFERENCE_BY_ID = 1; + +/** + * Namespace provided by the mongodb-core and node.js + * @external Duplex + */ + +/** + * Create a new GridStore instance + * + * Modes + * - **"r"** - read only. This is the default mode. + * - **"w"** - write in truncate mode. Existing data will be overwriten. + * + * @class + * @param {Db} db A database instance to interact with. + * @param {object} [id] optional unique id for this file + * @param {string} [filename] optional filename for this file, no unique constrain on the field + * @param {string} mode set the mode for this file. + * @param {object} [options=null] Optional settings. + * @param {(number|string)} [options.w=null] The write concern. + * @param {number} [options.wtimeout=null] The write concern timeout. + * @param {boolean} [options.j=false] Specify a journal write concern. + * @param {boolean} [options.fsync=false] Specify a file sync write concern. + * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. + * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. + * @param {object} [options.metadata=null] Arbitrary data the user wants to store. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @property {number} chunkSize Get the gridstore chunk size. + * @property {number} md5 The md5 checksum for this file. + * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory + * @return {GridStore} a GridStore instance. + */ +var GridStore = function GridStore(db, id, filename, mode, options) { + if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); + var self = this; + this.db = db; + + // Handle options + if(typeof options === 'undefined') options = {}; + // Handle mode + if(typeof mode === 'undefined') { + mode = filename; + filename = undefined; + } else if(typeof mode == 'object') { + options = mode; + mode = filename; + filename = undefined; + } + + if(id instanceof ObjectID) { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } else if(typeof filename == 'undefined') { + this.referenceBy = REFERENCE_BY_FILENAME; + this.filename = id; + if (mode.indexOf('w') != null) { + this.fileId = new ObjectID(); + } + } else { + this.referenceBy = REFERENCE_BY_ID; + this.fileId = id; + this.filename = filename; + } + + // Set up the rest + this.mode = mode == null ? "r" : mode; + this.options = options || {}; + + // Opened + this.isOpen = false; + + // Set the root if overridden + this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; + this.position = 0; + this.readPreference = this.options.readPreference || db.options.readPreference || ReadPreference.PRIMARY; + this.writeConcern = _getWriteConcern(db, this.options); + // Set default chunk size + this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; + + // Get the promiseLibrary + var promiseLibrary = this.options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Set the promiseLibrary + this.promiseLibrary = promiseLibrary; + + Object.defineProperty(this, "chunkSize", { enumerable: true + , get: function () { + return this.internalChunkSize; + } + , set: function(value) { + if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { + this.internalChunkSize = this.internalChunkSize; + } else { + this.internalChunkSize = value; + } + } + }); + + Object.defineProperty(this, "md5", { enumerable: true + , get: function () { + return this.internalMd5; + } + }); + + Object.defineProperty(this, "chunkNumber", { enumerable: true + , get: function () { + return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; + } + }); +} + +var define = GridStore.define = new Define('Gridstore', GridStore, true); + +/** + * The callback format for the Gridstore.open method + * @callback GridStore~openCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The GridStore instance if the open method was successful. + */ + +/** + * Opens the file from the database and initialize this object. Also creates a + * new one if file does not exist. + * + * @method + * @param {GridStore~openCallback} [callback] this will be called after executing this method + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.open = function(callback) { + var self = this; + if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ + throw MongoError.create({message: "Illegal mode " + this.mode, driver:true}); + } + + // We provided a callback leg + if(typeof callback == 'function') return open(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + open(self, function(err, store) { + if(err) return reject(err); + resolve(store); + }) + }); +}; + +var open = function(self, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(self.db, self.options); + + // If we are writing we need to ensure we have the right indexes for md5's + if((self.mode == "w" || self.mode == "w+")) { + // Get files collection + var collection = self.collection(); + // Put index on filename + collection.ensureIndex([['filename', 1]], writeConcern, function(err, index) { + // Get chunk collection + var chunkCollection = self.chunkCollection(); + // Ensure index on chunk collection + chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], writeConcern, function(err, index) { + // Open the connection + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + }); + }); + } else { + // Open the gridstore + _open(self, writeConcern, function(err, r) { + if(err) return callback(err); + self.isOpen = true; + callback(err, r); + }); + } +} + +// Push the definition for open +define.classMethod('open', {callback: true, promise:true}); + +/** + * Verify if the file is at EOF. + * + * @method + * @return {boolean} true if the read/write head is at the end of this file. + */ +GridStore.prototype.eof = function() { + return this.position == this.length ? true : false; +} + +define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]}); + +/** + * The callback result format. + * @callback GridStore~resultCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {object} result The result from the callback. + */ + +/** + * Retrieves a single character from this file. + * + * @method + * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.getc = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return eof(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + eof(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var eof = function(self, callback) { + if(self.eof()) { + callback(null, null); + } else if(self.currentChunk.eof()) { + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + self.currentChunk = chunk; + self.position = self.position + 1; + callback(err, self.currentChunk.getc()); + }); + } else { + self.position = self.position + 1; + callback(null, self.currentChunk.getc()); + } +} + +define.classMethod('getc', {callback: true, promise:true}); + +/** + * Writes a string to the file with a newline character appended at the end if + * the given string does not have one. + * + * @method + * @param {string} string the string to write. + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.puts = function(string, callback) { + var self = this; + var finalString = string.match(/\n$/) == null ? string + "\n" : string; + // We provided a callback leg + if(typeof callback == 'function') return this.write(finalString, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + self.write(finalString, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('puts', {callback: true, promise:true}); + +/** + * Return a modified Readable stream including a possible transform method. + * + * @method + * @return {GridStoreStream} + */ +GridStore.prototype.stream = function() { + return new GridStoreStream(this); +} + +define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]}); + +/** + * Writes some data. This method will work properly only if initialized with mode "w" or "w+". + * + * @method + * @param {(string|Buffer)} data the data to write. + * @param {boolean} [close] closes this file after writing if set to true. + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.write = function write(data, close, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return _writeNormal(this, data, close, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + _writeNormal(self, data, close, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +define.classMethod('write', {callback: true, promise:true}); + +/** + * Handles the destroy part of a stream + * + * @method + * @result {null} + */ +GridStore.prototype.destroy = function destroy() { + // close and do not emit any more events. queued data is not sent. + if(!this.writable) return; + this.readable = false; + if(this.writable) { + this.writable = false; + this._q.length = 0; + this.emit('close'); + } +} + +define.classMethod('destroy', {callback: false, promise:false}); + +/** + * Stores a file from the file system to the GridFS database. + * + * @method + * @param {(string|Buffer|FileHandle)} file the file to store. + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.writeFile = function (file, callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return writeFile(self, file, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + writeFile(self, file, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var writeFile = function(self, file, callback) { + if (typeof file === 'string') { + fs.open(file, 'r', function (err, fd) { + if(err) return callback(err); + self.writeFile(fd, callback); + }); + return; + } + + self.open(function (err, self) { + if(err) return callback(err, self); + + fs.fstat(file, function (err, stats) { + if(err) return callback(err, self); + + var offset = 0; + var index = 0; + var numberOfChunksLeft = Math.min(stats.size / self.chunkSize); + + // Write a chunk + var writeChunk = function() { + fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { + if(err) return callback(err, self); + + offset = offset + bytesRead; + + // Create a new chunk for the data + var chunk = new Chunk(self, {n:index++}, self.writeConcern); + chunk.write(data, function(err, chunk) { + if(err) return callback(err, self); + + chunk.save({}, function(err, result) { + if(err) return callback(err, self); + + self.position = self.position + data.length; + + // Point to current chunk + self.currentChunk = chunk; + + if(offset >= stats.size) { + fs.close(file); + self.close(function(err, result) { + if(err) return callback(err, self); + return callback(null, self); + }); + } else { + return process.nextTick(writeChunk); + } + }); + }); + }); + } + + // Process the first write + process.nextTick(writeChunk); + }); + }); +} + +define.classMethod('writeFile', {callback: true, promise:true}); + +/** + * Saves this file to the database. This will overwrite the old entry if it + * already exists. This will work properly only if mode was initialized to + * "w" or "w+". + * + * @method + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.close = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return close(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + close(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var close = function(self, callback) { + if(self.mode[0] == "w") { + // Set up options + var options = self.writeConcern; + + if(self.currentChunk != null && self.currentChunk.position > 0) { + self.currentChunk.save({}, function(err, chunk) { + if(err && typeof callback == 'function') return callback(err); + + self.collection(function(err, files) { + if(err && typeof callback == 'function') return callback(err); + + // Build the mongo object + if(self.uploadDate != null) { + files.remove({'_id':self.fileId}, self.writeConcern, function(err, collection) { + if(err && typeof callback == 'function') return callback(err); + + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + }); + } else { + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + } + }); + }); + } else { + self.collection(function(err, files) { + if(err && typeof callback == 'function') return callback(err); + + self.uploadDate = new Date(); + buildMongoObject(self, function(err, mongoObject) { + if(err) { + if(typeof callback == 'function') return callback(err); else throw err; + } + + files.save(mongoObject, options, function(err) { + if(typeof callback == 'function') + callback(err, mongoObject); + }); + }); + }); + } + } else if(self.mode[0] == "r") { + if(typeof callback == 'function') + callback(null, null); + } else { + if(typeof callback == 'function') + callback(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true})); + } +} + +define.classMethod('close', {callback: true, promise:true}); + +/** + * The collection callback format. + * @callback GridStore~collectionCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Collection} collection The collection from the command execution. + */ + +/** + * Retrieve this file's chunks collection. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + */ +GridStore.prototype.chunkCollection = function(callback) { + if(typeof callback == 'function') + return this.db.collection((this.root + ".chunks"), callback); + return this.db.collection((this.root + ".chunks")); +}; + +define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]}); + +/** + * Deletes all the chunks of this file in the database. + * + * @method + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.unlink = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return unlink(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + unlink(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlink = function(self, callback) { + deleteChunks(self, function(err) { + if(err!==null) { + err.message = "at deleteChunks: " + err.message; + return callback(err); + } + + self.collection(function(err, collection) { + if(err!==null) { + err.message = "at collection: " + err.message; + return callback(err); + } + + collection.remove({'_id':self.fileId}, self.writeConcern, function(err) { + callback(err, self); + }); + }); + }); +} + +define.classMethod('unlink', {callback: true, promise:true}); + +/** + * Retrieves the file collection associated with this object. + * + * @method + * @param {GridStore~collectionCallback} callback the command callback. + * @return {Collection} + */ +GridStore.prototype.collection = function(callback) { + if(typeof callback == 'function') + this.db.collection(this.root + ".files", callback); + return this.db.collection(this.root + ".files"); +}; + +define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); + +/** + * The readlines callback format. + * @callback GridStore~readlinesCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {string[]} strings The array of strings returned. + */ + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.readlines = function(separator, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : "\n"; + separator = separator || "\n"; + + // We provided a callback leg + if(typeof callback == 'function') return readlines(self, separator, callback); + + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + readlines(self, separator, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlines = function(self, separator, callback) { + self.read(function(err, data) { + if(err) return callback(err); + + var items = data.toString().split(separator); + items = items.length > 0 ? items.splice(0, items.length - 1) : []; + for(var i = 0; i < items.length; i++) { + items[i] = items[i] + separator; + } + + callback(null, items); + }); +} + +define.classMethod('readlines', {callback: true, promise:true}); + +/** + * Deletes all the chunks of this file in the database if mode was set to "w" or + * "w+" and resets the read/write head to the initial position. + * + * @method + * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.rewind = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return rewind(self, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + rewind(self, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var rewind = function(self, callback) { + if(self.currentChunk.chunkNumber != 0) { + if(self.mode[0] == "w") { + deleteChunks(self, function(err, gridStore) { + if(err) return callback(err); + self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); + self.position = 0; + callback(null, self); + }); + } else { + self.currentChunk(0, function(err, chunk) { + if(err) return callback(err); + self.currentChunk = chunk; + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + }); + } + } else { + self.currentChunk.rewind(); + self.position = 0; + callback(null, self); + } +} + +define.classMethod('rewind', {callback: true, promise:true}); + +/** + * The read callback format. + * @callback GridStore~readCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Buffer} data The data read from the GridStore object + */ + +/** + * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. + * + * There are 3 signatures for this method: + * + * (callback) + * (length, callback) + * (length, buffer, callback) + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.read = function(length, buffer, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + buffer = args.length ? args.shift() : null; + // We provided a callback leg + if(typeof callback == 'function') return read(self, length, buffer, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + read(self, length, buffer, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var read = function(self, length, buffer, callback) { + // The data is a c-terminated string and thus the length - 1 + var finalLength = length == null ? self.length - self.position : length; + var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; + // Add a index to buffer to keep track of writing position or apply current index + finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; + + if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { + var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update internal position + self.position = self.position + finalBuffer.length; + // Check if we don't have a file at all + if(finalLength == 0 && finalBuffer.length == 0) return callback(MongoError.create({message: "File does not exist", driver:true}), null); + // Else return data + return callback(null, finalBuffer); + } + + // Read the next chunk + var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); + // Copy content to final buffer + slice.copy(finalBuffer, finalBuffer._index); + // Update index position + finalBuffer._index += slice.length; + + // Load next chunk and read more + nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { + if(err) return callback(err); + + if(chunk.length() > 0) { + self.currentChunk = chunk; + self.read(length, finalBuffer, callback); + } else { + if(finalBuffer._index > 0) { + callback(null, finalBuffer) + } else { + callback(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null); + } + } + }); +} + +define.classMethod('read', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~tellCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {number} position The current read position in the GridStore. + */ + +/** + * Retrieves the position of the read/write head of this file. + * + * @method + * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. + * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. + * @param {GridStore~tellCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.tell = function(callback) { + var self = this; + // We provided a callback leg + if(typeof callback == 'function') return callback(null, this.position); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + resolve(self.position); + }); +}; + +define.classMethod('tell', {callback: true, promise:true}); + +/** + * The tell callback format. + * @callback GridStore~gridStoreCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {GridStore} gridStore The gridStore. + */ + +/** + * Moves the read/write head to a new location. + * + * There are 3 signatures for this method + * + * Seek Location Modes + * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. + * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. + * - **GridStore.IO_SEEK_END**, set the position from the end of the file. + * + * @method + * @param {number} [position] the position to seek to + * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. + * @param {GridStore~gridStoreCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.prototype.seek = function(position, seekLocation, callback) { + var self = this; + + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + seekLocation = args.length ? args.shift() : null; + + // We provided a callback leg + if(typeof callback == 'function') return seek(self, position, seekLocation, callback); + // Return promise + return new self.promiseLibrary(function(resolve, reject) { + seek(self, position, seekLocation, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +} + +var seek = function(self, position, seekLocation, callback) { + // Seek only supports read mode + if(self.mode != 'r') { + return callback(MongoError.create({message: "seek is only supported for mode r", driver:true})) + } + + var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; + var finalPosition = position; + var targetPosition = 0; + + // Calculate the position + if(seekLocationFinal == GridStore.IO_SEEK_CUR) { + targetPosition = self.position + finalPosition; + } else if(seekLocationFinal == GridStore.IO_SEEK_END) { + targetPosition = self.length + finalPosition; + } else { + targetPosition = finalPosition; + } + + // Get the chunk + var newChunkNumber = Math.floor(targetPosition/self.chunkSize); + var seekChunk = function() { + nthChunk(self, newChunkNumber, function(err, chunk) { + self.currentChunk = chunk; + self.position = targetPosition; + self.currentChunk.position = (self.position % self.chunkSize); + callback(err, self); + }); + }; + + seekChunk(); +} + +define.classMethod('seek', {callback: true, promise:true}); + +/** + * @ignore + */ +var _open = function(self, options, callback) { + var collection = self.collection(); + // Create the query + var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; + query = null == self.fileId && self.filename == null ? null : query; + options.readPreference = self.readPreference; + + // Fetch the chunks + if(query != null) { + collection.findOne(query, options, function(err, doc) { + if(err) return error(err); + + // Check if the collection for the files exists otherwise prepare the new one + if(doc != null) { + self.fileId = doc._id; + // Prefer a new filename over the existing one if this is a write + self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename; + self.contentType = doc.contentType; + self.internalChunkSize = doc.chunkSize; + self.uploadDate = doc.uploadDate; + self.aliases = doc.aliases; + self.length = doc.length; + self.metadata = doc.metadata; + self.internalMd5 = doc.md5; + } else if (self.mode != 'r') { + self.fileId = self.fileId == null ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + } else { + self.length = 0; + var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId; + return error(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename)), driver:true}), self); + } + + // Process the mode of the object + if(self.mode == "r") { + nthChunk(self, 0, options, function(err, chunk) { + if(err) return error(err); + self.currentChunk = chunk; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w") { + // Delete any existing chunks + deleteChunks(self, options, function(err, result) { + if(err) return error(err); + self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); + self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w+") { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if(err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + }); + } else { + // Write only mode + self.fileId = null == self.fileId ? new ObjectID() : self.fileId; + self.contentType = GridStore.DEFAULT_CONTENT_TYPE; + self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; + self.length = 0; + + var collection2 = self.chunkCollection(); + // No file exists set up write mode + if(self.mode == "w") { + // Delete any existing chunks + deleteChunks(self, options, function(err, result) { + if(err) return error(err); + self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); + self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; + self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = 0; + callback(null, self); + }); + } else if(self.mode == "w+") { + nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { + if(err) return error(err); + // Set the current chunk + self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; + self.currentChunk.position = self.currentChunk.data.length(); + self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; + self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; + self.position = self.length; + callback(null, self); + }); + } + } + + // only pass error to callback once + function error (err) { + if(error.err) return; + callback(error.err = err); + } +}; + +/** + * @ignore + */ +var writeBuffer = function(self, buffer, close, callback) { + if(typeof close === "function") { callback = close; close = null; } + var finalClose = typeof close == 'boolean' ? close : false; + + if(self.mode != "w") { + callback(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename)), driver:true}), null); + } else { + if(self.currentChunk.position + buffer.length >= self.chunkSize) { + // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left + // to a new chunk (recursively) + var previousChunkNumber = self.currentChunk.chunkNumber; + var leftOverDataSize = self.chunkSize - self.currentChunk.position; + var firstChunkData = buffer.slice(0, leftOverDataSize); + var leftOverData = buffer.slice(leftOverDataSize); + // A list of chunks to write out + var chunksToWrite = [self.currentChunk.write(firstChunkData)]; + // If we have more data left than the chunk size let's keep writing new chunks + while(leftOverData.length >= self.chunkSize) { + // Create a new chunk and write to it + var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); + var firstChunkData = leftOverData.slice(0, self.chunkSize); + leftOverData = leftOverData.slice(self.chunkSize); + // Update chunk number + previousChunkNumber = previousChunkNumber + 1; + // Write data + newChunk.write(firstChunkData); + // Push chunk to save list + chunksToWrite.push(newChunk); + } + + // Set current chunk with remaining data + self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); + // If we have left over data write it + if(leftOverData.length > 0) self.currentChunk.write(leftOverData); + + // Update the position for the gridstore + self.position = self.position + buffer.length; + // Total number of chunks to write + var numberOfChunksToWrite = chunksToWrite.length; + + for(var i = 0; i < chunksToWrite.length; i++) { + chunksToWrite[i].save({}, function(err, result) { + if(err) return callback(err); + + numberOfChunksToWrite = numberOfChunksToWrite - 1; + + if(numberOfChunksToWrite <= 0) { + // We care closing the file before returning + if(finalClose) { + return self.close(function(err, result) { + callback(err, self); + }); + } + + // Return normally + return callback(null, self); + } + }); + } + } else { + // Update the position for the gridstore + self.position = self.position + buffer.length; + // We have less data than the chunk size just write it and callback + self.currentChunk.write(buffer); + // We care closing the file before returning + if(finalClose) { + return self.close(function(err, result) { + callback(err, self); + }); + } + // Return normally + return callback(null, self); + } + } +}; + +/** + * Creates a mongoDB object representation of this object. + * + *
    
    + *        {
    + *          '_id' : , // {number} id for this file
    + *          'filename' : , // {string} name for this file
    + *          'contentType' : , // {string} mime type for this file
    + *          'length' : , // {number} size of this file?
    + *          'chunksize' : , // {number} chunk size used by this file
    + *          'uploadDate' : , // {Date}
    + *          'aliases' : , // {array of string}
    + *          'metadata' : , // {string}
    + *        }
    + *        
    + * + * @ignore + */ +var buildMongoObject = function(self, callback) { + // Calcuate the length + var mongoObject = { + '_id': self.fileId, + 'filename': self.filename, + 'contentType': self.contentType, + 'length': self.position ? self.position : 0, + 'chunkSize': self.chunkSize, + 'uploadDate': self.uploadDate, + 'aliases': self.aliases, + 'metadata': self.metadata + }; + + var md5Command = {filemd5:self.fileId, root:self.root}; + self.db.command(md5Command, function(err, results) { + if(err) return callback(err); + + mongoObject.md5 = results.md5; + callback(null, mongoObject); + }); +}; + +/** + * Gets the nth chunk of this file. + * @ignore + */ +var nthChunk = function(self, chunkNumber, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + options.readPreference = self.readPreference; + // Get the nth chunk + self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) { + if(err) return callback(err); + + var finalChunk = chunk == null ? {} : chunk; + callback(null, new Chunk(self, finalChunk, self.writeConcern)); + }); +}; + +/** + * @ignore + */ +var lastChunkNumber = function(self) { + return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); +}; + +/** + * Deletes all the chunks of this file in the database. + * + * @ignore + */ +var deleteChunks = function(self, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + options = options || self.writeConcern; + + if(self.fileId != null) { + self.chunkCollection().remove({'files_id':self.fileId}, options, function(err, result) { + if(err) return callback(err, false); + callback(null, true); + }); + } else { + callback(null, true); + } +}; + +/** +* The collection to be used for holding the files and chunks collection. +* +* @classconstant DEFAULT_ROOT_COLLECTION +**/ +GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; + +/** +* Default file mime type +* +* @classconstant DEFAULT_CONTENT_TYPE +**/ +GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; + +/** +* Seek mode where the given length is absolute. +* +* @classconstant IO_SEEK_SET +**/ +GridStore.IO_SEEK_SET = 0; + +/** +* Seek mode where the given length is an offset to the current read/write head. +* +* @classconstant IO_SEEK_CUR +**/ +GridStore.IO_SEEK_CUR = 1; + +/** +* Seek mode where the given length is an offset to the end of the file. +* +* @classconstant IO_SEEK_END +**/ +GridStore.IO_SEEK_END = 2; + +/** + * Checks if a file exists in the database. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file to look for. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + exists(db, fileIdObject, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var exists = function(db, fileIdObject, rootCollection, options, callback) { + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Fetch collection + var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + db.collection(rootCollectionFinal + ".files", function(err, collection) { + if(err) return callback(err); + + // Build query + var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) + ? {'filename':fileIdObject} + : {'_id':fileIdObject}; // Attempt to locate file + + // We have a specific query + if(fileIdObject != null + && typeof fileIdObject == 'object' + && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') { + query = fileIdObject; + } + + // Check if the entry exists + collection.findOne(query, {readPreference:readPreference}, function(err, item) { + if(err) return callback(err); + callback(null, item == null ? false : true); + }); + }); +} + +define.staticMethod('exist', {callback: true, promise:true}); + +/** + * Gets the list of files stored in the GridFS. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] result from exists. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.list = function(db, rootCollection, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + rootCollection = args.length ? args.shift() : null; + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return list(db, rootCollection, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + list(db, rootCollection, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var list = function(db, rootCollection, options, callback) { + // Ensure we have correct values + if(rootCollection != null && typeof rootCollection == 'object') { + options = rootCollection; + rootCollection = null; + } + + // Establish read preference + var readPreference = options.readPreference || ReadPreference.PRIMARY; + // Check if we are returning by id not filename + var byId = options['id'] != null ? options['id'] : false; + // Fetch item + var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; + var items = []; + db.collection((rootCollectionFinal + ".files"), function(err, collection) { + if(err) return callback(err); + + collection.find({}, {readPreference:readPreference}, function(err, cursor) { + if(err) return callback(err); + + cursor.each(function(err, item) { + if(item != null) { + items.push(byId ? item._id : item.filename); + } else { + callback(err, items); + } + }); + }); + }); +} + +define.staticMethod('list', {callback: true, promise:true}); + +/** + * Reads the contents of a file. + * + * This method has the following signatures + * + * (db, name, callback) + * (db, name, length, callback) + * (db, name, length, offset, callback) + * (db, name, length, offset, options, callback) + * + * @method + * @static + * @param {Db} db the database to query. + * @param {string} name The name of the file. + * @param {number} [length] The size of data to read. + * @param {number} [offset] The offset from the head of the file of which to start reading from. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ + +GridStore.read = function(db, name, length, offset, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + length = args.length ? args.shift() : null; + offset = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readStatic(db, name, length, offset, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readStatic = function(db, name, length, offset, options, callback) { + new GridStore(db, name, "r", options).open(function(err, gridStore) { + if(err) return callback(err); + // Make sure we are not reading out of bounds + if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); + if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); + if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); + + if(offset != null) { + gridStore.seek(offset, function(err, gridStore) { + if(err) return callback(err); + gridStore.read(length, callback); + }); + } else { + gridStore.read(length, callback); + } + }); +} + +define.staticMethod('read', {callback: true, promise:true}); + +/** + * Read the entire file as a list of strings splitting by the provided separator. + * + * @method + * @static + * @param {Db} db the database to query. + * @param {(String|object)} name the name of the file. + * @param {string} [separator] The character to be recognized as the newline separator. + * @param {object} [options=null] Optional settings. + * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~readlinesCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.readlines = function(db, name, separator, options, callback) { + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + separator = args.length ? args.shift() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options ? options.promiseLibrary : null; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback); + // Return promise + return new promiseLibrary(function(resolve, reject) { + readlinesStatic(db, name, separator, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var readlinesStatic = function(db, name, separator, options, callback) { + var finalSeperator = separator == null ? "\n" : separator; + new GridStore(db, name, "r", options).open(function(err, gridStore) { + if(err) return callback(err); + gridStore.readlines(finalSeperator, callback); + }); +} + +define.staticMethod('readlines', {callback: true, promise:true}); + +/** + * Deletes the chunks and metadata information of a file from GridFS. + * + * @method + * @static + * @param {Db} db The database to query. + * @param {(string|array)} names The name/names of the files to delete. + * @param {object} [options=null] Optional settings. + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {GridStore~resultCallback} [callback] the command callback. + * @return {Promise} returns Promise if no callback passed + */ +GridStore.unlink = function(db, names, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + options = args.length ? args.shift() : {}; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // We provided a callback leg + if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback); + + // Return promise + return new promiseLibrary(function(resolve, reject) { + unlinkStatic(self, db, names, options, function(err, r) { + if(err) return reject(err); + resolve(r); + }) + }); +}; + +var unlinkStatic = function(self, db, names, options, callback) { + // Get the write concern + var writeConcern = _getWriteConcern(db, options); + + // List of names + if(names.constructor == Array) { + var tc = 0; + for(var i = 0; i < names.length; i++) { + ++tc; + GridStore.unlink(db, names[i], options, function(result) { + if(--tc == 0) { + callback(null, self); + } + }); + } + } else { + new GridStore(db, names, "w", options).open(function(err, gridStore) { + if(err) return callback(err); + deleteChunks(gridStore, function(err, result) { + if(err) return callback(err); + gridStore.collection(function(err, collection) { + if(err) return callback(err); + collection.remove({'_id':gridStore.fileId}, writeConcern, function(err, result) { + callback(err, self); + }); + }); + }); + }); + } +} + +define.staticMethod('unlink', {callback: true, promise:true}); + +/** + * @ignore + */ +var _writeNormal = function(self, data, close, callback) { + // If we have a buffer write it using the writeBuffer method + if(Buffer.isBuffer(data)) { + return writeBuffer(self, data, close, callback); + } else { + return writeBuffer(self, new Buffer(data, 'binary'), close, callback); + } +} + +/** + * @ignore + */ +var _setWriteConcernHash = function(options) { + var finalOptions = {}; + if(options.w != null) finalOptions.w = options.w; + if(options.journal == true) finalOptions.j = options.journal; + if(options.j == true) finalOptions.j = options.j; + if(options.fsync == true) finalOptions.fsync = options.fsync; + if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; + return finalOptions; +} + +/** + * @ignore + */ +var _getWriteConcern = function(self, options) { + // Final options + var finalOptions = {w:1}; + options = options || {}; + + // Local options verification + if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { + finalOptions = _setWriteConcernHash(options); + } else if(options.safe != null && typeof options.safe == 'object') { + finalOptions = _setWriteConcernHash(options.safe); + } else if(typeof options.safe == "boolean") { + finalOptions = {w: (options.safe ? 1 : 0)}; + } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { + finalOptions = _setWriteConcernHash(self.options); + } else if(self.safe && (self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean')) { + finalOptions = _setWriteConcernHash(self.safe); + } else if(typeof self.safe == "boolean") { + finalOptions = {w: (self.safe ? 1 : 0)}; + } + + // Ensure we don't have an invalid combination of write concerns + if(finalOptions.w < 1 + && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw MongoError.create({message: "No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true", driver:true}); + + // Return the options + return finalOptions; +} + +/** + * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) + * + * @class + * @extends external:Duplex + * @return {GridStoreStream} a GridStoreStream instance. + */ +var GridStoreStream = function(gs) { + var self = this; + // Initialize the duplex stream + Duplex.call(this); + + // Get the gridstore + this.gs = gs; + + // End called + this.endCalled = false; + + // If we have a seek + this.totalBytesToRead = this.gs.length - this.gs.position; + this.seekPosition = this.gs.position; +} + +// +// Inherit duplex +inherits(GridStoreStream, Duplex); + +GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; + +// Set up override +GridStoreStream.prototype.pipe = function(destination) { + var self = this; + + // Only open gridstore if not already open + if(!self.gs.isOpen) { + self.gs.open(function(err) { + if(err) return self.emit('error', err); + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + }); + } else { + self.totalBytesToRead = self.gs.length - self.gs.position; + self._pipe.apply(self, [destination]); + } +} + +// Called by stream +GridStoreStream.prototype._read = function(n) { + var self = this; + + var read = function() { + // Read data + self.gs.read(length, function(err, buffer) { + if(err && !self.endCalled) return self.emit('error', err); + + // Stream is closed + if(self.endCalled || buffer == null) return self.push(null); + // Remove bytes read + if(buffer.length <= self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer.length; + self.push(buffer); + } else if(buffer.length > self.totalBytesToRead) { + self.totalBytesToRead = self.totalBytesToRead - buffer._index; + self.push(buffer.slice(0, buffer._index)); + } + + // Finished reading + if(self.totalBytesToRead <= 0) { + self.endCalled = true; + } + }); + } + + // Set read length + var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; + if(!self.gs.isOpen) { + self.gs.open(function(err, gs) { + self.totalBytesToRead = self.gs.length - self.gs.position; + if(err) return self.emit('error', err); + read(); + }); + } else { + read(); + } +} + +GridStoreStream.prototype.destroy = function() { + this.pause(); + this.endCalled = true; + this.gs.close(); + this.emit('end'); +} + +GridStoreStream.prototype.write = function(chunk, encoding, callback) { + var self = this; + if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true})) + // Do we have to open the gridstore + if(!self.gs.isOpen) { + self.gs.open(function() { + self.gs.isOpen = true; + self.gs.write(chunk, function() { + process.nextTick(function() { + self.emit('drain'); + }); + }); + }); + return false; + } else { + self.gs.write(chunk, function() { + self.emit('drain'); + }); + return true; + } +} + +GridStoreStream.prototype.end = function(chunk, encoding, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 0); + callback = args.pop(); + if(typeof callback != 'function') args.push(callback); + chunk = args.length ? args.shift() : null; + encoding = args.length ? args.shift() : null; + self.endCalled = true; + + if(chunk) { + self.gs.write(chunk, function() { + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); + }); + } + + self.gs.close(function() { + if(typeof callback == 'function') callback(); + self.emit('end') + }); +} + +/** + * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. + * @function external:Duplex#read + * @param {number} size Optional argument to specify how much data to read. + * @return {(String | Buffer | null)} + */ + +/** + * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. + * @function external:Duplex#setEncoding + * @param {string} encoding The encoding to use. + * @return {null} + */ + +/** + * This method will cause the readable stream to resume emitting data events. + * @function external:Duplex#resume + * @return {null} + */ + +/** + * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. + * @function external:Duplex#pause + * @return {null} + */ + +/** + * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. + * @function external:Duplex#pipe + * @param {Writable} destination The destination for writing data + * @param {object} [options] Pipe options + * @return {null} + */ + +/** + * This method will remove the hooks set up for a previous pipe() call. + * @function external:Duplex#unpipe + * @param {Writable} [destination] The destination for writing data + * @return {null} + */ + +/** + * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. + * @function external:Duplex#unshift + * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. + * @return {null} + */ + +/** + * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) + * @function external:Duplex#wrap + * @param {Stream} stream An "old style" readable stream. + * @return {null} + */ + +/** + * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. + * @function external:Duplex#write + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {boolean} + */ + +/** + * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. + * @function external:Duplex#end + * @param {(string|Buffer)} chunk The data to write + * @param {string} encoding The encoding, if chunk is a String + * @param {function} callback Callback for when this chunk of data is flushed + * @return {null} + */ + +/** + * GridStoreStream stream data event, fired for each document in the cursor. + * + * @event GridStoreStream#data + * @type {object} + */ + +/** + * GridStoreStream stream end event + * + * @event GridStoreStream#end + * @type {null} + */ + +/** + * GridStoreStream stream close event + * + * @event GridStoreStream#close + * @type {null} + */ + +/** + * GridStoreStream stream readable event + * + * @event GridStoreStream#readable + * @type {null} + */ + +/** + * GridStoreStream stream drain event + * + * @event GridStoreStream#drain + * @type {null} + */ + +/** + * GridStoreStream stream finish event + * + * @event GridStoreStream#finish + * @type {null} + */ + +/** + * GridStoreStream stream pipe event + * + * @event GridStoreStream#pipe + * @type {null} + */ + +/** + * GridStoreStream stream unpipe event + * + * @event GridStoreStream#unpipe + * @type {null} + */ + +/** + * GridStoreStream stream error event + * + * @event GridStoreStream#error + * @type {null} + */ + +/** + * @ignore + */ +module.exports = GridStore; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/metadata.js b/util/demographicsImporter/node_modules/mongodb/lib/metadata.js new file mode 100644 index 0000000..7dae562 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/metadata.js @@ -0,0 +1,64 @@ +var f = require('util').format; + +var Define = function(name, object, stream) { + this.name = name; + this.object = object; + this.stream = typeof stream == 'boolean' ? stream : false; + this.instrumentations = {}; +} + +Define.prototype.classMethod = function(name, options) { + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +var generateKey = function(keys, options) { + var parts = []; + for(var i = 0; i < keys.length; i++) { + parts.push(f('%s=%s', keys[i], options[keys[i]])); + } + + return parts.join(); +} + +Define.prototype.staticMethod = function(name, options) { + options.static = true; + var keys = Object.keys(options).sort(); + var key = generateKey(keys, options); + + // Add a list of instrumentations + if(this.instrumentations[key] == null) { + this.instrumentations[key] = { + methods: [], options: options + } + } + + // Push to list of method for this instrumentation + this.instrumentations[key].methods.push(name); +} + +Define.prototype.generate = function(keys, options) { + // Generate the return object + var object = { + name: this.name, obj: this.object, stream: this.stream, + instrumentations: [] + } + + for(var name in this.instrumentations) { + object.instrumentations.push(this.instrumentations[name]); + } + + return object; +} + +module.exports = Define; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/lib/mongo_client.js b/util/demographicsImporter/node_modules/mongodb/lib/mongo_client.js new file mode 100644 index 0000000..3ce2ad6 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/mongo_client.js @@ -0,0 +1,463 @@ +"use strict"; + +var parse = require('./url_parser') + , Server = require('./server') + , Mongos = require('./mongos') + , ReplSet = require('./replset') + , Define = require('./metadata') + , ReadPreference = require('./read_preference') + , Db = require('./db'); + +/** + * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. + * + * @example + * var MongoClient = require('mongodb').MongoClient, + * test = require('assert'); + * // Connection url + * var url = 'mongodb://localhost:27017/test'; + * // Connect using MongoClient + * MongoClient.connect(url, function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new MongoClient instance + * @class + * @return {MongoClient} a MongoClient instance. + */ +function MongoClient() { + /** + * The callback format for results + * @callback MongoClient~connectCallback + * @param {MongoError} error An error instance representing the error during the execution. + * @param {Db} db The connected database. + */ + + /** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ + this.connect = MongoClient.connect; +} + +var define = MongoClient.define = new Define('MongoClient', MongoClient, false); + +/** + * Connect to MongoDB using a url as documented at + * + * docs.mongodb.org/manual/reference/connection-string/ + * + * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver + * + * @method + * @static + * @param {string} url The connection URI string + * @param {object} [options=null] Optional settings. + * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication + * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** + * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** + * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** + * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** + * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible + * @param {MongoClient~connectCallback} [callback] The command result callback + * @return {Promise} returns Promise if no callback passed + */ +MongoClient.connect = function(url, options, callback) { + var args = Array.prototype.slice.call(arguments, 1); + callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; + options = args.length ? args.shift() : null; + options = options || {}; + + // Get the promiseLibrary + var promiseLibrary = options.promiseLibrary; + + // No promise library selected fall back + if(!promiseLibrary) { + promiseLibrary = typeof global.Promise == 'function' ? + global.Promise : require('es6-promise').Promise; + } + + // Return a promise + if(typeof callback != 'function') { + return new promiseLibrary(function(resolve, reject) { + connect(url, options, function(err, db) { + if(err) return reject(err); + resolve(db); + }); + }); + } + + // Fallback to callback based connect + connect(url, options, callback); +} + +define.staticMethod('connect', {callback: true, promise:true}); + +var connect = function(url, options, callback) { + var serverOptions = options.server || {}; + var mongosOptions = options.mongos || {}; + var replSetServersOptions = options.replSet || options.replSetServers || {}; + var dbOptions = options.db || {}; + + // If callback is null throw an exception + if(callback == null) + throw new Error("no callback function provided"); + + // Parse the string + var object = parse(url, options); + + // Merge in any options for db in options object + if(dbOptions) { + for(var name in dbOptions) object.db_options[name] = dbOptions[name]; + } + + // Added the url to the options + object.db_options.url = url; + + // Merge in any options for server in options object + if(serverOptions) { + for(var name in serverOptions) object.server_options[name] = serverOptions[name]; + } + + // Merge in any replicaset server options + if(replSetServersOptions) { + for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; + } + + if(replSetServersOptions.ssl + || replSetServersOptions.sslValidate + || replSetServersOptions.sslCA + || replSetServersOptions.sslCert + || replSetServersOptions.sslKey + || replSetServersOptions.sslPass) { + object.server_options.ssl = replSetServersOptions.ssl; + object.server_options.sslValidate = replSetServersOptions.sslValidate; + object.server_options.sslCA = replSetServersOptions.sslCA; + object.server_options.sslCert = replSetServersOptions.sslCert; + object.server_options.sslKey = replSetServersOptions.sslKey; + object.server_options.sslPass = replSetServersOptions.sslPass; + } + + // Merge in any replicaset server options + if(mongosOptions) { + for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; + } + + if(typeof object.server_options.poolSize == 'number') { + if(!object.mongos_options.poolSize) object.mongos_options.poolSize = object.server_options.poolSize; + if(!object.rs_options.poolSize) object.rs_options.poolSize = object.server_options.poolSize; + } + + if(mongosOptions.ssl + || mongosOptions.sslValidate + || mongosOptions.sslCA + || mongosOptions.sslCert + || mongosOptions.sslKey + || mongosOptions.sslPass) { + object.server_options.ssl = mongosOptions.ssl; + object.server_options.sslValidate = mongosOptions.sslValidate; + object.server_options.sslCA = mongosOptions.sslCA; + object.server_options.sslCert = mongosOptions.sslCert; + object.server_options.sslKey = mongosOptions.sslKey; + object.server_options.sslPass = mongosOptions.sslPass; + } + + // Set the promise library + object.db_options.promiseLibrary = options.promiseLibrary; + + // We need to ensure that the list of servers are only either direct members or mongos + // they cannot be a mix of monogs and mongod's + var totalNumberOfServers = object.servers.length; + var totalNumberOfMongosServers = 0; + var totalNumberOfMongodServers = 0; + var serverConfig = null; + var errorServers = {}; + + // Failure modes + if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host"); + + // If we have no db setting for the native parser try to set the c++ one first + object.db_options.native_parser = _setNativeParser(object.db_options); + // If no auto_reconnect is set, set it to true as default for single servers + if(typeof object.server_options.auto_reconnect != 'boolean') { + object.server_options.auto_reconnect = true; + } + + // If we have more than a server, it could be replicaset or mongos list + // need to verify that it's one or the other and fail if it's a mix + // Connect to all servers and run ismaster + for(var i = 0; i < object.servers.length; i++) { + // Set up socket options + var providedSocketOptions = object.server_options.socketOptions || {}; + + var _server_options = { + poolSize:1 + , socketOptions: { + connectTimeoutMS: providedSocketOptions.connectTimeoutMS || 30000 + , socketTimeoutMS: providedSocketOptions.socketTimeoutMS || 30000 + } + , auto_reconnect:false}; + + // Ensure we have ssl setup for the servers + if(object.server_options.ssl) { + _server_options.ssl = object.server_options.ssl; + _server_options.sslValidate = object.server_options.sslValidate; + _server_options.sslCA = object.server_options.sslCA; + _server_options.sslCert = object.server_options.sslCert; + _server_options.sslKey = object.server_options.sslKey; + _server_options.sslPass = object.server_options.sslPass; + } else if(object.rs_options.ssl) { + _server_options.ssl = object.rs_options.ssl; + _server_options.sslValidate = object.rs_options.sslValidate; + _server_options.sslCA = object.rs_options.sslCA; + _server_options.sslCert = object.rs_options.sslCert; + _server_options.sslKey = object.rs_options.sslKey; + _server_options.sslPass = object.rs_options.sslPass; + } + + // Error + var error = null; + // Set up the Server object + var _server = object.servers[i].domain_socket + ? new Server(object.servers[i].domain_socket, _server_options) + : new Server(object.servers[i].host, object.servers[i].port, _server_options); + + var connectFunction = function(__server) { + // Attempt connect + new Db(object.dbName, __server, {w:1, native_parser:false, promiseLibrary:options.promiseLibrary}).open(function(err, db) { + // Update number of servers + totalNumberOfServers = totalNumberOfServers - 1; + + // If no error do the correct checks + if(!err) { + // Close the connection + db.close(); + var isMasterDoc = db.serverConfig.isMasterDoc; + + // Check what type of server we have + if(isMasterDoc.setName) { + totalNumberOfMongodServers++; + } + + if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; + } else { + error = err; + errorServers[__server.host + ":" + __server.port] = __server; + } + + if(totalNumberOfServers == 0) { + // Error out + if(totalNumberOfMongodServers == 0 && totalNumberOfMongosServers == 0 && error) { + return callback(error, null); + } + + // If we have a mix of mongod and mongos, throw an error + if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { + if(db) db.close(); + return process.nextTick(function() { + try { + callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); + } catch (err) { + throw err + } + }) + } + + if(totalNumberOfMongodServers == 0 + && totalNumberOfMongosServers == 0 + && object.servers.length == 1 + && (!object.rs_options.replicaSet || !object.rs_options.rs_name)) { + + var obj = object.servers[0]; + serverConfig = obj.domain_socket ? + new Server(obj.domain_socket, object.server_options) + : new Server(obj.host, obj.port, object.server_options); + + } else if(totalNumberOfMongodServers > 0 + || totalNumberOfMongosServers > 0 + || object.rs_options.replicaSet || object.rs_options.rs_name) { + + var finalServers = object.servers + .filter(function(serverObj) { + return errorServers[serverObj.host + ":" + serverObj.port] == null; + }) + .map(function(serverObj) { + return new Server(serverObj.host, serverObj.port, object.server_options); + }); + + // Clean out any error servers + errorServers = {}; + + // Set up the final configuration + if(totalNumberOfMongodServers > 0) { + try { + + // If no replicaset name was provided, we wish to perform a + // direct connection + if(totalNumberOfMongodServers == 1 + && (!object.rs_options.replicaSet && !object.rs_options.rs_name)) { + serverConfig = finalServers[0]; + } else if(totalNumberOfMongodServers == 1) { + object.rs_options.replicaSet = object.rs_options.replicaSet || object.rs_options.rs_name; + serverConfig = new ReplSet(finalServers, object.rs_options); + } else { + serverConfig = new ReplSet(finalServers, object.rs_options); + } + + } catch(err) { + return callback(err, null); + } + } else { + serverConfig = new Mongos(finalServers, object.mongos_options); + } + } + + if(serverConfig == null) { + return process.nextTick(function() { + try { + callback(new Error("Could not locate any valid servers in initial seed list")); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + + // Ensure no firing of open event before we are ready + serverConfig.emitOpen = false; + // Set up all options etc and connect to the database + _finishConnecting(serverConfig, object, options, callback) + } + }); + } + + // Wrap the context of the call + connectFunction(_server); + } +} + +var _setNativeParser = function(db_options) { + if(typeof db_options.native_parser == 'boolean') return db_options.native_parser; + + try { + require('mongodb-core').BSON.BSONNative.BSON; + return true; + } catch(err) { + return false; + } +} + +var _finishConnecting = function(serverConfig, object, options, callback) { + // If we have a readPreference passed in by the db options + if(typeof object.db_options.readPreference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.readPreference); + } else if(typeof object.db_options.read_preference == 'string') { + object.db_options.readPreference = new ReadPreference(object.db_options.read_preference); + } + + // Do we have readPreference tags + if(object.db_options.readPreference && object.db_options.readPreferenceTags) { + object.db_options.readPreference.tags = object.db_options.readPreferenceTags; + } else if(object.db_options.readPreference && object.db_options.read_preference_tags) { + object.db_options.readPreference.tags = object.db_options.read_preference_tags; + } + + // Get the socketTimeoutMS + var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0; + + // If we have a replset, override with replicaset socket timeout option if available + if(serverConfig instanceof ReplSet) { + socketTimeoutMS = object.rs_options.socketOptions.socketTimeoutMS || socketTimeoutMS; + } + + // Set socketTimeout to the same as the connectTimeoutMS or 30 sec + serverConfig.connectTimeoutMS = serverConfig.connectTimeoutMS || 30000; + serverConfig.socketTimeoutMS = serverConfig.connectTimeoutMS; + + // Set up the db options + var db = new Db(object.dbName, serverConfig, object.db_options); + // Open the db + db.open(function(err, db){ + + if(err) { + return process.nextTick(function() { + try { + callback(err, null); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + + // Reset the socket timeout + serverConfig.socketTimeoutMS = socketTimeoutMS || 0; + + // Return object + if(err == null && object.auth){ + // What db to authenticate against + var authentication_db = db; + if(object.db_options && object.db_options.authSource) { + authentication_db = db.db(object.db_options.authSource); + } + + // Build options object + var options = {}; + if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism; + if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName; + + // Authenticate + authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){ + if(success){ + process.nextTick(function() { + try { + callback(null, db); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } else { + if(db) db.close(); + process.nextTick(function() { + try { + callback(err ? err : new Error('Could not authenticate user ' + object.auth[0]), null); + } catch (err) { + if(db) db.close(); + throw err + } + }); + } + }); + } else { + process.nextTick(function() { + try { + callback(err, db); + } catch (err) { + if(db) db.close(); + throw err + } + }) + } + }); +} + +module.exports = MongoClient diff --git a/util/demographicsImporter/node_modules/mongodb/lib/mongos.js b/util/demographicsImporter/node_modules/mongodb/lib/mongos.js new file mode 100644 index 0000000..6087d76 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/mongos.js @@ -0,0 +1,491 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , MongoCR = require('mongodb-core').MongoCR + , CMongos = require('mongodb-core').Mongos + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , Define = require('./metadata') + , Server = require('./server') + , Store = require('./topology_base').Store + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * **Mongos Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Mongos = require('mongodb').Mongos, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using Mongos + * var server = new Server('localhost', 27017); + * var db = new Db('test', new Mongos([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Mongos instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires Mongos#connect + * @fires Mongos#ha + * @fires Mongos#joined + * @fires Mongos#left + * @fires Mongos#fullsetup + * @fires Mongos#open + * @fires Mongos#close + * @fires Mongos#error + * @fires Mongos#timeout + * @fires Mongos#parseError + * @return {Mongos} a Mongos instance. + */ +var Mongos = function(servers, options) { + if(!(this instanceof Mongos)) return new Mongos(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Ensure we change the sslCA option to ca if available + if(options.sslCA) finalOptions.ca = options.sslCA; + if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; + if(options.sslKey) finalOptions.key = options.sslKey; + if(options.sslCert) finalOptions.cert = options.sslCert; + if(options.sslPass) finalOptions.passphrase = options.sslPass; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + if(options.socketOptions.socketTimeoutMS) + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Create the Mongos + var mongos = new CMongos(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + // Add auth prbufferMaxEntriesoviders + mongos.addAuthProvider('mongocr', new MongoCR()); + + // Internal state + this.s = { + // Create the Mongos + mongos: mongos + // Server capabilities + , sCapabilities: sCapabilities + // Debug turned on + , debug: debug + // Store option defaults + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Actual store of callbacks + , store: store + // Options + , options: options + } + + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return self.s.mongos.lastIsMaster(); } + }); + + // Last ismaster + Object.defineProperty(this, 'numberOfConnectedServers', { + enumerable:true, get: function() { + return self.s.mongos.s.mongosState.connectedServers().length; + } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.mongos.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.mongos.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(Mongos, EventEmitter); + +var define = Mongos.define = new Define('Mongos', Mongos, false); + +// Connect +Mongos.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.removeListener(e, connectErrorHandler); + }); + + self.s.mongos.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect'); + self.s.store.execute(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.mongos.removeAllListeners(e); + }); + + // Set up listeners + self.s.mongos.once('timeout', errorHandler('timeout')); + self.s.mongos.once('error', errorHandler('error')); + self.s.mongos.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Set up serverConfig listeners + self.s.mongos.on('joined', relay('joined')); + self.s.mongos.on('left', relay('left')); + self.s.mongos.on('fullsetup', relay('fullsetup')); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + self.s.mongos.once('timeout', connectErrorHandler('timeout')); + self.s.mongos.once('error', connectErrorHandler('error')); + self.s.mongos.once('close', connectErrorHandler('close')); + self.s.mongos.once('connect', connectHandler); + // Reconnect server + self.s.mongos.on('reconnect', reconnectHandler); + + // Start connection + self.s.mongos.connect(_options); +} + +Mongos.prototype.parserType = function() { + return this.s.mongos.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Server capabilities +Mongos.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.mongos.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); + this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Mongos.prototype.command = function(ns, cmd, options, callback) { + this.s.mongos.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Mongos.prototype.insert = function(ns, ops, options, callback) { + this.s.mongos.insert(ns, ops, options, function(e, m) { + callback(e, m) + }); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Mongos.prototype.update = function(ns, ops, options, callback) { + this.s.mongos.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Mongos.prototype.remove = function(ns, ops, options, callback) { + this.s.mongos.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// IsConnected +Mongos.prototype.isConnected = function() { + return this.s.mongos.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Mongos.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.mongos.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Mongos.prototype.setBSONParserType = function(type) { + return this.s.mongos.setBSONParserType(type); +} + +Mongos.prototype.lastIsMaster = function() { + return this.s.mongos.lastIsMaster(); +} + +Mongos.prototype.close = function(forceClosed) { + this.s.mongos.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Mongos.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.mongos.auth.apply(this.s.mongos, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Mongos.prototype.connections = function() { + return this.s.mongos.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * The mongos high availability event + * + * @event Mongos#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the mongos set + * + * @event Mongos#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos set + * + * @event Mongos#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. + * + * @event Mongos#fullsetup + * @type {Mongos} + */ + +/** + * Mongos open event, emitted when mongos can start processing commands. + * + * @event Mongos#open + * @type {Mongos} + */ + +/** + * Mongos close event + * + * @event Mongos#close + * @type {object} + */ + +/** + * Mongos error event, emitted if there is an error listener. + * + * @event Mongos#error + * @type {MongoError} + */ + +/** + * Mongos timeout event + * + * @event Mongos#timeout + * @type {object} + */ + +/** + * Mongos parseError event + * + * @event Mongos#parseError + * @type {object} + */ + +module.exports = Mongos; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/read_preference.js b/util/demographicsImporter/node_modules/mongodb/lib/read_preference.js new file mode 100644 index 0000000..73b253a --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/read_preference.js @@ -0,0 +1,104 @@ +"use strict"; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * ReadPreference = require('mongodb').ReadPreference, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * test.equal(null, err); + * // Perform a read + * var cursor = db.collection('t').find({}); + * cursor.setReadPreference(ReadPreference.PRIMARY); + * cursor.toArray(function(err, docs) { + * test.equal(null, err); + * db.close(); + * }); + * }); + */ + +/** + * Creates a new ReadPreference instance + * + * Read Preferences + * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). + * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. + * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. + * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. + * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. + * + * @class + * @param {string} mode The ReadPreference mode as listed above. + * @param {object} tags An object representing read preference tags. + * @property {string} mode The ReadPreference mode. + * @property {object} tags The ReadPreference tags. + * @return {ReadPreference} a ReadPreference instance. + */ +var ReadPreference = function(mode, tags) { + if(!(this instanceof ReadPreference)) + return new ReadPreference(mode, tags); + this._type = 'ReadPreference'; + this.mode = mode; + this.tags = tags; +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +ReadPreference.isValid = function(_mode) { + return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED + || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED + || _mode == ReadPreference.NEAREST + || _mode == true || _mode == false || _mode == null); +} + +/** + * Validate if a mode is legal + * + * @method + * @param {string} mode The string representing the read preference mode. + * @return {boolean} + */ +ReadPreference.prototype.isValid = function(mode) { + var _mode = typeof mode == 'string' ? mode : this.mode; + return ReadPreference.isValid(_mode); +} + +/** + * @ignore + */ +ReadPreference.prototype.toObject = function() { + var object = {mode:this.mode}; + + if(this.tags != null) { + object['tags'] = this.tags; + } + + return object; +} + +/** + * @ignore + */ +ReadPreference.PRIMARY = 'primary'; +ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; +ReadPreference.SECONDARY = 'secondary'; +ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; +ReadPreference.NEAREST = 'nearest' + +/** + * @ignore + */ +module.exports = ReadPreference; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/lib/replset.js b/util/demographicsImporter/node_modules/mongodb/lib/replset.js new file mode 100644 index 0000000..8a71b42 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/replset.js @@ -0,0 +1,555 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format + , Server = require('./server') + , Mongos = require('./mongos') + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , ReadPreference = require('./read_preference') + , MongoCR = require('mongodb-core').MongoCR + , MongoError = require('mongodb-core').MongoError + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , CServer = require('mongodb-core').Server + , CReplSet = require('mongodb-core').ReplSet + , CoreReadPreference = require('mongodb-core').ReadPreference + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connections. + * + * **ReplSet Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * ReplSet = require('mongodb').ReplSet, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using ReplSet + * var server = new Server('localhost', 27017); + * var db = new Db('test', new ReplSet([server])); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new ReplSet instance + * @class + * @deprecated + * @param {Server[]} servers A seedlist of servers participating in the replicaset. + * @param {object} [options=null] Optional settings. + * @param {booelan} [options.ha=true] Turn on high availability monitoring. + * @param {number} [options.haInterval=5000] Time between each replicaset status check. + * @param {string} options.replicaSet The name of the replicaset to connect to. + * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + * @fires ReplSet#fullsetup + * @fires ReplSet#open + * @fires ReplSet#close + * @fires ReplSet#error + * @fires ReplSet#timeout + * @fires ReplSet#parseError + * @return {ReplSet} a ReplSet instance. + */ +var ReplSet = function(servers, options) { + if(!(this instanceof ReplSet)) return new ReplSet(servers, options); + options = options || {}; + var self = this; + + // Ensure all the instances are Server + for(var i = 0; i < servers.length; i++) { + if(!(servers[i] instanceof Server)) { + throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); + } + } + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Set up event emitter + EventEmitter.call(this); + + // Debug tag + var tag = options.tag; + + // Build seed list + var seedlist = servers.map(function(x) { + return {host: x.host, port: x.port} + }); + + // Final options + var finalOptions = shallowClone(options); + + // Default values + finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; + finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + finalOptions.cursorFactory = Cursor; + + // Add the store + finalOptions.disconnectHandler = store; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + } + + // Get the name + var replicaSet = options.replicaSet || options.rs_name; + + // Set up options + finalOptions.setName = replicaSet; + + // Are we running in debug mode + var debug = typeof options.debug == 'boolean' ? options.debug : false; + if(debug) { + finalOptions.debug = debug; + } + + // Map keep alive setting + if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAlive = true; + if(typeof options.socketOptions.keepAlive == 'number') { + finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + } + } + + // Connection timeout + if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { + finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; + } + + // Socket timeout + if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { + finalOptions.socketTimeout = options.socketOptions.socketTimeout; + } + + // noDelay + if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { + finalOptions.noDelay = options.socketOptions.noDelay; + } + + if(typeof options.secondaryAcceptableLatencyMS == 'number') { + finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; + } + + if(options.connectWithNoPrimary == true) { + finalOptions.secondaryOnlyConnectionAllowed = true; + } + + // Add the non connection store + finalOptions.disconnectHandler = store; + + // Translate the options + if(options.sslCA) finalOptions.ca = options.sslCA; + if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; + if(options.sslKey) finalOptions.key = options.sslKey; + if(options.sslCert) finalOptions.cert = options.sslCert; + if(options.sslPass) finalOptions.passphrase = options.sslPass; + + // Create the ReplSet + var replset = new CReplSet(seedlist, finalOptions) + // Server capabilities + var sCapabilities = null; + // Add auth prbufferMaxEntriesoviders + replset.addAuthProvider('mongocr', new MongoCR()); + + // Listen to reconnect event + replset.on('reconnect', function() { + self.emit('reconnect'); + store.execute(); + }); + + // Internal state + this.s = { + // Replicaset + replset: replset + // Server capabilities + , sCapabilities: null + // Debug tag + , tag: options.tag + // Store options + , storeOptions: storeOptions + // Cloned options + , clonedOptions: finalOptions + // Store + , store: store + // Options + , options: options + } + + // Debug + if(debug) { + // Last ismaster + Object.defineProperty(this, 'replset', { + enumerable:true, get: function() { return replset; } + }); + } + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { return replset.lastIsMaster(); } + }); + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return replset.bson; + } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return replset.haInterval; } + }); +} + +/** + * @ignore + */ +inherits(ReplSet, EventEmitter); + +var define = ReplSet.define = new Define('ReplSet', ReplSet, false); + +// Ensure the right read Preference object +var translateReadPreference = function(options) { + if(typeof options.readPreference == 'string') { + options.readPreference = new CoreReadPreference(options.readPreference); + } else if(options.readPreference instanceof ReadPreference) { + options.readPreference = new CoreReadPreference(options.readPreference.mode + , options.readPreference.tags); + } + + return options; +} + +ReplSet.prototype.parserType = function() { + return this.s.replset.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Connect method +ReplSet.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.replset.removeAllListeners(e); + }); + + // Set up listeners + self.s.replset.once('timeout', errorHandler('timeout')); + self.s.replset.once('error', errorHandler('error')); + self.s.replset.once('close', errorHandler('close')); + + // relay the event + var relay = function(event) { + return function(t, server) { + self.emit(event, t, server); + } + } + + // Replset events relay + var replsetRelay = function(event) { + return function(t, server) { + self.emit(event, t, server.lastIsMaster(), server); + } + } + + // Relay ha + var relayHa = function(t, state) { + self.emit('ha', t, state); + + if(t == 'start') { + self.emit('ha_connect', t, state); + } else if(t == 'end') { + self.emit('ha_ismaster', t, state); + } + } + + // Set up serverConfig listeners + self.s.replset.on('joined', replsetRelay('joined')); + self.s.replset.on('left', relay('left')); + self.s.replset.on('ping', relay('ping')); + self.s.replset.on('ha', relayHa); + + self.s.replset.on('fullsetup', function(topology) { + self.emit('fullsetup', null, self); + }); + + self.s.replset.on('all', function(topology) { + self.emit('all', null, self); + }); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + ['timeout', 'error', 'close'].forEach(function(e) { + self.s.replset.removeListener(e, connectErrorHandler); + }); + + self.s.replset.removeListener('connect', connectErrorHandler); + // Destroy the replset + self.s.replset.destroy(); + + // Try to callback + try { + callback(err); + } catch(err) { + if(!self.s.replset.isConnected()) + process.nextTick(function() { throw err; }) + } + } + } + + // Set up listeners + self.s.replset.once('timeout', connectErrorHandler('timeout')); + self.s.replset.once('error', connectErrorHandler('error')); + self.s.replset.once('close', connectErrorHandler('close')); + self.s.replset.once('connect', connectHandler); + + // Start connection + self.s.replset.connect(_options); +} + +// Server capabilities +ReplSet.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.replset.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); + this.s.sCapabilities = new ServerCapabilities(this.s.replset.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +ReplSet.prototype.command = function(ns, cmd, options, callback) { + options = translateReadPreference(options); + this.s.replset.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +ReplSet.prototype.insert = function(ns, ops, options, callback) { + this.s.replset.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +ReplSet.prototype.update = function(ns, ops, options, callback) { + this.s.replset.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +ReplSet.prototype.remove = function(ns, ops, options, callback) { + this.s.replset.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// IsConnected +ReplSet.prototype.isConnected = function() { + return this.s.replset.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +ReplSet.prototype.setBSONParserType = function(type) { + return this.s.replset.setBSONParserType(type); +} + +// Insert +ReplSet.prototype.cursor = function(ns, cmd, options) { + options = translateReadPreference(options); + options.disconnectHandler = this.s.store; + return this.s.replset.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +ReplSet.prototype.lastIsMaster = function() { + return this.s.replset.lastIsMaster(); +} + +ReplSet.prototype.close = function(forceClosed) { + var self = this; + this.s.replset.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } + + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); +} + +define.classMethod('close', {callback: false, promise:false}); + +ReplSet.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.replset.auth.apply(this.s.replset, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +ReplSet.prototype.connections = function() { + return this.s.replset.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +/** + * ReplSet open event, emitted when replicaset can start processing commands. + * + * @event ReplSet#open + * @type {Replset} + */ + +/** + * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. + * + * @event ReplSet#fullsetup + * @type {Replset} + */ + +/** + * ReplSet close event + * + * @event ReplSet#close + * @type {object} + */ + +/** + * ReplSet error event, emitted if there is an error listener. + * + * @event ReplSet#error + * @type {MongoError} + */ + +/** + * ReplSet timeout event + * + * @event ReplSet#timeout + * @type {object} + */ + +/** + * ReplSet parseError event + * + * @event ReplSet#parseError + * @type {object} + */ + +module.exports = ReplSet; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/server.js b/util/demographicsImporter/node_modules/mongodb/lib/server.js new file mode 100644 index 0000000..eff7771 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/server.js @@ -0,0 +1,437 @@ +"use strict"; + +var EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , CServer = require('mongodb-core').Server + , Cursor = require('./cursor') + , AggregationCursor = require('./aggregation_cursor') + , CommandCursor = require('./command_cursor') + , f = require('util').format + , ServerCapabilities = require('./topology_base').ServerCapabilities + , Store = require('./topology_base').Store + , Define = require('./metadata') + , MongoError = require('mongodb-core').MongoError + , shallowClone = require('./utils').shallowClone; + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * **Server Should not be used, use MongoClient.connect** + * @example + * var Db = require('mongodb').Db, + * Server = require('mongodb').Server, + * test = require('assert'); + * // Connect using single Server + * var db = new Db('test', new Server('localhost', 27017);); + * db.open(function(err, db) { + * // Get an additional db + * db.close(); + * }); + */ + +/** + * Creates a new Server instance + * @class + * @deprecated + * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. + * @param {number} [port] The server port if IP4. + * @param {object} [options=null] Optional settings. + * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. + * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) + * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) + * @param {object} [options.socketOptions=null] Socket options + * @param {boolean} [options.socketOptions.autoReconnect=false] Reconnect on error. + * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. + * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. + * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting + * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + * @return {Server} a Server instance. + */ +var Server = function(host, port, options) { + options = options || {}; + if(!(this instanceof Server)) return new Server(host, port, options); + EventEmitter.call(this); + var self = this; + + // Store option defaults + var storeOptions = { + force: false + , bufferMaxEntries: -1 + } + + // Shared global store + var store = options.store || new Store(self, storeOptions); + + // Detect if we have a socket connection + if(host.indexOf('\/') != -1) { + if(port != null && typeof port == 'object') { + options = port; + port = null; + } + } else if(port == null) { + throw MongoError.create({message: 'port must be specified', driver:true}); + } + + // Clone options + var clonedOptions = shallowClone(options); + clonedOptions.host = host; + clonedOptions.port = port; + + // Reconnect + var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; + reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; + var emitError = typeof options.emitError == 'boolean' ? options.emitError : true; + var poolSize = typeof options.poolSize == 'number' ? options.poolSize : 5; + + // Socket options passed down + if(options.socketOptions) { + if(options.socketOptions.connectTimeoutMS) { + this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; + clonedOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; + } + + if(options.socketOptions.socketTimeoutMS) { + clonedOptions.socketTimeout = options.socketOptions.socketTimeoutMS; + } + + if(typeof options.socketOptions.keepAlive == 'number') { + clonedOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; + clonedOptions.keepAlive = true; + } + + if(typeof options.socketOptions.noDelay == 'boolean') { + clonedOptions.noDelay = options.socketOptions.noDelay; + } + } + + // Add the cursor factory function + clonedOptions.cursorFactory = Cursor; + clonedOptions.reconnect = reconnect; + clonedOptions.emitError = emitError; + clonedOptions.size = poolSize; + + // Translate the options + if(clonedOptions.sslCA) clonedOptions.ca = clonedOptions.sslCA; + if(typeof clonedOptions.sslValidate == 'boolean') clonedOptions.rejectUnauthorized = clonedOptions.sslValidate; + if(clonedOptions.sslKey) clonedOptions.key = clonedOptions.sslKey; + if(clonedOptions.sslCert) clonedOptions.cert = clonedOptions.sslCert; + if(clonedOptions.sslPass) clonedOptions.passphrase = clonedOptions.sslPass; + + // Add the non connection store + clonedOptions.disconnectHandler = store; + + // Create an instance of a server instance from mongodb-core + var server = new CServer(clonedOptions); + // Server capabilities + var sCapabilities = null; + + // Define the internal properties + this.s = { + // Create an instance of a server instance from mongodb-core + server: server + // Server capabilities + , sCapabilities: null + // Cloned options + , clonedOptions: clonedOptions + // Reconnect + , reconnect: reconnect + // Emit error + , emitError: emitError + // Pool size + , poolSize: poolSize + // Store Options + , storeOptions: storeOptions + // Store + , store: store + // Host + , host: host + // Port + , port: port + // Options + , options: options + } + + // BSON property + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + return self.s.server.bson; + } + }); + + // Last ismaster + Object.defineProperty(this, 'isMasterDoc', { + enumerable:true, get: function() { + return self.s.server.lastIsMaster(); + } + }); + + // Last ismaster + Object.defineProperty(this, 'poolSize', { + enumerable:true, get: function() { return self.s.server.connections().length; } + }); + + Object.defineProperty(this, 'autoReconnect', { + enumerable:true, get: function() { return self.s.reconnect; } + }); + + Object.defineProperty(this, 'host', { + enumerable:true, get: function() { return self.s.host; } + }); + + Object.defineProperty(this, 'port', { + enumerable:true, get: function() { return self.s.port; } + }); +} + +inherits(Server, EventEmitter); + +var define = Server.define = new Define('Server', Server, false); + +Server.prototype.parserType = function() { + return this.s.server.parserType(); +} + +define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); + +// Connect +Server.prototype.connect = function(db, _options, callback) { + var self = this; + if('function' === typeof _options) callback = _options, _options = {}; + if(_options == null) _options = {}; + if(!('function' === typeof callback)) callback = null; + self.s.options = _options; + + // Update bufferMaxEntries + self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; + + // Error handler + var connectErrorHandler = function(event) { + return function(err) { + // Remove all event handlers + var events = ['timeout', 'error', 'close']; + events.forEach(function(e) { + self.s.server.removeListener(e, connectHandlers[e]); + }); + + self.s.server.removeListener('connect', connectErrorHandler); + + // Try to callback + try { + callback(err); + } catch(err) { + process.nextTick(function() { throw err; }) + } + } + } + + // Actual handler + var errorHandler = function(event) { + return function(err) { + if(event != 'error') { + self.emit(event, err); + } + } + } + + // Error handler + var reconnectHandler = function(err) { + self.emit('reconnect', self); + self.s.store.execute(); + } + + // Destroy called on topology, perform cleanup + var destroyHandler = function() { + self.s.store.flush(); + } + + // Connect handler + var connectHandler = function() { + // Clear out all the current handlers left over + ["timeout", "error", "close"].forEach(function(e) { + self.s.server.removeAllListeners(e); + }); + + // Set up listeners + self.s.server.once('timeout', errorHandler('timeout')); + self.s.server.once('error', errorHandler('error')); + self.s.server.on('close', errorHandler('close')); + // Only called on destroy + self.s.server.once('destroy', destroyHandler); + + // Emit open event + self.emit('open', null, self); + + // Return correctly + try { + callback(null, self); + } catch(err) { + console.log(err.stack) + process.nextTick(function() { throw err; }) + } + } + + // Set up listeners + var connectHandlers = { + timeout: connectErrorHandler('timeout'), + error: connectErrorHandler('error'), + close: connectErrorHandler('close') + }; + + // Add the event handlers + self.s.server.once('timeout', connectHandlers.timeout); + self.s.server.once('error', connectHandlers.error); + self.s.server.once('close', connectHandlers.close); + self.s.server.once('connect', connectHandler); + // Reconnect server + self.s.server.on('reconnect', reconnectHandler); + + // Start connection + self.s.server.connect(_options); +} + +// Server capabilities +Server.prototype.capabilities = function() { + if(this.s.sCapabilities) return this.s.sCapabilities; + if(this.s.server.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); + this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster()); + return this.s.sCapabilities; +} + +define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); + +// Command +Server.prototype.command = function(ns, cmd, options, callback) { + this.s.server.command(ns, cmd, options, callback); +} + +define.classMethod('command', {callback: true, promise:false}); + +// Insert +Server.prototype.insert = function(ns, ops, options, callback) { + this.s.server.insert(ns, ops, options, callback); +} + +define.classMethod('insert', {callback: true, promise:false}); + +// Update +Server.prototype.update = function(ns, ops, options, callback) { + this.s.server.update(ns, ops, options, callback); +} + +define.classMethod('update', {callback: true, promise:false}); + +// Remove +Server.prototype.remove = function(ns, ops, options, callback) { + this.s.server.remove(ns, ops, options, callback); +} + +define.classMethod('remove', {callback: true, promise:false}); + +// IsConnected +Server.prototype.isConnected = function() { + return this.s.server.isConnected(); +} + +define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); + +// Insert +Server.prototype.cursor = function(ns, cmd, options) { + options.disconnectHandler = this.s.store; + return this.s.server.cursor(ns, cmd, options); +} + +define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); + +Server.prototype.setBSONParserType = function(type) { + return this.s.server.setBSONParserType(type); +} + +Server.prototype.lastIsMaster = function() { + return this.s.server.lastIsMaster(); +} + +Server.prototype.close = function(forceClosed) { + this.s.server.destroy(); + // We need to wash out all stored processes + if(forceClosed == true) { + this.s.storeOptions.force = forceClosed; + this.s.store.flush(); + } +} + +define.classMethod('close', {callback: false, promise:false}); + +Server.prototype.auth = function() { + var args = Array.prototype.slice.call(arguments, 0); + this.s.server.auth.apply(this.s.server, args); +} + +define.classMethod('auth', {callback: true, promise:false}); + +/** + * All raw connections + * @method + * @return {array} + */ +Server.prototype.connections = function() { + return this.s.server.connections(); +} + +define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); + +/** + * Server connect event + * + * @event Server#connect + * @type {object} + */ + +/** + * Server close event + * + * @event Server#close + * @type {object} + */ + +/** + * Server reconnect event + * + * @event Server#reconnect + * @type {object} + */ + +/** + * Server error event + * + * @event Server#error + * @type {MongoError} + */ + +/** + * Server timeout event + * + * @event Server#timeout + * @type {object} + */ + +/** + * Server parseError event + * + * @event Server#parseError + * @type {object} + */ + +module.exports = Server; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/topology_base.js b/util/demographicsImporter/node_modules/mongodb/lib/topology_base.js new file mode 100644 index 0000000..000f7ec --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/topology_base.js @@ -0,0 +1,152 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError + , f = require('util').format; + +// The store of ops +var Store = function(topology, storeOptions) { + var self = this; + var storedOps = []; + storeOptions = storeOptions || {force:false, bufferMaxEntries: -1} + + // Internal state + this.s = { + storedOps: storedOps + , storeOptions: storeOptions + , topology: topology + } + + Object.defineProperty(this, 'length', { + enumerable:true, get: function() { return self.s.storedOps.length; } + }); +} + +Store.prototype.add = function(opType, ns, ops, options, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true})); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, n: ns, o: ops, op: options, c: callback}) +} + +Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { + if(this.s.storeOptions.force) { + return callback(MongoError.create({message: "db closed by application", driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries == 0) { + return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { + while(this.s.storedOps.length > 0) { + var op = this.s.storedOps.shift(); + op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); + } + + return; + } + + this.s.storedOps.push({t: opType, m: method, o: object, p: params, c: callback}) +} + +Store.prototype.flush = function() { + while(this.s.storedOps.length > 0) { + this.s.storedOps.shift().c(MongoError.create({message: f("no connection available for operation"), driver:true })); + } +} + +Store.prototype.execute = function() { + // Get current ops + var ops = this.s.storedOps; + // Reset the ops + this.s.storedOps = []; + + // Execute all the stored ops + while(ops.length > 0) { + var op = ops.shift(); + + if(op.t == 'cursor') { + op.o[op.m].apply(op.o, op.p); + } else { + this.s.topology[op.t](op.n, op.o, op.op, op.c); + } + } +} + +Store.prototype.all = function() { + return this.s.storedOps; +} + +// Server capabilities +var ServerCapabilities = function(ismaster) { + var setup_get_property = function(object, name, value) { + Object.defineProperty(object, name, { + enumerable: true + , get: function () { return value; } + }); + } + + // Capabilities + var aggregationCursor = false; + var writeCommands = false; + var textSearch = false; + var authCommands = false; + var listCollections = false; + var listIndexes = false; + var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; + + if(ismaster.minWireVersion >= 0) { + textSearch = true; + } + + if(ismaster.maxWireVersion >= 1) { + aggregationCursor = true; + authCommands = true; + } + + if(ismaster.maxWireVersion >= 2) { + writeCommands = true; + } + + if(ismaster.maxWireVersion >= 3) { + listCollections = true; + listIndexes = true; + } + + // If no min or max wire version set to 0 + if(ismaster.minWireVersion == null) { + ismaster.minWireVersion = 0; + } + + if(ismaster.maxWireVersion == null) { + ismaster.maxWireVersion = 0; + } + + // Map up read only parameters + setup_get_property(this, "hasAggregationCursor", aggregationCursor); + setup_get_property(this, "hasWriteCommands", writeCommands); + setup_get_property(this, "hasTextSearch", textSearch); + setup_get_property(this, "hasAuthCommands", authCommands); + setup_get_property(this, "hasListCollectionsCommand", listCollections); + setup_get_property(this, "hasListIndexesCommand", listIndexes); + setup_get_property(this, "minWireVersion", ismaster.minWireVersion); + setup_get_property(this, "maxWireVersion", ismaster.maxWireVersion); + setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); +} + +exports.Store = Store; +exports.ServerCapabilities = ServerCapabilities; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/url_parser.js b/util/demographicsImporter/node_modules/mongodb/lib/url_parser.js new file mode 100644 index 0000000..eccc1e0 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/url_parser.js @@ -0,0 +1,295 @@ +"use strict"; + +var ReadPreference = require('./read_preference'); + +module.exports = function(url, options) { + // Ensure we have a default options object if none set + options = options || {}; + // Variables + var connection_part = ''; + var auth_part = ''; + var query_string_part = ''; + var dbName = 'admin'; + + // Must start with mongodb + if(url.indexOf("mongodb://") != 0) + throw Error("URL must be in the format mongodb://user:pass@host:port/dbname"); + // If we have a ? mark cut the query elements off + if(url.indexOf("?") != -1) { + query_string_part = url.substr(url.indexOf("?") + 1); + connection_part = url.substring("mongodb://".length, url.indexOf("?")) + } else { + connection_part = url.substring("mongodb://".length); + } + + // Check if we have auth params + if(connection_part.indexOf("@") != -1) { + auth_part = connection_part.split("@")[0]; + connection_part = connection_part.split("@")[1]; + } + + // Check if the connection string has a db + if(connection_part.indexOf(".sock") != -1) { + if(connection_part.indexOf(".sock/") != -1) { + dbName = connection_part.split(".sock/")[1]; + connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); + } + } else if(connection_part.indexOf("/") != -1) { + dbName = connection_part.split("/")[1]; + connection_part = connection_part.split("/")[0]; + } + + // Result object + var object = {}; + + // Pick apart the authentication part of the string + var authPart = auth_part || ''; + var auth = authPart.split(':', 2); + + // Decode the URI components + auth[0] = decodeURIComponent(auth[0]); + if(auth[1]){ + auth[1] = decodeURIComponent(auth[1]); + } + + // Add auth to final object if we have 2 elements + if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; + + // Variables used for temporary storage + var hostPart; + var urlOptions; + var servers; + var serverOptions = {socketOptions: {}}; + var dbOptions = {read_preference_tags: []}; + var replSetServersOptions = {socketOptions: {}}; + // Add server options to final object + object.server_options = serverOptions; + object.db_options = dbOptions; + object.rs_options = replSetServersOptions; + object.mongos_options = {}; + + // Let's check if we are using a domain socket + if(url.match(/\.sock/)) { + // Split out the socket part + var domainSocket = url.substring( + url.indexOf("mongodb://") + "mongodb://".length + , url.lastIndexOf(".sock") + ".sock".length); + // Clean out any auth stuff if any + if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; + servers = [{domain_socket: domainSocket}]; + } else { + // Split up the db + hostPart = connection_part; + // Deduplicate servers + var deduplicatedServers = {}; + + // Parse all server results + servers = hostPart.split(',').map(function(h) { + var _host, _port, ipv6match; + //check if it matches [IPv6]:port, where the port number is optional + if ((ipv6match = /\[([^\]]+)\](?:\:(.+))?/.exec(h))) { + _host = ipv6match[1]; + _port = parseInt(ipv6match[2], 10) || 27017; + } else { + //otherwise assume it's IPv4, or plain hostname + var hostPort = h.split(':', 2); + _host = hostPort[0] || 'localhost'; + _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; + // Check for localhost?safe=true style case + if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; + } + + // No entry returned for duplicate servr + if(deduplicatedServers[_host + "_" + _port]) return null; + deduplicatedServers[_host + "_" + _port] = 1; + + // Return the mapped object + return {host: _host, port: _port}; + }).filter(function(x) { + return x != null; + }); + } + + // Get the db name + object.dbName = dbName || 'admin'; + // Split up all the options + urlOptions = (query_string_part || '').split(/[&;]/); + // Ugh, we have to figure out which options go to which constructor manually. + urlOptions.forEach(function(opt) { + if(!opt) return; + var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; + // Options implementations + switch(name) { + case 'slaveOk': + case 'slave_ok': + serverOptions.slave_ok = (value == 'true'); + dbOptions.slaveOk = (value == 'true'); + break; + case 'maxPoolSize': + case 'poolSize': + serverOptions.poolSize = parseInt(value, 10); + replSetServersOptions.poolSize = parseInt(value, 10); + break; + case 'autoReconnect': + case 'auto_reconnect': + serverOptions.auto_reconnect = (value == 'true'); + break; + case 'minPoolSize': + throw new Error("minPoolSize not supported"); + case 'maxIdleTimeMS': + throw new Error("maxIdleTimeMS not supported"); + case 'waitQueueMultiple': + throw new Error("waitQueueMultiple not supported"); + case 'waitQueueTimeoutMS': + throw new Error("waitQueueTimeoutMS not supported"); + case 'uuidRepresentation': + throw new Error("uuidRepresentation not supported"); + case 'ssl': + if(value == 'prefer') { + serverOptions.ssl = value; + replSetServersOptions.ssl = value; + break; + } + serverOptions.ssl = (value == 'true'); + replSetServersOptions.ssl = (value == 'true'); + break; + case 'replicaSet': + case 'rs_name': + replSetServersOptions.rs_name = value; + break; + case 'reconnectWait': + replSetServersOptions.reconnectWait = parseInt(value, 10); + break; + case 'retries': + replSetServersOptions.retries = parseInt(value, 10); + break; + case 'readSecondary': + case 'read_secondary': + replSetServersOptions.read_secondary = (value == 'true'); + break; + case 'fsync': + dbOptions.fsync = (value == 'true'); + break; + case 'journal': + dbOptions.j = (value == 'true'); + break; + case 'safe': + dbOptions.safe = (value == 'true'); + break; + case 'nativeParser': + case 'native_parser': + dbOptions.native_parser = (value == 'true'); + break; + case 'readConcernLevel': + dbOptions.readConcern = {level: value}; + break; + case 'connectTimeoutMS': + serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); + break; + case 'socketTimeoutMS': + serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); + break; + case 'w': + dbOptions.w = parseInt(value, 10); + if(isNaN(dbOptions.w)) dbOptions.w = value; + break; + case 'authSource': + dbOptions.authSource = value; + break; + case 'gssapiServiceName': + dbOptions.gssapiServiceName = value; + break; + case 'authMechanism': + if(value == 'GSSAPI') { + // If no password provided decode only the principal + if(object.auth == null) { + var urlDecodeAuthPart = decodeURIComponent(authPart); + if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); + object.auth = {user: urlDecodeAuthPart, password: null}; + } else { + object.auth.user = decodeURIComponent(object.auth.user); + } + } else if(value == 'MONGODB-X509') { + object.auth = {user: decodeURIComponent(authPart)}; + } + + // Only support GSSAPI or MONGODB-CR for now + if(value != 'GSSAPI' + && value != 'MONGODB-X509' + && value != 'MONGODB-CR' + && value != 'DEFAULT' + && value != 'SCRAM-SHA-1' + && value != 'PLAIN') + throw new Error("only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); + + // Authentication mechanism + dbOptions.authMechanism = value; + break; + case 'authMechanismProperties': + // Split up into key, value pairs + var values = value.split(','); + var o = {}; + // For each value split into key, value + values.forEach(function(x) { + var v = x.split(':'); + o[v[0]] = v[1]; + }); + + // Set all authMechanismProperties + dbOptions.authMechanismProperties = o; + // Set the service name value + if(typeof o.SERVICE_NAME == 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; + break; + case 'wtimeoutMS': + dbOptions.wtimeout = parseInt(value, 10); + break; + case 'readPreference': + if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); + dbOptions.read_preference = value; + break; + case 'readPreferenceTags': + // Decode the value + value = decodeURIComponent(value); + // Contains the tag object + var tagObject = {}; + if(value == null || value == '') { + dbOptions.read_preference_tags.push(tagObject); + break; + } + + // Split up the tags + var tags = value.split(/\,/); + for(var i = 0; i < tags.length; i++) { + var parts = tags[i].trim().split(/\:/); + tagObject[parts[0]] = parts[1]; + } + + // Set the preferences tags + dbOptions.read_preference_tags.push(tagObject); + break; + default: + break; + } + }); + + // No tags: should be null (not []) + if(dbOptions.read_preference_tags.length === 0) { + dbOptions.read_preference_tags = null; + } + + // Validate if there are an invalid write concern combinations + if((dbOptions.w == -1 || dbOptions.w == 0) && ( + dbOptions.journal == true + || dbOptions.fsync == true + || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") + + // If no read preference set it to primary + if(!dbOptions.read_preference) dbOptions.read_preference = 'primary'; + + // Add servers to result + object.servers = servers; + // Returned parsed object + return object; +} diff --git a/util/demographicsImporter/node_modules/mongodb/lib/utils.js b/util/demographicsImporter/node_modules/mongodb/lib/utils.js new file mode 100644 index 0000000..cb20e67 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/lib/utils.js @@ -0,0 +1,234 @@ +"use strict"; + +var MongoError = require('mongodb-core').MongoError, + f = require('util').format; + +var shallowClone = function(obj) { + var copy = {}; + for(var name in obj) copy[name] = obj[name]; + return copy; +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +var formatSortValue = exports.formatSortValue = function(sortDirection) { + var value = ("" + sortDirection).toLowerCase(); + + switch (value) { + case 'ascending': + case 'asc': + case '1': + return 1; + case 'descending': + case 'desc': + case '-1': + return -1; + default: + throw new Error("Illegal sort clause, must be of the form " + + "[['field1', '(ascending|descending)'], " + + "['field2', '(ascending|descending)']]"); + } +}; + +var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { + var orderBy = {}; + if(sortValue == null) return null; + if (Array.isArray(sortValue)) { + if(sortValue.length === 0) { + return null; + } + + for(var i = 0; i < sortValue.length; i++) { + if(sortValue[i].constructor == String) { + orderBy[sortValue[i]] = 1; + } else { + orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); + } + } + } else if(sortValue != null && typeof sortValue == 'object') { + orderBy = sortValue; + } else if (typeof sortValue == 'string') { + orderBy[sortValue] = 1; + } else { + throw new Error("Illegal sort clause, must be of the form " + + "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); + } + + return orderBy; +}; + +var checkCollectionName = function checkCollectionName (collectionName) { + if('string' !== typeof collectionName) { + throw Error("collection name must be a String"); + } + + if(!collectionName || collectionName.indexOf('..') != -1) { + throw Error("collection names cannot be empty"); + } + + if(collectionName.indexOf('$') != -1 && + collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { + throw Error("collection names must not contain '$'"); + } + + if(collectionName.match(/^\.|\.$/) != null) { + throw Error("collection names must not start or end with '.'"); + } + + // Validate that we are not passing 0x00 in the colletion name + if(!!~collectionName.indexOf("\x00")) { + throw new Error("collection names cannot contain a null character"); + } +}; + +var handleCallback = function(callback, err, value1, value2) { + try { + if(callback == null) return; + if(value2) return callback(err, value1, value2); + return callback(err, value1); + } catch(err) { + process.nextTick(function() { throw err; }); + return false; + } + + return true; +} + +/** + * Wrap a Mongo error document in an Error instance + * @ignore + * @api private + */ +var toError = function(error) { + if (error instanceof Error) return error; + + var msg = error.err || error.errmsg || error.errMessage || error; + var e = MongoError.create({message: msg, driver:true}); + + // Get all object keys + var keys = typeof error == 'object' + ? Object.keys(error) + : []; + + for(var i = 0; i < keys.length; i++) { + e[keys[i]] = error[keys[i]]; + } + + return e; +} + +/** + * @ignore + */ +var normalizeHintField = function normalizeHintField(hint) { + var finalHint = null; + + if(typeof hint == 'string') { + finalHint = hint; + } else if(Array.isArray(hint)) { + finalHint = {}; + + hint.forEach(function(param) { + finalHint[param] = 1; + }); + } else if(hint != null && typeof hint == 'object') { + finalHint = {}; + for (var name in hint) { + finalHint[name] = hint[name]; + } + } + + return finalHint; +}; + +/** + * Create index name based on field spec + * + * @ignore + * @api private + */ +var parseIndexOptions = function(fieldOrSpec) { + var fieldHash = {}; + var indexes = []; + var keys; + + // Get all the fields accordingly + if('string' == typeof fieldOrSpec) { + // 'type' + indexes.push(fieldOrSpec + '_' + 1); + fieldHash[fieldOrSpec] = 1; + } else if(Array.isArray(fieldOrSpec)) { + fieldOrSpec.forEach(function(f) { + if('string' == typeof f) { + // [{location:'2d'}, 'type'] + indexes.push(f + '_' + 1); + fieldHash[f] = 1; + } else if(Array.isArray(f)) { + // [['location', '2d'],['type', 1]] + indexes.push(f[0] + '_' + (f[1] || 1)); + fieldHash[f[0]] = f[1] || 1; + } else if(isObject(f)) { + // [{location:'2d'}, {type:1}] + keys = Object.keys(f); + keys.forEach(function(k) { + indexes.push(k + '_' + f[k]); + fieldHash[k] = f[k]; + }); + } else { + // undefined (ignore) + } + }); + } else if(isObject(fieldOrSpec)) { + // {location:'2d', type:1} + keys = Object.keys(fieldOrSpec); + keys.forEach(function(key) { + indexes.push(key + '_' + fieldOrSpec[key]); + fieldHash[key] = fieldOrSpec[key]; + }); + } + + return { + name: indexes.join("_"), keys: keys, fieldHash: fieldHash + } +} + +var isObject = exports.isObject = function (arg) { + return '[object Object]' == toString.call(arg) +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +var decorateCommand = function(command, options, exclude) { + for(var name in options) { + if(exclude[name] == null) command[name] = options[name]; + } + + return command; +} + +exports.shallowClone = shallowClone; +exports.getSingleProperty = getSingleProperty; +exports.checkCollectionName = checkCollectionName; +exports.toError = toError; +exports.formattedOrderClause = formattedOrderClause; +exports.parseIndexOptions = parseIndexOptions; +exports.normalizeHintField = normalizeHintField; +exports.handleCallback = handleCallback; +exports.decorateCommand = decorateCommand; +exports.isObject = isObject; +exports.debugOptions = debugOptions; diff --git a/util/demographicsImporter/node_modules/mongodb/load.js b/util/demographicsImporter/node_modules/mongodb/load.js new file mode 100644 index 0000000..01b570e --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/load.js @@ -0,0 +1,32 @@ +var MongoClient = require('./').MongoClient; + +MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { + var col = db.collection('test'); + col.ensureIndex({dt:-1}, function() { + var docs = []; + for(var i = 0; i < 100; i++) { + docs.push({a:i, dt:i, ot:i}); + } + console.log("------------------------------- 0") + + col.insertMany(docs, function() { + // Start firing finds + + for(var i = 0; i < 100; i++) { + setInterval(function() { + col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) { + console.log("-------------------------------- 1") + }); + }, 10) + } + + // while(true) { + // + // // console.log("------------------------------- 1") + // col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) { + // console.log("-------------------------------- 1") + // }); + // } + }); + }); +}); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md new file mode 100644 index 0000000..e06b496 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md @@ -0,0 +1,9 @@ +# Master + +# 2.0.0 + +* re-sync with RSVP. Many large performance improvements and bugfixes. + +# 1.0.0 + +* first subset of RSVP diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE new file mode 100644 index 0000000..954ec59 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/README.md new file mode 100644 index 0000000..ca8678e --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/README.md @@ -0,0 +1,61 @@ +# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) + +This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js), if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). + +For API details and how to use promises, see the JavaScript Promises HTML5Rocks article. + +## Downloads + +* [es6-promise](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.js) +* [es6-promise-min](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise-min.js) + +## Node.js + +To install: + +```sh +npm install es6-promise +``` + +To use: + +```js +var Promise = require('es6-promise').Promise; +``` + +## Usage in IE<9 + +`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example. + +However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production: + +```js +promise['catch'](function(err) { + // ... +}); +``` + +Or use `.then` instead: + +```js +promise.then(undefined, function(err) { + // ... +}); +``` + +## Auto-polyfill + +To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: + +```js +require('es6-promise').polyfill(); +``` + +Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. + +## Building & Testing + +* `npm run build` to build +* `npm test` to run tests +* `npm start` to run a build watcher, and webserver to test +* `npm run test:server` for a testem test runner and watching builder diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js new file mode 100644 index 0000000..308f3ac --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js @@ -0,0 +1,957 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 2.1.1 + */ + +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + function lib$es6$promise$asap$$asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + lib$es6$promise$asap$$scheduleFlush(); + } + } + + var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + var nextTick = process.nextTick; + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // setImmediate should be used instead instead + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function() { + nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertex() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFullfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$default(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { + return lib$es6$promise$utils$$isArray(input); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; + + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + var lib$es6$promise$promise$$counter = 0; + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$default(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js new file mode 100644 index 0000000..0552e12 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js @@ -0,0 +1,9 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE + * @version 2.1.1 + */ + +(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;function lib$es6$promise$asap$$asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){lib$es6$promise$asap$$scheduleFlush()}}var lib$es6$promise$asap$$default=lib$es6$promise$asap$$asap;var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){var nextTick=process.nextTick;var version=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);if(Array.isArray(version)&&version[1]==="0"&&version[2]==="10"){nextTick=setImmediate}return function(){nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i +// +// 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. + +// when used in node, this will actually load the util module we depend on +// versus loading the builtin util module as happens otherwise +// this is a bug in node module loading as far as I am concerned +var util = require('util/'); + +var pSlice = Array.prototype.slice; +var hasOwn = Object.prototype.hasOwnProperty; + +// 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 = module.exports = ok; + +// 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.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail; + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } + else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = stackStartFunction.name; + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } +}; + +// assert.AssertionError instanceof Error +util.inherits(assert.AssertionError, Error); + +function replacer(key, value) { + if (util.isUndefined(value)) { + return '' + value; + } + if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { + return value.toString(); + } + if (util.isFunction(value) || util.isRegExp(value)) { + return value.toString(); + } + return value; +} + +function truncate(s, n) { + if (util.isString(s)) { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } +} + +function getMessage(self) { + return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + + self.operator + ' ' + + truncate(JSON.stringify(self.expected, replacer), 128); +} + +// 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);. + +function ok(value, message) { + if (!value) fail(value, true, message, '==', assert.ok); +} +assert.ok = 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; + + } else if (util.isBuffer(actual) && util.isBuffer(expected)) { + if (actual.length != expected.length) return false; + + for (var i = 0; i < actual.length; i++) { + if (actual[i] !== expected[i]) return false; + } + + 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 (util.isDate(actual) && util.isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (util.isRegExp(actual) && util.isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if (!util.isObject(actual) && !util.isObject(expected)) { + return actual == expected; + + // 7.5 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 isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; +} + +function objEquiv(a, b) { + if (util.isNullOrUndefined(a) || util.isNullOrUndefined(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 = objectKeys(a), + kb = objectKeys(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 expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } else if (actual instanceof expected) { + return true; + } else if (expected.call({}, actual) === true) { + return true; + } + + return false; +} + +function _throws(shouldThrow, block, expected, message) { + var actual; + + if (util.isString(expected)) { + message = expected; + expected = null; + } + + try { + block(); + } catch (e) { + actual = e; + } + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail(actual, expected, 'Missing expected exception' + message); + } + + if (!shouldThrow && expectedException(actual, expected)) { + fail(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } +} + +// 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*/message) { + _throws.apply(this, [false].concat(pSlice.call(arguments))); +}; + +assert.ifError = function(err) { if (err) {throw err;}}; + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; +}; + +},{"util/":6}],3:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],4:[function(require,module,exports){ +// shim for using process in browser + +var process = module.exports = {}; + +process.nextTick = (function () { + var canSetImmediate = typeof window !== 'undefined' + && window.setImmediate; + var canMutationObserver = typeof window !== 'undefined' + && window.MutationObserver; + var canPost = typeof window !== 'undefined' + && window.postMessage && window.addEventListener + ; + + if (canSetImmediate) { + return function (f) { return window.setImmediate(f) }; + } + + var queue = []; + + if (canMutationObserver) { + var hiddenDiv = document.createElement("div"); + var observer = new MutationObserver(function () { + var queueList = queue.slice(); + queue.length = 0; + queueList.forEach(function (fn) { + fn(); + }); + }); + + observer.observe(hiddenDiv, { attributes: true }); + + return function nextTick(fn) { + if (!queue.length) { + hiddenDiv.setAttribute('yes', 'no'); + } + queue.push(fn); + }; + } + + if (canPost) { + window.addEventListener('message', function (ev) { + var source = ev.source; + if ((source === window || source === null) && ev.data === 'process-tick') { + ev.stopPropagation(); + if (queue.length > 0) { + var fn = queue.shift(); + fn(); + } + } + }, true); + + return function nextTick(fn) { + queue.push(fn); + window.postMessage('process-tick', '*'); + }; + } + + return function nextTick(fn) { + setTimeout(fn, 0); + }; +})(); + +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +// TODO(shtylman) +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; + +},{}],5:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],6:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":5,"_process":4,"inherits":3}],7:[function(require,module,exports){ +require("./tests/2.1.2"); +require("./tests/2.1.3"); +require("./tests/2.2.1"); +require("./tests/2.2.2"); +require("./tests/2.2.3"); +require("./tests/2.2.4"); +require("./tests/2.2.5"); +require("./tests/2.2.6"); +require("./tests/2.2.7"); +require("./tests/2.3.1"); +require("./tests/2.3.2"); +require("./tests/2.3.3"); +require("./tests/2.3.4"); + +},{"./tests/2.1.2":8,"./tests/2.1.3":9,"./tests/2.2.1":10,"./tests/2.2.2":11,"./tests/2.2.3":12,"./tests/2.2.4":13,"./tests/2.2.5":14,"./tests/2.2.6":15,"./tests/2.2.7":16,"./tests/2.3.1":17,"./tests/2.3.2":18,"./tests/2.3.3":19,"./tests/2.3.4":20}],8:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; + +var adapter = global.adapter; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.1.2.1: When fulfilled, a promise: must not transition to any other state.", function () { + testFulfilled(dummy, function (promise, done) { + var onFulfilledCalled = false; + + promise.then(function onFulfilled() { + onFulfilledCalled = true; + }, function onRejected() { + assert.strictEqual(onFulfilledCalled, false); + done(); + }); + + setTimeout(done, 100); + }); + + specify("trying to fulfill then immediately reject", function (done) { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }, function onRejected() { + assert.strictEqual(onFulfilledCalled, false); + done(); + }); + + d.resolve(dummy); + d.reject(dummy); + setTimeout(done, 100); + }); + + specify("trying to fulfill then reject, delayed", function (done) { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }, function onRejected() { + assert.strictEqual(onFulfilledCalled, false); + done(); + }); + + setTimeout(function () { + d.resolve(dummy); + d.reject(dummy); + }, 50); + setTimeout(done, 100); + }); + + specify("trying to fulfill immediately then reject delayed", function (done) { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }, function onRejected() { + assert.strictEqual(onFulfilledCalled, false); + done(); + }); + + d.resolve(dummy); + setTimeout(function () { + d.reject(dummy); + }, 50); + setTimeout(done, 100); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],9:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testRejected = require("./helpers/testThreeCases").testRejected; + +var adapter = global.adapter; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.1.3.1: When rejected, a promise: must not transition to any other state.", function () { + testRejected(dummy, function (promise, done) { + var onRejectedCalled = false; + + promise.then(function onFulfilled() { + assert.strictEqual(onRejectedCalled, false); + done(); + }, function onRejected() { + onRejectedCalled = true; + }); + + setTimeout(done, 100); + }); + + specify("trying to reject then immediately fulfill", function (done) { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(function onFulfilled() { + assert.strictEqual(onRejectedCalled, false); + done(); + }, function onRejected() { + onRejectedCalled = true; + }); + + d.reject(dummy); + d.resolve(dummy); + setTimeout(done, 100); + }); + + specify("trying to reject then fulfill, delayed", function (done) { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(function onFulfilled() { + assert.strictEqual(onRejectedCalled, false); + done(); + }, function onRejected() { + onRejectedCalled = true; + }); + + setTimeout(function () { + d.reject(dummy); + d.resolve(dummy); + }, 50); + setTimeout(done, 100); + }); + + specify("trying to reject immediately then fulfill delayed", function (done) { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(function onFulfilled() { + assert.strictEqual(onRejectedCalled, false); + done(); + }, function onRejected() { + onRejectedCalled = true; + }); + + d.reject(dummy); + setTimeout(function () { + d.resolve(dummy); + }, 50); + setTimeout(done, 100); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],10:[function(require,module,exports){ +(function (global){ +"use strict"; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.2.1: Both `onFulfilled` and `onRejected` are optional arguments.", function () { + describe("2.2.1.1: If `onFulfilled` is not a function, it must be ignored.", function () { + describe("applied to a directly-rejected promise", function () { + function testNonFunction(nonFunction, stringRepresentation) { + specify("`onFulfilled` is " + stringRepresentation, function (done) { + rejected(dummy).then(nonFunction, function () { + done(); + }); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + }); + + describe("applied to a promise rejected and then chained off of", function () { + function testNonFunction(nonFunction, stringRepresentation) { + specify("`onFulfilled` is " + stringRepresentation, function (done) { + rejected(dummy).then(function () { }, undefined).then(nonFunction, function () { + done(); + }); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + }); + }); + + describe("2.2.1.2: If `onRejected` is not a function, it must be ignored.", function () { + describe("applied to a directly-fulfilled promise", function () { + function testNonFunction(nonFunction, stringRepresentation) { + specify("`onRejected` is " + stringRepresentation, function (done) { + resolved(dummy).then(function () { + done(); + }, nonFunction); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + }); + + describe("applied to a promise fulfilled and then chained off of", function () { + function testNonFunction(nonFunction, stringRepresentation) { + specify("`onFulfilled` is " + stringRepresentation, function (done) { + resolved(dummy).then(undefined, function () { }).then(function () { + done(); + }, nonFunction); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],11:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality + +describe("2.2.2: If `onFulfilled` is a function,", function () { + describe("2.2.2.1: it must be called after `promise` is fulfilled, with `promise`’s fulfillment value as its " + + "first argument.", function () { + testFulfilled(sentinel, function (promise, done) { + promise.then(function onFulfilled(value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("2.2.2.2: it must not be called before `promise` is fulfilled", function () { + specify("fulfilled after a delay", function (done) { + var d = deferred(); + var isFulfilled = false; + + d.promise.then(function onFulfilled() { + assert.strictEqual(isFulfilled, true); + done(); + }); + + setTimeout(function () { + d.resolve(dummy); + isFulfilled = true; + }, 50); + }); + + specify("never fulfilled", function (done) { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + done(); + }); + + setTimeout(function () { + assert.strictEqual(onFulfilledCalled, false); + done(); + }, 150); + }); + }); + + describe("2.2.2.3: it must not be called more than once.", function () { + specify("already-fulfilled", function (done) { + var timesCalled = 0; + + resolved(dummy).then(function onFulfilled() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + }); + + specify("trying to fulfill a pending promise more than once, immediately", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + d.resolve(dummy); + d.resolve(dummy); + }); + + specify("trying to fulfill a pending promise more than once, delayed", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + setTimeout(function () { + d.resolve(dummy); + d.resolve(dummy); + }, 50); + }); + + specify("trying to fulfill a pending promise more than once, immediately then delayed", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + d.resolve(dummy); + setTimeout(function () { + d.resolve(dummy); + }, 50); + }); + + specify("when multiple `then` calls are made, spaced apart in time", function (done) { + var d = deferred(); + var timesCalled = [0, 0, 0]; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[0], 1); + }); + + setTimeout(function () { + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[1], 1); + }); + }, 50); + + setTimeout(function () { + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[2], 1); + done(); + }); + }, 100); + + setTimeout(function () { + d.resolve(dummy); + }, 150); + }); + + specify("when `then` is interleaved with fulfillment", function (done) { + var d = deferred(); + var timesCalled = [0, 0]; + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[0], 1); + }); + + d.resolve(dummy); + + d.promise.then(function onFulfilled() { + assert.strictEqual(++timesCalled[1], 1); + done(); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],12:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testRejected = require("./helpers/testThreeCases").testRejected; + +var adapter = global.adapter; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality + +describe("2.2.3: If `onRejected` is a function,", function () { + describe("2.2.3.1: it must be called after `promise` is rejected, with `promise`’s rejection reason as its " + + "first argument.", function () { + testRejected(sentinel, function (promise, done) { + promise.then(null, function onRejected(reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("2.2.3.2: it must not be called before `promise` is rejected", function () { + specify("rejected after a delay", function (done) { + var d = deferred(); + var isRejected = false; + + d.promise.then(null, function onRejected() { + assert.strictEqual(isRejected, true); + done(); + }); + + setTimeout(function () { + d.reject(dummy); + isRejected = true; + }, 50); + }); + + specify("never rejected", function (done) { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(null, function onRejected() { + onRejectedCalled = true; + done(); + }); + + setTimeout(function () { + assert.strictEqual(onRejectedCalled, false); + done(); + }, 150); + }); + }); + + describe("2.2.3.3: it must not be called more than once.", function () { + specify("already-rejected", function (done) { + var timesCalled = 0; + + rejected(dummy).then(null, function onRejected() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + }); + + specify("trying to reject a pending promise more than once, immediately", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + d.reject(dummy); + d.reject(dummy); + }); + + specify("trying to reject a pending promise more than once, delayed", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + setTimeout(function () { + d.reject(dummy); + d.reject(dummy); + }, 50); + }); + + specify("trying to reject a pending promise more than once, immediately then delayed", function (done) { + var d = deferred(); + var timesCalled = 0; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled, 1); + done(); + }); + + d.reject(dummy); + setTimeout(function () { + d.reject(dummy); + }, 50); + }); + + specify("when multiple `then` calls are made, spaced apart in time", function (done) { + var d = deferred(); + var timesCalled = [0, 0, 0]; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[0], 1); + }); + + setTimeout(function () { + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[1], 1); + }); + }, 50); + + setTimeout(function () { + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[2], 1); + done(); + }); + }, 100); + + setTimeout(function () { + d.reject(dummy); + }, 150); + }); + + specify("when `then` is interleaved with rejection", function (done) { + var d = deferred(); + var timesCalled = [0, 0]; + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[0], 1); + }); + + d.reject(dummy); + + d.promise.then(null, function onRejected() { + assert.strictEqual(++timesCalled[1], 1); + done(); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],13:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; +var testRejected = require("./helpers/testThreeCases").testRejected; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.2.4: `onFulfilled` or `onRejected` must not be called until the execution context stack contains only " + + "platform code.", function () { + describe("`then` returns before the promise becomes fulfilled or rejected", function () { + testFulfilled(dummy, function (promise, done) { + var thenHasReturned = false; + + promise.then(function onFulfilled() { + assert.strictEqual(thenHasReturned, true); + done(); + }); + + thenHasReturned = true; + }); + testRejected(dummy, function (promise, done) { + var thenHasReturned = false; + + promise.then(null, function onRejected() { + assert.strictEqual(thenHasReturned, true); + done(); + }); + + thenHasReturned = true; + }); + }); + + describe("Clean-stack execution ordering tests (fulfillment case)", function () { + specify("when `onFulfilled` is added immediately before the promise is fulfilled", + function () { + var d = deferred(); + var onFulfilledCalled = false; + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }); + + d.resolve(dummy); + + assert.strictEqual(onFulfilledCalled, false); + }); + + specify("when `onFulfilled` is added immediately after the promise is fulfilled", + function () { + var d = deferred(); + var onFulfilledCalled = false; + + d.resolve(dummy); + + d.promise.then(function onFulfilled() { + onFulfilledCalled = true; + }); + + assert.strictEqual(onFulfilledCalled, false); + }); + + specify("when one `onFulfilled` is added inside another `onFulfilled`", function (done) { + var promise = resolved(); + var firstOnFulfilledFinished = false; + + promise.then(function () { + promise.then(function () { + assert.strictEqual(firstOnFulfilledFinished, true); + done(); + }); + firstOnFulfilledFinished = true; + }); + }); + + specify("when `onFulfilled` is added inside an `onRejected`", function (done) { + var promise = rejected(); + var promise2 = resolved(); + var firstOnRejectedFinished = false; + + promise.then(null, function () { + promise2.then(function () { + assert.strictEqual(firstOnRejectedFinished, true); + done(); + }); + firstOnRejectedFinished = true; + }); + }); + + specify("when the promise is fulfilled asynchronously", function (done) { + var d = deferred(); + var firstStackFinished = false; + + setTimeout(function () { + d.resolve(dummy); + firstStackFinished = true; + }, 0); + + d.promise.then(function () { + assert.strictEqual(firstStackFinished, true); + done(); + }); + }); + }); + + describe("Clean-stack execution ordering tests (rejection case)", function () { + specify("when `onRejected` is added immediately before the promise is rejected", + function () { + var d = deferred(); + var onRejectedCalled = false; + + d.promise.then(null, function onRejected() { + onRejectedCalled = true; + }); + + d.reject(dummy); + + assert.strictEqual(onRejectedCalled, false); + }); + + specify("when `onRejected` is added immediately after the promise is rejected", + function () { + var d = deferred(); + var onRejectedCalled = false; + + d.reject(dummy); + + d.promise.then(null, function onRejected() { + onRejectedCalled = true; + }); + + assert.strictEqual(onRejectedCalled, false); + }); + + specify("when `onRejected` is added inside an `onFulfilled`", function (done) { + var promise = resolved(); + var promise2 = rejected(); + var firstOnFulfilledFinished = false; + + promise.then(function () { + promise2.then(null, function () { + assert.strictEqual(firstOnFulfilledFinished, true); + done(); + }); + firstOnFulfilledFinished = true; + }); + }); + + specify("when one `onRejected` is added inside another `onRejected`", function (done) { + var promise = rejected(); + var firstOnRejectedFinished = false; + + promise.then(null, function () { + promise.then(null, function () { + assert.strictEqual(firstOnRejectedFinished, true); + done(); + }); + firstOnRejectedFinished = true; + }); + }); + + specify("when the promise is rejected asynchronously", function (done) { + var d = deferred(); + var firstStackFinished = false; + + setTimeout(function () { + d.reject(dummy); + firstStackFinished = true; + }, 0); + + d.promise.then(null, function () { + assert.strictEqual(firstStackFinished, true); + done(); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/testThreeCases":22,"assert":2}],14:[function(require,module,exports){ +(function (global){ +/*jshint strict: false */ + +var assert = require("assert"); + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +function impimentsUseStrictCorrectly() { + "use strict"; + function test() { + /*jshint validthis:true */ + return !this; + } + return test(); +} +describe("2.2.5 `onFulfilled` and `onRejected` must be called as functions (i.e. with no `this` value).", function () { + if (impimentsUseStrictCorrectly()) { + describe("strict mode", function () { + specify("fulfilled", function (done) { + resolved(dummy).then(function onFulfilled() { + "use strict"; + + assert.strictEqual(this, undefined); + done(); + }); + }); + + specify("rejected", function (done) { + rejected(dummy).then(null, function onRejected() { + "use strict"; + + assert.strictEqual(this, undefined); + done(); + }); + }); + }); + } + describe("sloppy mode", function () { + specify("fulfilled", function (done) { + resolved(dummy).then(function onFulfilled() { + assert.strictEqual(this, global); + done(); + }); + }); + + specify("rejected", function (done) { + rejected(dummy).then(null, function onRejected() { + assert.strictEqual(this, global); + done(); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"assert":2}],15:[function(require,module,exports){ +"use strict"; + +var assert = require("assert"); +var sinon = require("sinon"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; +var testRejected = require("./helpers/testThreeCases").testRejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var other = { other: "other" }; // a value we don't want to be strict equal to +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality +var sentinel2 = { sentinel2: "sentinel2" }; +var sentinel3 = { sentinel3: "sentinel3" }; + +function callbackAggregator(times, ultimateCallback) { + var soFar = 0; + return function () { + if (++soFar === times) { + ultimateCallback(); + } + }; +} + +describe("2.2.6: `then` may be called multiple times on the same promise.", function () { + describe("2.2.6.1: If/when `promise` is fulfilled, all respective `onFulfilled` callbacks must execute in the " + + "order of their originating calls to `then`.", function () { + describe("multiple boring fulfillment handlers", function () { + testFulfilled(sentinel, function (promise, done) { + var handler1 = sinon.stub().returns(other); + var handler2 = sinon.stub().returns(other); + var handler3 = sinon.stub().returns(other); + + var spy = sinon.spy(); + promise.then(handler1, spy); + promise.then(handler2, spy); + promise.then(handler3, spy); + + promise.then(function (value) { + assert.strictEqual(value, sentinel); + + sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); + sinon.assert.notCalled(spy); + + done(); + }); + }); + }); + + describe("multiple fulfillment handlers, one of which throws", function () { + testFulfilled(sentinel, function (promise, done) { + var handler1 = sinon.stub().returns(other); + var handler2 = sinon.stub().throws(other); + var handler3 = sinon.stub().returns(other); + + var spy = sinon.spy(); + promise.then(handler1, spy); + promise.then(handler2, spy); + promise.then(handler3, spy); + + promise.then(function (value) { + assert.strictEqual(value, sentinel); + + sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); + sinon.assert.notCalled(spy); + + done(); + }); + }); + }); + + describe("results in multiple branching chains with their own fulfillment values", function () { + testFulfilled(dummy, function (promise, done) { + var semiDone = callbackAggregator(3, done); + + promise.then(function () { + return sentinel; + }).then(function (value) { + assert.strictEqual(value, sentinel); + semiDone(); + }); + + promise.then(function () { + throw sentinel2; + }).then(null, function (reason) { + assert.strictEqual(reason, sentinel2); + semiDone(); + }); + + promise.then(function () { + return sentinel3; + }).then(function (value) { + assert.strictEqual(value, sentinel3); + semiDone(); + }); + }); + }); + + describe("`onFulfilled` handlers are called in the original order", function () { + testFulfilled(dummy, function (promise, done) { + var handler1 = sinon.spy(function handler1() {}); + var handler2 = sinon.spy(function handler2() {}); + var handler3 = sinon.spy(function handler3() {}); + + promise.then(handler1); + promise.then(handler2); + promise.then(handler3); + + promise.then(function () { + sinon.assert.callOrder(handler1, handler2, handler3); + done(); + }); + }); + + describe("even when one handler is added inside another handler", function () { + testFulfilled(dummy, function (promise, done) { + var handler1 = sinon.spy(function handler1() {}); + var handler2 = sinon.spy(function handler2() {}); + var handler3 = sinon.spy(function handler3() {}); + + promise.then(function () { + handler1(); + promise.then(handler3); + }); + promise.then(handler2); + + promise.then(function () { + // Give implementations a bit of extra time to flush their internal queue, if necessary. + setTimeout(function () { + sinon.assert.callOrder(handler1, handler2, handler3); + done(); + }, 15); + }); + }); + }); + }); + }); + + describe("2.2.6.2: If/when `promise` is rejected, all respective `onRejected` callbacks must execute in the " + + "order of their originating calls to `then`.", function () { + describe("multiple boring rejection handlers", function () { + testRejected(sentinel, function (promise, done) { + var handler1 = sinon.stub().returns(other); + var handler2 = sinon.stub().returns(other); + var handler3 = sinon.stub().returns(other); + + var spy = sinon.spy(); + promise.then(spy, handler1); + promise.then(spy, handler2); + promise.then(spy, handler3); + + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + + sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); + sinon.assert.notCalled(spy); + + done(); + }); + }); + }); + + describe("multiple rejection handlers, one of which throws", function () { + testRejected(sentinel, function (promise, done) { + var handler1 = sinon.stub().returns(other); + var handler2 = sinon.stub().throws(other); + var handler3 = sinon.stub().returns(other); + + var spy = sinon.spy(); + promise.then(spy, handler1); + promise.then(spy, handler2); + promise.then(spy, handler3); + + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + + sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); + sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); + sinon.assert.notCalled(spy); + + done(); + }); + }); + }); + + describe("results in multiple branching chains with their own fulfillment values", function () { + testRejected(sentinel, function (promise, done) { + var semiDone = callbackAggregator(3, done); + + promise.then(null, function () { + return sentinel; + }).then(function (value) { + assert.strictEqual(value, sentinel); + semiDone(); + }); + + promise.then(null, function () { + throw sentinel2; + }).then(null, function (reason) { + assert.strictEqual(reason, sentinel2); + semiDone(); + }); + + promise.then(null, function () { + return sentinel3; + }).then(function (value) { + assert.strictEqual(value, sentinel3); + semiDone(); + }); + }); + }); + + describe("`onRejected` handlers are called in the original order", function () { + testRejected(dummy, function (promise, done) { + var handler1 = sinon.spy(function handler1() {}); + var handler2 = sinon.spy(function handler2() {}); + var handler3 = sinon.spy(function handler3() {}); + + promise.then(null, handler1); + promise.then(null, handler2); + promise.then(null, handler3); + + promise.then(null, function () { + sinon.assert.callOrder(handler1, handler2, handler3); + done(); + }); + }); + + describe("even when one handler is added inside another handler", function () { + testRejected(dummy, function (promise, done) { + var handler1 = sinon.spy(function handler1() {}); + var handler2 = sinon.spy(function handler2() {}); + var handler3 = sinon.spy(function handler3() {}); + + promise.then(null, function () { + handler1(); + promise.then(null, handler3); + }); + promise.then(null, handler2); + + promise.then(null, function () { + // Give implementations a bit of extra time to flush their internal queue, if necessary. + setTimeout(function () { + sinon.assert.callOrder(handler1, handler2, handler3); + done(); + }, 15); + }); + }); + }); + }); + }); +}); + +},{"./helpers/testThreeCases":22,"assert":2,"sinon":24}],16:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; +var testRejected = require("./helpers/testThreeCases").testRejected; +var reasons = require("./helpers/reasons"); + +var adapter = global.adapter; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality +var other = { other: "other" }; // a value we don't want to be strict equal to + +describe("2.2.7: `then` must return a promise: `promise2 = promise1.then(onFulfilled, onRejected)`", function () { + specify("is a promise", function () { + var promise1 = deferred().promise; + var promise2 = promise1.then(); + + assert(typeof promise2 === "object" || typeof promise2 === "function"); + assert.notStrictEqual(promise2, null); + assert.strictEqual(typeof promise2.then, "function"); + }); + + describe("2.2.7.1: If either `onFulfilled` or `onRejected` returns a value `x`, run the Promise Resolution " + + "Procedure `[[Resolve]](promise2, x)`", function () { + specify("see separate 3.3 tests", function () { }); + }); + + describe("2.2.7.2: If either `onFulfilled` or `onRejected` throws an exception `e`, `promise2` must be rejected " + + "with `e` as the reason.", function () { + function testReason(expectedReason, stringRepresentation) { + describe("The reason is " + stringRepresentation, function () { + testFulfilled(dummy, function (promise1, done) { + var promise2 = promise1.then(function onFulfilled() { + throw expectedReason; + }); + + promise2.then(null, function onPromise2Rejected(actualReason) { + assert.strictEqual(actualReason, expectedReason); + done(); + }); + }); + testRejected(dummy, function (promise1, done) { + var promise2 = promise1.then(null, function onRejected() { + throw expectedReason; + }); + + promise2.then(null, function onPromise2Rejected(actualReason) { + assert.strictEqual(actualReason, expectedReason); + done(); + }); + }); + }); + } + + Object.keys(reasons).forEach(function (stringRepresentation) { + testReason(reasons[stringRepresentation], stringRepresentation); + }); + }); + + describe("2.2.7.3: If `onFulfilled` is not a function and `promise1` is fulfilled, `promise2` must be fulfilled " + + "with the same value.", function () { + + function testNonFunction(nonFunction, stringRepresentation) { + describe("`onFulfilled` is " + stringRepresentation, function () { + testFulfilled(sentinel, function (promise1, done) { + var promise2 = promise1.then(nonFunction); + + promise2.then(function onPromise2Fulfilled(value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + testNonFunction([function () { return other; }], "an array containing a function"); + }); + + describe("2.2.7.4: If `onRejected` is not a function and `promise1` is rejected, `promise2` must be rejected " + + "with the same reason.", function () { + + function testNonFunction(nonFunction, stringRepresentation) { + describe("`onRejected` is " + stringRepresentation, function () { + testRejected(sentinel, function (promise1, done) { + var promise2 = promise1.then(null, nonFunction); + + promise2.then(null, function onPromise2Rejected(reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + } + + testNonFunction(undefined, "`undefined`"); + testNonFunction(null, "`null`"); + testNonFunction(false, "`false`"); + testNonFunction(5, "`5`"); + testNonFunction({}, "an object"); + testNonFunction([function () { return other; }], "an array containing a function"); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/reasons":21,"./helpers/testThreeCases":22,"assert":2}],17:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.3.1: If `promise` and `x` refer to the same object, reject `promise` with a `TypeError' as the reason.", + function () { + specify("via return from a fulfilled promise", function (done) { + var promise = resolved(dummy).then(function () { + return promise; + }); + + promise.then(null, function (reason) { + assert(reason instanceof TypeError); + done(); + }); + }); + + specify("via return from a rejected promise", function (done) { + var promise = rejected(dummy).then(null, function () { + return promise; + }); + + promise.then(null, function (reason) { + assert(reason instanceof TypeError); + done(); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"assert":2}],18:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality + +function testPromiseResolution(xFactory, test) { + specify("via return from a fulfilled promise", function (done) { + var promise = resolved(dummy).then(function onBasePromiseFulfilled() { + return xFactory(); + }); + + test(promise, done); + }); + + specify("via return from a rejected promise", function (done) { + var promise = rejected(dummy).then(null, function onBasePromiseRejected() { + return xFactory(); + }); + + test(promise, done); + }); +} + +describe("2.3.2: If `x` is a promise, adopt its state", function () { + describe("2.3.2.1: If `x` is pending, `promise` must remain pending until `x` is fulfilled or rejected.", + function () { + function xFactory() { + return deferred().promise; + } + + testPromiseResolution(xFactory, function (promise, done) { + var wasFulfilled = false; + var wasRejected = false; + + promise.then( + function onPromiseFulfilled() { + wasFulfilled = true; + }, + function onPromiseRejected() { + wasRejected = true; + } + ); + + setTimeout(function () { + assert.strictEqual(wasFulfilled, false); + assert.strictEqual(wasRejected, false); + done(); + }, 100); + }); + }); + + describe("2.3.2.2: If/when `x` is fulfilled, fulfill `promise` with the same value.", function () { + describe("`x` is already-fulfilled", function () { + function xFactory() { + return resolved(sentinel); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function onPromiseFulfilled(value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("`x` is eventually-fulfilled", function () { + var d = null; + + function xFactory() { + d = deferred(); + setTimeout(function () { + d.resolve(sentinel); + }, 50); + return d.promise; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function onPromiseFulfilled(value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + }); + + describe("2.3.2.3: If/when `x` is rejected, reject `promise` with the same reason.", function () { + describe("`x` is already-rejected", function () { + function xFactory() { + return rejected(sentinel); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function onPromiseRejected(reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`x` is eventually-rejected", function () { + var d = null; + + function xFactory() { + d = deferred(); + setTimeout(function () { + d.reject(sentinel); + }, 50); + return d.promise; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function onPromiseRejected(reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"assert":2}],19:[function(require,module,exports){ +(function (global){ +"use strict"; + +var assert = require("assert"); +var thenables = require("./helpers/thenables"); +var reasons = require("./helpers/reasons"); + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it +var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality +var other = { other: "other" }; // a value we don't want to be strict equal to +var sentinelArray = [sentinel]; // a sentinel fulfillment value to test when we need an array + +function testPromiseResolution(xFactory, test) { + specify("via return from a fulfilled promise", function (done) { + var promise = resolved(dummy).then(function onBasePromiseFulfilled() { + return xFactory(); + }); + + test(promise, done); + }); + + specify("via return from a rejected promise", function (done) { + var promise = rejected(dummy).then(null, function onBasePromiseRejected() { + return xFactory(); + }); + + test(promise, done); + }); +} + +function testCallingResolvePromise(yFactory, stringRepresentation, test) { + describe("`y` is " + stringRepresentation, function () { + describe("`then` calls `resolvePromise` synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + resolvePromise(yFactory()); + } + }; + } + + testPromiseResolution(xFactory, test); + }); + + describe("`then` calls `resolvePromise` asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + setTimeout(function () { + resolvePromise(yFactory()); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, test); + }); + }); +} + +function testCallingRejectPromise(r, stringRepresentation, test) { + describe("`r` is " + stringRepresentation, function () { + describe("`then` calls `rejectPromise` synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(r); + } + }; + } + + testPromiseResolution(xFactory, test); + }); + + describe("`then` calls `rejectPromise` asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + rejectPromise(r); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, test); + }); + }); +} + +function testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, fulfillmentValue) { + testCallingResolvePromise(yFactory, stringRepresentation, function (promise, done) { + promise.then(function onPromiseFulfilled(value) { + assert.strictEqual(value, fulfillmentValue); + done(); + }); + }); +} + +function testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, rejectionReason) { + testCallingResolvePromise(yFactory, stringRepresentation, function (promise, done) { + promise.then(null, function onPromiseRejected(reason) { + assert.strictEqual(reason, rejectionReason); + done(); + }); + }); +} + +function testCallingRejectPromiseRejectsWith(reason, stringRepresentation) { + testCallingRejectPromise(reason, stringRepresentation, function (promise, done) { + promise.then(null, function onPromiseRejected(rejectionReason) { + assert.strictEqual(rejectionReason, reason); + done(); + }); + }); +} + +describe("2.3.3: Otherwise, if `x` is an object or function,", function () { + describe("2.3.3.1: Let `then` be `x.then`", function () { + describe("`x` is an object with null prototype", function () { + var numberOfTimesThenWasRetrieved = null; + + beforeEach(function () { + numberOfTimesThenWasRetrieved = 0; + }); + + function xFactory() { + return Object.create(null, { + then: { + get: function () { + ++numberOfTimesThenWasRetrieved; + return function thenMethodForX(onFulfilled) { + onFulfilled(); + }; + } + } + }); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + assert.strictEqual(numberOfTimesThenWasRetrieved, 1); + done(); + }); + }); + }); + + describe("`x` is an object with normal Object.prototype", function () { + var numberOfTimesThenWasRetrieved = null; + + beforeEach(function () { + numberOfTimesThenWasRetrieved = 0; + }); + + function xFactory() { + return Object.create(Object.prototype, { + then: { + get: function () { + ++numberOfTimesThenWasRetrieved; + return function thenMethodForX(onFulfilled) { + onFulfilled(); + }; + } + } + }); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + assert.strictEqual(numberOfTimesThenWasRetrieved, 1); + done(); + }); + }); + }); + + describe("`x` is a function", function () { + var numberOfTimesThenWasRetrieved = null; + + beforeEach(function () { + numberOfTimesThenWasRetrieved = 0; + }); + + function xFactory() { + function x() { } + + Object.defineProperty(x, "then", { + get: function () { + ++numberOfTimesThenWasRetrieved; + return function thenMethodForX(onFulfilled) { + onFulfilled(); + }; + } + }); + + return x; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + assert.strictEqual(numberOfTimesThenWasRetrieved, 1); + done(); + }); + }); + }); + }); + + describe("2.3.3.2: If retrieving the property `x.then` results in a thrown exception `e`, reject `promise` with " + + "`e` as the reason.", function () { + function testRejectionViaThrowingGetter(e, stringRepresentation) { + function xFactory() { + return Object.create(Object.prototype, { + then: { + get: function () { + throw e; + } + } + }); + } + + describe("`e` is " + stringRepresentation, function () { + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, e); + done(); + }); + }); + }); + } + + Object.keys(reasons).forEach(function (stringRepresentation) { + testRejectionViaThrowingGetter(reasons[stringRepresentation], stringRepresentation); + }); + }); + + describe("2.3.3.3: If `then` is a function, call it with `x` as `this`, first argument `resolvePromise`, and " + + "second argument `rejectPromise`", function () { + describe("Calls with `x` as `this` and two function arguments", function () { + function xFactory() { + var x = { + then: function (onFulfilled, onRejected) { + assert.strictEqual(this, x); + assert.strictEqual(typeof onFulfilled, "function"); + assert.strictEqual(typeof onRejected, "function"); + onFulfilled(); + } + }; + return x; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + done(); + }); + }); + }); + + describe("Uses the original value of `then`", function () { + var numberOfTimesThenWasRetrieved = null; + + beforeEach(function () { + numberOfTimesThenWasRetrieved = 0; + }); + + function xFactory() { + return Object.create(Object.prototype, { + then: { + get: function () { + if (numberOfTimesThenWasRetrieved === 0) { + return function (onFulfilled) { + onFulfilled(); + }; + } + return null; + } + } + }); + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function () { + done(); + }); + }); + }); + + describe("2.3.3.3.1: If/when `resolvePromise` is called with value `y`, run `[[Resolve]](promise, y)`", + function () { + describe("`y` is not a thenable", function () { + testCallingResolvePromiseFulfillsWith(function () { return undefined; }, "`undefined`", undefined); + testCallingResolvePromiseFulfillsWith(function () { return null; }, "`null`", null); + testCallingResolvePromiseFulfillsWith(function () { return false; }, "`false`", false); + testCallingResolvePromiseFulfillsWith(function () { return 5; }, "`5`", 5); + testCallingResolvePromiseFulfillsWith(function () { return sentinel; }, "an object", sentinel); + testCallingResolvePromiseFulfillsWith(function () { return sentinelArray; }, "an array", sentinelArray); + }); + + describe("`y` is a thenable", function () { + Object.keys(thenables.fulfilled).forEach(function (stringRepresentation) { + function yFactory() { + return thenables.fulfilled[stringRepresentation](sentinel); + } + + testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, sentinel); + }); + + Object.keys(thenables.rejected).forEach(function (stringRepresentation) { + function yFactory() { + return thenables.rejected[stringRepresentation](sentinel); + } + + testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, sentinel); + }); + }); + + describe("`y` is a thenable for a thenable", function () { + Object.keys(thenables.fulfilled).forEach(function (outerStringRepresentation) { + var outerThenableFactory = thenables.fulfilled[outerStringRepresentation]; + + Object.keys(thenables.fulfilled).forEach(function (innerStringRepresentation) { + var innerThenableFactory = thenables.fulfilled[innerStringRepresentation]; + + var stringRepresentation = outerStringRepresentation + " for " + innerStringRepresentation; + + function yFactory() { + return outerThenableFactory(innerThenableFactory(sentinel)); + } + + testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, sentinel); + }); + + Object.keys(thenables.rejected).forEach(function (innerStringRepresentation) { + var innerThenableFactory = thenables.rejected[innerStringRepresentation]; + + var stringRepresentation = outerStringRepresentation + " for " + innerStringRepresentation; + + function yFactory() { + return outerThenableFactory(innerThenableFactory(sentinel)); + } + + testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, sentinel); + }); + }); + }); + }); + + describe("2.3.3.3.2: If/when `rejectPromise` is called with reason `r`, reject `promise` with `r`", + function () { + Object.keys(reasons).forEach(function (stringRepresentation) { + testCallingRejectPromiseRejectsWith(reasons[stringRepresentation], stringRepresentation); + }); + }); + + describe("2.3.3.3.3: If both `resolvePromise` and `rejectPromise` are called, or multiple calls to the same " + + "argument are made, the first call takes precedence, and any further calls are ignored.", + function () { + describe("calling `resolvePromise` then `rejectPromise`, both synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(sentinel); + rejectPromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` synchronously then `rejectPromise` asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(sentinel); + + setTimeout(function () { + rejectPromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` then `rejectPromise`, both asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + resolvePromise(sentinel); + }, 0); + + setTimeout(function () { + rejectPromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` with an asynchronously-fulfilled promise, then calling " + + "`rejectPromise`, both synchronously", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.resolve(sentinel); + }, 50); + + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(d.promise); + rejectPromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` with an asynchronously-rejected promise, then calling " + + "`rejectPromise`, both synchronously", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.reject(sentinel); + }, 50); + + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(d.promise); + rejectPromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` then `resolvePromise`, both synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + resolvePromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` synchronously then `resolvePromise` asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + + setTimeout(function () { + resolvePromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` then `resolvePromise`, both asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + rejectPromise(sentinel); + }, 0); + + setTimeout(function () { + resolvePromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` twice synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + resolvePromise(sentinel); + resolvePromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` twice, first synchronously then asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + resolvePromise(sentinel); + + setTimeout(function () { + resolvePromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` twice, both times asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise) { + setTimeout(function () { + resolvePromise(sentinel); + }, 0); + + setTimeout(function () { + resolvePromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` with an asynchronously-fulfilled promise, then calling it again, both " + + "times synchronously", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.resolve(sentinel); + }, 50); + + return { + then: function (resolvePromise) { + resolvePromise(d.promise); + resolvePromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("calling `resolvePromise` with an asynchronously-rejected promise, then calling it again, both " + + "times synchronously", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.reject(sentinel); + }, 50); + + return { + then: function (resolvePromise) { + resolvePromise(d.promise); + resolvePromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` twice synchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + rejectPromise(other); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` twice, first synchronously then asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + + setTimeout(function () { + rejectPromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("calling `rejectPromise` twice, both times asynchronously", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + rejectPromise(sentinel); + }, 0); + + setTimeout(function () { + rejectPromise(other); + }, 0); + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("saving and abusing `resolvePromise` and `rejectPromise`", function () { + var savedResolvePromise, savedRejectPromise; + + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + savedResolvePromise = resolvePromise; + savedRejectPromise = rejectPromise; + } + }; + } + + beforeEach(function () { + savedResolvePromise = null; + savedRejectPromise = null; + }); + + testPromiseResolution(xFactory, function (promise, done) { + var timesFulfilled = 0; + var timesRejected = 0; + + promise.then( + function () { + ++timesFulfilled; + }, + function () { + ++timesRejected; + } + ); + + if (savedResolvePromise && savedRejectPromise) { + savedResolvePromise(dummy); + savedResolvePromise(dummy); + savedRejectPromise(dummy); + savedRejectPromise(dummy); + } + + setTimeout(function () { + savedResolvePromise(dummy); + savedResolvePromise(dummy); + savedRejectPromise(dummy); + savedRejectPromise(dummy); + }, 50); + + setTimeout(function () { + assert.strictEqual(timesFulfilled, 1); + assert.strictEqual(timesRejected, 0); + done(); + }, 100); + }); + }); + }); + + describe("2.3.3.3.4: If calling `then` throws an exception `e`,", function () { + describe("2.3.3.3.4.1: If `resolvePromise` or `rejectPromise` have been called, ignore it.", function () { + describe("`resolvePromise` was called with a non-thenable", function () { + function xFactory() { + return { + then: function (resolvePromise) { + resolvePromise(sentinel); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("`resolvePromise` was called with an asynchronously-fulfilled promise", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.resolve(sentinel); + }, 50); + + return { + then: function (resolvePromise) { + resolvePromise(d.promise); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("`resolvePromise` was called with an asynchronously-rejected promise", function () { + function xFactory() { + var d = deferred(); + setTimeout(function () { + d.reject(sentinel); + }, 50); + + return { + then: function (resolvePromise) { + resolvePromise(d.promise); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`rejectPromise` was called", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`resolvePromise` then `rejectPromise` were called", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + resolvePromise(sentinel); + rejectPromise(other); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, sentinel); + done(); + }); + }); + }); + + describe("`rejectPromise` then `resolvePromise` were called", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + rejectPromise(sentinel); + resolvePromise(other); + throw other; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + }); + + describe("2.3.3.3.4.2: Otherwise, reject `promise` with `e` as the reason.", function () { + describe("straightforward case", function () { + function xFactory() { + return { + then: function () { + throw sentinel; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`resolvePromise` is called asynchronously before the `throw`", function () { + function xFactory() { + return { + then: function (resolvePromise) { + setTimeout(function () { + resolvePromise(other); + }, 0); + throw sentinel; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + + describe("`rejectPromise` is called asynchronously before the `throw`", function () { + function xFactory() { + return { + then: function (resolvePromise, rejectPromise) { + setTimeout(function () { + rejectPromise(other); + }, 0); + throw sentinel; + } + }; + } + + testPromiseResolution(xFactory, function (promise, done) { + promise.then(null, function (reason) { + assert.strictEqual(reason, sentinel); + done(); + }); + }); + }); + }); + }); + }); + + describe("2.3.3.4: If `then` is not a function, fulfill promise with `x`", function () { + function testFulfillViaNonFunction(then, stringRepresentation) { + var x = null; + + beforeEach(function () { + x = { then: then }; + }); + + function xFactory() { + return x; + } + + describe("`then` is " + stringRepresentation, function () { + testPromiseResolution(xFactory, function (promise, done) { + promise.then(function (value) { + assert.strictEqual(value, x); + done(); + }); + }); + }); + } + + testFulfillViaNonFunction(5, "`5`"); + testFulfillViaNonFunction({}, "an object"); + testFulfillViaNonFunction([function () { }], "an array containing a function"); + testFulfillViaNonFunction(/a-b/i, "a regular expression"); + testFulfillViaNonFunction(Object.create(Function.prototype), "an object inheriting from `Function.prototype`"); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./helpers/reasons":21,"./helpers/thenables":23,"assert":2}],20:[function(require,module,exports){ +"use strict"; + +var assert = require("assert"); +var testFulfilled = require("./helpers/testThreeCases").testFulfilled; +var testRejected = require("./helpers/testThreeCases").testRejected; + +var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it + +describe("2.3.4: If `x` is not an object or function, fulfill `promise` with `x`", function () { + function testValue(expectedValue, stringRepresentation, beforeEachHook, afterEachHook) { + describe("The value is " + stringRepresentation, function () { + if (typeof beforeEachHook === "function") { + beforeEach(beforeEachHook); + } + if (typeof afterEachHook === "function") { + afterEach(afterEachHook); + } + + testFulfilled(dummy, function (promise1, done) { + var promise2 = promise1.then(function onFulfilled() { + return expectedValue; + }); + + promise2.then(function onPromise2Fulfilled(actualValue) { + assert.strictEqual(actualValue, expectedValue); + done(); + }); + }); + testRejected(dummy, function (promise1, done) { + var promise2 = promise1.then(null, function onRejected() { + return expectedValue; + }); + + promise2.then(function onPromise2Fulfilled(actualValue) { + assert.strictEqual(actualValue, expectedValue); + done(); + }); + }); + }); + } + + testValue(undefined, "`undefined`"); + testValue(null, "`null`"); + testValue(false, "`false`"); + testValue(true, "`true`"); + testValue(0, "`0`"); + + testValue( + true, + "`true` with `Boolean.prototype` modified to have a `then` method", + function () { + Boolean.prototype.then = function () {}; + }, + function () { + delete Boolean.prototype.then; + } + ); + + testValue( + 1, + "`1` with `Number.prototype` modified to have a `then` method", + function () { + Number.prototype.then = function () {}; + }, + function () { + delete Number.prototype.then; + } + ); +}); + +},{"./helpers/testThreeCases":22,"assert":2}],21:[function(require,module,exports){ +(function (global){ +"use strict"; + +// This module exports some valid rejection reason factories, keyed by human-readable versions of their names. + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; + +var dummy = { dummy: "dummy" }; + +exports["`undefined`"] = function () { + return undefined; +}; + +exports["`null`"] = function () { + return null; +}; + +exports["`false`"] = function () { + return false; +}; + +exports["`0`"] = function () { + return 0; +}; + +exports["an error"] = function () { + return new Error(); +}; + +exports["an error without a stack"] = function () { + var error = new Error(); + delete error.stack; + + return error; +}; + +exports["a date"] = function () { + return new Date(); +}; + +exports["an object"] = function () { + return {}; +}; + +exports["an always-pending thenable"] = function () { + return { then: function () { } }; +}; + +exports["a fulfilled promise"] = function () { + return resolved(dummy); +}; + +exports["a rejected promise"] = function () { + return rejected(dummy); +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],22:[function(require,module,exports){ +(function (global){ +"use strict"; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +exports.testFulfilled = function (value, test) { + specify("already-fulfilled", function (done) { + test(resolved(value), done); + }); + + specify("immediately-fulfilled", function (done) { + var d = deferred(); + test(d.promise, done); + d.resolve(value); + }); + + specify("eventually-fulfilled", function (done) { + var d = deferred(); + test(d.promise, done); + setTimeout(function () { + d.resolve(value); + }, 50); + }); +}; + +exports.testRejected = function (reason, test) { + specify("already-rejected", function (done) { + test(rejected(reason), done); + }); + + specify("immediately-rejected", function (done) { + var d = deferred(); + test(d.promise, done); + d.reject(reason); + }); + + specify("eventually-rejected", function (done) { + var d = deferred(); + test(d.promise, done); + setTimeout(function () { + d.reject(reason); + }, 50); + }); +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],23:[function(require,module,exports){ +(function (global){ +"use strict"; + +var adapter = global.adapter; +var resolved = adapter.resolved; +var rejected = adapter.rejected; +var deferred = adapter.deferred; + +var other = { other: "other" }; // a value we don't want to be strict equal to + +exports.fulfilled = { + "a synchronously-fulfilled custom thenable": function (value) { + return { + then: function (onFulfilled) { + onFulfilled(value); + } + }; + }, + + "an asynchronously-fulfilled custom thenable": function (value) { + return { + then: function (onFulfilled) { + setTimeout(function () { + onFulfilled(value); + }, 0); + } + }; + }, + + "a synchronously-fulfilled one-time thenable": function (value) { + var numberOfTimesThenRetrieved = 0; + return Object.create(null, { + then: { + get: function () { + if (numberOfTimesThenRetrieved === 0) { + ++numberOfTimesThenRetrieved; + return function (onFulfilled) { + onFulfilled(value); + }; + } + return null; + } + } + }); + }, + + "a thenable that tries to fulfill twice": function (value) { + return { + then: function (onFulfilled) { + onFulfilled(value); + onFulfilled(other); + } + }; + }, + + "a thenable that fulfills but then throws": function (value) { + return { + then: function (onFulfilled) { + onFulfilled(value); + throw other; + } + }; + }, + + "an already-fulfilled promise": function (value) { + return resolved(value); + }, + + "an eventually-fulfilled promise": function (value) { + var d = deferred(); + setTimeout(function () { + d.resolve(value); + }, 50); + return d.promise; + } +}; + +exports.rejected = { + "a synchronously-rejected custom thenable": function (reason) { + return { + then: function (onFulfilled, onRejected) { + onRejected(reason); + } + }; + }, + + "an asynchronously-rejected custom thenable": function (reason) { + return { + then: function (onFulfilled, onRejected) { + setTimeout(function () { + onRejected(reason); + }, 0); + } + }; + }, + + "a synchronously-rejected one-time thenable": function (reason) { + var numberOfTimesThenRetrieved = 0; + return Object.create(null, { + then: { + get: function () { + if (numberOfTimesThenRetrieved === 0) { + ++numberOfTimesThenRetrieved; + return function (onFulfilled, onRejected) { + onRejected(reason); + }; + } + return null; + } + } + }); + }, + + "a thenable that immediately throws in `then`": function (reason) { + return { + then: function () { + throw reason; + } + }; + }, + + "an object with a throwing `then` accessor": function (reason) { + return Object.create(null, { + then: { + get: function () { + throw reason; + } + } + }); + }, + + "an already-rejected promise": function (reason) { + return rejected(reason); + }, + + "an eventually-rejected promise": function (reason) { + var d = deferred(); + setTimeout(function () { + d.reject(reason); + }, 50); + return d.promise; + } +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],24:[function(require,module,exports){ +/** + * Sinon core utilities. For internal use only. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +var sinon = (function () { + var sinon; + var isNode = typeof module !== "undefined" && module.exports && typeof require === "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + sinon = module.exports = require("./sinon/util/core"); + require("./sinon/extend"); + require("./sinon/typeOf"); + require("./sinon/times_in_words"); + require("./sinon/spy"); + require("./sinon/call"); + require("./sinon/behavior"); + require("./sinon/stub"); + require("./sinon/mock"); + require("./sinon/collection"); + require("./sinon/assert"); + require("./sinon/sandbox"); + require("./sinon/test"); + require("./sinon/test_case"); + require("./sinon/match"); + require("./sinon/format"); + require("./sinon/log_error"); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + sinon = module.exports; + } else { + sinon = {}; + } + + return sinon; +}()); + +},{"./sinon/assert":25,"./sinon/behavior":26,"./sinon/call":27,"./sinon/collection":28,"./sinon/extend":29,"./sinon/format":30,"./sinon/log_error":31,"./sinon/match":32,"./sinon/mock":33,"./sinon/sandbox":34,"./sinon/spy":35,"./sinon/stub":36,"./sinon/test":37,"./sinon/test_case":38,"./sinon/times_in_words":39,"./sinon/typeOf":40,"./sinon/util/core":41}],25:[function(require,module,exports){ +(function (global){ +/** + * @depend times_in_words.js + * @depend util/core.js + * @depend match.js + * @depend format.js + */ +/** + * Assertions matching the test spy retrieval interface. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon, global) { + var slice = Array.prototype.slice; + + function makeApi(sinon) { + var assert; + + function verifyIsStub() { + var method; + + for (var i = 0, l = arguments.length; i < l; ++i) { + method = arguments[i]; + + if (!method) { + assert.fail("fake is not a spy"); + } + + if (method.proxy) { + verifyIsStub(method.proxy); + } else { + if (typeof method != "function") { + assert.fail(method + " is not a function"); + } + + if (typeof method.getCall != "function") { + assert.fail(method + " is not stubbed"); + } + } + + } + } + + function failAssertion(object, msg) { + object = object || global; + var failMethod = object.fail || assert.fail; + failMethod.call(object, msg); + } + + function mirrorPropAsAssertion(name, method, message) { + if (arguments.length == 2) { + message = method; + method = name; + } + + assert[name] = function (fake) { + verifyIsStub(fake); + + var args = slice.call(arguments, 1); + var failed = false; + + if (typeof method == "function") { + failed = !method(fake); + } else { + failed = typeof fake[method] == "function" ? + !fake[method].apply(fake, args) : !fake[method]; + } + + if (failed) { + failAssertion(this, (fake.printf || fake.proxy.printf).apply(fake, [message].concat(args))); + } else { + assert.pass(name); + } + }; + } + + function exposedName(prefix, prop) { + return !prefix || /^fail/.test(prop) ? prop : + prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1); + } + + assert = { + failException: "AssertError", + + fail: function fail(message) { + var error = new Error(message); + error.name = this.failException || assert.failException; + + throw error; + }, + + pass: function pass(assertion) {}, + + callOrder: function assertCallOrder() { + verifyIsStub.apply(null, arguments); + var expected = "", actual = ""; + + if (!sinon.calledInOrder(arguments)) { + try { + expected = [].join.call(arguments, ", "); + var calls = slice.call(arguments); + var i = calls.length; + while (i) { + if (!calls[--i].called) { + calls.splice(i, 1); + } + } + actual = sinon.orderByFirstCall(calls).join(", "); + } catch (e) { + // If this fails, we'll just fall back to the blank string + } + + failAssertion(this, "expected " + expected + " to be " + + "called in order but were called as " + actual); + } else { + assert.pass("callOrder"); + } + }, + + callCount: function assertCallCount(method, count) { + verifyIsStub(method); + + if (method.callCount != count) { + var msg = "expected %n to be called " + sinon.timesInWords(count) + + " but was called %c%C"; + failAssertion(this, method.printf(msg)); + } else { + assert.pass("callCount"); + } + }, + + expose: function expose(target, options) { + if (!target) { + throw new TypeError("target is null or undefined"); + } + + var o = options || {}; + var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix; + var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail; + + for (var method in this) { + if (method != "expose" && (includeFail || !/^(fail)/.test(method))) { + target[exposedName(prefix, method)] = this[method]; + } + } + + return target; + }, + + match: function match(actual, expectation) { + var matcher = sinon.match(expectation); + if (matcher.test(actual)) { + assert.pass("match"); + } else { + var formatted = [ + "expected value to match", + " expected = " + sinon.format(expectation), + " actual = " + sinon.format(actual) + ] + failAssertion(this, formatted.join("\n")); + } + } + }; + + mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called"); + mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; }, + "expected %n to not have been called but was called %c%C"); + mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C"); + mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C"); + mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C"); + mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t"); + mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t"); + mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new"); + mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new"); + mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C"); + mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C"); + mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C"); + mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C"); + mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C"); + mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C"); + mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C"); + mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C"); + mirrorPropAsAssertion("threw", "%n did not throw exception%C"); + mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C"); + + sinon.assert = assert; + return assert; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./match"); + require("./format"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } + +}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./format":30,"./match":32,"./util/core":41}],26:[function(require,module,exports){ +(function (process){ +/** + * @depend util/core.js + * @depend extend.js + */ +/** + * Stub behavior + * + * @author Christian Johansen (christian@cjohansen.no) + * @author Tim Fischbach (mail@timfischbach.de) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + var slice = Array.prototype.slice; + var join = Array.prototype.join; + var useLeftMostCallback = -1; + var useRightMostCallback = -2; + + var nextTick = (function () { + if (typeof process === "object" && typeof process.nextTick === "function") { + return process.nextTick; + } else if (typeof setImmediate === "function") { + return setImmediate; + } else { + return function (callback) { + setTimeout(callback, 0); + }; + } + })(); + + function throwsException(error, message) { + if (typeof error == "string") { + this.exception = new Error(message || ""); + this.exception.name = error; + } else if (!error) { + this.exception = new Error("Error"); + } else { + this.exception = error; + } + + return this; + } + + function getCallback(behavior, args) { + var callArgAt = behavior.callArgAt; + + if (callArgAt >= 0) { + return args[callArgAt]; + } + + var argumentList; + + if (callArgAt === useLeftMostCallback) { + argumentList = args; + } + + if (callArgAt === useRightMostCallback) { + argumentList = slice.call(args).reverse(); + } + + var callArgProp = behavior.callArgProp; + + for (var i = 0, l = argumentList.length; i < l; ++i) { + if (!callArgProp && typeof argumentList[i] == "function") { + return argumentList[i]; + } + + if (callArgProp && argumentList[i] && + typeof argumentList[i][callArgProp] == "function") { + return argumentList[i][callArgProp]; + } + } + + return null; + } + + function makeApi(sinon) { + function getCallbackError(behavior, func, args) { + if (behavior.callArgAt < 0) { + var msg; + + if (behavior.callArgProp) { + msg = sinon.functionName(behavior.stub) + + " expected to yield to '" + behavior.callArgProp + + "', but no object with such a property was passed."; + } else { + msg = sinon.functionName(behavior.stub) + + " expected to yield, but no callback was passed."; + } + + if (args.length > 0) { + msg += " Received [" + join.call(args, ", ") + "]"; + } + + return msg; + } + + return "argument at index " + behavior.callArgAt + " is not a function: " + func; + } + + function callCallback(behavior, args) { + if (typeof behavior.callArgAt == "number") { + var func = getCallback(behavior, args); + + if (typeof func != "function") { + throw new TypeError(getCallbackError(behavior, func, args)); + } + + if (behavior.callbackAsync) { + nextTick(function () { + func.apply(behavior.callbackContext, behavior.callbackArguments); + }); + } else { + func.apply(behavior.callbackContext, behavior.callbackArguments); + } + } + } + + var proto = { + create: function create(stub) { + var behavior = sinon.extend({}, sinon.behavior); + delete behavior.create; + behavior.stub = stub; + + return behavior; + }, + + isPresent: function isPresent() { + return (typeof this.callArgAt == "number" || + this.exception || + typeof this.returnArgAt == "number" || + this.returnThis || + this.returnValueDefined); + }, + + invoke: function invoke(context, args) { + callCallback(this, args); + + if (this.exception) { + throw this.exception; + } else if (typeof this.returnArgAt == "number") { + return args[this.returnArgAt]; + } else if (this.returnThis) { + return context; + } + + return this.returnValue; + }, + + onCall: function onCall(index) { + return this.stub.onCall(index); + }, + + onFirstCall: function onFirstCall() { + return this.stub.onFirstCall(); + }, + + onSecondCall: function onSecondCall() { + return this.stub.onSecondCall(); + }, + + onThirdCall: function onThirdCall() { + return this.stub.onThirdCall(); + }, + + withArgs: function withArgs(/* arguments */) { + throw new Error("Defining a stub by invoking \"stub.onCall(...).withArgs(...)\" is not supported. " + + "Use \"stub.withArgs(...).onCall(...)\" to define sequential behavior for calls with certain arguments."); + }, + + callsArg: function callsArg(pos) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + + this.callArgAt = pos; + this.callbackArguments = []; + this.callbackContext = undefined; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + callsArgOn: function callsArgOn(pos, context) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + if (typeof context != "object") { + throw new TypeError("argument context is not an object"); + } + + this.callArgAt = pos; + this.callbackArguments = []; + this.callbackContext = context; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + callsArgWith: function callsArgWith(pos) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + + this.callArgAt = pos; + this.callbackArguments = slice.call(arguments, 1); + this.callbackContext = undefined; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + callsArgOnWith: function callsArgWith(pos, context) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + if (typeof context != "object") { + throw new TypeError("argument context is not an object"); + } + + this.callArgAt = pos; + this.callbackArguments = slice.call(arguments, 2); + this.callbackContext = context; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + yields: function () { + this.callArgAt = useLeftMostCallback; + this.callbackArguments = slice.call(arguments, 0); + this.callbackContext = undefined; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + yieldsRight: function () { + this.callArgAt = useRightMostCallback; + this.callbackArguments = slice.call(arguments, 0); + this.callbackContext = undefined; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + yieldsOn: function (context) { + if (typeof context != "object") { + throw new TypeError("argument context is not an object"); + } + + this.callArgAt = useLeftMostCallback; + this.callbackArguments = slice.call(arguments, 1); + this.callbackContext = context; + this.callArgProp = undefined; + this.callbackAsync = false; + + return this; + }, + + yieldsTo: function (prop) { + this.callArgAt = useLeftMostCallback; + this.callbackArguments = slice.call(arguments, 1); + this.callbackContext = undefined; + this.callArgProp = prop; + this.callbackAsync = false; + + return this; + }, + + yieldsToOn: function (prop, context) { + if (typeof context != "object") { + throw new TypeError("argument context is not an object"); + } + + this.callArgAt = useLeftMostCallback; + this.callbackArguments = slice.call(arguments, 2); + this.callbackContext = context; + this.callArgProp = prop; + this.callbackAsync = false; + + return this; + }, + + throws: throwsException, + throwsException: throwsException, + + returns: function returns(value) { + this.returnValue = value; + this.returnValueDefined = true; + + return this; + }, + + returnsArg: function returnsArg(pos) { + if (typeof pos != "number") { + throw new TypeError("argument index is not number"); + } + + this.returnArgAt = pos; + + return this; + }, + + returnsThis: function returnsThis() { + this.returnThis = true; + + return this; + } + }; + + // create asynchronous versions of callsArg* and yields* methods + for (var method in proto) { + // need to avoid creating anotherasync versions of the newly added async methods + if (proto.hasOwnProperty(method) && + method.match(/^(callsArg|yields)/) && + !method.match(/Async/)) { + proto[method + "Async"] = (function (syncFnName) { + return function () { + var result = this[syncFnName].apply(this, arguments); + this.callbackAsync = true; + return result; + }; + })(method); + } + } + + sinon.behavior = proto; + return proto; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./extend"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +}).call(this,require('_process')) +},{"./extend":29,"./util/core":41,"_process":4}],27:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend match.js + * @depend format.js + */ +/** + * Spy calls + * + * @author Christian Johansen (christian@cjohansen.no) + * @author Maximilian Antoni (mail@maxantoni.de) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + * Copyright (c) 2013 Maximilian Antoni + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + function throwYieldError(proxy, text, args) { + var msg = sinon.functionName(proxy) + text; + if (args.length) { + msg += " Received [" + slice.call(args).join(", ") + "]"; + } + throw new Error(msg); + } + + var slice = Array.prototype.slice; + + var callProto = { + calledOn: function calledOn(thisValue) { + if (sinon.match && sinon.match.isMatcher(thisValue)) { + return thisValue.test(this.thisValue); + } + return this.thisValue === thisValue; + }, + + calledWith: function calledWith() { + var l = arguments.length; + if (l > this.args.length) { + return false; + } + for (var i = 0; i < l; i += 1) { + if (!sinon.deepEqual(arguments[i], this.args[i])) { + return false; + } + } + + return true; + }, + + calledWithMatch: function calledWithMatch() { + var l = arguments.length; + if (l > this.args.length) { + return false; + } + for (var i = 0; i < l; i += 1) { + var actual = this.args[i]; + var expectation = arguments[i]; + if (!sinon.match || !sinon.match(expectation).test(actual)) { + return false; + } + } + return true; + }, + + calledWithExactly: function calledWithExactly() { + return arguments.length == this.args.length && + this.calledWith.apply(this, arguments); + }, + + notCalledWith: function notCalledWith() { + return !this.calledWith.apply(this, arguments); + }, + + notCalledWithMatch: function notCalledWithMatch() { + return !this.calledWithMatch.apply(this, arguments); + }, + + returned: function returned(value) { + return sinon.deepEqual(value, this.returnValue); + }, + + threw: function threw(error) { + if (typeof error === "undefined" || !this.exception) { + return !!this.exception; + } + + return this.exception === error || this.exception.name === error; + }, + + calledWithNew: function calledWithNew() { + return this.proxy.prototype && this.thisValue instanceof this.proxy; + }, + + calledBefore: function (other) { + return this.callId < other.callId; + }, + + calledAfter: function (other) { + return this.callId > other.callId; + }, + + callArg: function (pos) { + this.args[pos](); + }, + + callArgOn: function (pos, thisValue) { + this.args[pos].apply(thisValue); + }, + + callArgWith: function (pos) { + this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); + }, + + callArgOnWith: function (pos, thisValue) { + var args = slice.call(arguments, 2); + this.args[pos].apply(thisValue, args); + }, + + yield: function () { + this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); + }, + + yieldOn: function (thisValue) { + var args = this.args; + for (var i = 0, l = args.length; i < l; ++i) { + if (typeof args[i] === "function") { + args[i].apply(thisValue, slice.call(arguments, 1)); + return; + } + } + throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); + }, + + yieldTo: function (prop) { + this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); + }, + + yieldToOn: function (prop, thisValue) { + var args = this.args; + for (var i = 0, l = args.length; i < l; ++i) { + if (args[i] && typeof args[i][prop] === "function") { + args[i][prop].apply(thisValue, slice.call(arguments, 2)); + return; + } + } + throwYieldError(this.proxy, " cannot yield to '" + prop + + "' since no callback was passed.", args); + }, + + toString: function () { + var callStr = this.proxy.toString() + "("; + var args = []; + + for (var i = 0, l = this.args.length; i < l; ++i) { + args.push(sinon.format(this.args[i])); + } + + callStr = callStr + args.join(", ") + ")"; + + if (typeof this.returnValue != "undefined") { + callStr += " => " + sinon.format(this.returnValue); + } + + if (this.exception) { + callStr += " !" + this.exception.name; + + if (this.exception.message) { + callStr += "(" + this.exception.message + ")"; + } + } + + return callStr; + } + }; + + callProto.invokeCallback = callProto.yield; + + function createSpyCall(spy, thisValue, args, returnValue, exception, id) { + if (typeof id !== "number") { + throw new TypeError("Call id is not a number"); + } + var proxyCall = sinon.create(callProto); + proxyCall.proxy = spy; + proxyCall.thisValue = thisValue; + proxyCall.args = args; + proxyCall.returnValue = returnValue; + proxyCall.exception = exception; + proxyCall.callId = id; + + return proxyCall; + } + createSpyCall.toString = callProto.toString; // used by mocks + + sinon.spyCall = createSpyCall; + return createSpyCall; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./match"); + require("./format"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./format":30,"./match":32,"./util/core":41}],28:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend spy.js + * @depend stub.js + * @depend mock.js + */ +/** + * Collections of stubs, spies and mocks. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + var push = [].push; + var hasOwnProperty = Object.prototype.hasOwnProperty; + + function getFakes(fakeCollection) { + if (!fakeCollection.fakes) { + fakeCollection.fakes = []; + } + + return fakeCollection.fakes; + } + + function each(fakeCollection, method) { + var fakes = getFakes(fakeCollection); + + for (var i = 0, l = fakes.length; i < l; i += 1) { + if (typeof fakes[i][method] == "function") { + fakes[i][method](); + } + } + } + + function compact(fakeCollection) { + var fakes = getFakes(fakeCollection); + var i = 0; + while (i < fakes.length) { + fakes.splice(i, 1); + } + } + + function makeApi(sinon) { + var collection = { + verify: function resolve() { + each(this, "verify"); + }, + + restore: function restore() { + each(this, "restore"); + compact(this); + }, + + reset: function restore() { + each(this, "reset"); + }, + + verifyAndRestore: function verifyAndRestore() { + var exception; + + try { + this.verify(); + } catch (e) { + exception = e; + } + + this.restore(); + + if (exception) { + throw exception; + } + }, + + add: function add(fake) { + push.call(getFakes(this), fake); + return fake; + }, + + spy: function spy() { + return this.add(sinon.spy.apply(sinon, arguments)); + }, + + stub: function stub(object, property, value) { + if (property) { + var original = object[property]; + + if (typeof original != "function") { + if (!hasOwnProperty.call(object, property)) { + throw new TypeError("Cannot stub non-existent own property " + property); + } + + object[property] = value; + + return this.add({ + restore: function () { + object[property] = original; + } + }); + } + } + if (!property && !!object && typeof object == "object") { + var stubbedObj = sinon.stub.apply(sinon, arguments); + + for (var prop in stubbedObj) { + if (typeof stubbedObj[prop] === "function") { + this.add(stubbedObj[prop]); + } + } + + return stubbedObj; + } + + return this.add(sinon.stub.apply(sinon, arguments)); + }, + + mock: function mock() { + return this.add(sinon.mock.apply(sinon, arguments)); + }, + + inject: function inject(obj) { + var col = this; + + obj.spy = function () { + return col.spy.apply(col, arguments); + }; + + obj.stub = function () { + return col.stub.apply(col, arguments); + }; + + obj.mock = function () { + return col.mock.apply(col, arguments); + }; + + return obj; + } + }; + + sinon.collection = collection; + return collection; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./mock"); + require("./spy"); + require("./stub"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./mock":33,"./spy":35,"./stub":36,"./util/core":41}],29:[function(require,module,exports){ +/** + * @depend util/core.js + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + + // Adapted from https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug + var hasDontEnumBug = (function () { + var obj = { + constructor: function () { + return "0"; + }, + toString: function () { + return "1"; + }, + valueOf: function () { + return "2"; + }, + toLocaleString: function () { + return "3"; + }, + prototype: function () { + return "4"; + }, + isPrototypeOf: function () { + return "5"; + }, + propertyIsEnumerable: function () { + return "6"; + }, + hasOwnProperty: function () { + return "7"; + }, + length: function () { + return "8"; + }, + unique: function () { + return "9" + } + }; + + var result = []; + for (var prop in obj) { + result.push(obj[prop]()); + } + return result.join("") !== "0123456789"; + })(); + + /* Public: Extend target in place with all (own) properties from sources in-order. Thus, last source will + * override properties in previous sources. + * + * target - The Object to extend + * sources - Objects to copy properties from. + * + * Returns the extended target + */ + function extend(target /*, sources */) { + var sources = Array.prototype.slice.call(arguments, 1), + source, i, prop; + + for (i = 0; i < sources.length; i++) { + source = sources[i]; + + for (prop in source) { + if (source.hasOwnProperty(prop)) { + target[prop] = source[prop]; + } + } + + // Make sure we copy (own) toString method even when in JScript with DontEnum bug + // See https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug + if (hasDontEnumBug && source.hasOwnProperty("toString") && source.toString !== target.toString) { + target.toString = source.toString; + } + } + + return target; + }; + + sinon.extend = extend; + return sinon.extend; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./util/core":41}],30:[function(require,module,exports){ +/** + * @depend util/core.js + */ +/** + * Format functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2014 Christian Johansen + */ +"use strict"; + +(function (sinon, formatio) { + function makeApi(sinon) { + function valueFormatter(value) { + return "" + value; + } + + function getFormatioFormatter() { + var formatter = formatio.configure({ + quoteStrings: false, + limitChildrenCount: 250 + }); + + function format() { + return formatter.ascii.apply(formatter, arguments); + }; + + return format; + } + + function getNodeFormatter(value) { + function format(value) { + return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; + }; + + try { + var util = require("util"); + } catch (e) { + /* Node, but no util module - would be very old, but better safe than sorry */ + } + + return util ? format : valueFormatter; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function", + formatter; + + if (isNode) { + try { + formatio = require("formatio"); + } catch (e) {} + } + + if (formatio) { + formatter = getFormatioFormatter() + } else if (isNode) { + formatter = getNodeFormatter(); + } else { + formatter = valueFormatter; + } + + sinon.format = formatter; + return sinon.format; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}( + (typeof sinon == "object" && sinon || null), + (typeof formatio == "object" && formatio) +)); + +},{"./util/core":41,"formatio":48,"util":6}],31:[function(require,module,exports){ +/** + * @depend util/core.js + */ +/** + * Logs errors + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2014 Christian Johansen + */ +"use strict"; + +(function (sinon) { + // cache a reference to setTimeout, so that our reference won't be stubbed out + // when using fake timers and errors will still get logged + // https://github.com/cjohansen/Sinon.JS/issues/381 + var realSetTimeout = setTimeout; + + function makeApi(sinon) { + + function log() {} + + function logError(label, err) { + var msg = label + " threw exception: "; + + sinon.log(msg + "[" + err.name + "] " + err.message); + + if (err.stack) { + sinon.log(err.stack); + } + + logError.setTimeout(function () { + err.message = msg + err.message; + throw err; + }, 0); + }; + + // wrap realSetTimeout with something we can stub in tests + logError.setTimeout = function (func, timeout) { + realSetTimeout(func, timeout); + } + + var exports = {}; + exports.log = sinon.log = log; + exports.logError = sinon.logError = logError; + + return exports; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./util/core":41}],32:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend typeOf.js + */ +/*jslint eqeqeq: false, onevar: false, plusplus: false*/ +/*global module, require, sinon*/ +/** + * Match functions + * + * @author Maximilian Antoni (mail@maxantoni.de) + * @license BSD + * + * Copyright (c) 2012 Maximilian Antoni + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + function assertType(value, type, name) { + var actual = sinon.typeOf(value); + if (actual !== type) { + throw new TypeError("Expected type of " + name + " to be " + + type + ", but was " + actual); + } + } + + var matcher = { + toString: function () { + return this.message; + } + }; + + function isMatcher(object) { + return matcher.isPrototypeOf(object); + } + + function matchObject(expectation, actual) { + if (actual === null || actual === undefined) { + return false; + } + for (var key in expectation) { + if (expectation.hasOwnProperty(key)) { + var exp = expectation[key]; + var act = actual[key]; + if (match.isMatcher(exp)) { + if (!exp.test(act)) { + return false; + } + } else if (sinon.typeOf(exp) === "object") { + if (!matchObject(exp, act)) { + return false; + } + } else if (!sinon.deepEqual(exp, act)) { + return false; + } + } + } + return true; + } + + matcher.or = function (m2) { + if (!arguments.length) { + throw new TypeError("Matcher expected"); + } else if (!isMatcher(m2)) { + m2 = match(m2); + } + var m1 = this; + var or = sinon.create(matcher); + or.test = function (actual) { + return m1.test(actual) || m2.test(actual); + }; + or.message = m1.message + ".or(" + m2.message + ")"; + return or; + }; + + matcher.and = function (m2) { + if (!arguments.length) { + throw new TypeError("Matcher expected"); + } else if (!isMatcher(m2)) { + m2 = match(m2); + } + var m1 = this; + var and = sinon.create(matcher); + and.test = function (actual) { + return m1.test(actual) && m2.test(actual); + }; + and.message = m1.message + ".and(" + m2.message + ")"; + return and; + }; + + var match = function (expectation, message) { + var m = sinon.create(matcher); + var type = sinon.typeOf(expectation); + switch (type) { + case "object": + if (typeof expectation.test === "function") { + m.test = function (actual) { + return expectation.test(actual) === true; + }; + m.message = "match(" + sinon.functionName(expectation.test) + ")"; + return m; + } + var str = []; + for (var key in expectation) { + if (expectation.hasOwnProperty(key)) { + str.push(key + ": " + expectation[key]); + } + } + m.test = function (actual) { + return matchObject(expectation, actual); + }; + m.message = "match(" + str.join(", ") + ")"; + break; + case "number": + m.test = function (actual) { + return expectation == actual; + }; + break; + case "string": + m.test = function (actual) { + if (typeof actual !== "string") { + return false; + } + return actual.indexOf(expectation) !== -1; + }; + m.message = "match(\"" + expectation + "\")"; + break; + case "regexp": + m.test = function (actual) { + if (typeof actual !== "string") { + return false; + } + return expectation.test(actual); + }; + break; + case "function": + m.test = expectation; + if (message) { + m.message = message; + } else { + m.message = "match(" + sinon.functionName(expectation) + ")"; + } + break; + default: + m.test = function (actual) { + return sinon.deepEqual(expectation, actual); + }; + } + if (!m.message) { + m.message = "match(" + expectation + ")"; + } + return m; + }; + + match.isMatcher = isMatcher; + + match.any = match(function () { + return true; + }, "any"); + + match.defined = match(function (actual) { + return actual !== null && actual !== undefined; + }, "defined"); + + match.truthy = match(function (actual) { + return !!actual; + }, "truthy"); + + match.falsy = match(function (actual) { + return !actual; + }, "falsy"); + + match.same = function (expectation) { + return match(function (actual) { + return expectation === actual; + }, "same(" + expectation + ")"); + }; + + match.typeOf = function (type) { + assertType(type, "string", "type"); + return match(function (actual) { + return sinon.typeOf(actual) === type; + }, "typeOf(\"" + type + "\")"); + }; + + match.instanceOf = function (type) { + assertType(type, "function", "type"); + return match(function (actual) { + return actual instanceof type; + }, "instanceOf(" + sinon.functionName(type) + ")"); + }; + + function createPropertyMatcher(propertyTest, messagePrefix) { + return function (property, value) { + assertType(property, "string", "property"); + var onlyProperty = arguments.length === 1; + var message = messagePrefix + "(\"" + property + "\""; + if (!onlyProperty) { + message += ", " + value; + } + message += ")"; + return match(function (actual) { + if (actual === undefined || actual === null || + !propertyTest(actual, property)) { + return false; + } + return onlyProperty || sinon.deepEqual(value, actual[property]); + }, message); + }; + } + + match.has = createPropertyMatcher(function (actual, property) { + if (typeof actual === "object") { + return property in actual; + } + return actual[property] !== undefined; + }, "has"); + + match.hasOwn = createPropertyMatcher(function (actual, property) { + return actual.hasOwnProperty(property); + }, "hasOwn"); + + match.bool = match.typeOf("boolean"); + match.number = match.typeOf("number"); + match.string = match.typeOf("string"); + match.object = match.typeOf("object"); + match.func = match.typeOf("function"); + match.array = match.typeOf("array"); + match.regexp = match.typeOf("regexp"); + match.date = match.typeOf("date"); + + sinon.match = match; + return match; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./typeOf"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./typeOf":40,"./util/core":41}],33:[function(require,module,exports){ +/** + * @depend times_in_words.js + * @depend util/core.js + * @depend call.js + * @depend extend.js + * @depend match.js + * @depend spy.js + * @depend stub.js + * @depend format.js + */ +/** + * Mock functions. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + var push = [].push; + var match = sinon.match; + + function mock(object) { + if (!object) { + return sinon.expectation.create("Anonymous mock"); + } + + return mock.create(object); + } + + function each(collection, callback) { + if (!collection) { + return; + } + + for (var i = 0, l = collection.length; i < l; i += 1) { + callback(collection[i]); + } + } + + sinon.extend(mock, { + create: function create(object) { + if (!object) { + throw new TypeError("object is null"); + } + + var mockObject = sinon.extend({}, mock); + mockObject.object = object; + delete mockObject.create; + + return mockObject; + }, + + expects: function expects(method) { + if (!method) { + throw new TypeError("method is falsy"); + } + + if (!this.expectations) { + this.expectations = {}; + this.proxies = []; + } + + if (!this.expectations[method]) { + this.expectations[method] = []; + var mockObject = this; + + sinon.wrapMethod(this.object, method, function () { + return mockObject.invokeMethod(method, this, arguments); + }); + + push.call(this.proxies, method); + } + + var expectation = sinon.expectation.create(method); + push.call(this.expectations[method], expectation); + + return expectation; + }, + + restore: function restore() { + var object = this.object; + + each(this.proxies, function (proxy) { + if (typeof object[proxy].restore == "function") { + object[proxy].restore(); + } + }); + }, + + verify: function verify() { + var expectations = this.expectations || {}; + var messages = [], met = []; + + each(this.proxies, function (proxy) { + each(expectations[proxy], function (expectation) { + if (!expectation.met()) { + push.call(messages, expectation.toString()); + } else { + push.call(met, expectation.toString()); + } + }); + }); + + this.restore(); + + if (messages.length > 0) { + sinon.expectation.fail(messages.concat(met).join("\n")); + } else if (met.length > 0) { + sinon.expectation.pass(messages.concat(met).join("\n")); + } + + return true; + }, + + invokeMethod: function invokeMethod(method, thisValue, args) { + var expectations = this.expectations && this.expectations[method]; + var length = expectations && expectations.length || 0, i; + + for (i = 0; i < length; i += 1) { + if (!expectations[i].met() && + expectations[i].allowsCall(thisValue, args)) { + return expectations[i].apply(thisValue, args); + } + } + + var messages = [], available, exhausted = 0; + + for (i = 0; i < length; i += 1) { + if (expectations[i].allowsCall(thisValue, args)) { + available = available || expectations[i]; + } else { + exhausted += 1; + } + push.call(messages, " " + expectations[i].toString()); + } + + if (exhausted === 0) { + return available.apply(thisValue, args); + } + + messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ + proxy: method, + args: args + })); + + sinon.expectation.fail(messages.join("\n")); + } + }); + + var times = sinon.timesInWords; + var slice = Array.prototype.slice; + + function callCountInWords(callCount) { + if (callCount == 0) { + return "never called"; + } else { + return "called " + times(callCount); + } + } + + function expectedCallCountInWords(expectation) { + var min = expectation.minCalls; + var max = expectation.maxCalls; + + if (typeof min == "number" && typeof max == "number") { + var str = times(min); + + if (min != max) { + str = "at least " + str + " and at most " + times(max); + } + + return str; + } + + if (typeof min == "number") { + return "at least " + times(min); + } + + return "at most " + times(max); + } + + function receivedMinCalls(expectation) { + var hasMinLimit = typeof expectation.minCalls == "number"; + return !hasMinLimit || expectation.callCount >= expectation.minCalls; + } + + function receivedMaxCalls(expectation) { + if (typeof expectation.maxCalls != "number") { + return false; + } + + return expectation.callCount == expectation.maxCalls; + } + + function verifyMatcher(possibleMatcher, arg) { + if (match && match.isMatcher(possibleMatcher)) { + return possibleMatcher.test(arg); + } else { + return true; + } + } + + sinon.expectation = { + minCalls: 1, + maxCalls: 1, + + create: function create(methodName) { + var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); + delete expectation.create; + expectation.method = methodName; + + return expectation; + }, + + invoke: function invoke(func, thisValue, args) { + this.verifyCallAllowed(thisValue, args); + + return sinon.spy.invoke.apply(this, arguments); + }, + + atLeast: function atLeast(num) { + if (typeof num != "number") { + throw new TypeError("'" + num + "' is not number"); + } + + if (!this.limitsSet) { + this.maxCalls = null; + this.limitsSet = true; + } + + this.minCalls = num; + + return this; + }, + + atMost: function atMost(num) { + if (typeof num != "number") { + throw new TypeError("'" + num + "' is not number"); + } + + if (!this.limitsSet) { + this.minCalls = null; + this.limitsSet = true; + } + + this.maxCalls = num; + + return this; + }, + + never: function never() { + return this.exactly(0); + }, + + once: function once() { + return this.exactly(1); + }, + + twice: function twice() { + return this.exactly(2); + }, + + thrice: function thrice() { + return this.exactly(3); + }, + + exactly: function exactly(num) { + if (typeof num != "number") { + throw new TypeError("'" + num + "' is not a number"); + } + + this.atLeast(num); + return this.atMost(num); + }, + + met: function met() { + return !this.failed && receivedMinCalls(this); + }, + + verifyCallAllowed: function verifyCallAllowed(thisValue, args) { + if (receivedMaxCalls(this)) { + this.failed = true; + sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); + } + + if ("expectedThis" in this && this.expectedThis !== thisValue) { + sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + + this.expectedThis); + } + + if (!("expectedArguments" in this)) { + return; + } + + if (!args) { + sinon.expectation.fail(this.method + " received no arguments, expected " + + sinon.format(this.expectedArguments)); + } + + if (args.length < this.expectedArguments.length) { + sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) + + "), expected " + sinon.format(this.expectedArguments)); + } + + if (this.expectsExactArgCount && + args.length != this.expectedArguments.length) { + sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) + + "), expected " + sinon.format(this.expectedArguments)); + } + + for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { + + if (!verifyMatcher(this.expectedArguments[i], args[i])) { + sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + + ", didn't match " + this.expectedArguments.toString()); + } + + if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { + sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + + ", expected " + sinon.format(this.expectedArguments)); + } + } + }, + + allowsCall: function allowsCall(thisValue, args) { + if (this.met() && receivedMaxCalls(this)) { + return false; + } + + if ("expectedThis" in this && this.expectedThis !== thisValue) { + return false; + } + + if (!("expectedArguments" in this)) { + return true; + } + + args = args || []; + + if (args.length < this.expectedArguments.length) { + return false; + } + + if (this.expectsExactArgCount && + args.length != this.expectedArguments.length) { + return false; + } + + for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { + if (!verifyMatcher(this.expectedArguments[i], args[i])) { + return false; + } + + if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { + return false; + } + } + + return true; + }, + + withArgs: function withArgs() { + this.expectedArguments = slice.call(arguments); + return this; + }, + + withExactArgs: function withExactArgs() { + this.withArgs.apply(this, arguments); + this.expectsExactArgCount = true; + return this; + }, + + on: function on(thisValue) { + this.expectedThis = thisValue; + return this; + }, + + toString: function () { + var args = (this.expectedArguments || []).slice(); + + if (!this.expectsExactArgCount) { + push.call(args, "[...]"); + } + + var callStr = sinon.spyCall.toString.call({ + proxy: this.method || "anonymous mock expectation", + args: args + }); + + var message = callStr.replace(", [...", "[, ...") + " " + + expectedCallCountInWords(this); + + if (this.met()) { + return "Expectation met: " + message; + } + + return "Expected " + message + " (" + + callCountInWords(this.callCount) + ")"; + }, + + verify: function verify() { + if (!this.met()) { + sinon.expectation.fail(this.toString()); + } else { + sinon.expectation.pass(this.toString()); + } + + return true; + }, + + pass: function pass(message) { + sinon.assert.pass(message); + }, + + fail: function fail(message) { + var exception = new Error(message); + exception.name = "ExpectationError"; + + throw exception; + } + }; + + sinon.mock = mock; + return mock; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./times_in_words"); + require("./call"); + require("./extend"); + require("./match"); + require("./spy"); + require("./stub"); + require("./format"); + + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./call":27,"./extend":29,"./format":30,"./match":32,"./spy":35,"./stub":36,"./times_in_words":39,"./util/core":41}],34:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend extend.js + * @depend collection.js + * @depend util/fake_timers.js + * @depend util/fake_server_with_clock.js + */ +/** + * Manages fake collections as well as fake utilities such as Sinon's + * timers and fake XHR implementation in one convenient object. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function () { + function makeApi(sinon) { + var push = [].push; + + function exposeValue(sandbox, config, key, value) { + if (!value) { + return; + } + + if (config.injectInto && !(key in config.injectInto)) { + config.injectInto[key] = value; + sandbox.injectedKeys.push(key); + } else { + push.call(sandbox.args, value); + } + } + + function prepareSandboxFromConfig(config) { + var sandbox = sinon.create(sinon.sandbox); + + if (config.useFakeServer) { + if (typeof config.useFakeServer == "object") { + sandbox.serverPrototype = config.useFakeServer; + } + + sandbox.useFakeServer(); + } + + if (config.useFakeTimers) { + if (typeof config.useFakeTimers == "object") { + sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); + } else { + sandbox.useFakeTimers(); + } + } + + return sandbox; + } + + sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { + useFakeTimers: function useFakeTimers() { + this.clock = sinon.useFakeTimers.apply(sinon, arguments); + + return this.add(this.clock); + }, + + serverPrototype: sinon.fakeServer, + + useFakeServer: function useFakeServer() { + var proto = this.serverPrototype || sinon.fakeServer; + + if (!proto || !proto.create) { + return null; + } + + this.server = proto.create(); + return this.add(this.server); + }, + + inject: function (obj) { + sinon.collection.inject.call(this, obj); + + if (this.clock) { + obj.clock = this.clock; + } + + if (this.server) { + obj.server = this.server; + obj.requests = this.server.requests; + } + + obj.match = sinon.match; + + return obj; + }, + + restore: function () { + sinon.collection.restore.apply(this, arguments); + this.restoreContext(); + }, + + restoreContext: function () { + if (this.injectedKeys) { + for (var i = 0, j = this.injectedKeys.length; i < j; i++) { + delete this.injectInto[this.injectedKeys[i]]; + } + this.injectedKeys = []; + } + }, + + create: function (config) { + if (!config) { + return sinon.create(sinon.sandbox); + } + + var sandbox = prepareSandboxFromConfig(config); + sandbox.args = sandbox.args || []; + sandbox.injectedKeys = []; + sandbox.injectInto = config.injectInto; + var prop, value, exposed = sandbox.inject({}); + + if (config.properties) { + for (var i = 0, l = config.properties.length; i < l; i++) { + prop = config.properties[i]; + value = exposed[prop] || prop == "sandbox" && sandbox; + exposeValue(sandbox, config, prop, value); + } + } else { + exposeValue(sandbox, config, "sandbox", value); + } + + return sandbox; + }, + + match: sinon.match + }); + + sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; + + return sinon.sandbox; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./extend"); + require("./util/fake_server_with_clock"); + require("./util/fake_timers"); + require("./collection"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}()); + +},{"./collection":28,"./extend":29,"./util/core":41,"./util/fake_server_with_clock":44,"./util/fake_timers":45}],35:[function(require,module,exports){ +/** + * @depend times_in_words.js + * @depend util/core.js + * @depend extend.js + * @depend call.js + * @depend format.js + */ +/** + * Spy functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + + function makeApi(sinon) { + var push = Array.prototype.push; + var slice = Array.prototype.slice; + var callId = 0; + + function spy(object, property, types) { + if (!property && typeof object == "function") { + return spy.create(object); + } + + if (!object && !property) { + return spy.create(function () { }); + } + + if (types) { + var methodDesc = sinon.getPropertyDescriptor(object, property); + for (var i = 0; i < types.length; i++) { + methodDesc[types[i]] = spy.create(methodDesc[types[i]]); + } + return sinon.wrapMethod(object, property, methodDesc); + } else { + var method = object[property]; + return sinon.wrapMethod(object, property, spy.create(method)); + } + } + + function matchingFake(fakes, args, strict) { + if (!fakes) { + return; + } + + for (var i = 0, l = fakes.length; i < l; i++) { + if (fakes[i].matches(args, strict)) { + return fakes[i]; + } + } + } + + function incrementCallCount() { + this.called = true; + this.callCount += 1; + this.notCalled = false; + this.calledOnce = this.callCount == 1; + this.calledTwice = this.callCount == 2; + this.calledThrice = this.callCount == 3; + } + + function createCallProperties() { + this.firstCall = this.getCall(0); + this.secondCall = this.getCall(1); + this.thirdCall = this.getCall(2); + this.lastCall = this.getCall(this.callCount - 1); + } + + var vars = "a,b,c,d,e,f,g,h,i,j,k,l"; + function createProxy(func, proxyLength) { + // Retain the function length: + var p; + if (proxyLength) { + eval("p = (function proxy(" + vars.substring(0, proxyLength * 2 - 1) + + ") { return p.invoke(func, this, slice.call(arguments)); });"); + } else { + p = function proxy() { + return p.invoke(func, this, slice.call(arguments)); + }; + } + return p; + } + + var uuid = 0; + + // Public API + var spyApi = { + reset: function () { + if (this.invoking) { + var err = new Error("Cannot reset Sinon function while invoking it. " + + "Move the call to .reset outside of the callback."); + err.name = "InvalidResetException"; + throw err; + } + + this.called = false; + this.notCalled = true; + this.calledOnce = false; + this.calledTwice = false; + this.calledThrice = false; + this.callCount = 0; + this.firstCall = null; + this.secondCall = null; + this.thirdCall = null; + this.lastCall = null; + this.args = []; + this.returnValues = []; + this.thisValues = []; + this.exceptions = []; + this.callIds = []; + if (this.fakes) { + for (var i = 0; i < this.fakes.length; i++) { + this.fakes[i].reset(); + } + } + + return this; + }, + + create: function create(func, spyLength) { + var name; + + if (typeof func != "function") { + func = function () { }; + } else { + name = sinon.functionName(func); + } + + if (!spyLength) { + spyLength = func.length; + } + + var proxy = createProxy(func, spyLength); + + sinon.extend(proxy, spy); + delete proxy.create; + sinon.extend(proxy, func); + + proxy.reset(); + proxy.prototype = func.prototype; + proxy.displayName = name || "spy"; + proxy.toString = sinon.functionToString; + proxy.instantiateFake = sinon.spy.create; + proxy.id = "spy#" + uuid++; + + return proxy; + }, + + invoke: function invoke(func, thisValue, args) { + var matching = matchingFake(this.fakes, args); + var exception, returnValue; + + incrementCallCount.call(this); + push.call(this.thisValues, thisValue); + push.call(this.args, args); + push.call(this.callIds, callId++); + + // Make call properties available from within the spied function: + createCallProperties.call(this); + + try { + this.invoking = true; + + if (matching) { + returnValue = matching.invoke(func, thisValue, args); + } else { + returnValue = (this.func || func).apply(thisValue, args); + } + + var thisCall = this.getCall(this.callCount - 1); + if (thisCall.calledWithNew() && typeof returnValue !== "object") { + returnValue = thisValue; + } + } catch (e) { + exception = e; + } finally { + delete this.invoking; + } + + push.call(this.exceptions, exception); + push.call(this.returnValues, returnValue); + + // Make return value and exception available in the calls: + createCallProperties.call(this); + + if (exception !== undefined) { + throw exception; + } + + return returnValue; + }, + + named: function named(name) { + this.displayName = name; + return this; + }, + + getCall: function getCall(i) { + if (i < 0 || i >= this.callCount) { + return null; + } + + return sinon.spyCall(this, this.thisValues[i], this.args[i], + this.returnValues[i], this.exceptions[i], + this.callIds[i]); + }, + + getCalls: function () { + var calls = []; + var i; + + for (i = 0; i < this.callCount; i++) { + calls.push(this.getCall(i)); + } + + return calls; + }, + + calledBefore: function calledBefore(spyFn) { + if (!this.called) { + return false; + } + + if (!spyFn.called) { + return true; + } + + return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; + }, + + calledAfter: function calledAfter(spyFn) { + if (!this.called || !spyFn.called) { + return false; + } + + return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; + }, + + withArgs: function () { + var args = slice.call(arguments); + + if (this.fakes) { + var match = matchingFake(this.fakes, args, true); + + if (match) { + return match; + } + } else { + this.fakes = []; + } + + var original = this; + var fake = this.instantiateFake(); + fake.matchingAguments = args; + fake.parent = this; + push.call(this.fakes, fake); + + fake.withArgs = function () { + return original.withArgs.apply(original, arguments); + }; + + for (var i = 0; i < this.args.length; i++) { + if (fake.matches(this.args[i])) { + incrementCallCount.call(fake); + push.call(fake.thisValues, this.thisValues[i]); + push.call(fake.args, this.args[i]); + push.call(fake.returnValues, this.returnValues[i]); + push.call(fake.exceptions, this.exceptions[i]); + push.call(fake.callIds, this.callIds[i]); + } + } + createCallProperties.call(fake); + + return fake; + }, + + matches: function (args, strict) { + var margs = this.matchingAguments; + + if (margs.length <= args.length && + sinon.deepEqual(margs, args.slice(0, margs.length))) { + return !strict || margs.length == args.length; + } + }, + + printf: function (format) { + var spy = this; + var args = slice.call(arguments, 1); + var formatter; + + return (format || "").replace(/%(.)/g, function (match, specifyer) { + formatter = spyApi.formatters[specifyer]; + + if (typeof formatter == "function") { + return formatter.call(null, spy, args); + } else if (!isNaN(parseInt(specifyer, 10))) { + return sinon.format(args[specifyer - 1]); + } + + return "%" + specifyer; + }); + } + }; + + function delegateToCalls(method, matchAny, actual, notCalled) { + spyApi[method] = function () { + if (!this.called) { + if (notCalled) { + return notCalled.apply(this, arguments); + } + return false; + } + + var currentCall; + var matches = 0; + + for (var i = 0, l = this.callCount; i < l; i += 1) { + currentCall = this.getCall(i); + + if (currentCall[actual || method].apply(currentCall, arguments)) { + matches += 1; + + if (matchAny) { + return true; + } + } + } + + return matches === this.callCount; + }; + } + + delegateToCalls("calledOn", true); + delegateToCalls("alwaysCalledOn", false, "calledOn"); + delegateToCalls("calledWith", true); + delegateToCalls("calledWithMatch", true); + delegateToCalls("alwaysCalledWith", false, "calledWith"); + delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch"); + delegateToCalls("calledWithExactly", true); + delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly"); + delegateToCalls("neverCalledWith", false, "notCalledWith", + function () { return true; }); + delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", + function () { return true; }); + delegateToCalls("threw", true); + delegateToCalls("alwaysThrew", false, "threw"); + delegateToCalls("returned", true); + delegateToCalls("alwaysReturned", false, "returned"); + delegateToCalls("calledWithNew", true); + delegateToCalls("alwaysCalledWithNew", false, "calledWithNew"); + delegateToCalls("callArg", false, "callArgWith", function () { + throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); + }); + spyApi.callArgWith = spyApi.callArg; + delegateToCalls("callArgOn", false, "callArgOnWith", function () { + throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); + }); + spyApi.callArgOnWith = spyApi.callArgOn; + delegateToCalls("yield", false, "yield", function () { + throw new Error(this.toString() + " cannot yield since it was not yet invoked."); + }); + // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. + spyApi.invokeCallback = spyApi.yield; + delegateToCalls("yieldOn", false, "yieldOn", function () { + throw new Error(this.toString() + " cannot yield since it was not yet invoked."); + }); + delegateToCalls("yieldTo", false, "yieldTo", function (property) { + throw new Error(this.toString() + " cannot yield to '" + property + + "' since it was not yet invoked."); + }); + delegateToCalls("yieldToOn", false, "yieldToOn", function (property) { + throw new Error(this.toString() + " cannot yield to '" + property + + "' since it was not yet invoked."); + }); + + spyApi.formatters = { + c: function (spy) { + return sinon.timesInWords(spy.callCount); + }, + + n: function (spy) { + return spy.toString(); + }, + + C: function (spy) { + var calls = []; + + for (var i = 0, l = spy.callCount; i < l; ++i) { + var stringifiedCall = " " + spy.getCall(i).toString(); + if (/\n/.test(calls[i - 1])) { + stringifiedCall = "\n" + stringifiedCall; + } + push.call(calls, stringifiedCall); + } + + return calls.length > 0 ? "\n" + calls.join("\n") : ""; + }, + + t: function (spy) { + var objects = []; + + for (var i = 0, l = spy.callCount; i < l; ++i) { + push.call(objects, sinon.format(spy.thisValues[i])); + } + + return objects.join(", "); + }, + + "*": function (spy, args) { + var formatted = []; + + for (var i = 0, l = args.length; i < l; ++i) { + push.call(formatted, sinon.format(args[i])); + } + + return formatted.join(", "); + } + }; + + sinon.extend(spy, spyApi); + + spy.spyCall = sinon.spyCall; + sinon.spy = spy; + + return spy; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./call"); + require("./extend"); + require("./times_in_words"); + require("./format"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./call":27,"./extend":29,"./format":30,"./times_in_words":39,"./util/core":41}],36:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend extend.js + * @depend spy.js + * @depend behavior.js + */ +/** + * Stub functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + function stub(object, property, func) { + if (!!func && typeof func != "function" && typeof func != "object") { + throw new TypeError("Custom stub should be a function or a property descriptor"); + } + + var wrapper; + + if (func) { + if (typeof func == "function") { + wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; + } else { + wrapper = func; + if (sinon.spy && sinon.spy.create) { + var types = sinon.objectKeys(wrapper); + for (var i = 0; i < types.length; i++) { + wrapper[types[i]] = sinon.spy.create(wrapper[types[i]]); + } + } + } + } else { + var stubLength = 0; + if (typeof object == "object" && typeof object[property] == "function") { + stubLength = object[property].length; + } + wrapper = stub.create(stubLength); + } + + if (!object && typeof property === "undefined") { + return sinon.stub.create(); + } + + if (typeof property === "undefined" && typeof object == "object") { + for (var prop in object) { + if (typeof object[prop] === "function") { + stub(object, prop); + } + } + + return object; + } + + return sinon.wrapMethod(object, property, wrapper); + } + + function getDefaultBehavior(stub) { + return stub.defaultBehavior || getParentBehaviour(stub) || sinon.behavior.create(stub); + } + + function getParentBehaviour(stub) { + return (stub.parent && getCurrentBehavior(stub.parent)); + } + + function getCurrentBehavior(stub) { + var behavior = stub.behaviors[stub.callCount - 1]; + return behavior && behavior.isPresent() ? behavior : getDefaultBehavior(stub); + } + + var uuid = 0; + + var proto = { + create: function create(stubLength) { + var functionStub = function () { + return getCurrentBehavior(functionStub).invoke(this, arguments); + }; + + functionStub.id = "stub#" + uuid++; + var orig = functionStub; + functionStub = sinon.spy.create(functionStub, stubLength); + functionStub.func = orig; + + sinon.extend(functionStub, stub); + functionStub.instantiateFake = sinon.stub.create; + functionStub.displayName = "stub"; + functionStub.toString = sinon.functionToString; + + functionStub.defaultBehavior = null; + functionStub.behaviors = []; + + return functionStub; + }, + + resetBehavior: function () { + var i; + + this.defaultBehavior = null; + this.behaviors = []; + + delete this.returnValue; + delete this.returnArgAt; + this.returnThis = false; + + if (this.fakes) { + for (i = 0; i < this.fakes.length; i++) { + this.fakes[i].resetBehavior(); + } + } + }, + + onCall: function onCall(index) { + if (!this.behaviors[index]) { + this.behaviors[index] = sinon.behavior.create(this); + } + + return this.behaviors[index]; + }, + + onFirstCall: function onFirstCall() { + return this.onCall(0); + }, + + onSecondCall: function onSecondCall() { + return this.onCall(1); + }, + + onThirdCall: function onThirdCall() { + return this.onCall(2); + } + }; + + for (var method in sinon.behavior) { + if (sinon.behavior.hasOwnProperty(method) && + !proto.hasOwnProperty(method) && + method != "create" && + method != "withArgs" && + method != "invoke") { + proto[method] = (function (behaviorMethod) { + return function () { + this.defaultBehavior = this.defaultBehavior || sinon.behavior.create(this); + this.defaultBehavior[behaviorMethod].apply(this.defaultBehavior, arguments); + return this; + }; + }(method)); + } + } + + sinon.extend(stub, proto); + sinon.stub = stub; + + return stub; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./behavior"); + require("./spy"); + require("./extend"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./behavior":26,"./extend":29,"./spy":35,"./util/core":41}],37:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend sandbox.js + */ +/** + * Test function, sandboxes fakes + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + var slice = Array.prototype.slice; + + function test(callback) { + var type = typeof callback; + + if (type != "function") { + throw new TypeError("sinon.test needs to wrap a test function, got " + type); + } + + function sinonSandboxedTest() { + var config = sinon.getConfig(sinon.config); + config.injectInto = config.injectIntoThis && this || config.injectInto; + var sandbox = sinon.sandbox.create(config); + var args = slice.call(arguments); + var oldDone = args.length && args[args.length - 1]; + var exception, result; + + if (typeof oldDone == "function") { + args[args.length - 1] = function sinonDone(result) { + if (result) { + sandbox.restore(); + throw exception; + } else { + sandbox.verifyAndRestore(); + } + oldDone(result); + }; + } + + try { + result = callback.apply(this, args.concat(sandbox.args)); + } catch (e) { + exception = e; + } + + if (typeof oldDone != "function") { + if (typeof exception !== "undefined") { + sandbox.restore(); + throw exception; + } else { + sandbox.verifyAndRestore(); + } + } + + return result; + } + + if (callback.length) { + return function sinonAsyncSandboxedTest(callback) { + return sinonSandboxedTest.apply(this, arguments); + }; + } + + return sinonSandboxedTest; + } + + test.config = { + injectIntoThis: true, + injectInto: null, + properties: ["spy", "stub", "mock", "clock", "server", "requests"], + useFakeTimers: true, + useFakeServer: true + }; + + sinon.test = test; + return test; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./sandbox"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (sinon) { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./sandbox":34,"./util/core":41}],38:[function(require,module,exports){ +/** + * @depend util/core.js + * @depend test.js + */ +/** + * Test case, sandboxes all test functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + function createTest(property, setUp, tearDown) { + return function () { + if (setUp) { + setUp.apply(this, arguments); + } + + var exception, result; + + try { + result = property.apply(this, arguments); + } catch (e) { + exception = e; + } + + if (tearDown) { + tearDown.apply(this, arguments); + } + + if (exception) { + throw exception; + } + + return result; + }; + } + + function makeApi(sinon) { + function testCase(tests, prefix) { + /*jsl:ignore*/ + if (!tests || typeof tests != "object") { + throw new TypeError("sinon.testCase needs an object with test functions"); + } + /*jsl:end*/ + + prefix = prefix || "test"; + var rPrefix = new RegExp("^" + prefix); + var methods = {}, testName, property, method; + var setUp = tests.setUp; + var tearDown = tests.tearDown; + + for (testName in tests) { + if (tests.hasOwnProperty(testName)) { + property = tests[testName]; + + if (/^(setUp|tearDown)$/.test(testName)) { + continue; + } + + if (typeof property == "function" && rPrefix.test(testName)) { + method = property; + + if (setUp || tearDown) { + method = createTest(property, setUp, tearDown); + } + + methods[testName] = sinon.test(method); + } else { + methods[testName] = tests[testName]; + } + } + } + + return methods; + } + + sinon.testCase = testCase; + return testCase; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + require("./test"); + module.exports = makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./test":37,"./util/core":41}],39:[function(require,module,exports){ +/** + * @depend util/core.js + */ +"use strict"; + +(function (sinon) { + function makeApi(sinon) { + + function timesInWords(count) { + switch (count) { + case 1: + return "once"; + case 2: + return "twice"; + case 3: + return "thrice"; + default: + return (count || 0) + " times"; + } + } + + sinon.timesInWords = timesInWords; + return sinon.timesInWords; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{"./util/core":41}],40:[function(require,module,exports){ +/** + * @depend util/core.js + */ +/** + * Format functions + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2014 Christian Johansen + */ +"use strict"; + +(function (sinon, formatio) { + function makeApi(sinon) { + function typeOf(value) { + if (value === null) { + return "null"; + } else if (value === undefined) { + return "undefined"; + } + var string = Object.prototype.toString.call(value); + return string.substring(8, string.length - 1).toLowerCase(); + }; + + sinon.typeOf = typeOf; + return sinon.typeOf; + } + + function loadDependencies(require, exports, module) { + var sinon = require("./util/core"); + module.exports = makeApi(sinon); + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}( + (typeof sinon == "object" && sinon || null), + (typeof formatio == "object" && formatio) +)); + +},{"./util/core":41}],41:[function(require,module,exports){ +/** + * @depend ../../sinon.js + */ +/** + * Sinon core utilities. For internal use only. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (sinon) { + var div = typeof document != "undefined" && document.createElement("div"); + var hasOwn = Object.prototype.hasOwnProperty; + + function isDOMNode(obj) { + var success = false; + + try { + obj.appendChild(div); + success = div.parentNode == obj; + } catch (e) { + return false; + } finally { + try { + obj.removeChild(div); + } catch (e) { + // Remove failed, not much we can do about that + } + } + + return success; + } + + function isElement(obj) { + return div && obj && obj.nodeType === 1 && isDOMNode(obj); + } + + function isFunction(obj) { + return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply); + } + + function isReallyNaN(val) { + return typeof val === "number" && isNaN(val); + } + + function mirrorProperties(target, source) { + for (var prop in source) { + if (!hasOwn.call(target, prop)) { + target[prop] = source[prop]; + } + } + } + + function isRestorable(obj) { + return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon; + } + + // Cheap way to detect if we have ES5 support. + var hasES5Support = "keys" in Object; + + function makeApi(sinon) { + sinon.wrapMethod = function wrapMethod(object, property, method) { + if (!object) { + throw new TypeError("Should wrap property of object"); + } + + if (typeof method != "function" && typeof method != "object") { + throw new TypeError("Method wrapper should be a function or a property descriptor"); + } + + function checkWrappedMethod(wrappedMethod) { + if (!isFunction(wrappedMethod)) { + error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + + property + " as function"); + } else if (wrappedMethod.restore && wrappedMethod.restore.sinon) { + error = new TypeError("Attempted to wrap " + property + " which is already wrapped"); + } else if (wrappedMethod.calledBefore) { + var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; + error = new TypeError("Attempted to wrap " + property + " which is already " + verb); + } + + if (error) { + if (wrappedMethod && wrappedMethod.stackTrace) { + error.stack += "\n--------------\n" + wrappedMethod.stackTrace; + } + throw error; + } + } + + var error, wrappedMethod; + + // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem + // when using hasOwn.call on objects from other frames. + var owned = object.hasOwnProperty ? object.hasOwnProperty(property) : hasOwn.call(object, property); + + if (hasES5Support) { + var methodDesc = (typeof method == "function") ? {value: method} : method, + wrappedMethodDesc = sinon.getPropertyDescriptor(object, property), + i; + + if (!wrappedMethodDesc) { + error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + + property + " as function"); + } else if (wrappedMethodDesc.restore && wrappedMethodDesc.restore.sinon) { + error = new TypeError("Attempted to wrap " + property + " which is already wrapped"); + } + if (error) { + if (wrappedMethodDesc && wrappedMethodDesc.stackTrace) { + error.stack += "\n--------------\n" + wrappedMethodDesc.stackTrace; + } + throw error; + } + + var types = sinon.objectKeys(methodDesc); + for (i = 0; i < types.length; i++) { + wrappedMethod = wrappedMethodDesc[types[i]]; + checkWrappedMethod(wrappedMethod); + } + + mirrorProperties(methodDesc, wrappedMethodDesc); + for (i = 0; i < types.length; i++) { + mirrorProperties(methodDesc[types[i]], wrappedMethodDesc[types[i]]); + } + Object.defineProperty(object, property, methodDesc); + } else { + wrappedMethod = object[property]; + checkWrappedMethod(wrappedMethod); + object[property] = method; + method.displayName = property; + } + + method.displayName = property; + + // Set up a stack trace which can be used later to find what line of + // code the original method was created on. + method.stackTrace = (new Error("Stack Trace for original")).stack; + + method.restore = function () { + // For prototype properties try to reset by delete first. + // If this fails (ex: localStorage on mobile safari) then force a reset + // via direct assignment. + if (!owned) { + try { + delete object[property]; + } catch (e) {} + // For native code functions `delete` fails without throwing an error + // on Chrome < 43, PhantomJS, etc. + // Use strict equality comparison to check failures then force a reset + // via direct assignment. + if (object[property] === method) { + object[property] = wrappedMethod; + } + } else if (hasES5Support) { + Object.defineProperty(object, property, wrappedMethodDesc); + } + + if (!hasES5Support && object[property] === method) { + object[property] = wrappedMethod; + } + }; + + method.restore.sinon = true; + + if (!hasES5Support) { + mirrorProperties(method, wrappedMethod); + } + + return method; + }; + + sinon.create = function create(proto) { + var F = function () {}; + F.prototype = proto; + return new F(); + }; + + sinon.deepEqual = function deepEqual(a, b) { + if (sinon.match && sinon.match.isMatcher(a)) { + return a.test(b); + } + + if (typeof a != "object" || typeof b != "object") { + if (isReallyNaN(a) && isReallyNaN(b)) { + return true; + } else { + return a === b; + } + } + + if (isElement(a) || isElement(b)) { + return a === b; + } + + if (a === b) { + return true; + } + + if ((a === null && b !== null) || (a !== null && b === null)) { + return false; + } + + if (a instanceof RegExp && b instanceof RegExp) { + return (a.source === b.source) && (a.global === b.global) && + (a.ignoreCase === b.ignoreCase) && (a.multiline === b.multiline); + } + + var aString = Object.prototype.toString.call(a); + if (aString != Object.prototype.toString.call(b)) { + return false; + } + + if (aString == "[object Date]") { + return a.valueOf() === b.valueOf(); + } + + var prop, aLength = 0, bLength = 0; + + if (aString == "[object Array]" && a.length !== b.length) { + return false; + } + + for (prop in a) { + aLength += 1; + + if (!(prop in b)) { + return false; + } + + if (!deepEqual(a[prop], b[prop])) { + return false; + } + } + + for (prop in b) { + bLength += 1; + } + + return aLength == bLength; + }; + + sinon.functionName = function functionName(func) { + var name = func.displayName || func.name; + + // Use function decomposition as a last resort to get function + // name. Does not rely on function decomposition to work - if it + // doesn't debugging will be slightly less informative + // (i.e. toString will say 'spy' rather than 'myFunc'). + if (!name) { + var matches = func.toString().match(/function ([^\s\(]+)/); + name = matches && matches[1]; + } + + return name; + }; + + sinon.functionToString = function toString() { + if (this.getCall && this.callCount) { + var thisValue, prop, i = this.callCount; + + while (i--) { + thisValue = this.getCall(i).thisValue; + + for (prop in thisValue) { + if (thisValue[prop] === this) { + return prop; + } + } + } + } + + return this.displayName || "sinon fake"; + }; + + sinon.objectKeys = function objectKeys(obj) { + if (obj !== Object(obj)) { + throw new TypeError("sinon.objectKeys called on a non-object"); + } + + var keys = []; + var key; + for (key in obj) { + if (hasOwn.call(obj, key)) { + keys.push(key); + } + } + + return keys; + }; + + sinon.getPropertyDescriptor = function getPropertyDescriptor(object, property) { + var proto = object, descriptor; + while (proto && !(descriptor = Object.getOwnPropertyDescriptor(proto, property))) { + proto = Object.getPrototypeOf(proto); + } + return descriptor; + } + + sinon.getConfig = function (custom) { + var config = {}; + custom = custom || {}; + var defaults = sinon.defaultConfig; + + for (var prop in defaults) { + if (defaults.hasOwnProperty(prop)) { + config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; + } + } + + return config; + }; + + sinon.defaultConfig = { + injectIntoThis: true, + injectInto: null, + properties: ["spy", "stub", "mock", "clock", "server", "requests"], + useFakeTimers: true, + useFakeServer: true + }; + + sinon.timesInWords = function timesInWords(count) { + return count == 1 && "once" || + count == 2 && "twice" || + count == 3 && "thrice" || + (count || 0) + " times"; + }; + + sinon.calledInOrder = function (spies) { + for (var i = 1, l = spies.length; i < l; i++) { + if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) { + return false; + } + } + + return true; + }; + + sinon.orderByFirstCall = function (spies) { + return spies.sort(function (a, b) { + // uuid, won't ever be equal + var aCall = a.getCall(0); + var bCall = b.getCall(0); + var aId = aCall && aCall.callId || -1; + var bId = bCall && bCall.callId || -1; + + return aId < bId ? -1 : 1; + }); + }; + + sinon.createStubInstance = function (constructor) { + if (typeof constructor !== "function") { + throw new TypeError("The constructor should be a function."); + } + return sinon.stub(sinon.create(constructor.prototype)); + }; + + sinon.restore = function (object) { + if (object !== null && typeof object === "object") { + for (var prop in object) { + if (isRestorable(object[prop])) { + object[prop].restore(); + } + } + } else if (isRestorable(object)) { + object.restore(); + } + }; + + return sinon; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports) { + makeApi(exports); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports); + } else if (!sinon) { + return; + } else { + makeApi(sinon); + } +}(typeof sinon == "object" && sinon || null)); + +},{}],42:[function(require,module,exports){ +/** + * Minimal Event interface implementation + * + * Original implementation by Sven Fuchs: https://gist.github.com/995028 + * Modifications and tests by Christian Johansen. + * + * @author Sven Fuchs (svenfuchs@artweb-design.de) + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2011 Sven Fuchs, Christian Johansen + */ +"use strict"; + +if (typeof sinon == "undefined") { + this.sinon = {}; +} + +(function () { + var push = [].push; + + function makeApi(sinon) { + sinon.Event = function Event(type, bubbles, cancelable, target) { + this.initEvent(type, bubbles, cancelable, target); + }; + + sinon.Event.prototype = { + initEvent: function (type, bubbles, cancelable, target) { + this.type = type; + this.bubbles = bubbles; + this.cancelable = cancelable; + this.target = target; + }, + + stopPropagation: function () {}, + + preventDefault: function () { + this.defaultPrevented = true; + } + }; + + sinon.ProgressEvent = function ProgressEvent(type, progressEventRaw, target) { + this.initEvent(type, false, false, target); + this.loaded = progressEventRaw.loaded || null; + this.total = progressEventRaw.total || null; + this.lengthComputable = !!progressEventRaw.total; + }; + + sinon.ProgressEvent.prototype = new sinon.Event(); + + sinon.ProgressEvent.prototype.constructor = sinon.ProgressEvent; + + sinon.CustomEvent = function CustomEvent(type, customData, target) { + this.initEvent(type, false, false, target); + this.detail = customData.detail || null; + }; + + sinon.CustomEvent.prototype = new sinon.Event(); + + sinon.CustomEvent.prototype.constructor = sinon.CustomEvent; + + sinon.EventTarget = { + addEventListener: function addEventListener(event, listener) { + this.eventListeners = this.eventListeners || {}; + this.eventListeners[event] = this.eventListeners[event] || []; + push.call(this.eventListeners[event], listener); + }, + + removeEventListener: function removeEventListener(event, listener) { + var listeners = this.eventListeners && this.eventListeners[event] || []; + + for (var i = 0, l = listeners.length; i < l; ++i) { + if (listeners[i] == listener) { + return listeners.splice(i, 1); + } + } + }, + + dispatchEvent: function dispatchEvent(event) { + var type = event.type; + var listeners = this.eventListeners && this.eventListeners[type] || []; + + for (var i = 0; i < listeners.length; i++) { + if (typeof listeners[i] == "function") { + listeners[i].call(this, event); + } else { + listeners[i].handleEvent(event); + } + } + + return !!event.defaultPrevented; + } + }; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require) { + var sinon = require("./core"); + makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require); + } else { + makeApi(sinon); + } +}()); + +},{"./core":41}],43:[function(require,module,exports){ +/** + * @depend fake_xdomain_request.js + * @depend fake_xml_http_request.js + * @depend ../format.js + * @depend ../log_error.js + */ +/** + * The Sinon "server" mimics a web server that receives requests from + * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, + * both synchronously and asynchronously. To respond synchronuously, canned + * answers have to be provided upfront. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +if (typeof sinon == "undefined") { + var sinon = {}; +} + +(function () { + var push = [].push; + function F() {} + + function create(proto) { + F.prototype = proto; + return new F(); + } + + function responseArray(handler) { + var response = handler; + + if (Object.prototype.toString.call(handler) != "[object Array]") { + response = [200, {}, handler]; + } + + if (typeof response[2] != "string") { + throw new TypeError("Fake server response body should be string, but was " + + typeof response[2]); + } + + return response; + } + + var wloc = typeof window !== "undefined" ? window.location : {}; + var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); + + function matchOne(response, reqMethod, reqUrl) { + var rmeth = response.method; + var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); + var url = response.url; + var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); + + return matchMethod && matchUrl; + } + + function match(response, request) { + var requestUrl = request.url; + + if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { + requestUrl = requestUrl.replace(rCurrLoc, ""); + } + + if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { + if (typeof response.response == "function") { + var ru = response.url; + var args = [request].concat(ru && typeof ru.exec == "function" ? ru.exec(requestUrl).slice(1) : []); + return response.response.apply(response, args); + } + + return true; + } + + return false; + } + + function makeApi(sinon) { + sinon.fakeServer = { + create: function () { + var server = create(this); + if (!sinon.xhr.supportsCORS) { + this.xhr = sinon.useFakeXDomainRequest(); + } else { + this.xhr = sinon.useFakeXMLHttpRequest(); + } + server.requests = []; + + this.xhr.onCreate = function (xhrObj) { + server.addRequest(xhrObj); + }; + + return server; + }, + + addRequest: function addRequest(xhrObj) { + var server = this; + push.call(this.requests, xhrObj); + + xhrObj.onSend = function () { + server.handleRequest(this); + + if (server.respondImmediately) { + server.respond(); + } else if (server.autoRespond && !server.responding) { + setTimeout(function () { + server.responding = false; + server.respond(); + }, server.autoRespondAfter || 10); + + server.responding = true; + } + }; + }, + + getHTTPMethod: function getHTTPMethod(request) { + if (this.fakeHTTPMethods && /post/i.test(request.method)) { + var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); + return !!matches ? matches[1] : request.method; + } + + return request.method; + }, + + handleRequest: function handleRequest(xhr) { + if (xhr.async) { + if (!this.queue) { + this.queue = []; + } + + push.call(this.queue, xhr); + } else { + this.processRequest(xhr); + } + }, + + log: function log(response, request) { + var str; + + str = "Request:\n" + sinon.format(request) + "\n\n"; + str += "Response:\n" + sinon.format(response) + "\n\n"; + + sinon.log(str); + }, + + respondWith: function respondWith(method, url, body) { + if (arguments.length == 1 && typeof method != "function") { + this.response = responseArray(method); + return; + } + + if (!this.responses) { this.responses = []; } + + if (arguments.length == 1) { + body = method; + url = method = null; + } + + if (arguments.length == 2) { + body = url; + url = method; + method = null; + } + + push.call(this.responses, { + method: method, + url: url, + response: typeof body == "function" ? body : responseArray(body) + }); + }, + + respond: function respond() { + if (arguments.length > 0) { + this.respondWith.apply(this, arguments); + } + + var queue = this.queue || []; + var requests = queue.splice(0, queue.length); + var request; + + while (request = requests.shift()) { + this.processRequest(request); + } + }, + + processRequest: function processRequest(request) { + try { + if (request.aborted) { + return; + } + + var response = this.response || [404, {}, ""]; + + if (this.responses) { + for (var l = this.responses.length, i = l - 1; i >= 0; i--) { + if (match.call(this, this.responses[i], request)) { + response = this.responses[i].response; + break; + } + } + } + + if (request.readyState != 4) { + this.log(response, request); + + request.respond(response[0], response[1], response[2]); + } + } catch (e) { + sinon.logError("Fake server request processing", e); + } + }, + + restore: function restore() { + return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); + } + }; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./core"); + require("./fake_xdomain_request"); + require("./fake_xml_http_request"); + require("../format"); + makeApi(sinon); + module.exports = sinon; + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else { + makeApi(sinon); + } +}()); + +},{"../format":30,"./core":41,"./fake_xdomain_request":46,"./fake_xml_http_request":47}],44:[function(require,module,exports){ +/** + * @depend fake_server.js + * @depend fake_timers.js + */ +/** + * Add-on for sinon.fakeServer that automatically handles a fake timer along with + * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery + * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, + * it polls the object for completion with setInterval. Dispite the direct + * motivation, there is nothing jQuery-specific in this file, so it can be used + * in any environment where the ajax implementation depends on setInterval or + * setTimeout. + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function () { + function makeApi(sinon) { + function Server() {} + Server.prototype = sinon.fakeServer; + + sinon.fakeServerWithClock = new Server(); + + sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { + if (xhr.async) { + if (typeof setTimeout.clock == "object") { + this.clock = setTimeout.clock; + } else { + this.clock = sinon.useFakeTimers(); + this.resetClock = true; + } + + if (!this.longestTimeout) { + var clockSetTimeout = this.clock.setTimeout; + var clockSetInterval = this.clock.setInterval; + var server = this; + + this.clock.setTimeout = function (fn, timeout) { + server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); + + return clockSetTimeout.apply(this, arguments); + }; + + this.clock.setInterval = function (fn, timeout) { + server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); + + return clockSetInterval.apply(this, arguments); + }; + } + } + + return sinon.fakeServer.addRequest.call(this, xhr); + }; + + sinon.fakeServerWithClock.respond = function respond() { + var returnVal = sinon.fakeServer.respond.apply(this, arguments); + + if (this.clock) { + this.clock.tick(this.longestTimeout || 0); + this.longestTimeout = 0; + + if (this.resetClock) { + this.clock.restore(); + this.resetClock = false; + } + } + + return returnVal; + }; + + sinon.fakeServerWithClock.restore = function restore() { + if (this.clock) { + this.clock.restore(); + } + + return sinon.fakeServer.restore.apply(this, arguments); + }; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require) { + var sinon = require("./core"); + require("./fake_server"); + require("./fake_timers"); + makeApi(sinon); + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require); + } else { + makeApi(sinon); + } +}()); + +},{"./core":41,"./fake_server":43,"./fake_timers":45}],45:[function(require,module,exports){ +(function (global){ +/*global lolex */ + +/** + * Fake timer API + * setTimeout + * setInterval + * clearTimeout + * clearInterval + * tick + * reset + * Date + * + * Inspired by jsUnitMockTimeOut from JsUnit + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +if (typeof sinon == "undefined") { + var sinon = {}; +} + +(function (global) { + function makeApi(sinon, lol) { + var llx = typeof lolex !== "undefined" ? lolex : lol; + + sinon.useFakeTimers = function () { + var now, methods = Array.prototype.slice.call(arguments); + + if (typeof methods[0] === "string") { + now = 0; + } else { + now = methods.shift(); + } + + var clock = llx.install(now || 0, methods); + clock.restore = clock.uninstall; + return clock; + }; + + sinon.clock = { + create: function (now) { + return llx.createClock(now); + } + }; + + sinon.timers = { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined), + clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate : undefined), + setInterval: setInterval, + clearInterval: clearInterval, + Date: Date + }; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, epxorts, module, lolex) { + var sinon = require("./core"); + makeApi(sinon, lolex); + module.exports = sinon; + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module, require("lolex")); + } else { + makeApi(sinon); + } +}(typeof global != "undefined" && typeof global !== "function" ? global : this)); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./core":41,"lolex":50}],46:[function(require,module,exports){ +/** + * @depend core.js + * @depend ../extend.js + * @depend event.js + * @depend ../log_error.js + */ +/** + * Fake XDomainRequest object + */ +"use strict"; + +if (typeof sinon == "undefined") { + this.sinon = {}; +} + +// wrapper for global +(function (global) { + var xdr = { XDomainRequest: global.XDomainRequest }; + xdr.GlobalXDomainRequest = global.XDomainRequest; + xdr.supportsXDR = typeof xdr.GlobalXDomainRequest != "undefined"; + xdr.workingXDR = xdr.supportsXDR ? xdr.GlobalXDomainRequest : false; + + function makeApi(sinon) { + sinon.xdr = xdr; + + function FakeXDomainRequest() { + this.readyState = FakeXDomainRequest.UNSENT; + this.requestBody = null; + this.requestHeaders = {}; + this.status = 0; + this.timeout = null; + + if (typeof FakeXDomainRequest.onCreate == "function") { + FakeXDomainRequest.onCreate(this); + } + } + + function verifyState(xdr) { + if (xdr.readyState !== FakeXDomainRequest.OPENED) { + throw new Error("INVALID_STATE_ERR"); + } + + if (xdr.sendFlag) { + throw new Error("INVALID_STATE_ERR"); + } + } + + function verifyRequestSent(xdr) { + if (xdr.readyState == FakeXDomainRequest.UNSENT) { + throw new Error("Request not sent"); + } + if (xdr.readyState == FakeXDomainRequest.DONE) { + throw new Error("Request done"); + } + } + + function verifyResponseBodyType(body) { + if (typeof body != "string") { + var error = new Error("Attempted to respond to fake XDomainRequest with " + + body + ", which is not a string."); + error.name = "InvalidBodyException"; + throw error; + } + } + + sinon.extend(FakeXDomainRequest.prototype, sinon.EventTarget, { + open: function open(method, url) { + this.method = method; + this.url = url; + + this.responseText = null; + this.sendFlag = false; + + this.readyStateChange(FakeXDomainRequest.OPENED); + }, + + readyStateChange: function readyStateChange(state) { + this.readyState = state; + var eventName = ""; + switch (this.readyState) { + case FakeXDomainRequest.UNSENT: + break; + case FakeXDomainRequest.OPENED: + break; + case FakeXDomainRequest.LOADING: + if (this.sendFlag) { + //raise the progress event + eventName = "onprogress"; + } + break; + case FakeXDomainRequest.DONE: + if (this.isTimeout) { + eventName = "ontimeout" + } else if (this.errorFlag || (this.status < 200 || this.status > 299)) { + eventName = "onerror"; + } else { + eventName = "onload" + } + break; + } + + // raising event (if defined) + if (eventName) { + if (typeof this[eventName] == "function") { + try { + this[eventName](); + } catch (e) { + sinon.logError("Fake XHR " + eventName + " handler", e); + } + } + } + }, + + send: function send(data) { + verifyState(this); + + if (!/^(get|head)$/i.test(this.method)) { + this.requestBody = data; + } + this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; + + this.errorFlag = false; + this.sendFlag = true; + this.readyStateChange(FakeXDomainRequest.OPENED); + + if (typeof this.onSend == "function") { + this.onSend(this); + } + }, + + abort: function abort() { + this.aborted = true; + this.responseText = null; + this.errorFlag = true; + + if (this.readyState > sinon.FakeXDomainRequest.UNSENT && this.sendFlag) { + this.readyStateChange(sinon.FakeXDomainRequest.DONE); + this.sendFlag = false; + } + }, + + setResponseBody: function setResponseBody(body) { + verifyRequestSent(this); + verifyResponseBodyType(body); + + var chunkSize = this.chunkSize || 10; + var index = 0; + this.responseText = ""; + + do { + this.readyStateChange(FakeXDomainRequest.LOADING); + this.responseText += body.substring(index, index + chunkSize); + index += chunkSize; + } while (index < body.length); + + this.readyStateChange(FakeXDomainRequest.DONE); + }, + + respond: function respond(status, contentType, body) { + // content-type ignored, since XDomainRequest does not carry this + // we keep the same syntax for respond(...) as for FakeXMLHttpRequest to ease + // test integration across browsers + this.status = typeof status == "number" ? status : 200; + this.setResponseBody(body || ""); + }, + + simulatetimeout: function simulatetimeout() { + this.status = 0; + this.isTimeout = true; + // Access to this should actually throw an error + this.responseText = undefined; + this.readyStateChange(FakeXDomainRequest.DONE); + } + }); + + sinon.extend(FakeXDomainRequest, { + UNSENT: 0, + OPENED: 1, + LOADING: 3, + DONE: 4 + }); + + sinon.useFakeXDomainRequest = function useFakeXDomainRequest() { + sinon.FakeXDomainRequest.restore = function restore(keepOnCreate) { + if (xdr.supportsXDR) { + global.XDomainRequest = xdr.GlobalXDomainRequest; + } + + delete sinon.FakeXDomainRequest.restore; + + if (keepOnCreate !== true) { + delete sinon.FakeXDomainRequest.onCreate; + } + }; + if (xdr.supportsXDR) { + global.XDomainRequest = sinon.FakeXDomainRequest; + } + return sinon.FakeXDomainRequest; + }; + + sinon.FakeXDomainRequest = FakeXDomainRequest; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./core"); + require("../extend"); + require("./event"); + require("../log_error"); + makeApi(sinon); + module.exports = sinon; + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else { + makeApi(sinon); + } +})(this); + +},{"../extend":29,"../log_error":31,"./core":41,"./event":42}],47:[function(require,module,exports){ +(function (global){ +/** + * @depend core.js + * @depend ../extend.js + * @depend event.js + * @depend ../log_error.js + */ +/** + * Fake XMLHttpRequest object + * + * @author Christian Johansen (christian@cjohansen.no) + * @license BSD + * + * Copyright (c) 2010-2013 Christian Johansen + */ +"use strict"; + +(function (global) { + + var supportsProgress = typeof ProgressEvent !== "undefined"; + var supportsCustomEvent = typeof CustomEvent !== "undefined"; + var sinonXhr = { XMLHttpRequest: global.XMLHttpRequest }; + sinonXhr.GlobalXMLHttpRequest = global.XMLHttpRequest; + sinonXhr.GlobalActiveXObject = global.ActiveXObject; + sinonXhr.supportsActiveX = typeof sinonXhr.GlobalActiveXObject != "undefined"; + sinonXhr.supportsXHR = typeof sinonXhr.GlobalXMLHttpRequest != "undefined"; + sinonXhr.workingXHR = sinonXhr.supportsXHR ? sinonXhr.GlobalXMLHttpRequest : sinonXhr.supportsActiveX + ? function () { return new sinonXhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; + sinonXhr.supportsCORS = sinonXhr.supportsXHR && "withCredentials" in (new sinonXhr.GlobalXMLHttpRequest()); + + /*jsl:ignore*/ + var unsafeHeaders = { + "Accept-Charset": true, + "Accept-Encoding": true, + Connection: true, + "Content-Length": true, + Cookie: true, + Cookie2: true, + "Content-Transfer-Encoding": true, + Date: true, + Expect: true, + Host: true, + "Keep-Alive": true, + Referer: true, + TE: true, + Trailer: true, + "Transfer-Encoding": true, + Upgrade: true, + "User-Agent": true, + Via: true + }; + /*jsl:end*/ + + function FakeXMLHttpRequest() { + this.readyState = FakeXMLHttpRequest.UNSENT; + this.requestHeaders = {}; + this.requestBody = null; + this.status = 0; + this.statusText = ""; + this.upload = new UploadProgress(); + if (sinonXhr.supportsCORS) { + this.withCredentials = false; + } + + var xhr = this; + var events = ["loadstart", "load", "abort", "loadend"]; + + function addEventListener(eventName) { + xhr.addEventListener(eventName, function (event) { + var listener = xhr["on" + eventName]; + + if (listener && typeof listener == "function") { + listener.call(this, event); + } + }); + } + + for (var i = events.length - 1; i >= 0; i--) { + addEventListener(events[i]); + } + + if (typeof FakeXMLHttpRequest.onCreate == "function") { + FakeXMLHttpRequest.onCreate(this); + } + } + + // An upload object is created for each + // FakeXMLHttpRequest and allows upload + // events to be simulated using uploadProgress + // and uploadError. + function UploadProgress() { + this.eventListeners = { + progress: [], + load: [], + abort: [], + error: [] + } + } + + UploadProgress.prototype.addEventListener = function addEventListener(event, listener) { + this.eventListeners[event].push(listener); + }; + + UploadProgress.prototype.removeEventListener = function removeEventListener(event, listener) { + var listeners = this.eventListeners[event] || []; + + for (var i = 0, l = listeners.length; i < l; ++i) { + if (listeners[i] == listener) { + return listeners.splice(i, 1); + } + } + }; + + UploadProgress.prototype.dispatchEvent = function dispatchEvent(event) { + var listeners = this.eventListeners[event.type] || []; + + for (var i = 0, listener; (listener = listeners[i]) != null; i++) { + listener(event); + } + }; + + function verifyState(xhr) { + if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { + throw new Error("INVALID_STATE_ERR"); + } + + if (xhr.sendFlag) { + throw new Error("INVALID_STATE_ERR"); + } + } + + function getHeader(headers, header) { + header = header.toLowerCase(); + + for (var h in headers) { + if (h.toLowerCase() == header) { + return h; + } + } + + return null; + } + + // filtering to enable a white-list version of Sinon FakeXhr, + // where whitelisted requests are passed through to real XHR + function each(collection, callback) { + if (!collection) { + return; + } + + for (var i = 0, l = collection.length; i < l; i += 1) { + callback(collection[i]); + } + } + function some(collection, callback) { + for (var index = 0; index < collection.length; index++) { + if (callback(collection[index]) === true) { + return true; + } + } + return false; + } + // largest arity in XHR is 5 - XHR#open + var apply = function (obj, method, args) { + switch (args.length) { + case 0: return obj[method](); + case 1: return obj[method](args[0]); + case 2: return obj[method](args[0], args[1]); + case 3: return obj[method](args[0], args[1], args[2]); + case 4: return obj[method](args[0], args[1], args[2], args[3]); + case 5: return obj[method](args[0], args[1], args[2], args[3], args[4]); + } + }; + + FakeXMLHttpRequest.filters = []; + FakeXMLHttpRequest.addFilter = function addFilter(fn) { + this.filters.push(fn) + }; + var IE6Re = /MSIE 6/; + FakeXMLHttpRequest.defake = function defake(fakeXhr, xhrArgs) { + var xhr = new sinonXhr.workingXHR(); + each([ + "open", + "setRequestHeader", + "send", + "abort", + "getResponseHeader", + "getAllResponseHeaders", + "addEventListener", + "overrideMimeType", + "removeEventListener" + ], function (method) { + fakeXhr[method] = function () { + return apply(xhr, method, arguments); + }; + }); + + var copyAttrs = function (args) { + each(args, function (attr) { + try { + fakeXhr[attr] = xhr[attr] + } catch (e) { + if (!IE6Re.test(navigator.userAgent)) { + throw e; + } + } + }); + }; + + var stateChange = function stateChange() { + fakeXhr.readyState = xhr.readyState; + if (xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { + copyAttrs(["status", "statusText"]); + } + if (xhr.readyState >= FakeXMLHttpRequest.LOADING) { + copyAttrs(["responseText", "response"]); + } + if (xhr.readyState === FakeXMLHttpRequest.DONE) { + copyAttrs(["responseXML"]); + } + if (fakeXhr.onreadystatechange) { + fakeXhr.onreadystatechange.call(fakeXhr, { target: fakeXhr }); + } + }; + + if (xhr.addEventListener) { + for (var event in fakeXhr.eventListeners) { + if (fakeXhr.eventListeners.hasOwnProperty(event)) { + each(fakeXhr.eventListeners[event], function (handler) { + xhr.addEventListener(event, handler); + }); + } + } + xhr.addEventListener("readystatechange", stateChange); + } else { + xhr.onreadystatechange = stateChange; + } + apply(xhr, "open", xhrArgs); + }; + FakeXMLHttpRequest.useFilters = false; + + function verifyRequestOpened(xhr) { + if (xhr.readyState != FakeXMLHttpRequest.OPENED) { + throw new Error("INVALID_STATE_ERR - " + xhr.readyState); + } + } + + function verifyRequestSent(xhr) { + if (xhr.readyState == FakeXMLHttpRequest.DONE) { + throw new Error("Request done"); + } + } + + function verifyHeadersReceived(xhr) { + if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { + throw new Error("No headers received"); + } + } + + function verifyResponseBodyType(body) { + if (typeof body != "string") { + var error = new Error("Attempted to respond to fake XMLHttpRequest with " + + body + ", which is not a string."); + error.name = "InvalidBodyException"; + throw error; + } + } + + FakeXMLHttpRequest.parseXML = function parseXML(text) { + var xmlDoc; + + if (typeof DOMParser != "undefined") { + var parser = new DOMParser(); + xmlDoc = parser.parseFromString(text, "text/xml"); + } else { + xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); + xmlDoc.async = "false"; + xmlDoc.loadXML(text); + } + + return xmlDoc; + }; + + FakeXMLHttpRequest.statusCodes = { + 100: "Continue", + 101: "Switching Protocols", + 200: "OK", + 201: "Created", + 202: "Accepted", + 203: "Non-Authoritative Information", + 204: "No Content", + 205: "Reset Content", + 206: "Partial Content", + 207: "Multi-Status", + 300: "Multiple Choice", + 301: "Moved Permanently", + 302: "Found", + 303: "See Other", + 304: "Not Modified", + 305: "Use Proxy", + 307: "Temporary Redirect", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 409: "Conflict", + 410: "Gone", + 411: "Length Required", + 412: "Precondition Failed", + 413: "Request Entity Too Large", + 414: "Request-URI Too Long", + 415: "Unsupported Media Type", + 416: "Requested Range Not Satisfiable", + 417: "Expectation Failed", + 422: "Unprocessable Entity", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Gateway Timeout", + 505: "HTTP Version Not Supported" + }; + + function makeApi(sinon) { + sinon.xhr = sinonXhr; + + sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { + async: true, + + open: function open(method, url, async, username, password) { + this.method = method; + this.url = url; + this.async = typeof async == "boolean" ? async : true; + this.username = username; + this.password = password; + this.responseText = null; + this.responseXML = null; + this.requestHeaders = {}; + this.sendFlag = false; + + if (FakeXMLHttpRequest.useFilters === true) { + var xhrArgs = arguments; + var defake = some(FakeXMLHttpRequest.filters, function (filter) { + return filter.apply(this, xhrArgs) + }); + if (defake) { + return FakeXMLHttpRequest.defake(this, arguments); + } + } + this.readyStateChange(FakeXMLHttpRequest.OPENED); + }, + + readyStateChange: function readyStateChange(state) { + this.readyState = state; + + if (typeof this.onreadystatechange == "function") { + try { + this.onreadystatechange(); + } catch (e) { + sinon.logError("Fake XHR onreadystatechange handler", e); + } + } + + this.dispatchEvent(new sinon.Event("readystatechange")); + + switch (this.readyState) { + case FakeXMLHttpRequest.DONE: + this.dispatchEvent(new sinon.Event("load", false, false, this)); + this.dispatchEvent(new sinon.Event("loadend", false, false, this)); + this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); + if (supportsProgress) { + this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); + this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); + } + break; + } + }, + + setRequestHeader: function setRequestHeader(header, value) { + verifyState(this); + + if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { + throw new Error("Refused to set unsafe header \"" + header + "\""); + } + + if (this.requestHeaders[header]) { + this.requestHeaders[header] += "," + value; + } else { + this.requestHeaders[header] = value; + } + }, + + // Helps testing + setResponseHeaders: function setResponseHeaders(headers) { + verifyRequestOpened(this); + this.responseHeaders = {}; + + for (var header in headers) { + if (headers.hasOwnProperty(header)) { + this.responseHeaders[header] = headers[header]; + } + } + + if (this.async) { + this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); + } else { + this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; + } + }, + + // Currently treats ALL data as a DOMString (i.e. no Document) + send: function send(data) { + verifyState(this); + + if (!/^(get|head)$/i.test(this.method)) { + var contentType = getHeader(this.requestHeaders, "Content-Type"); + if (this.requestHeaders[contentType]) { + var value = this.requestHeaders[contentType].split(";"); + this.requestHeaders[contentType] = value[0] + ";charset=utf-8"; + } else if (!(data instanceof FormData)) { + this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; + } + + this.requestBody = data; + } + + this.errorFlag = false; + this.sendFlag = this.async; + this.readyStateChange(FakeXMLHttpRequest.OPENED); + + if (typeof this.onSend == "function") { + this.onSend(this); + } + + this.dispatchEvent(new sinon.Event("loadstart", false, false, this)); + }, + + abort: function abort() { + this.aborted = true; + this.responseText = null; + this.errorFlag = true; + this.requestHeaders = {}; + + if (this.readyState > FakeXMLHttpRequest.UNSENT && this.sendFlag) { + this.readyStateChange(FakeXMLHttpRequest.DONE); + this.sendFlag = false; + } + + this.readyState = FakeXMLHttpRequest.UNSENT; + + this.dispatchEvent(new sinon.Event("abort", false, false, this)); + + this.upload.dispatchEvent(new sinon.Event("abort", false, false, this)); + + if (typeof this.onerror === "function") { + this.onerror(); + } + }, + + getResponseHeader: function getResponseHeader(header) { + if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { + return null; + } + + if (/^Set-Cookie2?$/i.test(header)) { + return null; + } + + header = getHeader(this.responseHeaders, header); + + return this.responseHeaders[header] || null; + }, + + getAllResponseHeaders: function getAllResponseHeaders() { + if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { + return ""; + } + + var headers = ""; + + for (var header in this.responseHeaders) { + if (this.responseHeaders.hasOwnProperty(header) && + !/^Set-Cookie2?$/i.test(header)) { + headers += header + ": " + this.responseHeaders[header] + "\r\n"; + } + } + + return headers; + }, + + setResponseBody: function setResponseBody(body) { + verifyRequestSent(this); + verifyHeadersReceived(this); + verifyResponseBodyType(body); + + var chunkSize = this.chunkSize || 10; + var index = 0; + this.responseText = ""; + + do { + if (this.async) { + this.readyStateChange(FakeXMLHttpRequest.LOADING); + } + + this.responseText += body.substring(index, index + chunkSize); + index += chunkSize; + } while (index < body.length); + + var type = this.getResponseHeader("Content-Type"); + + if (this.responseText && + (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { + try { + this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); + } catch (e) { + // Unable to parse XML - no biggie + } + } + + this.readyStateChange(FakeXMLHttpRequest.DONE); + }, + + respond: function respond(status, headers, body) { + this.status = typeof status == "number" ? status : 200; + this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; + this.setResponseHeaders(headers || {}); + this.setResponseBody(body || ""); + }, + + uploadProgress: function uploadProgress(progressEventRaw) { + if (supportsProgress) { + this.upload.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw)); + } + }, + + downloadProgress: function downloadProgress(progressEventRaw) { + if (supportsProgress) { + this.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw)); + } + }, + + uploadError: function uploadError(error) { + if (supportsCustomEvent) { + this.upload.dispatchEvent(new sinon.CustomEvent("error", {detail: error})); + } + } + }); + + sinon.extend(FakeXMLHttpRequest, { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 + }); + + sinon.useFakeXMLHttpRequest = function () { + FakeXMLHttpRequest.restore = function restore(keepOnCreate) { + if (sinonXhr.supportsXHR) { + global.XMLHttpRequest = sinonXhr.GlobalXMLHttpRequest; + } + + if (sinonXhr.supportsActiveX) { + global.ActiveXObject = sinonXhr.GlobalActiveXObject; + } + + delete FakeXMLHttpRequest.restore; + + if (keepOnCreate !== true) { + delete FakeXMLHttpRequest.onCreate; + } + }; + if (sinonXhr.supportsXHR) { + global.XMLHttpRequest = FakeXMLHttpRequest; + } + + if (sinonXhr.supportsActiveX) { + global.ActiveXObject = function ActiveXObject(objId) { + if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { + + return new FakeXMLHttpRequest(); + } + + return new sinonXhr.GlobalActiveXObject(objId); + }; + } + + return FakeXMLHttpRequest; + }; + + sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; + } + + var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; + var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; + + function loadDependencies(require, exports, module) { + var sinon = require("./core"); + require("../extend"); + require("./event"); + require("../log_error"); + makeApi(sinon); + module.exports = sinon; + } + + if (isAMD) { + define(loadDependencies); + } else if (isNode) { + loadDependencies(require, module.exports, module); + } else if (typeof sinon === "undefined") { + return; + } else { + makeApi(sinon); + } + +})(typeof global !== "undefined" ? global : this); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../extend":29,"../log_error":31,"./core":41,"./event":42}],48:[function(require,module,exports){ +(function (global){ +((typeof define === "function" && define.amd && function (m) { + define("formatio", ["samsam"], m); +}) || (typeof module === "object" && function (m) { + module.exports = m(require("samsam")); +}) || function (m) { this.formatio = m(this.samsam); } +)(function (samsam) { + "use strict"; + + var formatio = { + excludeConstructors: ["Object", /^.$/], + quoteStrings: true, + limitChildrenCount: 0 + }; + + var hasOwn = Object.prototype.hasOwnProperty; + + var specialObjects = []; + if (typeof global !== "undefined") { + specialObjects.push({ object: global, value: "[object global]" }); + } + if (typeof document !== "undefined") { + specialObjects.push({ + object: document, + value: "[object HTMLDocument]" + }); + } + if (typeof window !== "undefined") { + specialObjects.push({ object: window, value: "[object Window]" }); + } + + function functionName(func) { + if (!func) { return ""; } + if (func.displayName) { return func.displayName; } + if (func.name) { return func.name; } + var matches = func.toString().match(/function\s+([^\(]+)/m); + return (matches && matches[1]) || ""; + } + + function constructorName(f, object) { + var name = functionName(object && object.constructor); + var excludes = f.excludeConstructors || + formatio.excludeConstructors || []; + + var i, l; + for (i = 0, l = excludes.length; i < l; ++i) { + if (typeof excludes[i] === "string" && excludes[i] === name) { + return ""; + } else if (excludes[i].test && excludes[i].test(name)) { + return ""; + } + } + + return name; + } + + function isCircular(object, objects) { + if (typeof object !== "object") { return false; } + var i, l; + for (i = 0, l = objects.length; i < l; ++i) { + if (objects[i] === object) { return true; } + } + return false; + } + + function ascii(f, object, processed, indent) { + if (typeof object === "string") { + var qs = f.quoteStrings; + var quote = typeof qs !== "boolean" || qs; + return processed || quote ? '"' + object + '"' : object; + } + + if (typeof object === "function" && !(object instanceof RegExp)) { + return ascii.func(object); + } + + processed = processed || []; + + if (isCircular(object, processed)) { return "[Circular]"; } + + if (Object.prototype.toString.call(object) === "[object Array]") { + return ascii.array.call(f, object, processed); + } + + if (!object) { return String((1/object) === -Infinity ? "-0" : object); } + if (samsam.isElement(object)) { return ascii.element(object); } + + if (typeof object.toString === "function" && + object.toString !== Object.prototype.toString) { + return object.toString(); + } + + var i, l; + for (i = 0, l = specialObjects.length; i < l; i++) { + if (object === specialObjects[i].object) { + return specialObjects[i].value; + } + } + + return ascii.object.call(f, object, processed, indent); + } + + ascii.func = function (func) { + return "function " + functionName(func) + "() {}"; + }; + + ascii.array = function (array, processed) { + processed = processed || []; + processed.push(array); + var pieces = []; + var i, l; + l = (this.limitChildrenCount > 0) ? + Math.min(this.limitChildrenCount, array.length) : array.length; + + for (i = 0; i < l; ++i) { + pieces.push(ascii(this, array[i], processed)); + } + + if(l < array.length) + pieces.push("[... " + (array.length - l) + " more elements]"); + + return "[" + pieces.join(", ") + "]"; + }; + + ascii.object = function (object, processed, indent) { + processed = processed || []; + processed.push(object); + indent = indent || 0; + var pieces = [], properties = samsam.keys(object).sort(); + var length = 3; + var prop, str, obj, i, k, l; + l = (this.limitChildrenCount > 0) ? + Math.min(this.limitChildrenCount, properties.length) : properties.length; + + for (i = 0; i < l; ++i) { + prop = properties[i]; + obj = object[prop]; + + if (isCircular(obj, processed)) { + str = "[Circular]"; + } else { + str = ascii(this, obj, processed, indent + 2); + } + + str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; + length += str.length; + pieces.push(str); + } + + var cons = constructorName(this, object); + var prefix = cons ? "[" + cons + "] " : ""; + var is = ""; + for (i = 0, k = indent; i < k; ++i) { is += " "; } + + if(l < properties.length) + pieces.push("[... " + (properties.length - l) + " more elements]"); + + if (length + indent > 80) { + return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + + is + "}"; + } + return prefix + "{ " + pieces.join(", ") + " }"; + }; + + ascii.element = function (element) { + var tagName = element.tagName.toLowerCase(); + var attrs = element.attributes, attr, pairs = [], attrName, i, l, val; + + for (i = 0, l = attrs.length; i < l; ++i) { + attr = attrs.item(i); + attrName = attr.nodeName.toLowerCase().replace("html:", ""); + val = attr.nodeValue; + if (attrName !== "contenteditable" || val !== "inherit") { + if (!!val) { pairs.push(attrName + "=\"" + val + "\""); } + } + } + + var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); + var content = element.innerHTML; + + if (content.length > 20) { + content = content.substr(0, 20) + "[...]"; + } + + var res = formatted + pairs.join(" ") + ">" + content + + ""; + + return res.replace(/ contentEditable="inherit"/, ""); + }; + + function Formatio(options) { + for (var opt in options) { + this[opt] = options[opt]; + } + } + + Formatio.prototype = { + functionName: functionName, + + configure: function (options) { + return new Formatio(options); + }, + + constructorName: function (object) { + return constructorName(this, object); + }, + + ascii: function (object, processed, indent) { + return ascii(this, object, processed, indent); + } + }; + + return Formatio.prototype; +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"samsam":49}],49:[function(require,module,exports){ +((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) || + (typeof module === "object" && + function (m) { module.exports = m(); }) || // Node + function (m) { this.samsam = m(); } // Browser globals +)(function () { + var o = Object.prototype; + var div = typeof document !== "undefined" && document.createElement("div"); + + function isNaN(value) { + // Unlike global isNaN, this avoids type coercion + // typeof check avoids IE host object issues, hat tip to + // lodash + var val = value; // JsLint thinks value !== value is "weird" + return typeof value === "number" && value !== val; + } + + function getClass(value) { + // Returns the internal [[Class]] by calling Object.prototype.toString + // with the provided value as this. Return value is a string, naming the + // internal class, e.g. "Array" + return o.toString.call(value).split(/[ \]]/)[1]; + } + + /** + * @name samsam.isArguments + * @param Object object + * + * Returns ``true`` if ``object`` is an ``arguments`` object, + * ``false`` otherwise. + */ + function isArguments(object) { + if (getClass(object) === 'Arguments') { return true; } + if (typeof object !== "object" || typeof object.length !== "number" || + getClass(object) === "Array") { + return false; + } + if (typeof object.callee == "function") { return true; } + try { + object[object.length] = 6; + delete object[object.length]; + } catch (e) { + return true; + } + return false; + } + + /** + * @name samsam.isElement + * @param Object object + * + * Returns ``true`` if ``object`` is a DOM element node. Unlike + * Underscore.js/lodash, this function will return ``false`` if ``object`` + * is an *element-like* object, i.e. a regular object with a ``nodeType`` + * property that holds the value ``1``. + */ + function isElement(object) { + if (!object || object.nodeType !== 1 || !div) { return false; } + try { + object.appendChild(div); + object.removeChild(div); + } catch (e) { + return false; + } + return true; + } + + /** + * @name samsam.keys + * @param Object object + * + * Return an array of own property names. + */ + function keys(object) { + var ks = [], prop; + for (prop in object) { + if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); } + } + return ks; + } + + /** + * @name samsam.isDate + * @param Object value + * + * Returns true if the object is a ``Date``, or *date-like*. Duck typing + * of date objects work by checking that the object has a ``getTime`` + * function whose return value equals the return value from the object's + * ``valueOf``. + */ + function isDate(value) { + return typeof value.getTime == "function" && + value.getTime() == value.valueOf(); + } + + /** + * @name samsam.isNegZero + * @param Object value + * + * Returns ``true`` if ``value`` is ``-0``. + */ + function isNegZero(value) { + return value === 0 && 1 / value === -Infinity; + } + + /** + * @name samsam.equal + * @param Object obj1 + * @param Object obj2 + * + * Returns ``true`` if two objects are strictly equal. Compared to + * ``===`` there are two exceptions: + * + * - NaN is considered equal to NaN + * - -0 and +0 are not considered equal + */ + function identical(obj1, obj2) { + if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) { + return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2); + } + } + + + /** + * @name samsam.deepEqual + * @param Object obj1 + * @param Object obj2 + * + * Deep equal comparison. Two values are "deep equal" if: + * + * - They are equal, according to samsam.identical + * - They are both date objects representing the same time + * - They are both arrays containing elements that are all deepEqual + * - They are objects with the same set of properties, and each property + * in ``obj1`` is deepEqual to the corresponding property in ``obj2`` + * + * Supports cyclic objects. + */ + function deepEqualCyclic(obj1, obj2) { + + // used for cyclic comparison + // contain already visited objects + var objects1 = [], + objects2 = [], + // contain pathes (position in the object structure) + // of the already visited objects + // indexes same as in objects arrays + paths1 = [], + paths2 = [], + // contains combinations of already compared objects + // in the manner: { "$1['ref']$2['ref']": true } + compared = {}; + + /** + * used to check, if the value of a property is an object + * (cyclic logic is only needed for objects) + * only needed for cyclic logic + */ + function isObject(value) { + + if (typeof value === 'object' && value !== null && + !(value instanceof Boolean) && + !(value instanceof Date) && + !(value instanceof Number) && + !(value instanceof RegExp) && + !(value instanceof String)) { + + return true; + } + + return false; + } + + /** + * returns the index of the given object in the + * given objects array, -1 if not contained + * only needed for cyclic logic + */ + function getIndex(objects, obj) { + + var i; + for (i = 0; i < objects.length; i++) { + if (objects[i] === obj) { + return i; + } + } + + return -1; + } + + // does the recursion for the deep equal check + return (function deepEqual(obj1, obj2, path1, path2) { + var type1 = typeof obj1; + var type2 = typeof obj2; + + // == null also matches undefined + if (obj1 === obj2 || + isNaN(obj1) || isNaN(obj2) || + obj1 == null || obj2 == null || + type1 !== "object" || type2 !== "object") { + + return identical(obj1, obj2); + } + + // Elements are only equal if identical(expected, actual) + if (isElement(obj1) || isElement(obj2)) { return false; } + + var isDate1 = isDate(obj1), isDate2 = isDate(obj2); + if (isDate1 || isDate2) { + if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) { + return false; + } + } + + if (obj1 instanceof RegExp && obj2 instanceof RegExp) { + if (obj1.toString() !== obj2.toString()) { return false; } + } + + var class1 = getClass(obj1); + var class2 = getClass(obj2); + var keys1 = keys(obj1); + var keys2 = keys(obj2); + + if (isArguments(obj1) || isArguments(obj2)) { + if (obj1.length !== obj2.length) { return false; } + } else { + if (type1 !== type2 || class1 !== class2 || + keys1.length !== keys2.length) { + return false; + } + } + + var key, i, l, + // following vars are used for the cyclic logic + value1, value2, + isObject1, isObject2, + index1, index2, + newPath1, newPath2; + + for (i = 0, l = keys1.length; i < l; i++) { + key = keys1[i]; + if (!o.hasOwnProperty.call(obj2, key)) { + return false; + } + + // Start of the cyclic logic + + value1 = obj1[key]; + value2 = obj2[key]; + + isObject1 = isObject(value1); + isObject2 = isObject(value2); + + // determine, if the objects were already visited + // (it's faster to check for isObject first, than to + // get -1 from getIndex for non objects) + index1 = isObject1 ? getIndex(objects1, value1) : -1; + index2 = isObject2 ? getIndex(objects2, value2) : -1; + + // determine the new pathes of the objects + // - for non cyclic objects the current path will be extended + // by current property name + // - for cyclic objects the stored path is taken + newPath1 = index1 !== -1 + ? paths1[index1] + : path1 + '[' + JSON.stringify(key) + ']'; + newPath2 = index2 !== -1 + ? paths2[index2] + : path2 + '[' + JSON.stringify(key) + ']'; + + // stop recursion if current objects are already compared + if (compared[newPath1 + newPath2]) { + return true; + } + + // remember the current objects and their pathes + if (index1 === -1 && isObject1) { + objects1.push(value1); + paths1.push(newPath1); + } + if (index2 === -1 && isObject2) { + objects2.push(value2); + paths2.push(newPath2); + } + + // remember that the current objects are already compared + if (isObject1 && isObject2) { + compared[newPath1 + newPath2] = true; + } + + // End of cyclic logic + + // neither value1 nor value2 is a cycle + // continue with next level + if (!deepEqual(value1, value2, newPath1, newPath2)) { + return false; + } + } + + return true; + + }(obj1, obj2, '$1', '$2')); + } + + var match; + + function arrayContains(array, subset) { + if (subset.length === 0) { return true; } + var i, l, j, k; + for (i = 0, l = array.length; i < l; ++i) { + if (match(array[i], subset[0])) { + for (j = 0, k = subset.length; j < k; ++j) { + if (!match(array[i + j], subset[j])) { return false; } + } + return true; + } + } + return false; + } + + /** + * @name samsam.match + * @param Object object + * @param Object matcher + * + * Compare arbitrary value ``object`` with matcher. + */ + match = function match(object, matcher) { + if (matcher && typeof matcher.test === "function") { + return matcher.test(object); + } + + if (typeof matcher === "function") { + return matcher(object) === true; + } + + if (typeof matcher === "string") { + matcher = matcher.toLowerCase(); + var notNull = typeof object === "string" || !!object; + return notNull && + (String(object)).toLowerCase().indexOf(matcher) >= 0; + } + + if (typeof matcher === "number") { + return matcher === object; + } + + if (typeof matcher === "boolean") { + return matcher === object; + } + + if (typeof(matcher) === "undefined") { + return typeof(object) === "undefined"; + } + + if (matcher === null) { + return object === null; + } + + if (getClass(object) === "Array" && getClass(matcher) === "Array") { + return arrayContains(object, matcher); + } + + if (matcher && typeof matcher === "object") { + if (matcher === object) { + return true; + } + var prop; + for (prop in matcher) { + var value = object[prop]; + if (typeof value === "undefined" && + typeof object.getAttribute === "function") { + value = object.getAttribute(prop); + } + if (matcher[prop] === null || typeof matcher[prop] === 'undefined') { + if (value !== matcher[prop]) { + return false; + } + } else if (typeof value === "undefined" || !match(value, matcher[prop])) { + return false; + } + } + return true; + } + + throw new Error("Matcher was not a string, a number, a " + + "function, a boolean or an object"); + }; + + return { + isArguments: isArguments, + isElement: isElement, + isDate: isDate, + isNegZero: isNegZero, + identical: identical, + deepEqual: deepEqualCyclic, + match: match, + keys: keys + }; +}); + +},{}],50:[function(require,module,exports){ +(function (global){ +/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ +/*global global*/ +/** + * @author Christian Johansen (christian@cjohansen.no) and contributors + * @license BSD + * + * Copyright (c) 2010-2014 Christian Johansen + */ +"use strict"; + +// node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref() +// browsers, a number. +// see https://github.com/cjohansen/Sinon.JS/pull/436 +var timeoutResult = setTimeout(function() {}, 0); +var addTimerReturnsObject = typeof timeoutResult === "object"; +clearTimeout(timeoutResult); + +var NativeDate = Date; +var id = 1; + +/** + * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into + * number of milliseconds. This is used to support human-readable strings passed + * to clock.tick() + */ +function parseTime(str) { + if (!str) { + return 0; + } + + var strings = str.split(":"); + var l = strings.length, i = l; + var ms = 0, parsed; + + if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { + throw new Error("tick only understands numbers and 'h:m:s'"); + } + + while (i--) { + parsed = parseInt(strings[i], 10); + + if (parsed >= 60) { + throw new Error("Invalid time " + str); + } + + ms += parsed * Math.pow(60, (l - i - 1)); + } + + return ms * 1000; +} + +/** + * Used to grok the `now` parameter to createClock. + */ +function getEpoch(epoch) { + if (!epoch) { return 0; } + if (typeof epoch.getTime === "function") { return epoch.getTime(); } + if (typeof epoch === "number") { return epoch; } + throw new TypeError("now should be milliseconds since UNIX epoch"); +} + +function inRange(from, to, timer) { + return timer && timer.callAt >= from && timer.callAt <= to; +} + +function mirrorDateProperties(target, source) { + if (source.now) { + target.now = function now() { + return target.clock.now; + }; + } else { + delete target.now; + } + + if (source.toSource) { + target.toSource = function toSource() { + return source.toSource(); + }; + } else { + delete target.toSource; + } + + target.toString = function toString() { + return source.toString(); + }; + + target.prototype = source.prototype; + target.parse = source.parse; + target.UTC = source.UTC; + target.prototype.toUTCString = source.prototype.toUTCString; + + for (var prop in source) { + if (source.hasOwnProperty(prop)) { + target[prop] = source[prop]; + } + } + + return target; +} + +function createDate() { + function ClockDate(year, month, date, hour, minute, second, ms) { + // Defensive and verbose to avoid potential harm in passing + // explicit undefined when user does not pass argument + switch (arguments.length) { + case 0: + return new NativeDate(ClockDate.clock.now); + case 1: + return new NativeDate(year); + case 2: + return new NativeDate(year, month); + case 3: + return new NativeDate(year, month, date); + case 4: + return new NativeDate(year, month, date, hour); + case 5: + return new NativeDate(year, month, date, hour, minute); + case 6: + return new NativeDate(year, month, date, hour, minute, second); + default: + return new NativeDate(year, month, date, hour, minute, second, ms); + } + } + + return mirrorDateProperties(ClockDate, NativeDate); +} + +function addTimer(clock, timer) { + if (typeof timer.func === "undefined") { + throw new Error("Callback must be provided to timer calls"); + } + + if (!clock.timers) { + clock.timers = {}; + } + + timer.id = id++; + timer.createdAt = clock.now; + timer.callAt = clock.now + (timer.delay || 0); + + clock.timers[timer.id] = timer; + + if (addTimerReturnsObject) { + return { + id: timer.id, + ref: function() {}, + unref: function() {} + }; + } + else { + return timer.id; + } +} + +function firstTimerInRange(clock, from, to) { + var timers = clock.timers, timer = null; + + for (var id in timers) { + if (!inRange(from, to, timers[id])) { + continue; + } + + if (!timer || ~compareTimers(timer, timers[id])) { + timer = timers[id]; + } + } + + return timer; +} + +function compareTimers(a, b) { + // Sort first by absolute timing + if (a.callAt < b.callAt) { + return -1; + } + if (a.callAt > b.callAt) { + return 1; + } + + // Sort next by immediate, immediate timers take precedence + if (a.immediate && !b.immediate) { + return -1; + } + if (!a.immediate && b.immediate) { + return 1; + } + + // Sort next by creation time, earlier-created timers take precedence + if (a.createdAt < b.createdAt) { + return -1; + } + if (a.createdAt > b.createdAt) { + return 1; + } + + // Sort next by id, lower-id timers take precedence + if (a.id < b.id) { + return -1; + } + if (a.id > b.id) { + return 1; + } + + // As timer ids are unique, no fallback `0` is necessary +} + +function callTimer(clock, timer) { + if (typeof timer.interval == "number") { + clock.timers[timer.id].callAt += timer.interval; + } else { + delete clock.timers[timer.id]; + } + + try { + if (typeof timer.func == "function") { + timer.func.apply(null, timer.args); + } else { + eval(timer.func); + } + } catch (e) { + var exception = e; + } + + if (!clock.timers[timer.id]) { + if (exception) { + throw exception; + } + return; + } + + if (exception) { + throw exception; + } +} + +function uninstall(clock, target) { + var method; + + for (var i = 0, l = clock.methods.length; i < l; i++) { + method = clock.methods[i]; + + if (target[method].hadOwnProperty) { + target[method] = clock["_" + method]; + } else { + try { + delete target[method]; + } catch (e) {} + } + } + + // Prevent multiple executions which will completely remove these props + clock.methods = []; +} + +function hijackMethod(target, method, clock) { + clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method); + clock["_" + method] = target[method]; + + if (method == "Date") { + var date = mirrorDateProperties(clock[method], target[method]); + target[method] = date; + } else { + target[method] = function () { + return clock[method].apply(clock, arguments); + }; + + for (var prop in clock[method]) { + if (clock[method].hasOwnProperty(prop)) { + target[method][prop] = clock[method][prop]; + } + } + } + + target[method].clock = clock; +} + +var timers = { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined), + clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate: undefined), + setInterval: setInterval, + clearInterval: clearInterval, + Date: Date +}; + +var keys = Object.keys || function (obj) { + var ks = []; + for (var key in obj) { + ks.push(key); + } + return ks; +}; + +exports.timers = timers; + +var createClock = exports.createClock = function (now) { + var clock = { + now: getEpoch(now), + timeouts: {}, + Date: createDate() + }; + + clock.Date.clock = clock; + + clock.setTimeout = function setTimeout(func, timeout) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: timeout + }); + }; + + clock.clearTimeout = function clearTimeout(timerId) { + if (!timerId) { + // null appears to be allowed in most browsers, and appears to be + // relied upon by some libraries, like Bootstrap carousel + return; + } + if (!clock.timers) { + clock.timers = []; + } + // in Node, timerId is an object with .ref()/.unref(), and + // its .id field is the actual timer id. + if (typeof timerId === "object") { + timerId = timerId.id + } + if (timerId in clock.timers) { + delete clock.timers[timerId]; + } + }; + + clock.setInterval = function setInterval(func, timeout) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 2), + delay: timeout, + interval: timeout + }); + }; + + clock.clearInterval = function clearInterval(timerId) { + clock.clearTimeout(timerId); + }; + + clock.setImmediate = function setImmediate(func) { + return addTimer(clock, { + func: func, + args: Array.prototype.slice.call(arguments, 1), + immediate: true + }); + }; + + clock.clearImmediate = function clearImmediate(timerId) { + clock.clearTimeout(timerId); + }; + + clock.tick = function tick(ms) { + ms = typeof ms == "number" ? ms : parseTime(ms); + var tickFrom = clock.now, tickTo = clock.now + ms, previous = clock.now; + var timer = firstTimerInRange(clock, tickFrom, tickTo); + + var firstException; + while (timer && tickFrom <= tickTo) { + if (clock.timers[timer.id]) { + tickFrom = clock.now = timer.callAt; + try { + callTimer(clock, timer); + } catch (e) { + firstException = firstException || e; + } + } + + timer = firstTimerInRange(clock, previous, tickTo); + previous = tickFrom; + } + + clock.now = tickTo; + + if (firstException) { + throw firstException; + } + + return clock.now; + }; + + clock.reset = function reset() { + clock.timers = {}; + }; + + return clock; +}; + +exports.install = function install(target, now, toFake) { + if (typeof target === "number") { + toFake = now; + now = target; + target = null; + } + + if (!target) { + target = global; + } + + var clock = createClock(now); + + clock.uninstall = function () { + uninstall(clock, target); + }; + + clock.methods = toFake || []; + + if (clock.methods.length === 0) { + clock.methods = keys(timers); + } + + for (var i = 0, l = clock.methods.length; i < l; i++) { + hijackMethod(target, clock.methods[i], clock); + } + + return clock; +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],51:[function(require,module,exports){ +(function (process,global){ +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + function lib$es6$promise$asap$$asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + lib$es6$promise$asap$$scheduleFlush(); + } + } + + var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + var nextTick = process.nextTick; + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // setImmediate should be used instead instead + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function() { + nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertex() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFullfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$default(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { + return lib$es6$promise$utils$$isArray(input); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; + + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + var lib$es6$promise$promise$$counter = 0; + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$default(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + +//# sourceMappingURL=es6-promise.js.map +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"_process":4}],52:[function(require,module,exports){ +(function (global){ +/*global describe, specify, it, assert */ + +if (typeof Object.getPrototypeOf !== "function") { + Object.getPrototypeOf = "".__proto__ === String.prototype + ? function (object) { + return object.__proto__; + } + : function (object) { + // May break if the constructor has been tampered with + return object.constructor.prototype; + }; +} + +function keysOf(object) { + var results = []; + + for (var key in object) { + if (object.hasOwnProperty(key)) { + results.push(key); + } + } + + return results; +} + +var g = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this; +var Promise = g.adapter.Promise; +var assert = require('assert'); + +function objectEquals(obj1, obj2) { + for (var i in obj1) { + if (obj1.hasOwnProperty(i)) { + if (!obj2.hasOwnProperty(i)) return false; + if (obj1[i] != obj2[i]) return false; + } + } + for (var i in obj2) { + if (obj2.hasOwnProperty(i)) { + if (!obj1.hasOwnProperty(i)) return false; + if (obj1[i] != obj2[i]) return false; + } + } + return true; +} + +describe("extensions", function() { + describe("Promise constructor", function() { + it('should exist and have length 1', function() { + assert(Promise); + assert.equal(Promise.length, 1); + }); + + it('should fulfill if `resolve` is called with a value', function(done) { + var promise = new Promise(function(resolve) { resolve('value'); }); + + promise.then(function(value) { + assert.equal(value, 'value'); + done(); + }); + }); + + it('should reject if `reject` is called with a reason', function(done) { + var promise = new Promise(function(resolve, reject) { reject('reason'); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'reason'); + done(); + }); + }); + + it('should be a constructor', function() { + var promise = new Promise(function() {}); + + assert.equal(Object.getPrototypeOf(promise), Promise.prototype, '[[Prototype]] equals Promise.prototype'); + assert.equal(promise.constructor, Promise, 'constructor property of instances is set correctly'); + assert.equal(Promise.prototype.constructor, Promise, 'constructor property of prototype is set correctly'); + }); + + it('should NOT work without `new`', function() { + assert.throws(function(){ + Promise(function(resolve) { resolve('value'); }); + }, TypeError) + }); + + it('should throw a `TypeError` if not given a function', function() { + assert.throws(function () { + new Promise(); + }, TypeError); + + assert.throws(function () { + new Promise({}); + }, TypeError); + + assert.throws(function () { + new Promise('boo!'); + }, TypeError); + }); + + it('should reject on resolver exception', function(done) { + new Promise(function() { + throw 'error'; + }).then(null, function(e) { + assert.equal(e, 'error'); + done(); + }); + }); + + it('should not resolve multiple times', function(done) { + var resolver, rejector, fulfilled = 0, rejected = 0; + var thenable = { + then: function(resolve, reject) { + resolver = resolve; + rejector = reject; + } + }; + + var promise = new Promise(function(resolve) { + resolve(1); + }); + + promise.then(function(value){ + return thenable; + }).then(function(value){ + fulfilled++; + }, function(reason) { + rejected++; + }); + + setTimeout(function() { + resolver(1); + resolver(1); + rejector(1); + rejector(1); + + setTimeout(function() { + assert.equal(fulfilled, 1); + assert.equal(rejected, 0); + done(); + }, 20); + }, 20); + + }); + + describe('assimilation', function() { + it('should assimilate if `resolve` is called with a fulfilled promise', function(done) { + var originalPromise = new Promise(function(resolve) { resolve('original value'); }); + var promise = new Promise(function(resolve) { resolve(originalPromise); }); + + promise.then(function(value) { + assert.equal(value, 'original value'); + done(); + }); + }); + + it('should assimilate if `resolve` is called with a rejected promise', function(done) { + var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); + var promise = new Promise(function(resolve) { resolve(originalPromise); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'original reason'); + done(); + }); + }); + + it('should assimilate if `resolve` is called with a fulfilled thenable', function(done) { + var originalThenable = { + then: function (onFulfilled) { + setTimeout(function() { onFulfilled('original value'); }, 0); + } + }; + var promise = new Promise(function(resolve) { resolve(originalThenable); }); + + promise.then(function(value) { + assert.equal(value, 'original value'); + done(); + }); + }); + + it('should assimilate if `resolve` is called with a rejected thenable', function(done) { + var originalThenable = { + then: function (onFulfilled, onRejected) { + setTimeout(function() { onRejected('original reason'); }, 0); + } + }; + var promise = new Promise(function(resolve) { resolve(originalThenable); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'original reason'); + done(); + }); + }); + + + it('should assimilate two levels deep, for fulfillment of self fulfilling promises', function(done) { + var originalPromise, promise; + originalPromise = new Promise(function(resolve) { + setTimeout(function() { + resolve(originalPromise); + }, 0) + }); + + promise = new Promise(function(resolve) { + setTimeout(function() { + resolve(originalPromise); + }, 0); + }); + + promise.then(function(value) { + assert(false); + done(); + })['catch'](function(reason) { + assert.equal(reason.message, "You cannot resolve a promise with itself"); + assert(reason instanceof TypeError); + done(); + }); + }); + + it('should assimilate two levels deep, for fulfillment', function(done) { + var originalPromise = new Promise(function(resolve) { resolve('original value'); }); + var nextPromise = new Promise(function(resolve) { resolve(originalPromise); }); + var promise = new Promise(function(resolve) { resolve(nextPromise); }); + + promise.then(function(value) { + assert.equal(value, 'original value'); + done(); + }); + }); + + it('should assimilate two levels deep, for rejection', function(done) { + var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); + var nextPromise = new Promise(function(resolve) { resolve(originalPromise); }); + var promise = new Promise(function(resolve) { resolve(nextPromise); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'original reason'); + done(); + }); + }); + + it('should assimilate three levels deep, mixing thenables and promises (fulfilled case)', function(done) { + var originalPromise = new Promise(function(resolve) { resolve('original value'); }); + var intermediateThenable = { + then: function (onFulfilled) { + setTimeout(function() { onFulfilled(originalPromise); }, 0); + } + }; + var promise = new Promise(function(resolve) { resolve(intermediateThenable); }); + + promise.then(function(value) { + assert.equal(value, 'original value'); + done(); + }); + }); + + it('should assimilate three levels deep, mixing thenables and promises (rejected case)', function(done) { + var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); + var intermediateThenable = { + then: function (onFulfilled) { + setTimeout(function() { onFulfilled(originalPromise); }, 0); + } + }; + var promise = new Promise(function(resolve) { resolve(intermediateThenable); }); + + promise.then(function() { + assert(false); + done(); + }, function(reason) { + assert.equal(reason, 'original reason'); + done(); + }); + }); + }); + }); + + describe("Promise.all", function() { + testAll(function(){ + return Promise.all.apply(Promise, arguments); + }); + }); + + function testAll(all) { + it('should exist', function() { + assert(all); + }); + + it('throws when not passed an array', function(done) { + var nothing = assertRejection(all()); + var string = assertRejection(all('')); + var object = assertRejection(all({})); + + Promise.all([ + nothing, + string, + object + ]).then(function(){ done(); }); + }); + + specify('fulfilled only after all of the other promises are fulfilled', function(done) { + var firstResolved, secondResolved, firstResolver, secondResolver; + + var first = new Promise(function(resolve) { + firstResolver = resolve; + }); + first.then(function() { + firstResolved = true; + }); + + var second = new Promise(function(resolve) { + secondResolver = resolve; + }); + second.then(function() { + secondResolved = true; + }); + + setTimeout(function() { + firstResolver(true); + }, 0); + + setTimeout(function() { + secondResolver(true); + }, 0); + + all([first, second]).then(function() { + assert(firstResolved); + assert(secondResolved); + done(); + }); + }); + + specify('rejected as soon as a promise is rejected', function(done) { + var firstResolver, secondResolver; + + var first = new Promise(function(resolve, reject) { + firstResolver = { resolve: resolve, reject: reject }; + }); + + var second = new Promise(function(resolve, reject) { + secondResolver = { resolve: resolve, reject: reject }; + }); + + setTimeout(function() { + firstResolver.reject({}); + }, 0); + + var firstWasRejected, secondCompleted; + + first['catch'](function(){ + firstWasRejected = true; + }); + + second.then(function(){ + secondCompleted = true; + }, function() { + secondCompleted = true; + }); + + all([first, second]).then(function() { + assert(false); + }, function() { + assert(firstWasRejected); + assert(!secondCompleted); + done(); + }); + }); + + specify('passes the resolved values of each promise to the callback in the correct order', function(done) { + var firstResolver, secondResolver, thirdResolver; + + var first = new Promise(function(resolve, reject) { + firstResolver = { resolve: resolve, reject: reject }; + }); + + var second = new Promise(function(resolve, reject) { + secondResolver = { resolve: resolve, reject: reject }; + }); + + var third = new Promise(function(resolve, reject) { + thirdResolver = { resolve: resolve, reject: reject }; + }); + + thirdResolver.resolve(3); + firstResolver.resolve(1); + secondResolver.resolve(2); + + all([first, second, third]).then(function(results) { + assert(results.length === 3); + assert(results[0] === 1); + assert(results[1] === 2); + assert(results[2] === 3); + done(); + }); + }); + + specify('resolves an empty array passed to all()', function(done) { + all([]).then(function(results) { + assert(results.length === 0); + done(); + }); + }); + + specify('works with null', function(done) { + all([null]).then(function(results) { + assert.equal(results[0], null); + done(); + }); + }); + + specify('works with a mix of promises and thenables and non-promises', function(done) { + var promise = new Promise(function(resolve) { resolve(1); }); + var syncThenable = { then: function (onFulfilled) { onFulfilled(2); } }; + var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } }; + var nonPromise = 4; + + all([promise, syncThenable, asyncThenable, nonPromise]).then(function(results) { + assert(objectEquals(results, [1, 2, 3, 4])); + done(); + })['catch'](done); + }); + } + + describe("reject", function(){ + specify("it should exist", function(){ + assert(Promise.reject); + }); + + describe('it rejects', function(){ + var reason = 'the reason', + promise = Promise.reject(reason); + + promise.then(function(){ + assert(false, 'should not fulfill'); + }, function(actualReason){ + assert.equal(reason, actualReason); + }); + }); + }); + + function assertRejection(promise) { + return promise.then(function(){ + assert(false, 'expected rejection, but got fulfillment'); + }, function(reason){ + assert(reason instanceof Error); + }); + } + + describe('race', function() { + it("should exist", function() { + assert(Promise.race); + }); + + it("throws when not passed an array", function(done) { + var nothing = assertRejection(Promise.race()); + var string = assertRejection(Promise.race('')); + var object = assertRejection(Promise.race({})); + + Promise.all([ + nothing, + string, + object + ]).then(function(){ done(); }); + }); + + specify('fulfilled after one of the other promises are fulfilled', function(done) { + var firstResolved, secondResolved, firstResolver, secondResolver; + + var first = new Promise(function(resolve) { + firstResolver = resolve; + }); + first.then(function() { + firstResolved = true; + }); + + var second = new Promise(function(resolve) { + secondResolver = resolve; + }); + second.then(function() { + secondResolved = true; + }); + + setTimeout(function() { + firstResolver(true); + }, 100); + + setTimeout(function() { + secondResolver(true); + }, 0); + + Promise.race([first, second]).then(function() { + assert(secondResolved); + assert.equal(firstResolved, undefined); + done(); + }); + }); + + specify('the race begins on nextTurn and prioritized by array entry', function(done) { + var firstResolver, secondResolver, nonPromise = 5; + + var first = new Promise(function(resolve, reject) { + resolve(true); + }); + + var second = new Promise(function(resolve, reject) { + resolve(false); + }); + + Promise.race([first, second, nonPromise]).then(function(value) { + assert.equal(value, true); + done(); + }); + }); + + specify('rejected as soon as a promise is rejected', function(done) { + var firstResolver, secondResolver; + + var first = new Promise(function(resolve, reject) { + firstResolver = { resolve: resolve, reject: reject }; + }); + + var second = new Promise(function(resolve, reject) { + secondResolver = { resolve: resolve, reject: reject }; + }); + + setTimeout(function() { + firstResolver.reject({}); + }, 0); + + var firstWasRejected, secondCompleted; + + first['catch'](function(){ + firstWasRejected = true; + }); + + second.then(function(){ + secondCompleted = true; + }, function() { + secondCompleted = true; + }); + + Promise.race([first, second]).then(function() { + assert(false); + }, function() { + assert(firstWasRejected); + assert(!secondCompleted); + done(); + }); + }); + + specify('resolves an empty array to forever pending Promise', function(done) { + var foreverPendingPromise = Promise.race([]), + wasSettled = false; + + foreverPendingPromise.then(function() { + wasSettled = true; + }, function() { + wasSettled = true; + }); + + setTimeout(function() { + assert(!wasSettled); + done(); + }, 100); + }); + + specify('works with a mix of promises and thenables', function(done) { + var promise = new Promise(function(resolve) { setTimeout(function() { resolve(1); }, 10); }), + syncThenable = { then: function (onFulfilled) { onFulfilled(2); } }; + + Promise.race([promise, syncThenable]).then(function(result) { + assert(result, 2); + done(); + }); + }); + + specify('works with a mix of thenables and non-promises', function (done) { + var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } }, + nonPromise = 4; + + Promise.race([asyncThenable, nonPromise]).then(function(result) { + assert(result, 4); + done(); + }); + }); + }); + + describe("resolve", function(){ + specify("it should exist", function(){ + assert(Promise.resolve); + }); + + describe("1. If x is a promise, adopt its state ", function(){ + specify("1.1 If x is pending, promise must remain pending until x is fulfilled or rejected.", function(done){ + var expectedValue, resolver, thenable, wrapped; + + expectedValue = 'the value'; + thenable = { + then: function(resolve, reject){ + resolver = resolve; + } + }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(function(value){ + assert(value === expectedValue); + done(); + }); + + setTimeout(function(){ + resolver(expectedValue); + }, 10); + }); + + specify("1.2 If/when x is fulfilled, fulfill promise with the same value.", function(done){ + var expectedValue, thenable, wrapped; + + expectedValue = 'the value'; + thenable = { + then: function(resolve, reject){ + resolve(expectedValue); + } + }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(function(value){ + assert(value === expectedValue); + done(); + }) + }); + + specify("1.3 If/when x is rejected, reject promise with the same reason.", function(done){ + var expectedError, thenable, wrapped; + + expectedError = new Error(); + thenable = { + then: function(resolve, reject){ + reject(expectedError); + } + }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(null, function(error){ + assert(error === expectedError); + done(); + }); + }); + }); + + describe("2. Otherwise, if x is an object or function,", function(){ + specify("2.1 Let then x.then", function(done){ + var accessCount, resolver, wrapped, thenable; + + accessCount = 0; + thenable = { }; + + // we likely don't need to test this, if the browser doesn't support it + if (typeof Object.defineProperty !== "function") { done(); return; } + + Object.defineProperty(thenable, 'then', { + get: function(){ + accessCount++; + + if (accessCount > 1) { + throw new Error(); + } + + return function(){ }; + } + }); + + assert(accessCount === 0); + + wrapped = Promise.resolve(thenable); + + assert(accessCount === 1); + + done(); + }); + + specify("2.2 If retrieving the property x.then results in a thrown exception e, reject promise with e as the reason.", function(done){ + var wrapped, thenable, expectedError; + + expectedError = new Error(); + thenable = { }; + + // we likely don't need to test this, if the browser doesn't support it + if (typeof Object.defineProperty !== "function") { done(); return; } + + Object.defineProperty(thenable, 'then', { + get: function(){ + throw expectedError; + } + }); + + wrapped = Promise.resolve(thenable); + + wrapped.then(null, function(error){ + assert(error === expectedError, 'incorrect exception was thrown'); + done(); + }); + }); + + describe('2.3. If then is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise, where', function(){ + specify('2.3.1 If/when resolvePromise is called with a value y, run Resolve(promise, y)', function(done){ + var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis; + + thenable = { + then: function(resolve, reject){ + calledThis = this; + resolver = resolve; + rejector = reject; + } + }; + + expectedSuccess = 'success'; + wrapped = Promise.resolve(thenable); + + wrapped.then(function(success){ + assert(calledThis === thenable, 'this must be the thenable'); + assert(success === expectedSuccess, 'rejected promise with x'); + done(); + }); + + setTimeout(function() { + resolver(expectedSuccess); + }, 20); + }); + + specify('2.3.2 If/when rejectPromise is called with a reason r, reject promise with r.', function(done){ + var expectedError, resolver, rejector, thenable, wrapped, calledThis; + + thenable = { + then: function(resolve, reject){ + calledThis = this; + resolver = resolve; + rejector = reject; + } + }; + + expectedError = new Error(); + + wrapped = Promise.resolve(thenable); + + wrapped.then(null, function(error){ + assert(error === expectedError, 'rejected promise with x'); + done(); + }); + + setTimeout(function() { + rejector(expectedError); + }, 20); + }); + + specify("2.3.3 If both resolvePromise and rejectPromise are called, or multiple calls to the same argument are made, the first call takes precedence, and any further calls are ignored", function(done){ + var expectedError, expectedSuccess, resolver, rejector, thenable, wrapped, calledThis, + calledRejected, calledResolved; + + calledRejected = 0; + calledResolved = 0; + + thenable = { + then: function(resolve, reject){ + calledThis = this; + resolver = resolve; + rejector = reject; + } + }; + + expectedError = new Error(); + + wrapped = Promise.resolve(thenable); + + wrapped.then(function(){ + calledResolved++; + }, function(error){ + calledRejected++; + assert(calledResolved === 0, 'never resolved'); + assert(calledRejected === 1, 'rejected only once'); + assert(error === expectedError, 'rejected promise with x'); + }); + + setTimeout(function() { + rejector(expectedError); + rejector(expectedError); + + rejector('foo'); + + resolver('bar'); + resolver('baz'); + }, 20); + + setTimeout(function(){ + assert(calledRejected === 1, 'only rejected once'); + assert(calledResolved === 0, 'never resolved'); + done(); + }, 50); + }); + + describe("2.3.4 If calling then throws an exception e", function(){ + specify("2.3.4.1 If resolvePromise or rejectPromise have been called, ignore it.", function(done){ + var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis, + calledRejected, calledResolved; + + expectedSuccess = 'success'; + + thenable = { + then: function(resolve, reject){ + resolve(expectedSuccess); + throw expectedError; + } + }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(function(success){ + assert(success === expectedSuccess, 'resolved not errored'); + done(); + }); + }); + + specify("2.3.4.2 Otherwise, reject promise with e as the reason.", function(done) { + var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount; + + expectedError = new Error(); + callCount = 0; + + thenable = { then: function() { throw expectedError; } }; + + wrapped = Promise.resolve(thenable); + + wrapped.then(null, function(error){ + callCount++; + assert(expectedError === error, 'expected the correct error to be rejected'); + done(); + }); + + assert(callCount === 0, 'expected async, was sync'); + }); + }); + }); + + specify("2.4 If then is not a function, fulfill promise with x", function(done){ + var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount; + + thenable = { then: 3 }; + callCount = 0; + wrapped = Promise.resolve(thenable); + + wrapped.then(function(success){ + callCount++; + assert(thenable === success, 'fulfilled promise with x'); + done(); + }); + + assert(callCount === 0, 'expected async, was sync'); + }); + }); + + describe("3. If x is not an object or function, ", function(){ + specify("fulfill promise with x.", function(done){ + var thenable, callCount, wrapped; + + thenable = null; + callCount = 0; + wrapped = Promise.resolve(thenable); + + wrapped.then(function(success){ + callCount++; + assert(success === thenable, 'fulfilled promise with x'); + done(); + }, function(a){ + assert(false, 'should not also reject'); + }); + + assert(callCount === 0, 'expected async, was sync'); + }); + }); + }); + + if (typeof Worker !== 'undefined') { + describe('web worker', function () { + it('should work', function (done) { + this.timeout(2000); + var worker = new Worker('worker.js'); + worker.addEventListener('error', function(reason) { + done(new Error("Test failed:" + reason)); + }); + worker.addEventListener('message', function (e) { + worker.terminate(); + assert.equal(e.data, 'pong'); + done(); + }); + worker.postMessage('ping'); + }); + }); + } +}); + +// thanks to @wizardwerdna for the test case -> https://github.com/tildeio/rsvp.js/issues/66 +// Only run these tests in node (phantomjs cannot handle them) +if (typeof module !== 'undefined' && module.exports) { + + describe("using reduce to sum integers using promises", function(){ + it("should build the promise pipeline without error", function(){ + var array, iters, pZero, i; + + array = []; + iters = 1000; + + for (i=1; i<=iters; i++) { + array.push(i); + } + + pZero = Promise.resolve(0); + + array.reduce(function(promise, nextVal) { + return promise.then(function(currentVal) { + return Promise.resolve(currentVal + nextVal); + }); + }, pZero); + }); + + it("should get correct answer without blowing the nextTick stack", function(done){ + var pZero, array, iters, result, i; + + pZero = Promise.resolve(0); + + array = []; + iters = 1000; + + for (i=1; i<=iters; i++) { + array.push(i); + } + + result = array.reduce(function(promise, nextVal) { + return promise.then(function(currentVal) { + return Promise.resolve(currentVal + nextVal); + }); + }, pZero); + + result.then(function(value){ + assert.equal(value, (iters*(iters+1)/2)); + done(); + }); + }); + }); +} + +// Kudos to @Octane at https://github.com/getify/native-promise-only/issues/5 for this, and @getify for pinging me. +describe("Thenables should not be able to run code during assimilation", function () { + specify("resolving to a thenable", function () { + var thenCalled = false; + var thenable = { + then: function () { + thenCalled = true; + } + }; + + Promise.resolve(thenable); + assert.strictEqual(thenCalled, false); + }); + + specify("resolving to an evil promise", function () { + var thenCalled = false; + var evilPromise = Promise.resolve(); + evilPromise.then = function () { + thenCalled = true; + }; + + Promise.resolve(evilPromise); + assert.strictEqual(thenCalled, false); + }); +}); + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"assert":2}],53:[function(require,module,exports){ +(function (global){ +var assert = require('assert'); +var g = typeof window !== 'undefined' ? + window : typeof global !== 'undefined' ? global : this; + +var Promise = g.ES6Promise || require('./es6-promise').Promise; + +function defer() { + var deferred = {}; + + deferred.promise = new Promise(function(resolve, reject) { + deferred.resolve = resolve; + deferred.reject = reject; + }); + + return deferred; +} +var resolve = Promise.resolve; +var reject = Promise.reject; + + +module.exports = g.adapter = { + resolved: function(a) { return Promise.resolve(a); }, + rejected: function(a) { return Promise.reject(a); }, + deferred: defer, + Promise: Promise +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./es6-promise":51,"assert":2}]},{},[1]); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js new file mode 100644 index 0000000..5b096d6 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js @@ -0,0 +1,950 @@ +(function() { + "use strict"; + function lib$es6$promise$utils$$objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); + } + + function lib$es6$promise$utils$$isFunction(x) { + return typeof x === 'function'; + } + + function lib$es6$promise$utils$$isMaybeThenable(x) { + return typeof x === 'object' && x !== null; + } + + var lib$es6$promise$utils$$_isArray; + if (!Array.isArray) { + lib$es6$promise$utils$$_isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; + } else { + lib$es6$promise$utils$$_isArray = Array.isArray; + } + + var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; + var lib$es6$promise$asap$$len = 0; + var lib$es6$promise$asap$$toString = {}.toString; + var lib$es6$promise$asap$$vertxNext; + function lib$es6$promise$asap$$asap(callback, arg) { + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; + lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; + lib$es6$promise$asap$$len += 2; + if (lib$es6$promise$asap$$len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + lib$es6$promise$asap$$scheduleFlush(); + } + } + + var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; + + var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; + var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; + var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; + var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + + // test for web worker but not in IE10 + var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + + // node + function lib$es6$promise$asap$$useNextTick() { + var nextTick = process.nextTick; + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // setImmediate should be used instead instead + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function() { + nextTick(lib$es6$promise$asap$$flush); + }; + } + + // vertx + function lib$es6$promise$asap$$useVertxTimer() { + return function() { + lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); + }; + } + + function lib$es6$promise$asap$$useMutationObserver() { + var iterations = 0; + var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; + } + + // web worker + function lib$es6$promise$asap$$useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = lib$es6$promise$asap$$flush; + return function () { + channel.port2.postMessage(0); + }; + } + + function lib$es6$promise$asap$$useSetTimeout() { + return function() { + setTimeout(lib$es6$promise$asap$$flush, 1); + }; + } + + var lib$es6$promise$asap$$queue = new Array(1000); + function lib$es6$promise$asap$$flush() { + for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { + var callback = lib$es6$promise$asap$$queue[i]; + var arg = lib$es6$promise$asap$$queue[i+1]; + + callback(arg); + + lib$es6$promise$asap$$queue[i] = undefined; + lib$es6$promise$asap$$queue[i+1] = undefined; + } + + lib$es6$promise$asap$$len = 0; + } + + function lib$es6$promise$asap$$attemptVertex() { + try { + var r = require; + var vertx = r('vertx'); + lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; + return lib$es6$promise$asap$$useVertxTimer(); + } catch(e) { + return lib$es6$promise$asap$$useSetTimeout(); + } + } + + var lib$es6$promise$asap$$scheduleFlush; + // Decide what async method to use to triggering processing of queued callbacks: + if (lib$es6$promise$asap$$isNode) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); + } else if (lib$es6$promise$asap$$BrowserMutationObserver) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); + } else if (lib$es6$promise$asap$$isWorker) { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); + } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); + } else { + lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); + } + + function lib$es6$promise$$internal$$noop() {} + + var lib$es6$promise$$internal$$PENDING = void 0; + var lib$es6$promise$$internal$$FULFILLED = 1; + var lib$es6$promise$$internal$$REJECTED = 2; + + var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$selfFullfillment() { + return new TypeError("You cannot resolve a promise with itself"); + } + + function lib$es6$promise$$internal$$cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); + } + + function lib$es6$promise$$internal$$getThen(promise) { + try { + return promise.then; + } catch(error) { + lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; + return lib$es6$promise$$internal$$GET_THEN_ERROR; + } + } + + function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } + } + + function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { + lib$es6$promise$asap$$default(function(promise) { + var sealed = false; + var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + lib$es6$promise$$internal$$resolve(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + lib$es6$promise$$internal$$reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + lib$es6$promise$$internal$$reject(promise, error); + } + }, promise); + } + + function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { + if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, thenable._result); + } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, thenable._result); + } else { + lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { + lib$es6$promise$$internal$$resolve(promise, value); + }, function(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } + } + + function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); + } else { + var then = lib$es6$promise$$internal$$getThen(maybeThenable); + + if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); + } else if (then === undefined) { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } else if (lib$es6$promise$utils$$isFunction(then)) { + lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); + } else { + lib$es6$promise$$internal$$fulfill(promise, maybeThenable); + } + } + } + + function lib$es6$promise$$internal$$resolve(promise, value) { + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); + } else if (lib$es6$promise$utils$$objectOrFunction(value)) { + lib$es6$promise$$internal$$handleMaybeThenable(promise, value); + } else { + lib$es6$promise$$internal$$fulfill(promise, value); + } + } + + function lib$es6$promise$$internal$$publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + lib$es6$promise$$internal$$publish(promise); + } + + function lib$es6$promise$$internal$$fulfill(promise, value) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + + promise._result = value; + promise._state = lib$es6$promise$$internal$$FULFILLED; + + if (promise._subscribers.length !== 0) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); + } + } + + function lib$es6$promise$$internal$$reject(promise, reason) { + if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } + promise._state = lib$es6$promise$$internal$$REJECTED; + promise._result = reason; + + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); + } + + function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; + subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; + + if (length === 0 && parent._state) { + lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); + } + } + + function lib$es6$promise$$internal$$publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; + } + + function lib$es6$promise$$internal$$ErrorObject() { + this.error = null; + } + + var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); + + function lib$es6$promise$$internal$$tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; + return lib$es6$promise$$internal$$TRY_CATCH_ERROR; + } + } + + function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { + var hasCallback = lib$es6$promise$utils$$isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = lib$es6$promise$$internal$$tryCatch(callback, detail); + + if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== lib$es6$promise$$internal$$PENDING) { + // noop + } else if (hasCallback && succeeded) { + lib$es6$promise$$internal$$resolve(promise, value); + } else if (failed) { + lib$es6$promise$$internal$$reject(promise, error); + } else if (settled === lib$es6$promise$$internal$$FULFILLED) { + lib$es6$promise$$internal$$fulfill(promise, value); + } else if (settled === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } + } + + function lib$es6$promise$$internal$$initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + lib$es6$promise$$internal$$resolve(promise, value); + }, function rejectPromise(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + }); + } catch(e) { + lib$es6$promise$$internal$$reject(promise, e); + } + } + + function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); + } + } + } else { + lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); + } + } + + lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { + return lib$es6$promise$utils$$isArray(input); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { + this._result = new Array(this.length); + }; + + var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; + + lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (lib$es6$promise$utils$$isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === lib$es6$promise$$internal$$PENDING) { + enumerator._remaining--; + + if (state === lib$es6$promise$$internal$$REJECTED) { + lib$es6$promise$$internal$$reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + lib$es6$promise$$internal$$fulfill(promise, enumerator._result); + } + }; + + lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { + enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); + }); + }; + function lib$es6$promise$promise$all$$all(entries) { + return new lib$es6$promise$enumerator$$default(this, entries).promise; + } + var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; + function lib$es6$promise$promise$race$$race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + + if (!lib$es6$promise$utils$$isArray(entries)) { + lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + lib$es6$promise$$internal$$resolve(promise, value); + } + + function onRejection(reason) { + lib$es6$promise$$internal$$reject(promise, reason); + } + + for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { + lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; + } + var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; + function lib$es6$promise$promise$resolve$$resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$resolve(promise, object); + return promise; + } + var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; + function lib$es6$promise$promise$reject$$reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(lib$es6$promise$$internal$$noop); + lib$es6$promise$$internal$$reject(promise, reason); + return promise; + } + var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; + + var lib$es6$promise$promise$$counter = 0; + + function lib$es6$promise$promise$$needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); + } + + function lib$es6$promise$promise$$needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); + } + + var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; + /** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor + */ + function lib$es6$promise$promise$$Promise(resolver) { + this._id = lib$es6$promise$promise$$counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (lib$es6$promise$$internal$$noop !== resolver) { + if (!lib$es6$promise$utils$$isFunction(resolver)) { + lib$es6$promise$promise$$needsResolver(); + } + + if (!(this instanceof lib$es6$promise$promise$$Promise)) { + lib$es6$promise$promise$$needsNew(); + } + + lib$es6$promise$$internal$$initializePromise(this, resolver); + } + } + + lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; + lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; + lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; + lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; + + lib$es6$promise$promise$$Promise.prototype = { + constructor: lib$es6$promise$promise$$Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(lib$es6$promise$$internal$$noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + lib$es6$promise$asap$$default(function(){ + lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); + }); + } else { + lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } + }; + function lib$es6$promise$polyfill$$polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = lib$es6$promise$promise$$default; + } + var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; + + var lib$es6$promise$umd$$ES6Promise = { + 'Promise': lib$es6$promise$promise$$default, + 'polyfill': lib$es6$promise$polyfill$$default + }; + + /* global define:true module:true window: true */ + if (typeof define === 'function' && define['amd']) { + define(function() { return lib$es6$promise$umd$$ES6Promise; }); + } else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = lib$es6$promise$umd$$ES6Promise; + } else if (typeof this !== 'undefined') { + this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; + } + + lib$es6$promise$polyfill$$default(); +}).call(this); + +//# sourceMappingURL=es6-promise.js.map \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js new file mode 100644 index 0000000..34a1f52 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js @@ -0,0 +1 @@ +(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;function lib$es6$promise$asap$$asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){lib$es6$promise$asap$$scheduleFlush()}}var lib$es6$promise$asap$$default=lib$es6$promise$asap$$asap;var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){var nextTick=process.nextTick;var version=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);if(Array.isArray(version)&&version[1]==="0"&&version[2]==="10"){nextTick=setImmediate}return function(){nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i + + + rsvp.js Tests + + + +
    + + + + + + + + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js new file mode 100644 index 0000000..4817c9e --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js @@ -0,0 +1,902 @@ +/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ +;(function () { + // Detect the `define` function exposed by asynchronous module loaders. The + // strict `define` check is necessary for compatibility with `r.js`. + var isLoader = typeof define === "function" && define.amd; + + // A set of types used to distinguish objects from primitives. + var objectTypes = { + "function": true, + "object": true + }; + + // Detect the `exports` object exposed by CommonJS implementations. + var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; + + // Use the `global` object exposed by Node (including Browserify via + // `insert-module-globals`), Narwhal, and Ringo as the default context, + // and the `window` object in browsers. Rhino exports a `global` function + // instead. + var root = objectTypes[typeof window] && window || this, + freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; + + if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { + root = freeGlobal; + } + + // Public: Initializes JSON 3 using the given `context` object, attaching the + // `stringify` and `parse` functions to the specified `exports` object. + function runInContext(context, exports) { + context || (context = root["Object"]()); + exports || (exports = root["Object"]()); + + // Native constructor aliases. + var Number = context["Number"] || root["Number"], + String = context["String"] || root["String"], + Object = context["Object"] || root["Object"], + Date = context["Date"] || root["Date"], + SyntaxError = context["SyntaxError"] || root["SyntaxError"], + TypeError = context["TypeError"] || root["TypeError"], + Math = context["Math"] || root["Math"], + nativeJSON = context["JSON"] || root["JSON"]; + + // Delegate to the native `stringify` and `parse` implementations. + if (typeof nativeJSON == "object" && nativeJSON) { + exports.stringify = nativeJSON.stringify; + exports.parse = nativeJSON.parse; + } + + // Convenience aliases. + var objectProto = Object.prototype, + getClass = objectProto.toString, + isProperty, forEach, undef; + + // Test the `Date#getUTC*` methods. Based on work by @Yaffle. + var isExtended = new Date(-3509827334573292); + try { + // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical + // results for certain dates in Opera >= 10.53. + isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && + // Safari < 2.0.2 stores the internal millisecond time value correctly, + // but clips the values returned by the date methods to the range of + // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]). + isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; + } catch (exception) {} + + // Internal: Determines whether the native `JSON.stringify` and `parse` + // implementations are spec-compliant. Based on work by Ken Snyder. + function has(name) { + if (has[name] !== undef) { + // Return cached feature test result. + return has[name]; + } + var isSupported; + if (name == "bug-string-char-index") { + // IE <= 7 doesn't support accessing string characters using square + // bracket notation. IE 8 only supports this for primitives. + isSupported = "a"[0] != "a"; + } else if (name == "json") { + // Indicates whether both `JSON.stringify` and `JSON.parse` are + // supported. + isSupported = has("json-stringify") && has("json-parse"); + } else { + var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; + // Test `JSON.stringify`. + if (name == "json-stringify") { + var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; + if (stringifySupported) { + // A test function object with a custom `toJSON` method. + (value = function () { + return 1; + }).toJSON = value; + try { + stringifySupported = + // Firefox 3.1b1 and b2 serialize string, number, and boolean + // primitives as object literals. + stringify(0) === "0" && + // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object + // literals. + stringify(new Number()) === "0" && + stringify(new String()) == '""' && + // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or + // does not define a canonical JSON representation (this applies to + // objects with `toJSON` properties as well, *unless* they are nested + // within an object or array). + stringify(getClass) === undef && + // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and + // FF 3.1b3 pass this test. + stringify(undef) === undef && + // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, + // respectively, if the value is omitted entirely. + stringify() === undef && + // FF 3.1b1, 2 throw an error if the given value is not a number, + // string, array, object, Boolean, or `null` literal. This applies to + // objects with custom `toJSON` methods as well, unless they are nested + // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` + // methods entirely. + stringify(value) === "1" && + stringify([value]) == "[1]" && + // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of + // `"[null]"`. + stringify([undef]) == "[null]" && + // YUI 3.0.0b1 fails to serialize `null` literals. + stringify(null) == "null" && + // FF 3.1b1, 2 halts serialization if an array contains a function: + // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 + // elides non-JSON values from objects and arrays, unless they + // define custom `toJSON` methods. + stringify([undef, getClass, null]) == "[null,null,null]" && + // Simple serialization test. FF 3.1b1 uses Unicode escape sequences + // where character escape codes are expected (e.g., `\b` => `\u0008`). + stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && + // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. + stringify(null, value) === "1" && + stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && + // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly + // serialize extended years. + stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && + // The milliseconds are optional in ES 5, but required in 5.1. + stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && + // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative + // four-digit years instead of six-digit years. Credits: @Yaffle. + stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && + // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond + // values less than 1000. Credits: @Yaffle. + stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; + } catch (exception) { + stringifySupported = false; + } + } + isSupported = stringifySupported; + } + // Test `JSON.parse`. + if (name == "json-parse") { + var parse = exports.parse; + if (typeof parse == "function") { + try { + // FF 3.1b1, b2 will throw an exception if a bare literal is provided. + // Conforming implementations should also coerce the initial argument to + // a string prior to parsing. + if (parse("0") === 0 && !parse(false)) { + // Simple parsing test. + value = parse(serialized); + var parseSupported = value["a"].length == 5 && value["a"][0] === 1; + if (parseSupported) { + try { + // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. + parseSupported = !parse('"\t"'); + } catch (exception) {} + if (parseSupported) { + try { + // FF 4.0 and 4.0.1 allow leading `+` signs and leading + // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow + // certain octal literals. + parseSupported = parse("01") !== 1; + } catch (exception) {} + } + if (parseSupported) { + try { + // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal + // points. These environments, along with FF 3.1b1 and 2, + // also allow trailing commas in JSON objects and arrays. + parseSupported = parse("1.") !== 1; + } catch (exception) {} + } + } + } + } catch (exception) { + parseSupported = false; + } + } + isSupported = parseSupported; + } + } + return has[name] = !!isSupported; + } + + if (!has("json")) { + // Common `[[Class]]` name aliases. + var functionClass = "[object Function]", + dateClass = "[object Date]", + numberClass = "[object Number]", + stringClass = "[object String]", + arrayClass = "[object Array]", + booleanClass = "[object Boolean]"; + + // Detect incomplete support for accessing string characters by index. + var charIndexBuggy = has("bug-string-char-index"); + + // Define additional utility methods if the `Date` methods are buggy. + if (!isExtended) { + var floor = Math.floor; + // A mapping between the months of the year and the number of days between + // January 1st and the first of the respective month. + var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + // Internal: Calculates the number of days between the Unix epoch and the + // first day of the given month. + var getDay = function (year, month) { + return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); + }; + } + + // Internal: Determines if a property is a direct property of the given + // object. Delegates to the native `Object#hasOwnProperty` method. + if (!(isProperty = objectProto.hasOwnProperty)) { + isProperty = function (property) { + var members = {}, constructor; + if ((members.__proto__ = null, members.__proto__ = { + // The *proto* property cannot be set multiple times in recent + // versions of Firefox and SeaMonkey. + "toString": 1 + }, members).toString != getClass) { + // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but + // supports the mutable *proto* property. + isProperty = function (property) { + // Capture and break the object's prototype chain (see section 8.6.2 + // of the ES 5.1 spec). The parenthesized expression prevents an + // unsafe transformation by the Closure Compiler. + var original = this.__proto__, result = property in (this.__proto__ = null, this); + // Restore the original prototype chain. + this.__proto__ = original; + return result; + }; + } else { + // Capture a reference to the top-level `Object` constructor. + constructor = members.constructor; + // Use the `constructor` property to simulate `Object#hasOwnProperty` in + // other environments. + isProperty = function (property) { + var parent = (this.constructor || constructor).prototype; + return property in this && !(property in parent && this[property] === parent[property]); + }; + } + members = null; + return isProperty.call(this, property); + }; + } + + // Internal: Normalizes the `for...in` iteration algorithm across + // environments. Each enumerated key is yielded to a `callback` function. + forEach = function (object, callback) { + var size = 0, Properties, members, property; + + // Tests for bugs in the current environment's `for...in` algorithm. The + // `valueOf` property inherits the non-enumerable flag from + // `Object.prototype` in older versions of IE, Netscape, and Mozilla. + (Properties = function () { + this.valueOf = 0; + }).prototype.valueOf = 0; + + // Iterate over a new instance of the `Properties` class. + members = new Properties(); + for (property in members) { + // Ignore all properties inherited from `Object.prototype`. + if (isProperty.call(members, property)) { + size++; + } + } + Properties = members = null; + + // Normalize the iteration algorithm. + if (!size) { + // A list of non-enumerable properties inherited from `Object.prototype`. + members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; + // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable + // properties. + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, length; + var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; + for (property in object) { + // Gecko <= 1.0 enumerates the `prototype` property of functions under + // certain conditions; IE does not. + if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { + callback(property); + } + } + // Manually invoke the callback for each non-enumerable property. + for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); + }; + } else if (size == 2) { + // Safari <= 2.0.4 enumerates shadowed properties twice. + forEach = function (object, callback) { + // Create a set of iterated properties. + var members = {}, isFunction = getClass.call(object) == functionClass, property; + for (property in object) { + // Store each property name to prevent double enumeration. The + // `prototype` property of functions is not enumerated due to cross- + // environment inconsistencies. + if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { + callback(property); + } + } + }; + } else { + // No bugs detected; use the standard `for...in` algorithm. + forEach = function (object, callback) { + var isFunction = getClass.call(object) == functionClass, property, isConstructor; + for (property in object) { + if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { + callback(property); + } + } + // Manually invoke the callback for the `constructor` property due to + // cross-environment inconsistencies. + if (isConstructor || isProperty.call(object, (property = "constructor"))) { + callback(property); + } + }; + } + return forEach(object, callback); + }; + + // Public: Serializes a JavaScript `value` as a JSON string. The optional + // `filter` argument may specify either a function that alters how object and + // array members are serialized, or an array of strings and numbers that + // indicates which properties should be serialized. The optional `width` + // argument may be either a string or number that specifies the indentation + // level of the output. + if (!has("json-stringify")) { + // Internal: A map of control characters and their escaped equivalents. + var Escapes = { + 92: "\\\\", + 34: '\\"', + 8: "\\b", + 12: "\\f", + 10: "\\n", + 13: "\\r", + 9: "\\t" + }; + + // Internal: Converts `value` into a zero-padded string such that its + // length is at least equal to `width`. The `width` must be <= 6. + var leadingZeroes = "000000"; + var toPaddedString = function (width, value) { + // The `|| 0` expression is necessary to work around a bug in + // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. + return (leadingZeroes + (value || 0)).slice(-width); + }; + + // Internal: Double-quotes a string `value`, replacing all ASCII control + // characters (characters with code unit values between 0 and 31) with + // their escaped equivalents. This is an implementation of the + // `Quote(value)` operation defined in ES 5.1 section 15.12.3. + var unicodePrefix = "\\u00"; + var quote = function (value) { + var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; + var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); + for (; index < length; index++) { + var charCode = value.charCodeAt(index); + // If the character is a control character, append its Unicode or + // shorthand escape sequence; otherwise, append the character as-is. + switch (charCode) { + case 8: case 9: case 10: case 12: case 13: case 34: case 92: + result += Escapes[charCode]; + break; + default: + if (charCode < 32) { + result += unicodePrefix + toPaddedString(2, charCode.toString(16)); + break; + } + result += useCharIndex ? symbols[index] : value.charAt(index); + } + } + return result + '"'; + }; + + // Internal: Recursively serializes an object. Implements the + // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. + var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { + var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; + try { + // Necessary for host object support. + value = object[property]; + } catch (exception) {} + if (typeof value == "object" && value) { + className = getClass.call(value); + if (className == dateClass && !isProperty.call(value, "toJSON")) { + if (value > -1 / 0 && value < 1 / 0) { + // Dates are serialized according to the `Date#toJSON` method + // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 + // for the ISO 8601 date time string format. + if (getDay) { + // Manually compute the year, month, date, hours, minutes, + // seconds, and milliseconds if the `getUTC*` methods are + // buggy. Adapted from @Yaffle's `date-shim` project. + date = floor(value / 864e5); + for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); + for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); + date = 1 + date - getDay(year, month); + // The `time` value specifies the time within the day (see ES + // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used + // to compute `A modulo B`, as the `%` operator does not + // correspond to the `modulo` operation for negative numbers. + time = (value % 864e5 + 864e5) % 864e5; + // The hours, minutes, seconds, and milliseconds are obtained by + // decomposing the time within the day. See section 15.9.1.10. + hours = floor(time / 36e5) % 24; + minutes = floor(time / 6e4) % 60; + seconds = floor(time / 1e3) % 60; + milliseconds = time % 1e3; + } else { + year = value.getUTCFullYear(); + month = value.getUTCMonth(); + date = value.getUTCDate(); + hours = value.getUTCHours(); + minutes = value.getUTCMinutes(); + seconds = value.getUTCSeconds(); + milliseconds = value.getUTCMilliseconds(); + } + // Serialize extended years correctly. + value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + + "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + + // Months, dates, hours, minutes, and seconds should have two + // digits; milliseconds should have three. + "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + + // Milliseconds are optional in ES 5.0, but required in 5.1. + "." + toPaddedString(3, milliseconds) + "Z"; + } else { + value = null; + } + } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { + // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the + // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3 + // ignores all `toJSON` methods on these objects unless they are + // defined directly on an instance. + value = value.toJSON(property); + } + } + if (callback) { + // If a replacement function was provided, call it to obtain the value + // for serialization. + value = callback.call(object, property, value); + } + if (value === null) { + return "null"; + } + className = getClass.call(value); + if (className == booleanClass) { + // Booleans are represented literally. + return "" + value; + } else if (className == numberClass) { + // JSON numbers must be finite. `Infinity` and `NaN` are serialized as + // `"null"`. + return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; + } else if (className == stringClass) { + // Strings are double-quoted and escaped. + return quote("" + value); + } + // Recursively serialize objects and arrays. + if (typeof value == "object") { + // Check for cyclic structures. This is a linear search; performance + // is inversely proportional to the number of unique nested objects. + for (length = stack.length; length--;) { + if (stack[length] === value) { + // Cyclic structures cannot be serialized by `JSON.stringify`. + throw TypeError(); + } + } + // Add the object to the stack of traversed objects. + stack.push(value); + results = []; + // Save the current indentation level and indent one additional level. + prefix = indentation; + indentation += whitespace; + if (className == arrayClass) { + // Recursively serialize array elements. + for (index = 0, length = value.length; index < length; index++) { + element = serialize(index, value, callback, properties, whitespace, indentation, stack); + results.push(element === undef ? "null" : element); + } + result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; + } else { + // Recursively serialize object members. Members are selected from + // either a user-specified list of property names, or the object + // itself. + forEach(properties || value, function (property) { + var element = serialize(property, value, callback, properties, whitespace, indentation, stack); + if (element !== undef) { + // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} + // is not the empty string, let `member` {quote(property) + ":"} + // be the concatenation of `member` and the `space` character." + // The "`space` character" refers to the literal space + // character, not the `space` {width} argument provided to + // `JSON.stringify`. + results.push(quote(property) + ":" + (whitespace ? " " : "") + element); + } + }); + result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; + } + // Remove the object from the traversed object stack. + stack.pop(); + return result; + } + }; + + // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. + exports.stringify = function (source, filter, width) { + var whitespace, callback, properties, className; + if (objectTypes[typeof filter] && filter) { + if ((className = getClass.call(filter)) == functionClass) { + callback = filter; + } else if (className == arrayClass) { + // Convert the property names array into a makeshift set. + properties = {}; + for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); + } + } + if (width) { + if ((className = getClass.call(width)) == numberClass) { + // Convert the `width` to an integer and create a string containing + // `width` number of space characters. + if ((width -= width % 1) > 0) { + for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); + } + } else if (className == stringClass) { + whitespace = width.length <= 10 ? width : width.slice(0, 10); + } + } + // Opera <= 7.54u2 discards the values associated with empty string keys + // (`""`) only if they are used directly within an object member list + // (e.g., `!("" in { "": 1})`). + return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); + }; + } + + // Public: Parses a JSON source string. + if (!has("json-parse")) { + var fromCharCode = String.fromCharCode; + + // Internal: A map of escaped control characters and their unescaped + // equivalents. + var Unescapes = { + 92: "\\", + 34: '"', + 47: "/", + 98: "\b", + 116: "\t", + 110: "\n", + 102: "\f", + 114: "\r" + }; + + // Internal: Stores the parser state. + var Index, Source; + + // Internal: Resets the parser state and throws a `SyntaxError`. + var abort = function () { + Index = Source = null; + throw SyntaxError(); + }; + + // Internal: Returns the next token, or `"$"` if the parser has reached + // the end of the source string. A token may be a string, number, `null` + // literal, or Boolean literal. + var lex = function () { + var source = Source, length = source.length, value, begin, position, isSigned, charCode; + while (Index < length) { + charCode = source.charCodeAt(Index); + switch (charCode) { + case 9: case 10: case 13: case 32: + // Skip whitespace tokens, including tabs, carriage returns, line + // feeds, and space characters. + Index++; + break; + case 123: case 125: case 91: case 93: case 58: case 44: + // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at + // the current position. + value = charIndexBuggy ? source.charAt(Index) : source[Index]; + Index++; + return value; + case 34: + // `"` delimits a JSON string; advance to the next character and + // begin parsing the string. String tokens are prefixed with the + // sentinel `@` character to distinguish them from punctuators and + // end-of-string tokens. + for (value = "@", Index++; Index < length;) { + charCode = source.charCodeAt(Index); + if (charCode < 32) { + // Unescaped ASCII control characters (those with a code unit + // less than the space character) are not permitted. + abort(); + } else if (charCode == 92) { + // A reverse solidus (`\`) marks the beginning of an escaped + // control character (including `"`, `\`, and `/`) or Unicode + // escape sequence. + charCode = source.charCodeAt(++Index); + switch (charCode) { + case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: + // Revive escaped control characters. + value += Unescapes[charCode]; + Index++; + break; + case 117: + // `\u` marks the beginning of a Unicode escape sequence. + // Advance to the first character and validate the + // four-digit code point. + begin = ++Index; + for (position = Index + 4; Index < position; Index++) { + charCode = source.charCodeAt(Index); + // A valid sequence comprises four hexdigits (case- + // insensitive) that form a single hexadecimal value. + if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { + // Invalid Unicode escape sequence. + abort(); + } + } + // Revive the escaped character. + value += fromCharCode("0x" + source.slice(begin, Index)); + break; + default: + // Invalid escape sequence. + abort(); + } + } else { + if (charCode == 34) { + // An unescaped double-quote character marks the end of the + // string. + break; + } + charCode = source.charCodeAt(Index); + begin = Index; + // Optimize for the common case where a string is valid. + while (charCode >= 32 && charCode != 92 && charCode != 34) { + charCode = source.charCodeAt(++Index); + } + // Append the string as-is. + value += source.slice(begin, Index); + } + } + if (source.charCodeAt(Index) == 34) { + // Advance to the next character and return the revived string. + Index++; + return value; + } + // Unterminated string. + abort(); + default: + // Parse numbers and literals. + begin = Index; + // Advance past the negative sign, if one is specified. + if (charCode == 45) { + isSigned = true; + charCode = source.charCodeAt(++Index); + } + // Parse an integer or floating-point value. + if (charCode >= 48 && charCode <= 57) { + // Leading zeroes are interpreted as octal literals. + if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { + // Illegal octal literal. + abort(); + } + isSigned = false; + // Parse the integer component. + for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); + // Floats cannot contain a leading decimal point; however, this + // case is already accounted for by the parser. + if (source.charCodeAt(Index) == 46) { + position = ++Index; + // Parse the decimal component. + for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + // Illegal trailing decimal. + abort(); + } + Index = position; + } + // Parse exponents. The `e` denoting the exponent is + // case-insensitive. + charCode = source.charCodeAt(Index); + if (charCode == 101 || charCode == 69) { + charCode = source.charCodeAt(++Index); + // Skip past the sign following the exponent, if one is + // specified. + if (charCode == 43 || charCode == 45) { + Index++; + } + // Parse the exponential component. + for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); + if (position == Index) { + // Illegal empty exponent. + abort(); + } + Index = position; + } + // Coerce the parsed value to a JavaScript number. + return +source.slice(begin, Index); + } + // A negative sign may only precede numbers. + if (isSigned) { + abort(); + } + // `true`, `false`, and `null` literals. + if (source.slice(Index, Index + 4) == "true") { + Index += 4; + return true; + } else if (source.slice(Index, Index + 5) == "false") { + Index += 5; + return false; + } else if (source.slice(Index, Index + 4) == "null") { + Index += 4; + return null; + } + // Unrecognized token. + abort(); + } + } + // Return the sentinel `$` character if the parser has reached the end + // of the source string. + return "$"; + }; + + // Internal: Parses a JSON `value` token. + var get = function (value) { + var results, hasMembers; + if (value == "$") { + // Unexpected end of input. + abort(); + } + if (typeof value == "string") { + if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { + // Remove the sentinel `@` character. + return value.slice(1); + } + // Parse object and array literals. + if (value == "[") { + // Parses a JSON array, returning a new JavaScript array. + results = []; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + // A closing square bracket marks the end of the array literal. + if (value == "]") { + break; + } + // If the array literal contains elements, the current token + // should be a comma separating the previous element from the + // next. + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "]") { + // Unexpected trailing `,` in array literal. + abort(); + } + } else { + // A `,` must separate each array element. + abort(); + } + } + // Elisions and leading commas are not permitted. + if (value == ",") { + abort(); + } + results.push(get(value)); + } + return results; + } else if (value == "{") { + // Parses a JSON object, returning a new JavaScript object. + results = {}; + for (;; hasMembers || (hasMembers = true)) { + value = lex(); + // A closing curly brace marks the end of the object literal. + if (value == "}") { + break; + } + // If the object literal contains members, the current token + // should be a comma separator. + if (hasMembers) { + if (value == ",") { + value = lex(); + if (value == "}") { + // Unexpected trailing `,` in object literal. + abort(); + } + } else { + // A `,` must separate each object member. + abort(); + } + } + // Leading commas are not permitted, object property names must be + // double-quoted strings, and a `:` must separate each property + // name and value. + if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { + abort(); + } + results[value.slice(1)] = get(lex()); + } + return results; + } + // Unexpected token encountered. + abort(); + } + return value; + }; + + // Internal: Updates a traversed object member. + var update = function (source, property, callback) { + var element = walk(source, property, callback); + if (element === undef) { + delete source[property]; + } else { + source[property] = element; + } + }; + + // Internal: Recursively traverses a parsed JSON object, invoking the + // `callback` function for each value. This is an implementation of the + // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. + var walk = function (source, property, callback) { + var value = source[property], length; + if (typeof value == "object" && value) { + // `forEach` can't be used to traverse an array in Opera <= 8.54 + // because its `Object#hasOwnProperty` implementation returns `false` + // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). + if (getClass.call(value) == arrayClass) { + for (length = value.length; length--;) { + update(value, length, callback); + } + } else { + forEach(value, function (property) { + update(value, property, callback); + }); + } + } + return callback.call(source, property, value); + }; + + // Public: `JSON.parse`. See ES 5.1 section 15.12.2. + exports.parse = function (source, callback) { + var result, value; + Index = 0; + Source = "" + source; + result = get(lex()); + // If a JSON string contains multiple tokens, it is invalid. + if (lex() != "$") { + abort(); + } + // Reset the parser state. + Index = Source = null; + return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; + }; + } + } + + exports["runInContext"] = runInContext; + return exports; + } + + if (freeExports && !isLoader) { + // Export for CommonJS environments. + runInContext(root, freeExports); + } else { + // Export for web browsers and JavaScript engines. + var nativeJSON = root.JSON, + previousJSON = root["JSON3"], + isRestored = false; + + var JSON3 = runInContext(root, (root["JSON3"] = { + // Public: Restores the original value of the global `JSON` object and + // returns a reference to the `JSON3` object. + "noConflict": function () { + if (!isRestored) { + isRestored = true; + root.JSON = nativeJSON; + root["JSON3"] = previousJSON; + nativeJSON = previousJSON = null; + } + return JSON3; + } + })); + + root.JSON = { + "parse": JSON3.parse, + "stringify": JSON3.stringify + }; + } + + // Export for asynchronous module loaders. + if (isLoader) { + define(function () { + return JSON3; + }); + } +}).call(this); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css new file mode 100644 index 0000000..42b9798 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css @@ -0,0 +1,270 @@ +@charset "utf-8"; + +body { + margin:0; +} + +#mocha { + font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; + margin: 60px 50px; +} + +#mocha ul, +#mocha li { + margin: 0; + padding: 0; +} + +#mocha ul { + list-style: none; +} + +#mocha h1, +#mocha h2 { + margin: 0; +} + +#mocha h1 { + margin-top: 15px; + font-size: 1em; + font-weight: 200; +} + +#mocha h1 a { + text-decoration: none; + color: inherit; +} + +#mocha h1 a:hover { + text-decoration: underline; +} + +#mocha .suite .suite h1 { + margin-top: 0; + font-size: .8em; +} + +#mocha .hidden { + display: none; +} + +#mocha h2 { + font-size: 12px; + font-weight: normal; + cursor: pointer; +} + +#mocha .suite { + margin-left: 15px; +} + +#mocha .test { + margin-left: 15px; + overflow: hidden; +} + +#mocha .test.pending:hover h2::after { + content: '(pending)'; + font-family: arial, sans-serif; +} + +#mocha .test.pass.medium .duration { + background: #c09853; +} + +#mocha .test.pass.slow .duration { + background: #b94a48; +} + +#mocha .test.pass::before { + content: '✓'; + font-size: 12px; + display: block; + float: left; + margin-right: 5px; + color: #00d6b2; +} + +#mocha .test.pass .duration { + font-size: 9px; + margin-left: 5px; + padding: 2px 5px; + color: #fff; + -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + box-shadow: inset 0 1px 1px rgba(0,0,0,.2); + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + -ms-border-radius: 5px; + -o-border-radius: 5px; + border-radius: 5px; +} + +#mocha .test.pass.fast .duration { + display: none; +} + +#mocha .test.pending { + color: #0b97c4; +} + +#mocha .test.pending::before { + content: '◦'; + color: #0b97c4; +} + +#mocha .test.fail { + color: #c00; +} + +#mocha .test.fail pre { + color: black; +} + +#mocha .test.fail::before { + content: '✖'; + font-size: 12px; + display: block; + float: left; + margin-right: 5px; + color: #c00; +} + +#mocha .test pre.error { + color: #c00; + max-height: 300px; + overflow: auto; +} + +/** + * (1): approximate for browsers not supporting calc + * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border) + * ^^ seriously + */ +#mocha .test pre { + display: block; + float: left; + clear: left; + font: 12px/1.5 monaco, monospace; + margin: 5px; + padding: 15px; + border: 1px solid #eee; + max-width: 85%; /*(1)*/ + max-width: calc(100% - 42px); /*(2)*/ + word-wrap: break-word; + border-bottom-color: #ddd; + -webkit-border-radius: 3px; + -webkit-box-shadow: 0 1px 3px #eee; + -moz-border-radius: 3px; + -moz-box-shadow: 0 1px 3px #eee; + border-radius: 3px; +} + +#mocha .test h2 { + position: relative; +} + +#mocha .test a.replay { + position: absolute; + top: 3px; + right: 0; + text-decoration: none; + vertical-align: middle; + display: block; + width: 15px; + height: 15px; + line-height: 15px; + text-align: center; + background: #eee; + font-size: 15px; + -moz-border-radius: 15px; + border-radius: 15px; + -webkit-transition: opacity 200ms; + -moz-transition: opacity 200ms; + transition: opacity 200ms; + opacity: 0.3; + color: #888; +} + +#mocha .test:hover a.replay { + opacity: 1; +} + +#mocha-report.pass .test.fail { + display: none; +} + +#mocha-report.fail .test.pass { + display: none; +} + +#mocha-report.pending .test.pass, +#mocha-report.pending .test.fail { + display: none; +} +#mocha-report.pending .test.pass.pending { + display: block; +} + +#mocha-error { + color: #c00; + font-size: 1.5em; + font-weight: 100; + letter-spacing: 1px; +} + +#mocha-stats { + position: fixed; + top: 15px; + right: 10px; + font-size: 12px; + margin: 0; + color: #888; + z-index: 1; +} + +#mocha-stats .progress { + float: right; + padding-top: 0; +} + +#mocha-stats em { + color: black; +} + +#mocha-stats a { + text-decoration: none; + color: inherit; +} + +#mocha-stats a:hover { + border-bottom: 1px solid #eee; +} + +#mocha-stats li { + display: inline-block; + margin: 0 5px; + list-style: none; + padding-top: 11px; +} + +#mocha-stats canvas { + width: 40px; + height: 40px; +} + +#mocha code .comment { color: #ddd; } +#mocha code .init { color: #2f6fad; } +#mocha code .string { color: #5890ad; } +#mocha code .keyword { color: #8a6343; } +#mocha code .number { color: #2f6fad; } + +@media screen and (max-device-width: 480px) { + #mocha { + margin: 60px 0px; + } + + #mocha #stats { + position: absolute; + } +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js new file mode 100644 index 0000000..e8bee79 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js @@ -0,0 +1,6095 @@ +;(function(){ + +// CommonJS require() + +function require(p){ + var path = require.resolve(p) + , mod = require.modules[path]; + if (!mod) throw new Error('failed to require "' + p + '"'); + if (!mod.exports) { + mod.exports = {}; + mod.call(mod.exports, mod, mod.exports, require.relative(path)); + } + return mod.exports; + } + +require.modules = {}; + +require.resolve = function (path){ + var orig = path + , reg = path + '.js' + , index = path + '/index.js'; + return require.modules[reg] && reg + || require.modules[index] && index + || orig; + }; + +require.register = function (path, fn){ + require.modules[path] = fn; + }; + +require.relative = function (parent) { + return function(p){ + if ('.' != p.charAt(0)) return require(p); + + var path = parent.split('/') + , segs = p.split('/'); + path.pop(); + + for (var i = 0; i < segs.length; i++) { + var seg = segs[i]; + if ('..' == seg) path.pop(); + else if ('.' != seg) path.push(seg); + } + + return require(path.join('/')); + }; + }; + + +require.register("browser/debug.js", function(module, exports, require){ + +module.exports = function(type){ + return function(){ + } +}; + +}); // module: browser/debug.js + +require.register("browser/diff.js", function(module, exports, require){ +/* See LICENSE file for terms of use */ + +/* + * Text diff implementation. + * + * This library supports the following APIS: + * JsDiff.diffChars: Character by character diff + * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * JsDiff.diffLines: Line based diff + * + * JsDiff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ +var JsDiff = (function() { + /*jshint maxparams: 5*/ + function clonePath(path) { + return { newPos: path.newPos, components: path.components.slice(0) }; + } + function removeEmpty(array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + } + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + + return n; + } + + var Diff = function(ignoreWhitespace) { + this.ignoreWhitespace = ignoreWhitespace; + }; + Diff.prototype = { + diff: function(oldString, newString) { + // Handle the identity case (this is due to unrolling editLength == 0 + if (newString === oldString) { + return [{ value: newString }]; + } + if (!newString) { + return [{ value: oldString, removed: true }]; + } + if (!oldString) { + return [{ value: newString, added: true }]; + } + + newString = this.tokenize(newString); + oldString = this.tokenize(oldString); + + var newLen = newString.length, oldLen = oldString.length; + var maxEditLength = newLen + oldLen; + var bestPath = [{ newPos: -1, components: [] }]; + + // Seed editLength = 0 + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { + return bestPath[0].components; + } + + for (var editLength = 1; editLength <= maxEditLength; editLength++) { + for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { + var basePath; + var addPath = bestPath[diagonalPath-1], + removePath = bestPath[diagonalPath+1]; + oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath-1] = undefined; + } + + var canAdd = addPath && addPath.newPos+1 < newLen; + var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; + if (!canAdd && !canRemove) { + bestPath[diagonalPath] = undefined; + continue; + } + + // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { + basePath = clonePath(removePath); + this.pushComponent(basePath.components, oldString[oldPos], undefined, true); + } else { + basePath = clonePath(addPath); + basePath.newPos++; + this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); + } + + var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); + + if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { + return basePath.components; + } else { + bestPath[diagonalPath] = basePath; + } + } + } + }, + + pushComponent: function(components, value, added, removed) { + var last = components[components.length-1]; + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length-1] = + {value: this.join(last.value, value), added: added, removed: removed }; + } else { + components.push({value: value, added: added, removed: removed }); + } + }, + extractCommon: function(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath; + while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { + newPos++; + oldPos++; + + this.pushComponent(basePath.components, newString[newPos], undefined, undefined); + } + basePath.newPos = newPos; + return oldPos; + }, + + equals: function(left, right) { + var reWhitespace = /\S/; + if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { + return true; + } else { + return left === right; + } + }, + join: function(left, right) { + return left + right; + }, + tokenize: function(value) { + return value; + } + }; + + var CharDiff = new Diff(); + + var WordDiff = new Diff(true); + var WordWithSpaceDiff = new Diff(); + WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { + return removeEmpty(value.split(/(\s+|\b)/)); + }; + + var CssDiff = new Diff(true); + CssDiff.tokenize = function(value) { + return removeEmpty(value.split(/([{}:;,]|\s+)/)); + }; + + var LineDiff = new Diff(); + LineDiff.tokenize = function(value) { + var retLines = [], + lines = value.split(/^/m); + + for(var i = 0; i < lines.length; i++) { + var line = lines[i], + lastLine = lines[i - 1]; + + // Merge lines that may contain windows new lines + if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') { + retLines[retLines.length - 1] += '\n'; + } else if (line) { + retLines.push(line); + } + } + + return retLines; + }; + + return { + Diff: Diff, + + diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, + diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, + diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, + diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, + + diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, + + createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { + var ret = []; + + ret.push('Index: ' + fileName); + ret.push('==================================================================='); + ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); + ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); + + var diff = LineDiff.diff(oldStr, newStr); + if (!diff[diff.length-1].value) { + diff.pop(); // Remove trailing newline add + } + diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier + + function contextLines(lines) { + return lines.map(function(entry) { return ' ' + entry; }); + } + function eofNL(curRange, i, current) { + var last = diff[diff.length-2], + isLast = i === diff.length-2, + isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); + + // Figure out if this is the last line for the given file and missing NL + if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { + curRange.push('\\ No newline at end of file'); + } + } + + var oldRangeStart = 0, newRangeStart = 0, curRange = [], + oldLine = 1, newLine = 1; + for (var i = 0; i < diff.length; i++) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + if (!oldRangeStart) { + var prev = diff[i-1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = contextLines(prev.lines.slice(-4)); + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); + eofNL(curRange, i, current); + + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= 8 && i < diff.length-2) { + // Overlapping + curRange.push.apply(curRange, contextLines(lines)); + } else { + // end the range and output + var contextSize = Math.min(lines.length, 4); + ret.push( + '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) + + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) + + ' @@'); + ret.push.apply(ret, curRange); + ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); + if (lines.length <= 4) { + eofNL(ret, i, current); + } + + oldRangeStart = 0; newRangeStart = 0; curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; + } + } + + return ret.join('\n') + '\n'; + }, + + applyPatch: function(oldStr, uniDiff) { + var diffstr = uniDiff.split('\n'); + var diff = []; + var remEOFNL = false, + addEOFNL = false; + + for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { + if(diffstr[i][0] === '@') { + var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); + diff.unshift({ + start:meh[3], + oldlength:meh[2], + oldlines:[], + newlength:meh[4], + newlines:[] + }); + } else if(diffstr[i][0] === '+') { + diff[0].newlines.push(diffstr[i].substr(1)); + } else if(diffstr[i][0] === '-') { + diff[0].oldlines.push(diffstr[i].substr(1)); + } else if(diffstr[i][0] === ' ') { + diff[0].newlines.push(diffstr[i].substr(1)); + diff[0].oldlines.push(diffstr[i].substr(1)); + } else if(diffstr[i][0] === '\\') { + if (diffstr[i-1][0] === '+') { + remEOFNL = true; + } else if(diffstr[i-1][0] === '-') { + addEOFNL = true; + } + } + } + + var str = oldStr.split('\n'); + for (var i = diff.length - 1; i >= 0; i--) { + var d = diff[i]; + for (var j = 0; j < d.oldlength; j++) { + if(str[d.start-1+j] !== d.oldlines[j]) { + return false; + } + } + Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); + } + + if (remEOFNL) { + while (!str[str.length-1]) { + str.pop(); + } + } else if (addEOFNL) { + str.push(''); + } + return str.join('\n'); + }, + + convertChangesToXML: function(changes){ + var ret = []; + for ( var i = 0; i < changes.length; i++) { + var change = changes[i]; + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + return ret.join(''); + }, + + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + convertChangesToDMP: function(changes){ + var ret = [], change; + for ( var i = 0; i < changes.length; i++) { + change = changes[i]; + ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); + } + return ret; + } + }; +})(); + +if (typeof module !== 'undefined') { + module.exports = JsDiff; +} + +}); // module: browser/diff.js + +require.register("browser/escape-string-regexp.js", function(module, exports, require){ +'use strict'; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +}); // module: browser/escape-string-regexp.js + +require.register("browser/events.js", function(module, exports, require){ + +/** + * Module exports. + */ + +exports.EventEmitter = EventEmitter; + +/** + * Check if `obj` is an array. + */ + +function isArray(obj) { + return '[object Array]' == {}.toString.call(obj); +} + +/** + * Event emitter constructor. + * + * @api public + */ + +function EventEmitter(){}; + +/** + * Adds a listener. + * + * @api public + */ + +EventEmitter.prototype.on = function (name, fn) { + if (!this.$events) { + this.$events = {}; + } + + if (!this.$events[name]) { + this.$events[name] = fn; + } else if (isArray(this.$events[name])) { + this.$events[name].push(fn); + } else { + this.$events[name] = [this.$events[name], fn]; + } + + return this; +}; + +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +/** + * Adds a volatile listener. + * + * @api public + */ + +EventEmitter.prototype.once = function (name, fn) { + var self = this; + + function on () { + self.removeListener(name, on); + fn.apply(this, arguments); + }; + + on.listener = fn; + this.on(name, on); + + return this; +}; + +/** + * Removes a listener. + * + * @api public + */ + +EventEmitter.prototype.removeListener = function (name, fn) { + if (this.$events && this.$events[name]) { + var list = this.$events[name]; + + if (isArray(list)) { + var pos = -1; + + for (var i = 0, l = list.length; i < l; i++) { + if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { + pos = i; + break; + } + } + + if (pos < 0) { + return this; + } + + list.splice(pos, 1); + + if (!list.length) { + delete this.$events[name]; + } + } else if (list === fn || (list.listener && list.listener === fn)) { + delete this.$events[name]; + } + } + + return this; +}; + +/** + * Removes all listeners for an event. + * + * @api public + */ + +EventEmitter.prototype.removeAllListeners = function (name) { + if (name === undefined) { + this.$events = {}; + return this; + } + + if (this.$events && this.$events[name]) { + this.$events[name] = null; + } + + return this; +}; + +/** + * Gets all listeners for a certain event. + * + * @api public + */ + +EventEmitter.prototype.listeners = function (name) { + if (!this.$events) { + this.$events = {}; + } + + if (!this.$events[name]) { + this.$events[name] = []; + } + + if (!isArray(this.$events[name])) { + this.$events[name] = [this.$events[name]]; + } + + return this.$events[name]; +}; + +/** + * Emits an event. + * + * @api public + */ + +EventEmitter.prototype.emit = function (name) { + if (!this.$events) { + return false; + } + + var handler = this.$events[name]; + + if (!handler) { + return false; + } + + var args = [].slice.call(arguments, 1); + + if ('function' == typeof handler) { + handler.apply(this, args); + } else if (isArray(handler)) { + var listeners = handler.slice(); + + for (var i = 0, l = listeners.length; i < l; i++) { + listeners[i].apply(this, args); + } + } else { + return false; + } + + return true; +}; +}); // module: browser/events.js + +require.register("browser/fs.js", function(module, exports, require){ + +}); // module: browser/fs.js + +require.register("browser/glob.js", function(module, exports, require){ + +}); // module: browser/glob.js + +require.register("browser/path.js", function(module, exports, require){ + +}); // module: browser/path.js + +require.register("browser/progress.js", function(module, exports, require){ +/** + * Expose `Progress`. + */ + +module.exports = Progress; + +/** + * Initialize a new `Progress` indicator. + */ + +function Progress() { + this.percent = 0; + this.size(0); + this.fontSize(11); + this.font('helvetica, arial, sans-serif'); +} + +/** + * Set progress size to `n`. + * + * @param {Number} n + * @return {Progress} for chaining + * @api public + */ + +Progress.prototype.size = function(n){ + this._size = n; + return this; +}; + +/** + * Set text to `str`. + * + * @param {String} str + * @return {Progress} for chaining + * @api public + */ + +Progress.prototype.text = function(str){ + this._text = str; + return this; +}; + +/** + * Set font size to `n`. + * + * @param {Number} n + * @return {Progress} for chaining + * @api public + */ + +Progress.prototype.fontSize = function(n){ + this._fontSize = n; + return this; +}; + +/** + * Set font `family`. + * + * @param {String} family + * @return {Progress} for chaining + */ + +Progress.prototype.font = function(family){ + this._font = family; + return this; +}; + +/** + * Update percentage to `n`. + * + * @param {Number} n + * @return {Progress} for chaining + */ + +Progress.prototype.update = function(n){ + this.percent = n; + return this; +}; + +/** + * Draw on `ctx`. + * + * @param {CanvasRenderingContext2d} ctx + * @return {Progress} for chaining + */ + +Progress.prototype.draw = function(ctx){ + try { + var percent = Math.min(this.percent, 100) + , size = this._size + , half = size / 2 + , x = half + , y = half + , rad = half - 1 + , fontSize = this._fontSize; + + ctx.font = fontSize + 'px ' + this._font; + + var angle = Math.PI * 2 * (percent / 100); + ctx.clearRect(0, 0, size, size); + + // outer circle + ctx.strokeStyle = '#9f9f9f'; + ctx.beginPath(); + ctx.arc(x, y, rad, 0, angle, false); + ctx.stroke(); + + // inner circle + ctx.strokeStyle = '#eee'; + ctx.beginPath(); + ctx.arc(x, y, rad - 1, 0, angle, true); + ctx.stroke(); + + // text + var text = this._text || (percent | 0) + '%' + , w = ctx.measureText(text).width; + + ctx.fillText( + text + , x - w / 2 + 1 + , y + fontSize / 2 - 1); + } catch (ex) {} //don't fail if we can't render progress + return this; +}; + +}); // module: browser/progress.js + +require.register("browser/tty.js", function(module, exports, require){ + +exports.isatty = function(){ + return true; +}; + +exports.getWindowSize = function(){ + if ('innerHeight' in global) { + return [global.innerHeight, global.innerWidth]; + } else { + // In a Web Worker, the DOM Window is not available. + return [640, 480]; + } +}; + +}); // module: browser/tty.js + +require.register("context.js", function(module, exports, require){ + +/** + * Expose `Context`. + */ + +module.exports = Context; + +/** + * Initialize a new `Context`. + * + * @api private + */ + +function Context(){} + +/** + * Set or get the context `Runnable` to `runnable`. + * + * @param {Runnable} runnable + * @return {Context} + * @api private + */ + +Context.prototype.runnable = function(runnable){ + if (0 == arguments.length) return this._runnable; + this.test = this._runnable = runnable; + return this; +}; + +/** + * Set test timeout `ms`. + * + * @param {Number} ms + * @return {Context} self + * @api private + */ + +Context.prototype.timeout = function(ms){ + if (arguments.length === 0) return this.runnable().timeout(); + this.runnable().timeout(ms); + return this; +}; + +/** + * Set test timeout `enabled`. + * + * @param {Boolean} enabled + * @return {Context} self + * @api private + */ + +Context.prototype.enableTimeouts = function (enabled) { + this.runnable().enableTimeouts(enabled); + return this; +}; + + +/** + * Set test slowness threshold `ms`. + * + * @param {Number} ms + * @return {Context} self + * @api private + */ + +Context.prototype.slow = function(ms){ + this.runnable().slow(ms); + return this; +}; + +/** + * Inspect the context void of `._runnable`. + * + * @return {String} + * @api private + */ + +Context.prototype.inspect = function(){ + return JSON.stringify(this, function(key, val){ + if ('_runnable' == key) return; + if ('test' == key) return; + return val; + }, 2); +}; + +}); // module: context.js + +require.register("hook.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Runnable = require('./runnable'); + +/** + * Expose `Hook`. + */ + +module.exports = Hook; + +/** + * Initialize a new `Hook` with the given `title` and callback `fn`. + * + * @param {String} title + * @param {Function} fn + * @api private + */ + +function Hook(title, fn) { + Runnable.call(this, title, fn); + this.type = 'hook'; +} + +/** + * Inherit from `Runnable.prototype`. + */ + +function F(){}; +F.prototype = Runnable.prototype; +Hook.prototype = new F; +Hook.prototype.constructor = Hook; + + +/** + * Get or set the test `err`. + * + * @param {Error} err + * @return {Error} + * @api public + */ + +Hook.prototype.error = function(err){ + if (0 == arguments.length) { + var err = this._error; + this._error = null; + return err; + } + + this._error = err; +}; + +}); // module: hook.js + +require.register("interfaces/bdd.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') + , Test = require('../test') + , utils = require('../utils') + , escapeRe = require('browser/escape-string-regexp'); + +/** + * BDD-style interface: + * + * describe('Array', function(){ + * describe('#indexOf()', function(){ + * it('should return -1 when not present', function(){ + * + * }); + * + * it('should return the index when present', function(){ + * + * }); + * }); + * }); + * + */ + +module.exports = function(suite){ + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha){ + + /** + * Execute before running tests. + */ + + context.before = function(name, fn){ + suites[0].beforeAll(name, fn); + }; + + /** + * Execute after running tests. + */ + + context.after = function(name, fn){ + suites[0].afterAll(name, fn); + }; + + /** + * Execute before each test case. + */ + + context.beforeEach = function(name, fn){ + suites[0].beforeEach(name, fn); + }; + + /** + * Execute after each test case. + */ + + context.afterEach = function(name, fn){ + suites[0].afterEach(name, fn); + }; + + /** + * Describe a "suite" with the given `title` + * and callback `fn` containing nested suites + * and/or tests. + */ + + context.describe = context.context = function(title, fn){ + var suite = Suite.create(suites[0], title); + suite.file = file; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + return suite; + }; + + /** + * Pending describe. + */ + + context.xdescribe = + context.xcontext = + context.describe.skip = function(title, fn){ + var suite = Suite.create(suites[0], title); + suite.pending = true; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + }; + + /** + * Exclusive suite. + */ + + context.describe.only = function(title, fn){ + var suite = context.describe(title, fn); + mocha.grep(suite.fullTitle()); + return suite; + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.it = context.specify = function(title, fn){ + var suite = suites[0]; + if (suite.pending) fn = null; + var test = new Test(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.it.only = function(title, fn){ + var test = context.it(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); + return test; + }; + + /** + * Pending test case. + */ + + context.xit = + context.xspecify = + context.it.skip = function(title){ + context.it(title); + }; + }); +}; + +}); // module: interfaces/bdd.js + +require.register("interfaces/exports.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') + , Test = require('../test'); + +/** + * TDD-style interface: + * + * exports.Array = { + * '#indexOf()': { + * 'should return -1 when the value is not present': function(){ + * + * }, + * + * 'should return the correct index when the value is present': function(){ + * + * } + * } + * }; + * + */ + +module.exports = function(suite){ + var suites = [suite]; + + suite.on('require', visit); + + function visit(obj, file) { + var suite; + for (var key in obj) { + if ('function' == typeof obj[key]) { + var fn = obj[key]; + switch (key) { + case 'before': + suites[0].beforeAll(fn); + break; + case 'after': + suites[0].afterAll(fn); + break; + case 'beforeEach': + suites[0].beforeEach(fn); + break; + case 'afterEach': + suites[0].afterEach(fn); + break; + default: + var test = new Test(key, fn); + test.file = file; + suites[0].addTest(test); + } + } else { + suite = Suite.create(suites[0], key); + suites.unshift(suite); + visit(obj[key]); + suites.shift(); + } + } + } +}; + +}); // module: interfaces/exports.js + +require.register("interfaces/index.js", function(module, exports, require){ + +exports.bdd = require('./bdd'); +exports.tdd = require('./tdd'); +exports.qunit = require('./qunit'); +exports.exports = require('./exports'); + +}); // module: interfaces/index.js + +require.register("interfaces/qunit.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') + , Test = require('../test') + , escapeRe = require('browser/escape-string-regexp') + , utils = require('../utils'); + +/** + * QUnit-style interface: + * + * suite('Array'); + * + * test('#length', function(){ + * var arr = [1,2,3]; + * ok(arr.length == 3); + * }); + * + * test('#indexOf()', function(){ + * var arr = [1,2,3]; + * ok(arr.indexOf(1) == 0); + * ok(arr.indexOf(2) == 1); + * ok(arr.indexOf(3) == 2); + * }); + * + * suite('String'); + * + * test('#length', function(){ + * ok('foo'.length == 3); + * }); + * + */ + +module.exports = function(suite){ + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha){ + + /** + * Execute before running tests. + */ + + context.before = function(name, fn){ + suites[0].beforeAll(name, fn); + }; + + /** + * Execute after running tests. + */ + + context.after = function(name, fn){ + suites[0].afterAll(name, fn); + }; + + /** + * Execute before each test case. + */ + + context.beforeEach = function(name, fn){ + suites[0].beforeEach(name, fn); + }; + + /** + * Execute after each test case. + */ + + context.afterEach = function(name, fn){ + suites[0].afterEach(name, fn); + }; + + /** + * Describe a "suite" with the given `title`. + */ + + context.suite = function(title){ + if (suites.length > 1) suites.shift(); + var suite = Suite.create(suites[0], title); + suite.file = file; + suites.unshift(suite); + return suite; + }; + + /** + * Exclusive test-case. + */ + + context.suite.only = function(title, fn){ + var suite = context.suite(title, fn); + mocha.grep(suite.fullTitle()); + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.test = function(title, fn){ + var test = new Test(title, fn); + test.file = file; + suites[0].addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn){ + var test = context.test(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); + }; + + /** + * Pending test case. + */ + + context.test.skip = function(title){ + context.test(title); + }; + }); +}; + +}); // module: interfaces/qunit.js + +require.register("interfaces/tdd.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Suite = require('../suite') + , Test = require('../test') + , escapeRe = require('browser/escape-string-regexp') + , utils = require('../utils'); + +/** + * TDD-style interface: + * + * suite('Array', function(){ + * suite('#indexOf()', function(){ + * suiteSetup(function(){ + * + * }); + * + * test('should return -1 when not present', function(){ + * + * }); + * + * test('should return the index when present', function(){ + * + * }); + * + * suiteTeardown(function(){ + * + * }); + * }); + * }); + * + */ + +module.exports = function(suite){ + var suites = [suite]; + + suite.on('pre-require', function(context, file, mocha){ + + /** + * Execute before each test case. + */ + + context.setup = function(name, fn){ + suites[0].beforeEach(name, fn); + }; + + /** + * Execute after each test case. + */ + + context.teardown = function(name, fn){ + suites[0].afterEach(name, fn); + }; + + /** + * Execute before the suite. + */ + + context.suiteSetup = function(name, fn){ + suites[0].beforeAll(name, fn); + }; + + /** + * Execute after the suite. + */ + + context.suiteTeardown = function(name, fn){ + suites[0].afterAll(name, fn); + }; + + /** + * Describe a "suite" with the given `title` + * and callback `fn` containing nested suites + * and/or tests. + */ + + context.suite = function(title, fn){ + var suite = Suite.create(suites[0], title); + suite.file = file; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + return suite; + }; + + /** + * Pending suite. + */ + context.suite.skip = function(title, fn) { + var suite = Suite.create(suites[0], title); + suite.pending = true; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + }; + + /** + * Exclusive test-case. + */ + + context.suite.only = function(title, fn){ + var suite = context.suite(title, fn); + mocha.grep(suite.fullTitle()); + }; + + /** + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. + */ + + context.test = function(title, fn){ + var suite = suites[0]; + if (suite.pending) fn = null; + var test = new Test(title, fn); + test.file = file; + suite.addTest(test); + return test; + }; + + /** + * Exclusive test-case. + */ + + context.test.only = function(title, fn){ + var test = context.test(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); + }; + + /** + * Pending test case. + */ + + context.test.skip = function(title){ + context.test(title); + }; + }); +}; + +}); // module: interfaces/tdd.js + +require.register("mocha.js", function(module, exports, require){ +/*! + * mocha + * Copyright(c) 2011 TJ Holowaychuk + * MIT Licensed + */ + +/** + * Module dependencies. + */ + +var path = require('browser/path') + , escapeRe = require('browser/escape-string-regexp') + , utils = require('./utils'); + +/** + * Expose `Mocha`. + */ + +exports = module.exports = Mocha; + +/** + * To require local UIs and reporters when running in node. + */ + +if (typeof process !== 'undefined' && typeof process.cwd === 'function') { + var join = path.join + , cwd = process.cwd(); + module.paths.push(cwd, join(cwd, 'node_modules')); +} + +/** + * Expose internals. + */ + +exports.utils = utils; +exports.interfaces = require('./interfaces'); +exports.reporters = require('./reporters'); +exports.Runnable = require('./runnable'); +exports.Context = require('./context'); +exports.Runner = require('./runner'); +exports.Suite = require('./suite'); +exports.Hook = require('./hook'); +exports.Test = require('./test'); + +/** + * Return image `name` path. + * + * @param {String} name + * @return {String} + * @api private + */ + +function image(name) { + return __dirname + '/../images/' + name + '.png'; +} + +/** + * Setup mocha with `options`. + * + * Options: + * + * - `ui` name "bdd", "tdd", "exports" etc + * - `reporter` reporter instance, defaults to `mocha.reporters.spec` + * - `globals` array of accepted globals + * - `timeout` timeout in milliseconds + * - `bail` bail on the first test failure + * - `slow` milliseconds to wait before considering a test slow + * - `ignoreLeaks` ignore global leaks + * - `grep` string or regexp to filter tests with + * + * @param {Object} options + * @api public + */ + +function Mocha(options) { + options = options || {}; + this.files = []; + this.options = options; + this.grep(options.grep); + this.suite = new exports.Suite('', new exports.Context); + this.ui(options.ui); + this.bail(options.bail); + this.reporter(options.reporter); + if (null != options.timeout) this.timeout(options.timeout); + this.useColors(options.useColors) + if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts); + if (options.slow) this.slow(options.slow); + + this.suite.on('pre-require', function (context) { + exports.afterEach = context.afterEach || context.teardown; + exports.after = context.after || context.suiteTeardown; + exports.beforeEach = context.beforeEach || context.setup; + exports.before = context.before || context.suiteSetup; + exports.describe = context.describe || context.suite; + exports.it = context.it || context.test; + exports.setup = context.setup || context.beforeEach; + exports.suiteSetup = context.suiteSetup || context.before; + exports.suiteTeardown = context.suiteTeardown || context.after; + exports.suite = context.suite || context.describe; + exports.teardown = context.teardown || context.afterEach; + exports.test = context.test || context.it; + }); +} + +/** + * Enable or disable bailing on the first failure. + * + * @param {Boolean} [bail] + * @api public + */ + +Mocha.prototype.bail = function(bail){ + if (0 == arguments.length) bail = true; + this.suite.bail(bail); + return this; +}; + +/** + * Add test `file`. + * + * @param {String} file + * @api public + */ + +Mocha.prototype.addFile = function(file){ + this.files.push(file); + return this; +}; + +/** + * Set reporter to `reporter`, defaults to "spec". + * + * @param {String|Function} reporter name or constructor + * @api public + */ + +Mocha.prototype.reporter = function(reporter){ + if ('function' == typeof reporter) { + this._reporter = reporter; + } else { + reporter = reporter || 'spec'; + var _reporter; + try { _reporter = require('./reporters/' + reporter); } catch (err) {}; + if (!_reporter) try { _reporter = require(reporter); } catch (err) {}; + if (!_reporter && reporter === 'teamcity') + console.warn('The Teamcity reporter was moved to a package named ' + + 'mocha-teamcity-reporter ' + + '(https://npmjs.org/package/mocha-teamcity-reporter).'); + if (!_reporter) throw new Error('invalid reporter "' + reporter + '"'); + this._reporter = _reporter; + } + return this; +}; + +/** + * Set test UI `name`, defaults to "bdd". + * + * @param {String} bdd + * @api public + */ + +Mocha.prototype.ui = function(name){ + name = name || 'bdd'; + this._ui = exports.interfaces[name]; + if (!this._ui) try { this._ui = require(name); } catch (err) {}; + if (!this._ui) throw new Error('invalid interface "' + name + '"'); + this._ui = this._ui(this.suite); + return this; +}; + +/** + * Load registered files. + * + * @api private + */ + +Mocha.prototype.loadFiles = function(fn){ + var self = this; + var suite = this.suite; + var pending = this.files.length; + this.files.forEach(function(file){ + file = path.resolve(file); + suite.emit('pre-require', global, file, self); + suite.emit('require', require(file), file, self); + suite.emit('post-require', global, file, self); + --pending || (fn && fn()); + }); +}; + +/** + * Enable growl support. + * + * @api private + */ + +Mocha.prototype._growl = function(runner, reporter) { + var notify = require('growl'); + + runner.on('end', function(){ + var stats = reporter.stats; + if (stats.failures) { + var msg = stats.failures + ' of ' + runner.total + ' tests failed'; + notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); + } else { + notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { + name: 'mocha' + , title: 'Passed' + , image: image('ok') + }); + } + }); +}; + +/** + * Add regexp to grep, if `re` is a string it is escaped. + * + * @param {RegExp|String} re + * @return {Mocha} + * @api public + */ + +Mocha.prototype.grep = function(re){ + this.options.grep = 'string' == typeof re + ? new RegExp(escapeRe(re)) + : re; + return this; +}; + +/** + * Invert `.grep()` matches. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.invert = function(){ + this.options.invert = true; + return this; +}; + +/** + * Ignore global leaks. + * + * @param {Boolean} ignore + * @return {Mocha} + * @api public + */ + +Mocha.prototype.ignoreLeaks = function(ignore){ + this.options.ignoreLeaks = !!ignore; + return this; +}; + +/** + * Enable global leak checking. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.checkLeaks = function(){ + this.options.ignoreLeaks = false; + return this; +}; + +/** + * Enable growl support. + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.growl = function(){ + this.options.growl = true; + return this; +}; + +/** + * Ignore `globals` array or string. + * + * @param {Array|String} globals + * @return {Mocha} + * @api public + */ + +Mocha.prototype.globals = function(globals){ + this.options.globals = (this.options.globals || []).concat(globals); + return this; +}; + +/** + * Emit color output. + * + * @param {Boolean} colors + * @return {Mocha} + * @api public + */ + +Mocha.prototype.useColors = function(colors){ + this.options.useColors = arguments.length && colors != undefined + ? colors + : true; + return this; +}; + +/** + * Use inline diffs rather than +/-. + * + * @param {Boolean} inlineDiffs + * @return {Mocha} + * @api public + */ + +Mocha.prototype.useInlineDiffs = function(inlineDiffs) { + this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined + ? inlineDiffs + : false; + return this; +}; + +/** + * Set the timeout in milliseconds. + * + * @param {Number} timeout + * @return {Mocha} + * @api public + */ + +Mocha.prototype.timeout = function(timeout){ + this.suite.timeout(timeout); + return this; +}; + +/** + * Set slowness threshold in milliseconds. + * + * @param {Number} slow + * @return {Mocha} + * @api public + */ + +Mocha.prototype.slow = function(slow){ + this.suite.slow(slow); + return this; +}; + +/** + * Enable timeouts. + * + * @param {Boolean} enabled + * @return {Mocha} + * @api public + */ + +Mocha.prototype.enableTimeouts = function(enabled) { + this.suite.enableTimeouts(arguments.length && enabled !== undefined + ? enabled + : true); + return this +}; + +/** + * Makes all tests async (accepting a callback) + * + * @return {Mocha} + * @api public + */ + +Mocha.prototype.asyncOnly = function(){ + this.options.asyncOnly = true; + return this; +}; + +/** + * Disable syntax highlighting (in browser). + * @returns {Mocha} + * @api public + */ +Mocha.prototype.noHighlighting = function() { + this.options.noHighlighting = true; + return this; +}; + +/** + * Run tests and invoke `fn()` when complete. + * + * @param {Function} fn + * @return {Runner} + * @api public + */ + +Mocha.prototype.run = function(fn){ + if (this.files.length) this.loadFiles(); + var suite = this.suite; + var options = this.options; + options.files = this.files; + var runner = new exports.Runner(suite); + var reporter = new this._reporter(runner, options); + runner.ignoreLeaks = false !== options.ignoreLeaks; + runner.asyncOnly = options.asyncOnly; + if (options.grep) runner.grep(options.grep, options.invert); + if (options.globals) runner.globals(options.globals); + if (options.growl) this._growl(runner, reporter); + exports.reporters.Base.useColors = options.useColors; + exports.reporters.Base.inlineDiffs = options.useInlineDiffs; + return runner.run(fn); +}; + +}); // module: mocha.js + +require.register("ms.js", function(module, exports, require){ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} options + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options){ + options = options || {}; + if ('string' == typeof val) return parse(val); + return options['long'] ? longFormat(val) : shortFormat(val); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); + if (!match) return; + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 's': + return n * s; + case 'ms': + return n; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function shortFormat(ms) { + if (ms >= d) return Math.round(ms / d) + 'd'; + if (ms >= h) return Math.round(ms / h) + 'h'; + if (ms >= m) return Math.round(ms / m) + 'm'; + if (ms >= s) return Math.round(ms / s) + 's'; + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function longFormat(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) return; + if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; + return Math.ceil(ms / n) + ' ' + name + 's'; +} + +}); // module: ms.js + +require.register("reporters/base.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var tty = require('browser/tty') + , diff = require('browser/diff') + , ms = require('../ms') + , utils = require('../utils'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date + , setTimeout = global.setTimeout + , setInterval = global.setInterval + , clearTimeout = global.clearTimeout + , clearInterval = global.clearInterval; + +/** + * Check if both stdio streams are associated with a tty. + */ + +var isatty = tty.isatty(1) && tty.isatty(2); + +/** + * Expose `Base`. + */ + +exports = module.exports = Base; + +/** + * Enable coloring by default. + */ + +exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined); + +/** + * Inline diffs instead of +/- + */ + +exports.inlineDiffs = false; + +/** + * Default color map. + */ + +exports.colors = { + 'pass': 90 + , 'fail': 31 + , 'bright pass': 92 + , 'bright fail': 91 + , 'bright yellow': 93 + , 'pending': 36 + , 'suite': 0 + , 'error title': 0 + , 'error message': 31 + , 'error stack': 90 + , 'checkmark': 32 + , 'fast': 90 + , 'medium': 33 + , 'slow': 31 + , 'green': 32 + , 'light': 90 + , 'diff gutter': 90 + , 'diff added': 42 + , 'diff removed': 41 +}; + +/** + * Default symbol map. + */ + +exports.symbols = { + ok: '✓', + err: '✖', + dot: '․' +}; + +// With node.js on Windows: use symbols available in terminal default fonts +if ('win32' == process.platform) { + exports.symbols.ok = '\u221A'; + exports.symbols.err = '\u00D7'; + exports.symbols.dot = '.'; +} + +/** + * Color `str` with the given `type`, + * allowing colors to be disabled, + * as well as user-defined color + * schemes. + * + * @param {String} type + * @param {String} str + * @return {String} + * @api private + */ + +var color = exports.color = function(type, str) { + if (!exports.useColors) return str; + return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; +}; + +/** + * Expose term window size, with some + * defaults for when stderr is not a tty. + */ + +exports.window = { + width: isatty + ? process.stdout.getWindowSize + ? process.stdout.getWindowSize(1)[0] + : tty.getWindowSize()[1] + : 75 +}; + +/** + * Expose some basic cursor interactions + * that are common among reporters. + */ + +exports.cursor = { + hide: function(){ + isatty && process.stdout.write('\u001b[?25l'); + }, + + show: function(){ + isatty && process.stdout.write('\u001b[?25h'); + }, + + deleteLine: function(){ + isatty && process.stdout.write('\u001b[2K'); + }, + + beginningOfLine: function(){ + isatty && process.stdout.write('\u001b[0G'); + }, + + CR: function(){ + if (isatty) { + exports.cursor.deleteLine(); + exports.cursor.beginningOfLine(); + } else { + process.stdout.write('\r'); + } + } +}; + +/** + * Outut the given `failures` as a list. + * + * @param {Array} failures + * @api public + */ + +exports.list = function(failures){ + console.error(); + failures.forEach(function(test, i){ + // format + var fmt = color('error title', ' %s) %s:\n') + + color('error message', ' %s') + + color('error stack', '\n%s\n'); + + // msg + var err = test.err + , message = err.message || '' + , stack = err.stack || message + , index = stack.indexOf(message) + message.length + , msg = stack.slice(0, index) + , actual = err.actual + , expected = err.expected + , escape = true; + + // uncaught + if (err.uncaught) { + msg = 'Uncaught ' + msg; + } + + // explicitly show diff + if (err.showDiff && sameType(actual, expected)) { + escape = false; + err.actual = actual = utils.stringify(actual); + err.expected = expected = utils.stringify(expected); + } + + // actual / expected diff + if (err.showDiff && 'string' == typeof actual && 'string' == typeof expected) { + fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); + var match = message.match(/^([^:]+): expected/); + msg = '\n ' + color('error message', match ? match[1] : msg); + + if (exports.inlineDiffs) { + msg += inlineDiff(err, escape); + } else { + msg += unifiedDiff(err, escape); + } + } + + // indent stack trace without msg + stack = stack.slice(index ? index + 1 : index) + .replace(/^/gm, ' '); + + console.error(fmt, (i + 1), test.fullTitle(), msg, stack); + }); +}; + +/** + * Initialize a new `Base` reporter. + * + * All other reporters generally + * inherit from this reporter, providing + * stats such as test duration, number + * of tests passed / failed etc. + * + * @param {Runner} runner + * @api public + */ + +function Base(runner) { + var self = this + , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } + , failures = this.failures = []; + + if (!runner) return; + this.runner = runner; + + runner.stats = stats; + + runner.on('start', function(){ + stats.start = new Date; + }); + + runner.on('suite', function(suite){ + stats.suites = stats.suites || 0; + suite.root || stats.suites++; + }); + + runner.on('test end', function(test){ + stats.tests = stats.tests || 0; + stats.tests++; + }); + + runner.on('pass', function(test){ + stats.passes = stats.passes || 0; + + var medium = test.slow() / 2; + test.speed = test.duration > test.slow() + ? 'slow' + : test.duration > medium + ? 'medium' + : 'fast'; + + stats.passes++; + }); + + runner.on('fail', function(test, err){ + stats.failures = stats.failures || 0; + stats.failures++; + test.err = err; + failures.push(test); + }); + + runner.on('end', function(){ + stats.end = new Date; + stats.duration = new Date - stats.start; + }); + + runner.on('pending', function(){ + stats.pending++; + }); +} + +/** + * Output common epilogue used by many of + * the bundled reporters. + * + * @api public + */ + +Base.prototype.epilogue = function(){ + var stats = this.stats; + var tests; + var fmt; + + console.log(); + + // passes + fmt = color('bright pass', ' ') + + color('green', ' %d passing') + + color('light', ' (%s)'); + + console.log(fmt, + stats.passes || 0, + ms(stats.duration)); + + // pending + if (stats.pending) { + fmt = color('pending', ' ') + + color('pending', ' %d pending'); + + console.log(fmt, stats.pending); + } + + // failures + if (stats.failures) { + fmt = color('fail', ' %d failing'); + + console.error(fmt, + stats.failures); + + Base.list(this.failures); + console.error(); + } + + console.log(); +}; + +/** + * Pad the given `str` to `len`. + * + * @param {String} str + * @param {String} len + * @return {String} + * @api private + */ + +function pad(str, len) { + str = String(str); + return Array(len - str.length + 1).join(' ') + str; +} + + +/** + * Returns an inline diff between 2 strings with coloured ANSI output + * + * @param {Error} Error with actual/expected + * @return {String} Diff + * @api private + */ + +function inlineDiff(err, escape) { + var msg = errorDiff(err, 'WordsWithSpace', escape); + + // linenos + var lines = msg.split('\n'); + if (lines.length > 4) { + var width = String(lines.length).length; + msg = lines.map(function(str, i){ + return pad(++i, width) + ' |' + ' ' + str; + }).join('\n'); + } + + // legend + msg = '\n' + + color('diff removed', 'actual') + + ' ' + + color('diff added', 'expected') + + '\n\n' + + msg + + '\n'; + + // indent + msg = msg.replace(/^/gm, ' '); + return msg; +} + +/** + * Returns a unified diff between 2 strings + * + * @param {Error} Error with actual/expected + * @return {String} Diff + * @api private + */ + +function unifiedDiff(err, escape) { + var indent = ' '; + function cleanUp(line) { + if (escape) { + line = escapeInvisibles(line); + } + if (line[0] === '+') return indent + colorLines('diff added', line); + if (line[0] === '-') return indent + colorLines('diff removed', line); + if (line.match(/\@\@/)) return null; + if (line.match(/\\ No newline/)) return null; + else return indent + line; + } + function notBlank(line) { + return line != null; + } + msg = diff.createPatch('string', err.actual, err.expected); + var lines = msg.split('\n').splice(4); + return '\n ' + + colorLines('diff added', '+ expected') + ' ' + + colorLines('diff removed', '- actual') + + '\n\n' + + lines.map(cleanUp).filter(notBlank).join('\n'); +} + +/** + * Return a character diff for `err`. + * + * @param {Error} err + * @return {String} + * @api private + */ + +function errorDiff(err, type, escape) { + var actual = escape ? escapeInvisibles(err.actual) : err.actual; + var expected = escape ? escapeInvisibles(err.expected) : err.expected; + return diff['diff' + type](actual, expected).map(function(str){ + if (str.added) return colorLines('diff added', str.value); + if (str.removed) return colorLines('diff removed', str.value); + return str.value; + }).join(''); +} + +/** + * Returns a string with all invisible characters in plain text + * + * @param {String} line + * @return {String} + * @api private + */ +function escapeInvisibles(line) { + return line.replace(/\t/g, '') + .replace(/\r/g, '') + .replace(/\n/g, '\n'); +} + +/** + * Color lines for `str`, using the color `name`. + * + * @param {String} name + * @param {String} str + * @return {String} + * @api private + */ + +function colorLines(name, str) { + return str.split('\n').map(function(str){ + return color(name, str); + }).join('\n'); +} + +/** + * Check that a / b have the same type. + * + * @param {Object} a + * @param {Object} b + * @return {Boolean} + * @api private + */ + +function sameType(a, b) { + a = Object.prototype.toString.call(a); + b = Object.prototype.toString.call(b); + return a == b; +} + +}); // module: reporters/base.js + +require.register("reporters/doc.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , utils = require('../utils'); + +/** + * Expose `Doc`. + */ + +exports = module.exports = Doc; + +/** + * Initialize a new `Doc` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Doc(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , total = runner.total + , indents = 2; + + function indent() { + return Array(indents).join(' '); + } + + runner.on('suite', function(suite){ + if (suite.root) return; + ++indents; + console.log('%s
    ', indent()); + ++indents; + console.log('%s

    %s

    ', indent(), utils.escape(suite.title)); + console.log('%s
    ', indent()); + }); + + runner.on('suite end', function(suite){ + if (suite.root) return; + console.log('%s
    ', indent()); + --indents; + console.log('%s
    ', indent()); + --indents; + }); + + runner.on('pass', function(test){ + console.log('%s
    %s
    ', indent(), utils.escape(test.title)); + var code = utils.escape(utils.clean(test.fn.toString())); + console.log('%s
    %s
    ', indent(), code); + }); + + runner.on('fail', function(test, err){ + console.log('%s
    %s
    ', indent(), utils.escape(test.title)); + var code = utils.escape(utils.clean(test.fn.toString())); + console.log('%s
    %s
    ', indent(), code); + console.log('%s
    %s
    ', indent(), utils.escape(err)); + }); +} + +}); // module: reporters/doc.js + +require.register("reporters/dot.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , color = Base.color; + +/** + * Expose `Dot`. + */ + +exports = module.exports = Dot; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @param {Runner} runner + * @api public + */ + +function Dot(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , width = Base.window.width * .75 | 0 + , n = -1; + + runner.on('start', function(){ + process.stdout.write('\n '); + }); + + runner.on('pending', function(test){ + if (++n % width == 0) process.stdout.write('\n '); + process.stdout.write(color('pending', Base.symbols.dot)); + }); + + runner.on('pass', function(test){ + if (++n % width == 0) process.stdout.write('\n '); + if ('slow' == test.speed) { + process.stdout.write(color('bright yellow', Base.symbols.dot)); + } else { + process.stdout.write(color(test.speed, Base.symbols.dot)); + } + }); + + runner.on('fail', function(test, err){ + if (++n % width == 0) process.stdout.write('\n '); + process.stdout.write(color('fail', Base.symbols.dot)); + }); + + runner.on('end', function(){ + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Dot.prototype = new F; +Dot.prototype.constructor = Dot; + + +}); // module: reporters/dot.js + +require.register("reporters/html-cov.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var JSONCov = require('./json-cov') + , fs = require('browser/fs'); + +/** + * Expose `HTMLCov`. + */ + +exports = module.exports = HTMLCov; + +/** + * Initialize a new `JsCoverage` reporter. + * + * @param {Runner} runner + * @api public + */ + +function HTMLCov(runner) { + var jade = require('jade') + , file = __dirname + '/templates/coverage.jade' + , str = fs.readFileSync(file, 'utf8') + , fn = jade.compile(str, { filename: file }) + , self = this; + + JSONCov.call(this, runner, false); + + runner.on('end', function(){ + process.stdout.write(fn({ + cov: self.cov + , coverageClass: coverageClass + })); + }); +} + +/** + * Return coverage class for `n`. + * + * @return {String} + * @api private + */ + +function coverageClass(n) { + if (n >= 75) return 'high'; + if (n >= 50) return 'medium'; + if (n >= 25) return 'low'; + return 'terrible'; +} +}); // module: reporters/html-cov.js + +require.register("reporters/html.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , utils = require('../utils') + , Progress = require('../browser/progress') + , escape = utils.escape; + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date + , setTimeout = global.setTimeout + , setInterval = global.setInterval + , clearTimeout = global.clearTimeout + , clearInterval = global.clearInterval; + +/** + * Expose `HTML`. + */ + +exports = module.exports = HTML; + +/** + * Stats template. + */ + +var statsTemplate = ''; + +/** + * Initialize a new `HTML` reporter. + * + * @param {Runner} runner + * @api public + */ + +function HTML(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , total = runner.total + , stat = fragment(statsTemplate) + , items = stat.getElementsByTagName('li') + , passes = items[1].getElementsByTagName('em')[0] + , passesLink = items[1].getElementsByTagName('a')[0] + , failures = items[2].getElementsByTagName('em')[0] + , failuresLink = items[2].getElementsByTagName('a')[0] + , duration = items[3].getElementsByTagName('em')[0] + , canvas = stat.getElementsByTagName('canvas')[0] + , report = fragment('
      ') + , stack = [report] + , progress + , ctx + , root = document.getElementById('mocha'); + + if (canvas.getContext) { + var ratio = window.devicePixelRatio || 1; + canvas.style.width = canvas.width; + canvas.style.height = canvas.height; + canvas.width *= ratio; + canvas.height *= ratio; + ctx = canvas.getContext('2d'); + ctx.scale(ratio, ratio); + progress = new Progress; + } + + if (!root) return error('#mocha div missing, add it to your document'); + + // pass toggle + on(passesLink, 'click', function(){ + unhide(); + var name = /pass/.test(report.className) ? '' : ' pass'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) hideSuitesWithout('test pass'); + }); + + // failure toggle + on(failuresLink, 'click', function(){ + unhide(); + var name = /fail/.test(report.className) ? '' : ' fail'; + report.className = report.className.replace(/fail|pass/g, '') + name; + if (report.className.trim()) hideSuitesWithout('test fail'); + }); + + root.appendChild(stat); + root.appendChild(report); + + if (progress) progress.size(40); + + runner.on('suite', function(suite){ + if (suite.root) return; + + // suite + var url = self.suiteURL(suite); + var el = fragment('
    • %s

    • ', url, escape(suite.title)); + + // container + stack[0].appendChild(el); + stack.unshift(document.createElement('ul')); + el.appendChild(stack[0]); + }); + + runner.on('suite end', function(suite){ + if (suite.root) return; + stack.shift(); + }); + + runner.on('fail', function(test, err){ + if ('hook' == test.type) runner.emit('test end', test); + }); + + runner.on('test end', function(test){ + // TODO: add to stats + var percent = stats.tests / this.total * 100 | 0; + if (progress) progress.update(percent).draw(ctx); + + // update stats + var ms = new Date - stats.start; + text(passes, stats.passes); + text(failures, stats.failures); + text(duration, (ms / 1000).toFixed(2)); + + // test + if ('passed' == test.state) { + var url = self.testURL(test); + var el = fragment('
    • %e%ems

    • ', test.speed, test.title, test.duration, url); + } else if (test.pending) { + var el = fragment('
    • %e

    • ', test.title); + } else { + var el = fragment('
    • %e

    • ', test.title, encodeURIComponent(test.fullTitle())); + var str = test.err.stack || test.err.toString(); + + // FF / Opera do not add the message + if (!~str.indexOf(test.err.message)) { + str = test.err.message + '\n' + str; + } + + // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we + // check for the result of the stringifying. + if ('[object Error]' == str) str = test.err.message; + + // Safari doesn't give you a stack. Let's at least provide a source line. + if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { + str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; + } + + el.appendChild(fragment('
      %e
      ', str)); + } + + // toggle code + // TODO: defer + if (!test.pending) { + var h2 = el.getElementsByTagName('h2')[0]; + + on(h2, 'click', function(){ + pre.style.display = 'none' == pre.style.display + ? 'block' + : 'none'; + }); + + var pre = fragment('
      %e
      ', utils.clean(test.fn.toString())); + el.appendChild(pre); + pre.style.display = 'none'; + } + + // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. + if (stack[0]) stack[0].appendChild(el); + }); +} + +/** + * Provide suite URL + * + * @param {Object} [suite] + */ + +HTML.prototype.suiteURL = function(suite){ + return '?grep=' + encodeURIComponent(suite.fullTitle()); +}; + +/** + * Provide test URL + * + * @param {Object} [test] + */ + +HTML.prototype.testURL = function(test){ + return '?grep=' + encodeURIComponent(test.fullTitle()); +}; + +/** + * Display error `msg`. + */ + +function error(msg) { + document.body.appendChild(fragment('
      %s
      ', msg)); +} + +/** + * Return a DOM fragment from `html`. + */ + +function fragment(html) { + var args = arguments + , div = document.createElement('div') + , i = 1; + + div.innerHTML = html.replace(/%([se])/g, function(_, type){ + switch (type) { + case 's': return String(args[i++]); + case 'e': return escape(args[i++]); + } + }); + + return div.firstChild; +} + +/** + * Check for suites that do not have elements + * with `classname`, and hide them. + */ + +function hideSuitesWithout(classname) { + var suites = document.getElementsByClassName('suite'); + for (var i = 0; i < suites.length; i++) { + var els = suites[i].getElementsByClassName(classname); + if (0 == els.length) suites[i].className += ' hidden'; + } +} + +/** + * Unhide .hidden suites. + */ + +function unhide() { + var els = document.getElementsByClassName('suite hidden'); + for (var i = 0; i < els.length; ++i) { + els[i].className = els[i].className.replace('suite hidden', 'suite'); + } +} + +/** + * Set `el` text to `str`. + */ + +function text(el, str) { + if (el.textContent) { + el.textContent = str; + } else { + el.innerText = str; + } +} + +/** + * Listen on `event` with callback `fn`. + */ + +function on(el, event, fn) { + if (el.addEventListener) { + el.addEventListener(event, fn, false); + } else { + el.attachEvent('on' + event, fn); + } +} + +}); // module: reporters/html.js + +require.register("reporters/index.js", function(module, exports, require){ + +exports.Base = require('./base'); +exports.Dot = require('./dot'); +exports.Doc = require('./doc'); +exports.TAP = require('./tap'); +exports.JSON = require('./json'); +exports.HTML = require('./html'); +exports.List = require('./list'); +exports.Min = require('./min'); +exports.Spec = require('./spec'); +exports.Nyan = require('./nyan'); +exports.XUnit = require('./xunit'); +exports.Markdown = require('./markdown'); +exports.Progress = require('./progress'); +exports.Landing = require('./landing'); +exports.JSONCov = require('./json-cov'); +exports.HTMLCov = require('./html-cov'); +exports.JSONStream = require('./json-stream'); + +}); // module: reporters/index.js + +require.register("reporters/json-cov.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `JSONCov`. + */ + +exports = module.exports = JSONCov; + +/** + * Initialize a new `JsCoverage` reporter. + * + * @param {Runner} runner + * @param {Boolean} output + * @api public + */ + +function JSONCov(runner, output) { + var self = this + , output = 1 == arguments.length ? true : output; + + Base.call(this, runner); + + var tests = [] + , failures = [] + , passes = []; + + runner.on('test end', function(test){ + tests.push(test); + }); + + runner.on('pass', function(test){ + passes.push(test); + }); + + runner.on('fail', function(test){ + failures.push(test); + }); + + runner.on('end', function(){ + var cov = global._$jscoverage || {}; + var result = self.cov = map(cov); + result.stats = self.stats; + result.tests = tests.map(clean); + result.failures = failures.map(clean); + result.passes = passes.map(clean); + if (!output) return; + process.stdout.write(JSON.stringify(result, null, 2 )); + }); +} + +/** + * Map jscoverage data to a JSON structure + * suitable for reporting. + * + * @param {Object} cov + * @return {Object} + * @api private + */ + +function map(cov) { + var ret = { + instrumentation: 'node-jscoverage' + , sloc: 0 + , hits: 0 + , misses: 0 + , coverage: 0 + , files: [] + }; + + for (var filename in cov) { + var data = coverage(filename, cov[filename]); + ret.files.push(data); + ret.hits += data.hits; + ret.misses += data.misses; + ret.sloc += data.sloc; + } + + ret.files.sort(function(a, b) { + return a.filename.localeCompare(b.filename); + }); + + if (ret.sloc > 0) { + ret.coverage = (ret.hits / ret.sloc) * 100; + } + + return ret; +} + +/** + * Map jscoverage data for a single source file + * to a JSON structure suitable for reporting. + * + * @param {String} filename name of the source file + * @param {Object} data jscoverage coverage data + * @return {Object} + * @api private + */ + +function coverage(filename, data) { + var ret = { + filename: filename, + coverage: 0, + hits: 0, + misses: 0, + sloc: 0, + source: {} + }; + + data.source.forEach(function(line, num){ + num++; + + if (data[num] === 0) { + ret.misses++; + ret.sloc++; + } else if (data[num] !== undefined) { + ret.hits++; + ret.sloc++; + } + + ret.source[num] = { + source: line + , coverage: data[num] === undefined + ? '' + : data[num] + }; + }); + + ret.coverage = ret.hits / ret.sloc * 100; + + return ret; +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @param {Object} test + * @return {Object} + * @api private + */ + +function clean(test) { + return { + title: test.title + , fullTitle: test.fullTitle() + , duration: test.duration + } +} + +}); // module: reporters/json-cov.js + +require.register("reporters/json-stream.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , color = Base.color; + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `List` test reporter. + * + * @param {Runner} runner + * @api public + */ + +function List(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , total = runner.total; + + runner.on('start', function(){ + console.log(JSON.stringify(['start', { total: total }])); + }); + + runner.on('pass', function(test){ + console.log(JSON.stringify(['pass', clean(test)])); + }); + + runner.on('fail', function(test, err){ + console.log(JSON.stringify(['fail', clean(test)])); + }); + + runner.on('end', function(){ + process.stdout.write(JSON.stringify(['end', self.stats])); + }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @param {Object} test + * @return {Object} + * @api private + */ + +function clean(test) { + return { + title: test.title + , fullTitle: test.fullTitle() + , duration: test.duration + } +} +}); // module: reporters/json-stream.js + +require.register("reporters/json.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `JSON`. + */ + +exports = module.exports = JSONReporter; + +/** + * Initialize a new `JSON` reporter. + * + * @param {Runner} runner + * @api public + */ + +function JSONReporter(runner) { + var self = this; + Base.call(this, runner); + + var tests = [] + , pending = [] + , failures = [] + , passes = []; + + runner.on('test end', function(test){ + tests.push(test); + }); + + runner.on('pass', function(test){ + passes.push(test); + }); + + runner.on('fail', function(test){ + failures.push(test); + }); + + runner.on('pending', function(test){ + pending.push(test); + }); + + runner.on('end', function(){ + var obj = { + stats: self.stats, + tests: tests.map(clean), + pending: pending.map(clean), + failures: failures.map(clean), + passes: passes.map(clean) + }; + + runner.testResults = obj; + + process.stdout.write(JSON.stringify(obj, null, 2)); + }); +} + +/** + * Return a plain-object representation of `test` + * free of cyclic properties etc. + * + * @param {Object} test + * @return {Object} + * @api private + */ + +function clean(test) { + return { + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + err: errorJSON(test.err || {}) + } +} + +/** + * Transform `error` into a JSON object. + * @param {Error} err + * @return {Object} + */ + +function errorJSON(err) { + var res = {}; + Object.getOwnPropertyNames(err).forEach(function(key) { + res[key] = err[key]; + }, err); + return res; +} + +}); // module: reporters/json.js + +require.register("reporters/landing.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `Landing`. + */ + +exports = module.exports = Landing; + +/** + * Airplane color. + */ + +Base.colors.plane = 0; + +/** + * Airplane crash color. + */ + +Base.colors['plane crash'] = 31; + +/** + * Runway color. + */ + +Base.colors.runway = 90; + +/** + * Initialize a new `Landing` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Landing(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , width = Base.window.width * .75 | 0 + , total = runner.total + , stream = process.stdout + , plane = color('plane', '✈') + , crashed = -1 + , n = 0; + + function runway() { + var buf = Array(width).join('-'); + return ' ' + color('runway', buf); + } + + runner.on('start', function(){ + stream.write('\n '); + cursor.hide(); + }); + + runner.on('test end', function(test){ + // check if the plane crashed + var col = -1 == crashed + ? width * ++n / total | 0 + : crashed; + + // show the crash + if ('failed' == test.state) { + plane = color('plane crash', '✈'); + crashed = col; + } + + // render landing strip + stream.write('\u001b[4F\n\n'); + stream.write(runway()); + stream.write('\n '); + stream.write(color('runway', Array(col).join('⋅'))); + stream.write(plane) + stream.write(color('runway', Array(width - col).join('⋅') + '\n')); + stream.write(runway()); + stream.write('\u001b[0m'); + }); + + runner.on('end', function(){ + cursor.show(); + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Landing.prototype = new F; +Landing.prototype.constructor = Landing; + +}); // module: reporters/landing.js + +require.register("reporters/list.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `List`. + */ + +exports = module.exports = List; + +/** + * Initialize a new `List` test reporter. + * + * @param {Runner} runner + * @api public + */ + +function List(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , n = 0; + + runner.on('start', function(){ + console.log(); + }); + + runner.on('test', function(test){ + process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); + }); + + runner.on('pending', function(test){ + var fmt = color('checkmark', ' -') + + color('pending', ' %s'); + console.log(fmt, test.fullTitle()); + }); + + runner.on('pass', function(test){ + var fmt = color('checkmark', ' '+Base.symbols.dot) + + color('pass', ' %s: ') + + color(test.speed, '%dms'); + cursor.CR(); + console.log(fmt, test.fullTitle(), test.duration); + }); + + runner.on('fail', function(test, err){ + cursor.CR(); + console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); + }); + + runner.on('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +List.prototype = new F; +List.prototype.constructor = List; + + +}); // module: reporters/list.js + +require.register("reporters/markdown.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var Base = require('./base') + , utils = require('../utils'); + +/** + * Expose `Markdown`. + */ + +exports = module.exports = Markdown; + +/** + * Initialize a new `Markdown` reporter. + * + * @param {Runner} runner + * @api public + */ + +function Markdown(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , level = 0 + , buf = ''; + + function title(str) { + return Array(level).join('#') + ' ' + str; + } + + function indent() { + return Array(level).join(' '); + } + + function mapTOC(suite, obj) { + var ret = obj; + obj = obj[suite.title] = obj[suite.title] || { suite: suite }; + suite.suites.forEach(function(suite){ + mapTOC(suite, obj); + }); + return ret; + } + + function stringifyTOC(obj, level) { + ++level; + var buf = ''; + var link; + for (var key in obj) { + if ('suite' == key) continue; + if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; + if (key) buf += Array(level).join(' ') + link; + buf += stringifyTOC(obj[key], level); + } + --level; + return buf; + } + + function generateTOC(suite) { + var obj = mapTOC(suite, {}); + return stringifyTOC(obj, 0); + } + + generateTOC(runner.suite); + + runner.on('suite', function(suite){ + ++level; + var slug = utils.slug(suite.fullTitle()); + buf += '' + '\n'; + buf += title(suite.title) + '\n'; + }); + + runner.on('suite end', function(suite){ + --level; + }); + + runner.on('pass', function(test){ + var code = utils.clean(test.fn.toString()); + buf += test.title + '.\n'; + buf += '\n```js\n'; + buf += code + '\n'; + buf += '```\n\n'; + }); + + runner.on('end', function(){ + process.stdout.write('# TOC\n'); + process.stdout.write(generateTOC(runner.suite)); + process.stdout.write(buf); + }); +} +}); // module: reporters/markdown.js + +require.register("reporters/min.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base'); + +/** + * Expose `Min`. + */ + +exports = module.exports = Min; + +/** + * Initialize a new `Min` minimal test reporter (best used with --watch). + * + * @param {Runner} runner + * @api public + */ + +function Min(runner) { + Base.call(this, runner); + + runner.on('start', function(){ + // clear screen + process.stdout.write('\u001b[2J'); + // set cursor position + process.stdout.write('\u001b[1;3H'); + }); + + runner.on('end', this.epilogue.bind(this)); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Min.prototype = new F; +Min.prototype.constructor = Min; + + +}); // module: reporters/min.js + +require.register("reporters/nyan.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var Base = require('./base') + , color = Base.color; + +/** + * Expose `Dot`. + */ + +exports = module.exports = NyanCat; + +/** + * Initialize a new `Dot` matrix test reporter. + * + * @param {Runner} runner + * @api public + */ + +function NyanCat(runner) { + Base.call(this, runner); + var self = this + , stats = this.stats + , width = Base.window.width * .75 | 0 + , rainbowColors = this.rainbowColors = self.generateColors() + , colorIndex = this.colorIndex = 0 + , numerOfLines = this.numberOfLines = 4 + , trajectories = this.trajectories = [[], [], [], []] + , nyanCatWidth = this.nyanCatWidth = 11 + , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) + , scoreboardWidth = this.scoreboardWidth = 5 + , tick = this.tick = 0 + , n = 0; + + runner.on('start', function(){ + Base.cursor.hide(); + self.draw(); + }); + + runner.on('pending', function(test){ + self.draw(); + }); + + runner.on('pass', function(test){ + self.draw(); + }); + + runner.on('fail', function(test, err){ + self.draw(); + }); + + runner.on('end', function(){ + Base.cursor.show(); + for (var i = 0; i < self.numberOfLines; i++) write('\n'); + self.epilogue(); + }); +} + +/** + * Draw the nyan cat + * + * @api private + */ + +NyanCat.prototype.draw = function(){ + this.appendRainbow(); + this.drawScoreboard(); + this.drawRainbow(); + this.drawNyanCat(); + this.tick = !this.tick; +}; + +/** + * Draw the "scoreboard" showing the number + * of passes, failures and pending tests. + * + * @api private + */ + +NyanCat.prototype.drawScoreboard = function(){ + var stats = this.stats; + var colors = Base.colors; + + function draw(color, n) { + write(' '); + write('\u001b[' + color + 'm' + n + '\u001b[0m'); + write('\n'); + } + + draw(colors.green, stats.passes); + draw(colors.fail, stats.failures); + draw(colors.pending, stats.pending); + write('\n'); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Append the rainbow. + * + * @api private + */ + +NyanCat.prototype.appendRainbow = function(){ + var segment = this.tick ? '_' : '-'; + var rainbowified = this.rainbowify(segment); + + for (var index = 0; index < this.numberOfLines; index++) { + var trajectory = this.trajectories[index]; + if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); + trajectory.push(rainbowified); + } +}; + +/** + * Draw the rainbow. + * + * @api private + */ + +NyanCat.prototype.drawRainbow = function(){ + var self = this; + + this.trajectories.forEach(function(line, index) { + write('\u001b[' + self.scoreboardWidth + 'C'); + write(line.join('')); + write('\n'); + }); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Draw the nyan cat + * + * @api private + */ + +NyanCat.prototype.drawNyanCat = function() { + var self = this; + var startWidth = this.scoreboardWidth + this.trajectories[0].length; + var color = '\u001b[' + startWidth + 'C'; + var padding = ''; + + write(color); + write('_,------,'); + write('\n'); + + write(color); + padding = self.tick ? ' ' : ' '; + write('_|' + padding + '/\\_/\\ '); + write('\n'); + + write(color); + padding = self.tick ? '_' : '__'; + var tail = self.tick ? '~' : '^'; + var face; + write(tail + '|' + padding + this.face() + ' '); + write('\n'); + + write(color); + padding = self.tick ? ' ' : ' '; + write(padding + '"" "" '); + write('\n'); + + this.cursorUp(this.numberOfLines); +}; + +/** + * Draw nyan cat face. + * + * @return {String} + * @api private + */ + +NyanCat.prototype.face = function() { + var stats = this.stats; + if (stats.failures) { + return '( x .x)'; + } else if (stats.pending) { + return '( o .o)'; + } else if(stats.passes) { + return '( ^ .^)'; + } else { + return '( - .-)'; + } +}; + +/** + * Move cursor up `n`. + * + * @param {Number} n + * @api private + */ + +NyanCat.prototype.cursorUp = function(n) { + write('\u001b[' + n + 'A'); +}; + +/** + * Move cursor down `n`. + * + * @param {Number} n + * @api private + */ + +NyanCat.prototype.cursorDown = function(n) { + write('\u001b[' + n + 'B'); +}; + +/** + * Generate rainbow colors. + * + * @return {Array} + * @api private + */ + +NyanCat.prototype.generateColors = function(){ + var colors = []; + + for (var i = 0; i < (6 * 7); i++) { + var pi3 = Math.floor(Math.PI / 3); + var n = (i * (1.0 / 6)); + var r = Math.floor(3 * Math.sin(n) + 3); + var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); + var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); + colors.push(36 * r + 6 * g + b + 16); + } + + return colors; +}; + +/** + * Apply rainbow to the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +NyanCat.prototype.rainbowify = function(str){ + var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; + this.colorIndex += 1; + return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; +}; + +/** + * Stdout helper. + */ + +function write(string) { + process.stdout.write(string); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +NyanCat.prototype = new F; +NyanCat.prototype.constructor = NyanCat; + + +}); // module: reporters/nyan.js + +require.register("reporters/progress.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `Progress`. + */ + +exports = module.exports = Progress; + +/** + * General progress bar color. + */ + +Base.colors.progress = 90; + +/** + * Initialize a new `Progress` bar test reporter. + * + * @param {Runner} runner + * @param {Object} options + * @api public + */ + +function Progress(runner, options) { + Base.call(this, runner); + + var self = this + , options = options || {} + , stats = this.stats + , width = Base.window.width * .50 | 0 + , total = runner.total + , complete = 0 + , max = Math.max + , lastN = -1; + + // default chars + options.open = options.open || '['; + options.complete = options.complete || '▬'; + options.incomplete = options.incomplete || Base.symbols.dot; + options.close = options.close || ']'; + options.verbose = false; + + // tests started + runner.on('start', function(){ + console.log(); + cursor.hide(); + }); + + // tests complete + runner.on('test end', function(){ + complete++; + var incomplete = total - complete + , percent = complete / total + , n = width * percent | 0 + , i = width - n; + + if (lastN === n && !options.verbose) { + // Don't re-render the line if it hasn't changed + return; + } + lastN = n; + + cursor.CR(); + process.stdout.write('\u001b[J'); + process.stdout.write(color('progress', ' ' + options.open)); + process.stdout.write(Array(n).join(options.complete)); + process.stdout.write(Array(i).join(options.incomplete)); + process.stdout.write(color('progress', options.close)); + if (options.verbose) { + process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); + } + }); + + // tests are complete, output some stats + // and the failures if any + runner.on('end', function(){ + cursor.show(); + console.log(); + self.epilogue(); + }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Progress.prototype = new F; +Progress.prototype.constructor = Progress; + + +}); // module: reporters/progress.js + +require.register("reporters/spec.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `Spec`. + */ + +exports = module.exports = Spec; + +/** + * Initialize a new `Spec` test reporter. + * + * @param {Runner} runner + * @api public + */ + +function Spec(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , indents = 0 + , n = 0; + + function indent() { + return Array(indents).join(' ') + } + + runner.on('start', function(){ + console.log(); + }); + + runner.on('suite', function(suite){ + ++indents; + console.log(color('suite', '%s%s'), indent(), suite.title); + }); + + runner.on('suite end', function(suite){ + --indents; + if (1 == indents) console.log(); + }); + + runner.on('pending', function(test){ + var fmt = indent() + color('pending', ' - %s'); + console.log(fmt, test.title); + }); + + runner.on('pass', function(test){ + if ('fast' == test.speed) { + var fmt = indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s '); + cursor.CR(); + console.log(fmt, test.title); + } else { + var fmt = indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s ') + + color(test.speed, '(%dms)'); + cursor.CR(); + console.log(fmt, test.title, test.duration); + } + }); + + runner.on('fail', function(test, err){ + cursor.CR(); + console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); + }); + + runner.on('end', self.epilogue.bind(self)); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +Spec.prototype = new F; +Spec.prototype.constructor = Spec; + + +}); // module: reporters/spec.js + +require.register("reporters/tap.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , cursor = Base.cursor + , color = Base.color; + +/** + * Expose `TAP`. + */ + +exports = module.exports = TAP; + +/** + * Initialize a new `TAP` reporter. + * + * @param {Runner} runner + * @api public + */ + +function TAP(runner) { + Base.call(this, runner); + + var self = this + , stats = this.stats + , n = 1 + , passes = 0 + , failures = 0; + + runner.on('start', function(){ + var total = runner.grepTotal(runner.suite); + console.log('%d..%d', 1, total); + }); + + runner.on('test end', function(){ + ++n; + }); + + runner.on('pending', function(test){ + console.log('ok %d %s # SKIP -', n, title(test)); + }); + + runner.on('pass', function(test){ + passes++; + console.log('ok %d %s', n, title(test)); + }); + + runner.on('fail', function(test, err){ + failures++; + console.log('not ok %d %s', n, title(test)); + if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); + }); + + runner.on('end', function(){ + console.log('# tests ' + (passes + failures)); + console.log('# pass ' + passes); + console.log('# fail ' + failures); + }); +} + +/** + * Return a TAP-safe title of `test` + * + * @param {Object} test + * @return {String} + * @api private + */ + +function title(test) { + return test.fullTitle().replace(/#/g, ''); +} + +}); // module: reporters/tap.js + +require.register("reporters/xunit.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Base = require('./base') + , utils = require('../utils') + , escape = utils.escape; + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date + , setTimeout = global.setTimeout + , setInterval = global.setInterval + , clearTimeout = global.clearTimeout + , clearInterval = global.clearInterval; + +/** + * Expose `XUnit`. + */ + +exports = module.exports = XUnit; + +/** + * Initialize a new `XUnit` reporter. + * + * @param {Runner} runner + * @api public + */ + +function XUnit(runner) { + Base.call(this, runner); + var stats = this.stats + , tests = [] + , self = this; + + runner.on('pending', function(test){ + tests.push(test); + }); + + runner.on('pass', function(test){ + tests.push(test); + }); + + runner.on('fail', function(test){ + tests.push(test); + }); + + runner.on('end', function(){ + console.log(tag('testsuite', { + name: 'Mocha Tests' + , tests: stats.tests + , failures: stats.failures + , errors: stats.failures + , skipped: stats.tests - stats.failures - stats.passes + , timestamp: (new Date).toUTCString() + , time: (stats.duration / 1000) || 0 + }, false)); + + tests.forEach(test); + console.log(''); + }); +} + +/** + * Inherit from `Base.prototype`. + */ + +function F(){}; +F.prototype = Base.prototype; +XUnit.prototype = new F; +XUnit.prototype.constructor = XUnit; + + +/** + * Output tag for the given `test.` + */ + +function test(test) { + var attrs = { + classname: test.parent.fullTitle() + , name: test.title + , time: (test.duration / 1000) || 0 + }; + + if ('failed' == test.state) { + var err = test.err; + console.log(tag('testcase', attrs, false, tag('failure', {}, false, cdata(escape(err.message) + "\n" + err.stack)))); + } else if (test.pending) { + console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); + } else { + console.log(tag('testcase', attrs, true) ); + } +} + +/** + * HTML tag helper. + */ + +function tag(name, attrs, close, content) { + var end = close ? '/>' : '>' + , pairs = [] + , tag; + + for (var key in attrs) { + pairs.push(key + '="' + escape(attrs[key]) + '"'); + } + + tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; + if (content) tag += content + ''; +} + +}); // module: reporters/xunit.js + +require.register("runnable.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var EventEmitter = require('browser/events').EventEmitter + , debug = require('browser/debug')('mocha:runnable') + , milliseconds = require('./ms'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date + , setTimeout = global.setTimeout + , setInterval = global.setInterval + , clearTimeout = global.clearTimeout + , clearInterval = global.clearInterval; + +/** + * Object#toString(). + */ + +var toString = Object.prototype.toString; + +/** + * Expose `Runnable`. + */ + +module.exports = Runnable; + +/** + * Initialize a new `Runnable` with the given `title` and callback `fn`. + * + * @param {String} title + * @param {Function} fn + * @api private + */ + +function Runnable(title, fn) { + this.title = title; + this.fn = fn; + this.async = fn && fn.length; + this.sync = ! this.async; + this._timeout = 2000; + this._slow = 75; + this._enableTimeouts = true; + this.timedOut = false; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ + +function F(){}; +F.prototype = EventEmitter.prototype; +Runnable.prototype = new F; +Runnable.prototype.constructor = Runnable; + + +/** + * Set & get timeout `ms`. + * + * @param {Number|String} ms + * @return {Runnable|Number} ms or self + * @api private + */ + +Runnable.prototype.timeout = function(ms){ + if (0 == arguments.length) return this._timeout; + if (ms === 0) this._enableTimeouts = false; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('timeout %d', ms); + this._timeout = ms; + if (this.timer) this.resetTimeout(); + return this; +}; + +/** + * Set & get slow `ms`. + * + * @param {Number|String} ms + * @return {Runnable|Number} ms or self + * @api private + */ + +Runnable.prototype.slow = function(ms){ + if (0 === arguments.length) return this._slow; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('timeout %d', ms); + this._slow = ms; + return this; +}; + +/** + * Set and & get timeout `enabled`. + * + * @param {Boolean} enabled + * @return {Runnable|Boolean} enabled or self + * @api private + */ + +Runnable.prototype.enableTimeouts = function(enabled){ + if (arguments.length === 0) return this._enableTimeouts; + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Return the full title generated by recursively + * concatenating the parent's full title. + * + * @return {String} + * @api public + */ + +Runnable.prototype.fullTitle = function(){ + return this.parent.fullTitle() + ' ' + this.title; +}; + +/** + * Clear the timeout. + * + * @api private + */ + +Runnable.prototype.clearTimeout = function(){ + clearTimeout(this.timer); +}; + +/** + * Inspect the runnable void of private properties. + * + * @return {String} + * @api private + */ + +Runnable.prototype.inspect = function(){ + return JSON.stringify(this, function(key, val){ + if ('_' == key[0]) return; + if ('parent' == key) return '#'; + if ('ctx' == key) return '#'; + return val; + }, 2); +}; + +/** + * Reset the timeout. + * + * @api private + */ + +Runnable.prototype.resetTimeout = function(){ + var self = this; + var ms = this.timeout() || 1e9; + + if (!this._enableTimeouts) return; + this.clearTimeout(); + this.timer = setTimeout(function(){ + if (!self._enableTimeouts) return; + self.callback(new Error('timeout of ' + ms + 'ms exceeded')); + self.timedOut = true; + }, ms); +}; + +/** + * Whitelist these globals for this test run + * + * @api private + */ +Runnable.prototype.globals = function(arr){ + var self = this; + this._allowedGlobals = arr; +}; + +/** + * Run the test and invoke `fn(err)`. + * + * @param {Function} fn + * @api private + */ + +Runnable.prototype.run = function(fn){ + var self = this + , start = new Date + , ctx = this.ctx + , finished + , emitted; + + // Some times the ctx exists but it is not runnable + if (ctx && ctx.runnable) ctx.runnable(this); + + // called multiple times + function multiple(err) { + if (emitted) return; + emitted = true; + self.emit('error', err || new Error('done() called multiple times')); + } + + // finished + function done(err) { + var ms = self.timeout(); + if (self.timedOut) return; + if (finished) return multiple(err); + self.clearTimeout(); + self.duration = new Date - start; + finished = true; + if (!err && self.duration > ms && self._enableTimeouts) err = new Error('timeout of ' + ms + 'ms exceeded'); + fn(err); + } + + // for .resetTimeout() + this.callback = done; + + // explicit async with `done` argument + if (this.async) { + this.resetTimeout(); + + try { + this.fn.call(ctx, function(err){ + if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); + if (null != err) { + if (Object.prototype.toString.call(err) === '[object Object]') { + return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err))); + } else { + return done(new Error('done() invoked with non-Error: ' + err)); + } + } + done(); + }); + } catch (err) { + done(err); + } + return; + } + + if (this.asyncOnly) { + return done(new Error('--async-only option in use without declaring `done()`')); + } + + // sync or promise-returning + try { + if (this.pending) { + done(); + } else { + callFn(this.fn); + } + } catch (err) { + done(err); + } + + function callFn(fn) { + var result = fn.call(ctx); + if (result && typeof result.then === 'function') { + self.resetTimeout(); + result + .then(function() { + done() + }, + function(reason) { + done(reason || new Error('Promise rejected with no or falsy reason')) + }); + } else { + done(); + } + } +}; + +}); // module: runnable.js + +require.register("runner.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var EventEmitter = require('browser/events').EventEmitter + , debug = require('browser/debug')('mocha:runner') + , Test = require('./test') + , utils = require('./utils') + , filter = utils.filter + , keys = utils.keys; + +/** + * Non-enumerable globals. + */ + +var globals = [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'XMLHttpRequest', + 'Date' +]; + +/** + * Expose `Runner`. + */ + +module.exports = Runner; + +/** + * Initialize a `Runner` for the given `suite`. + * + * Events: + * + * - `start` execution started + * - `end` execution complete + * - `suite` (suite) test suite execution started + * - `suite end` (suite) all tests (and sub-suites) have finished + * - `test` (test) test execution started + * - `test end` (test) test completed + * - `hook` (hook) hook execution started + * - `hook end` (hook) hook complete + * - `pass` (test) test passed + * - `fail` (test, err) test failed + * - `pending` (test) test pending + * + * @api public + */ + +function Runner(suite) { + var self = this; + this._globals = []; + this._abort = false; + this.suite = suite; + this.total = suite.total(); + this.failures = 0; + this.on('test end', function(test){ self.checkGlobals(test); }); + this.on('hook end', function(hook){ self.checkGlobals(hook); }); + this.grep(/.*/); + this.globals(this.globalProps().concat(extraGlobals())); +} + +/** + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + * + * @param {Function} fn + * @api private + */ + +Runner.immediately = global.setImmediate || process.nextTick; + +/** + * Inherit from `EventEmitter.prototype`. + */ + +function F(){}; +F.prototype = EventEmitter.prototype; +Runner.prototype = new F; +Runner.prototype.constructor = Runner; + + +/** + * Run tests with full titles matching `re`. Updates runner.total + * with number of tests matched. + * + * @param {RegExp} re + * @param {Boolean} invert + * @return {Runner} for chaining + * @api public + */ + +Runner.prototype.grep = function(re, invert){ + debug('grep %s', re); + this._grep = re; + this._invert = invert; + this.total = this.grepTotal(this.suite); + return this; +}; + +/** + * Returns the number of tests matching the grep search for the + * given suite. + * + * @param {Suite} suite + * @return {Number} + * @api public + */ + +Runner.prototype.grepTotal = function(suite) { + var self = this; + var total = 0; + + suite.eachTest(function(test){ + var match = self._grep.test(test.fullTitle()); + if (self._invert) match = !match; + if (match) total++; + }); + + return total; +}; + +/** + * Return a list of global properties. + * + * @return {Array} + * @api private + */ + +Runner.prototype.globalProps = function() { + var props = utils.keys(global); + + // non-enumerables + for (var i = 0; i < globals.length; ++i) { + if (~utils.indexOf(props, globals[i])) continue; + props.push(globals[i]); + } + + return props; +}; + +/** + * Allow the given `arr` of globals. + * + * @param {Array} arr + * @return {Runner} for chaining + * @api public + */ + +Runner.prototype.globals = function(arr){ + if (0 == arguments.length) return this._globals; + debug('globals %j', arr); + this._globals = this._globals.concat(arr); + return this; +}; + +/** + * Check for global variable leaks. + * + * @api private + */ + +Runner.prototype.checkGlobals = function(test){ + if (this.ignoreLeaks) return; + var ok = this._globals; + + var globals = this.globalProps(); + var leaks; + + if (test) { + ok = ok.concat(test._allowedGlobals || []); + } + + if(this.prevGlobalsLength == globals.length) return; + this.prevGlobalsLength = globals.length; + + leaks = filterLeaks(ok, globals); + this._globals = this._globals.concat(leaks); + + if (leaks.length > 1) { + this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); + } else if (leaks.length) { + this.fail(test, new Error('global leak detected: ' + leaks[0])); + } +}; + +/** + * Fail the given `test`. + * + * @param {Test} test + * @param {Error} err + * @api private + */ + +Runner.prototype.fail = function(test, err){ + ++this.failures; + test.state = 'failed'; + + if ('string' == typeof err) { + err = new Error('the string "' + err + '" was thrown, throw an Error :)'); + } + + this.emit('fail', test, err); +}; + +/** + * Fail the given `hook` with `err`. + * + * Hook failures work in the following pattern: + * - If bail, then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter + * execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks + * + * @param {Hook} hook + * @param {Error} err + * @api private + */ + +Runner.prototype.failHook = function(hook, err){ + this.fail(hook, err); + if (this.suite.bail()) { + this.emit('end'); + } +}; + +/** + * Run hook `name` callbacks and then invoke `fn()`. + * + * @param {String} name + * @param {Function} function + * @api private + */ + +Runner.prototype.hook = function(name, fn){ + var suite = this.suite + , hooks = suite['_' + name] + , self = this + , timer; + + function next(i) { + var hook = hooks[i]; + if (!hook) return fn(); + if (self.failures && suite.bail()) return fn(); + self.currentRunnable = hook; + + hook.ctx.currentTest = self.test; + + self.emit('hook', hook); + + hook.on('error', function(err){ + self.failHook(hook, err); + }); + + hook.run(function(err){ + hook.removeAllListeners('error'); + var testError = hook.error(); + if (testError) self.fail(self.test, testError); + if (err) { + self.failHook(hook, err); + + // stop executing hooks, notify callee of hook err + return fn(err); + } + self.emit('hook end', hook); + delete hook.ctx.currentTest; + next(++i); + }); + } + + Runner.immediately(function(){ + next(0); + }); +}; + +/** + * Run hook `name` for the given array of `suites` + * in order, and callback `fn(err, errSuite)`. + * + * @param {String} name + * @param {Array} suites + * @param {Function} fn + * @api private + */ + +Runner.prototype.hooks = function(name, suites, fn){ + var self = this + , orig = this.suite; + + function next(suite) { + self.suite = suite; + + if (!suite) { + self.suite = orig; + return fn(); + } + + self.hook(name, function(err){ + if (err) { + var errSuite = self.suite; + self.suite = orig; + return fn(err, errSuite); + } + + next(suites.pop()); + }); + } + + next(suites.pop()); +}; + +/** + * Run hooks from the top level down. + * + * @param {String} name + * @param {Function} fn + * @api private + */ + +Runner.prototype.hookUp = function(name, fn){ + var suites = [this.suite].concat(this.parents()).reverse(); + this.hooks(name, suites, fn); +}; + +/** + * Run hooks from the bottom up. + * + * @param {String} name + * @param {Function} fn + * @api private + */ + +Runner.prototype.hookDown = function(name, fn){ + var suites = [this.suite].concat(this.parents()); + this.hooks(name, suites, fn); +}; + +/** + * Return an array of parent Suites from + * closest to furthest. + * + * @return {Array} + * @api private + */ + +Runner.prototype.parents = function(){ + var suite = this.suite + , suites = []; + while (suite = suite.parent) suites.push(suite); + return suites; +}; + +/** + * Run the current test and callback `fn(err)`. + * + * @param {Function} fn + * @api private + */ + +Runner.prototype.runTest = function(fn){ + var test = this.test + , self = this; + + if (this.asyncOnly) test.asyncOnly = true; + + try { + test.on('error', function(err){ + self.fail(test, err); + }); + test.run(fn); + } catch (err) { + fn(err); + } +}; + +/** + * Run tests in the given `suite` and invoke + * the callback `fn()` when complete. + * + * @param {Suite} suite + * @param {Function} fn + * @api private + */ + +Runner.prototype.runTests = function(suite, fn){ + var self = this + , tests = suite.tests.slice() + , test; + + + function hookErr(err, errSuite, after) { + // before/after Each hook for errSuite failed: + var orig = self.suite; + + // for failed 'after each' hook start from errSuite parent, + // otherwise start from errSuite itself + self.suite = after ? errSuite.parent : errSuite; + + if (self.suite) { + // call hookUp afterEach + self.hookUp('afterEach', function(err2, errSuite2) { + self.suite = orig; + // some hooks may fail even now + if (err2) return hookErr(err2, errSuite2, true); + // report error suite + fn(errSuite); + }); + } else { + // there is no need calling other 'after each' hooks + self.suite = orig; + fn(errSuite); + } + } + + function next(err, errSuite) { + // if we bail after first err + if (self.failures && suite._bail) return fn(); + + if (self._abort) return fn(); + + if (err) return hookErr(err, errSuite, true); + + // next test + test = tests.shift(); + + // all done + if (!test) return fn(); + + // grep + var match = self._grep.test(test.fullTitle()); + if (self._invert) match = !match; + if (!match) return next(); + + // pending + if (test.pending) { + self.emit('pending', test); + self.emit('test end', test); + return next(); + } + + // execute test and hook(s) + self.emit('test', self.test = test); + self.hookDown('beforeEach', function(err, errSuite){ + + if (err) return hookErr(err, errSuite, false); + + self.currentRunnable = self.test; + self.runTest(function(err){ + test = self.test; + + if (err) { + self.fail(test, err); + self.emit('test end', test); + return self.hookUp('afterEach', next); + } + + test.state = 'passed'; + self.emit('pass', test); + self.emit('test end', test); + self.hookUp('afterEach', next); + }); + }); + } + + this.next = next; + next(); +}; + +/** + * Run the given `suite` and invoke the + * callback `fn()` when complete. + * + * @param {Suite} suite + * @param {Function} fn + * @api private + */ + +Runner.prototype.runSuite = function(suite, fn){ + var total = this.grepTotal(suite) + , self = this + , i = 0; + + debug('run suite %s', suite.fullTitle()); + + if (!total) return fn(); + + this.emit('suite', this.suite = suite); + + function next(errSuite) { + if (errSuite) { + // current suite failed on a hook from errSuite + if (errSuite == suite) { + // if errSuite is current suite + // continue to the next sibling suite + return done(); + } else { + // errSuite is among the parents of current suite + // stop execution of errSuite and all sub-suites + return done(errSuite); + } + } + + if (self._abort) return done(); + + var curr = suite.suites[i++]; + if (!curr) return done(); + self.runSuite(curr, next); + } + + function done(errSuite) { + self.suite = suite; + self.hook('afterAll', function(){ + self.emit('suite end', suite); + fn(errSuite); + }); + } + + this.hook('beforeAll', function(err){ + if (err) return done(); + self.runTests(suite, next); + }); +}; + +/** + * Handle uncaught exceptions. + * + * @param {Error} err + * @api private + */ + +Runner.prototype.uncaught = function(err){ + if (err) { + debug('uncaught exception %s', err !== function () { + return this; + }.call(err) ? err : ( err.message || err )); + } else { + debug('uncaught undefined exception'); + err = new Error('Caught undefined error, did you throw without specifying what?'); + } + err.uncaught = true; + + var runnable = this.currentRunnable; + if (!runnable) return; + + var wasAlreadyDone = runnable.state; + this.fail(runnable, err); + + runnable.clearTimeout(); + + if (wasAlreadyDone) return; + + // recover from test + if ('test' == runnable.type) { + this.emit('test end', runnable); + this.hookUp('afterEach', this.next); + return; + } + + // bail on hooks + this.emit('end'); +}; + +/** + * Run the root suite and invoke `fn(failures)` + * on completion. + * + * @param {Function} fn + * @return {Runner} for chaining + * @api public + */ + +Runner.prototype.run = function(fn){ + var self = this + , fn = fn || function(){}; + + function uncaught(err){ + self.uncaught(err); + } + + debug('start'); + + // callback + this.on('end', function(){ + debug('end'); + process.removeListener('uncaughtException', uncaught); + fn(self.failures); + }); + + // run suites + this.emit('start'); + this.runSuite(this.suite, function(){ + debug('finished running'); + self.emit('end'); + }); + + // uncaught exception + process.on('uncaughtException', uncaught); + + return this; +}; + +/** + * Cleanly abort execution + * + * @return {Runner} for chaining + * @api public + */ +Runner.prototype.abort = function(){ + debug('aborting'); + this._abort = true; +}; + +/** + * Filter leaks with the given globals flagged as `ok`. + * + * @param {Array} ok + * @param {Array} globals + * @return {Array} + * @api private + */ + +function filterLeaks(ok, globals) { + return filter(globals, function(key){ + // Firefox and Chrome exposes iframes as index inside the window object + if (/^d+/.test(key)) return false; + + // in firefox + // if runner runs in an iframe, this iframe's window.getInterface method not init at first + // it is assigned in some seconds + if (global.navigator && /^getInterface/.test(key)) return false; + + // an iframe could be approached by window[iframeIndex] + // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak + if (global.navigator && /^\d+/.test(key)) return false; + + // Opera and IE expose global variables for HTML element IDs (issue #243) + if (/^mocha-/.test(key)) return false; + + var matched = filter(ok, function(ok){ + if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); + return key == ok; + }); + return matched.length == 0 && (!global.navigator || 'onerror' !== key); + }); +} + +/** + * Array of globals dependent on the environment. + * + * @return {Array} + * @api private + */ + + function extraGlobals() { + if (typeof(process) === 'object' && + typeof(process.version) === 'string') { + + var nodeVersion = process.version.split('.').reduce(function(a, v) { + return a << 8 | v; + }); + + // 'errno' was renamed to process._errno in v0.9.11. + + if (nodeVersion < 0x00090B) { + return ['errno']; + } + } + + return []; + } + +}); // module: runner.js + +require.register("suite.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var EventEmitter = require('browser/events').EventEmitter + , debug = require('browser/debug')('mocha:suite') + , milliseconds = require('./ms') + , utils = require('./utils') + , Hook = require('./hook'); + +/** + * Expose `Suite`. + */ + +exports = module.exports = Suite; + +/** + * Create a new `Suite` with the given `title` + * and parent `Suite`. When a suite with the + * same title is already present, that suite + * is returned to provide nicer reporter + * and more flexible meta-testing. + * + * @param {Suite} parent + * @param {String} title + * @return {Suite} + * @api public + */ + +exports.create = function(parent, title){ + var suite = new Suite(title, parent.ctx); + suite.parent = parent; + if (parent.pending) suite.pending = true; + title = suite.fullTitle(); + parent.addSuite(suite); + return suite; +}; + +/** + * Initialize a new `Suite` with the given + * `title` and `ctx`. + * + * @param {String} title + * @param {Context} ctx + * @api private + */ + +function Suite(title, parentContext) { + this.title = title; + var context = function() {}; + context.prototype = parentContext; + this.ctx = new context(); + this.suites = []; + this.tests = []; + this.pending = false; + this._beforeEach = []; + this._beforeAll = []; + this._afterEach = []; + this._afterAll = []; + this.root = !title; + this._timeout = 2000; + this._enableTimeouts = true; + this._slow = 75; + this._bail = false; +} + +/** + * Inherit from `EventEmitter.prototype`. + */ + +function F(){}; +F.prototype = EventEmitter.prototype; +Suite.prototype = new F; +Suite.prototype.constructor = Suite; + + +/** + * Return a clone of this `Suite`. + * + * @return {Suite} + * @api private + */ + +Suite.prototype.clone = function(){ + var suite = new Suite(this.title); + debug('clone'); + suite.ctx = this.ctx; + suite.timeout(this.timeout()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); + suite.bail(this.bail()); + return suite; +}; + +/** + * Set timeout `ms` or short-hand such as "2s". + * + * @param {Number|String} ms + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.timeout = function(ms){ + if (0 == arguments.length) return this._timeout; + if (ms === 0) this._enableTimeouts = false; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('timeout %d', ms); + this._timeout = parseInt(ms, 10); + return this; +}; + +/** + * Set timeout `enabled`. + * + * @param {Boolean} enabled + * @return {Suite|Boolean} self or enabled + * @api private + */ + +Suite.prototype.enableTimeouts = function(enabled){ + if (arguments.length === 0) return this._enableTimeouts; + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Set slow `ms` or short-hand such as "2s". + * + * @param {Number|String} ms + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.slow = function(ms){ + if (0 === arguments.length) return this._slow; + if ('string' == typeof ms) ms = milliseconds(ms); + debug('slow %d', ms); + this._slow = ms; + return this; +}; + +/** + * Sets whether to bail after first error. + * + * @parma {Boolean} bail + * @return {Suite|Number} for chaining + * @api private + */ + +Suite.prototype.bail = function(bail){ + if (0 == arguments.length) return this._bail; + debug('bail %s', bail); + this._bail = bail; + return this; +}; + +/** + * Run `fn(test[, done])` before running tests. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.beforeAll = function(title, fn){ + if (this.pending) return this; + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"before all" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + this._beforeAll.push(hook); + this.emit('beforeAll', hook); + return this; +}; + +/** + * Run `fn(test[, done])` after running tests. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.afterAll = function(title, fn){ + if (this.pending) return this; + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"after all" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + this._afterAll.push(hook); + this.emit('afterAll', hook); + return this; +}; + +/** + * Run `fn(test[, done])` before each test case. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.beforeEach = function(title, fn){ + if (this.pending) return this; + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"before each" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + this._beforeEach.push(hook); + this.emit('beforeEach', hook); + return this; +}; + +/** + * Run `fn(test[, done])` after each test case. + * + * @param {Function} fn + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.afterEach = function(title, fn){ + if (this.pending) return this; + if ('function' === typeof title) { + fn = title; + title = fn.name; + } + title = '"after each" hook' + (title ? ': ' + title : ''); + + var hook = new Hook(title, fn); + hook.parent = this; + hook.timeout(this.timeout()); + hook.enableTimeouts(this.enableTimeouts()); + hook.slow(this.slow()); + hook.ctx = this.ctx; + this._afterEach.push(hook); + this.emit('afterEach', hook); + return this; +}; + +/** + * Add a test `suite`. + * + * @param {Suite} suite + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.addSuite = function(suite){ + suite.parent = this; + suite.timeout(this.timeout()); + suite.enableTimeouts(this.enableTimeouts()); + suite.slow(this.slow()); + suite.bail(this.bail()); + this.suites.push(suite); + this.emit('suite', suite); + return this; +}; + +/** + * Add a `test` to this suite. + * + * @param {Test} test + * @return {Suite} for chaining + * @api private + */ + +Suite.prototype.addTest = function(test){ + test.parent = this; + test.timeout(this.timeout()); + test.enableTimeouts(this.enableTimeouts()); + test.slow(this.slow()); + test.ctx = this.ctx; + this.tests.push(test); + this.emit('test', test); + return this; +}; + +/** + * Return the full title generated by recursively + * concatenating the parent's full title. + * + * @return {String} + * @api public + */ + +Suite.prototype.fullTitle = function(){ + if (this.parent) { + var full = this.parent.fullTitle(); + if (full) return full + ' ' + this.title; + } + return this.title; +}; + +/** + * Return the total number of tests. + * + * @return {Number} + * @api public + */ + +Suite.prototype.total = function(){ + return utils.reduce(this.suites, function(sum, suite){ + return sum + suite.total(); + }, 0) + this.tests.length; +}; + +/** + * Iterates through each suite recursively to find + * all tests. Applies a function in the format + * `fn(test)`. + * + * @param {Function} fn + * @return {Suite} + * @api private + */ + +Suite.prototype.eachTest = function(fn){ + utils.forEach(this.tests, fn); + utils.forEach(this.suites, function(suite){ + suite.eachTest(fn); + }); + return this; +}; + +}); // module: suite.js + +require.register("test.js", function(module, exports, require){ + +/** + * Module dependencies. + */ + +var Runnable = require('./runnable'); + +/** + * Expose `Test`. + */ + +module.exports = Test; + +/** + * Initialize a new `Test` with the given `title` and callback `fn`. + * + * @param {String} title + * @param {Function} fn + * @api private + */ + +function Test(title, fn) { + Runnable.call(this, title, fn); + this.pending = !fn; + this.type = 'test'; +} + +/** + * Inherit from `Runnable.prototype`. + */ + +function F(){}; +F.prototype = Runnable.prototype; +Test.prototype = new F; +Test.prototype.constructor = Test; + + +}); // module: test.js + +require.register("utils.js", function(module, exports, require){ +/** + * Module dependencies. + */ + +var fs = require('browser/fs') + , path = require('browser/path') + , basename = path.basename + , exists = fs.existsSync || path.existsSync + , glob = require('browser/glob') + , join = path.join + , debug = require('browser/debug')('mocha:watch'); + +/** + * Ignored directories. + */ + +var ignore = ['node_modules', '.git']; + +/** + * Escape special characters in the given string of html. + * + * @param {String} html + * @return {String} + * @api private + */ + +exports.escape = function(html){ + return String(html) + .replace(/&/g, '&') + .replace(/"/g, '"') + .replace(//g, '>'); +}; + +/** + * Array#forEach (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @param {Object} scope + * @api private + */ + +exports.forEach = function(arr, fn, scope){ + for (var i = 0, l = arr.length; i < l; i++) + fn.call(scope, arr[i], i); +}; + +/** + * Array#map (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @param {Object} scope + * @api private + */ + +exports.map = function(arr, fn, scope){ + var result = []; + for (var i = 0, l = arr.length; i < l; i++) + result.push(fn.call(scope, arr[i], i)); + return result; +}; + +/** + * Array#indexOf (<=IE8) + * + * @parma {Array} arr + * @param {Object} obj to find index of + * @param {Number} start + * @api private + */ + +exports.indexOf = function(arr, obj, start){ + for (var i = start || 0, l = arr.length; i < l; i++) { + if (arr[i] === obj) + return i; + } + return -1; +}; + +/** + * Array#reduce (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @param {Object} initial value + * @api private + */ + +exports.reduce = function(arr, fn, val){ + var rval = val; + + for (var i = 0, l = arr.length; i < l; i++) { + rval = fn(rval, arr[i], i, arr); + } + + return rval; +}; + +/** + * Array#filter (<=IE8) + * + * @param {Array} array + * @param {Function} fn + * @api private + */ + +exports.filter = function(arr, fn){ + var ret = []; + + for (var i = 0, l = arr.length; i < l; i++) { + var val = arr[i]; + if (fn(val, i, arr)) ret.push(val); + } + + return ret; +}; + +/** + * Object.keys (<=IE8) + * + * @param {Object} obj + * @return {Array} keys + * @api private + */ + +exports.keys = Object.keys || function(obj) { + var keys = [] + , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 + + for (var key in obj) { + if (has.call(obj, key)) { + keys.push(key); + } + } + + return keys; +}; + +/** + * Watch the given `files` for changes + * and invoke `fn(file)` on modification. + * + * @param {Array} files + * @param {Function} fn + * @api private + */ + +exports.watch = function(files, fn){ + var options = { interval: 100 }; + files.forEach(function(file){ + debug('file %s', file); + fs.watchFile(file, options, function(curr, prev){ + if (prev.mtime < curr.mtime) fn(file); + }); + }); +}; + +/** + * Ignored files. + */ + +function ignored(path){ + return !~ignore.indexOf(path); +} + +/** + * Lookup files in the given `dir`. + * + * @return {Array} + * @api private + */ + +exports.files = function(dir, ext, ret){ + ret = ret || []; + ext = ext || ['js']; + + var re = new RegExp('\\.(' + ext.join('|') + ')$'); + + fs.readdirSync(dir) + .filter(ignored) + .forEach(function(path){ + path = join(dir, path); + if (fs.statSync(path).isDirectory()) { + exports.files(path, ext, ret); + } else if (path.match(re)) { + ret.push(path); + } + }); + + return ret; +}; + +/** + * Compute a slug from the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.slug = function(str){ + return str + .toLowerCase() + .replace(/ +/g, '-') + .replace(/[^-\w]/g, ''); +}; + +/** + * Strip the function definition from `str`, + * and re-indent for pre whitespace. + */ + +exports.clean = function(str) { + str = str + .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '') + .replace(/^function *\(.*\) *{|\(.*\) *=> *{?/, '') + .replace(/\s+\}$/, ''); + + var spaces = str.match(/^\n?( *)/)[1].length + , tabs = str.match(/^\n?(\t*)/)[1].length + , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm'); + + str = str.replace(re, ''); + + return exports.trim(str); +}; + +/** + * Trim the given `str`. + * + * @param {String} str + * @return {String} + * @api private + */ + +exports.trim = function(str){ + return str.replace(/^\s+|\s+$/g, ''); +}; + +/** + * Parse the given `qs`. + * + * @param {String} qs + * @return {Object} + * @api private + */ + +exports.parseQuery = function(qs){ + return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ + var i = pair.indexOf('=') + , key = pair.slice(0, i) + , val = pair.slice(++i); + + obj[key] = decodeURIComponent(val); + return obj; + }, {}); +}; + +/** + * Highlight the given string of `js`. + * + * @param {String} js + * @return {String} + * @api private + */ + +function highlight(js) { + return js + .replace(//g, '>') + .replace(/\/\/(.*)/gm, '//$1') + .replace(/('.*?')/gm, '$1') + .replace(/(\d+\.\d+)/gm, '$1') + .replace(/(\d+)/gm, '$1') + .replace(/\bnew[ \t]+(\w+)/gm, 'new $1') + .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') +} + +/** + * Highlight the contents of tag `name`. + * + * @param {String} name + * @api private + */ + +exports.highlightTags = function(name) { + var code = document.getElementById('mocha').getElementsByTagName(name); + for (var i = 0, len = code.length; i < len; ++i) { + code[i].innerHTML = highlight(code[i].innerHTML); + } +}; + + +/** + * Stringify `obj`. + * + * @param {Object} obj + * @return {String} + * @api private + */ + +exports.stringify = function(obj) { + if (obj instanceof RegExp) return obj.toString(); + return JSON.stringify(exports.canonicalize(obj), null, 2).replace(/,(\n|$)/g, '$1'); +}; + +/** + * Return a new object that has the keys in sorted order. + * @param {Object} obj + * @param {Array} [stack] + * @return {Object} + * @api private + */ + +exports.canonicalize = function(obj, stack) { + stack = stack || []; + + if (exports.indexOf(stack, obj) !== -1) return '[Circular]'; + + var canonicalizedObj; + + if ({}.toString.call(obj) === '[object Array]') { + stack.push(obj); + canonicalizedObj = exports.map(obj, function (item) { + return exports.canonicalize(item, stack); + }); + stack.pop(); + } else if (typeof obj === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + exports.forEach(exports.keys(obj).sort(), function (key) { + canonicalizedObj[key] = exports.canonicalize(obj[key], stack); + }); + stack.pop(); + } else { + canonicalizedObj = obj; + } + + return canonicalizedObj; + }; + +/** + * Lookup file names at the given `path`. + */ +exports.lookupFiles = function lookupFiles(path, extensions, recursive) { + var files = []; + var re = new RegExp('\\.(' + extensions.join('|') + ')$'); + + if (!exists(path)) { + if (exists(path + '.js')) { + path += '.js'; + } else { + files = glob.sync(path); + if (!files.length) throw new Error("cannot resolve path (or pattern) '" + path + "'"); + return files; + } + } + + try { + var stat = fs.statSync(path); + if (stat.isFile()) return path; + } + catch (ignored) { + return; + } + + fs.readdirSync(path).forEach(function(file){ + file = join(path, file); + try { + var stat = fs.statSync(file); + if (stat.isDirectory()) { + if (recursive) { + files = files.concat(lookupFiles(file, extensions, recursive)); + } + return; + } + } + catch (ignored) { + return; + } + if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') return; + files.push(file); + }); + + return files; +}; + +}); // module: utils.js +// The global object is "self" in Web Workers. +var global = (function() { return this; })(); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; + +/** + * Node shims. + * + * These are meant only to allow + * mocha.js to run untouched, not + * to allow running node code in + * the browser. + */ + +var process = {}; +process.exit = function(status){}; +process.stdout = {}; + +var uncaughtExceptionHandlers = []; + +var originalOnerrorHandler = global.onerror; + +/** + * Remove uncaughtException listener. + * Revert to original onerror handler if previously defined. + */ + +process.removeListener = function(e, fn){ + if ('uncaughtException' == e) { + if (originalOnerrorHandler) { + global.onerror = originalOnerrorHandler; + } else { + global.onerror = function() {}; + } + var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn); + if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); } + } +}; + +/** + * Implements uncaughtException listener. + */ + +process.on = function(e, fn){ + if ('uncaughtException' == e) { + global.onerror = function(err, url, line){ + fn(new Error(err + ' (' + url + ':' + line + ')')); + return true; + }; + uncaughtExceptionHandlers.push(fn); + } +}; + +/** + * Expose mocha. + */ + +var Mocha = global.Mocha = require('mocha'), + mocha = global.mocha = new Mocha({ reporter: 'html' }); + +// The BDD UI is registered by default, but no UI will be functional in the +// browser without an explicit call to the overridden `mocha.ui` (see below). +// Ensure that this default UI does not expose its methods to the global scope. +mocha.suite.removeAllListeners('pre-require'); + +var immediateQueue = [] + , immediateTimeout; + +function timeslice() { + var immediateStart = new Date().getTime(); + while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { + immediateQueue.shift()(); + } + if (immediateQueue.length) { + immediateTimeout = setTimeout(timeslice, 0); + } else { + immediateTimeout = null; + } +} + +/** + * High-performance override of Runner.immediately. + */ + +Mocha.Runner.immediately = function(callback) { + immediateQueue.push(callback); + if (!immediateTimeout) { + immediateTimeout = setTimeout(timeslice, 0); + } +}; + +/** + * Function to allow assertion libraries to throw errors directly into mocha. + * This is useful when running tests in a browser because window.onerror will + * only receive the 'message' attribute of the Error. + */ +mocha.throwError = function(err) { + Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) { + fn(err); + }); + throw err; +}; + +/** + * Override ui to ensure that the ui functions are initialized. + * Normally this would happen in Mocha.prototype.loadFiles. + */ + +mocha.ui = function(ui){ + Mocha.prototype.ui.call(this, ui); + this.suite.emit('pre-require', global, null, this); + return this; +}; + +/** + * Setup mocha with the given setting options. + */ + +mocha.setup = function(opts){ + if ('string' == typeof opts) opts = { ui: opts }; + for (var opt in opts) this[opt](opts[opt]); + return this; +}; + +/** + * Run mocha, returning the Runner. + */ + +mocha.run = function(fn){ + var options = mocha.options; + mocha.globals('location'); + + var query = Mocha.utils.parseQuery(global.location.search || ''); + if (query.grep) mocha.grep(query.grep); + if (query.invert) mocha.invert(); + + return Mocha.prototype.run.call(mocha, function(err){ + // The DOM Document is not available in Web Workers. + var document = global.document; + if (document && document.getElementById('mocha') && options.noHighlighting !== true) { + Mocha.utils.highlightTags('code'); + } + if (fn) fn(err); + }); +}; + +/** + * Expose the process shim. + */ + +Mocha.process = process; +})(); \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js new file mode 100644 index 0000000..7ad9f8a --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js @@ -0,0 +1,16 @@ +importScripts('es6-promise.js'); +new ES6Promise.Promise(function(resolve, reject) { + self.onmessage = function (e) { + if (e.data === 'ping') { + resolve('pong'); + } else { + reject(new Error('wrong message')); + } + }; +}).then(function (result) { + self.postMessage(result); +}, function (err){ + setTimeout(function () { + throw err; + }); +}); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js new file mode 100644 index 0000000..5984f70 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js @@ -0,0 +1,18 @@ +import Promise from './es6-promise/promise'; +import polyfill from './es6-promise/polyfill'; + +var ES6Promise = { + 'Promise': Promise, + 'polyfill': polyfill +}; + +/* global define:true module:true window: true */ +if (typeof define === 'function' && define['amd']) { + define(function() { return ES6Promise; }); +} else if (typeof module !== 'undefined' && module['exports']) { + module['exports'] = ES6Promise; +} else if (typeof this !== 'undefined') { + this['ES6Promise'] = ES6Promise; +} + +polyfill(); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js new file mode 100644 index 0000000..daee2c3 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js @@ -0,0 +1,250 @@ +import { + objectOrFunction, + isFunction +} from './utils'; + +import asap from './asap'; + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var GET_THEN_ERROR = new ErrorObject(); + +function selfFullfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function getThen(promise) { + try { + return promise.then; + } catch(error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} + +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch(e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then) { + asap(function(promise) { + var sealed = false; + var error = tryThen(then, thenable, function(value) { + if (sealed) { return; } + sealed = true; + if (thenable !== value) { + resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function(reason) { + if (sealed) { return; } + sealed = true; + + reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function(value) { + resolve(promise, value); + }, function(reason) { + reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable) { + if (maybeThenable.constructor === promise.constructor) { + handleOwnThenable(promise, maybeThenable); + } else { + var then = getThen(maybeThenable); + + if (then === GET_THEN_ERROR) { + reject(promise, GET_THEN_ERROR.error); + } else if (then === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then)) { + handleForeignThenable(promise, maybeThenable, then); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function resolve(promise, value) { + if (promise === value) { + reject(promise, selfFullfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { return; } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function reject(promise, reason) { + if (promise._state !== PENDING) { return; } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var subscribers = parent._subscribers; + var length = subscribers.length; + + parent._onerror = null; + + subscribers[length] = child; + subscribers[length + FULFILLED] = onFulfillment; + subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { return; } + + var child, callback, detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} + +var TRY_CATCH_ERROR = new ErrorObject(); + +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch(e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value, error, succeeded, failed; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + reject(promise, cannotReturnOwn()); + return; + } + + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + resolve(promise, value); + } else if (failed) { + reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value){ + resolve(promise, value); + }, function rejectPromise(reason) { + reject(promise, reason); + }); + } catch(e) { + reject(promise, e); + } +} + +export { + noop, + resolve, + reject, + fulfill, + subscribe, + publish, + publishRejection, + initializePromise, + invokeCallback, + FULFILLED, + REJECTED, + PENDING +}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js new file mode 100644 index 0000000..4f7dcee --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js @@ -0,0 +1,111 @@ +var len = 0; +var toString = {}.toString; +var vertxNext; +export default function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + scheduleFlush(); + } +} + +var browserWindow = (typeof window !== 'undefined') ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && + typeof importScripts !== 'undefined' && + typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + var nextTick = process.nextTick; + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // setImmediate should be used instead instead + var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); + if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { + nextTick = setImmediate; + } + return function() { + nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + return function() { + vertxNext(flush); + }; +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function() { + node.data = (iterations = ++iterations % 2); + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + return function() { + setTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i+=2) { + var callback = queue[i]; + var arg = queue[i+1]; + + callback(arg); + + queue[i] = undefined; + queue[i+1] = undefined; + } + + len = 0; +} + +function attemptVertex() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch(e) { + return useSetTimeout(); + } +} + +var scheduleFlush; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && typeof require === 'function') { + scheduleFlush = attemptVertex(); +} else { + scheduleFlush = useSetTimeout(); +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js new file mode 100644 index 0000000..03fdf8c --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js @@ -0,0 +1,113 @@ +import { + isArray, + isMaybeThenable +} from './utils'; + +import { + noop, + reject, + fulfill, + subscribe, + FULFILLED, + REJECTED, + PENDING +} from './-internal'; + +function Enumerator(Constructor, input) { + var enumerator = this; + + enumerator._instanceConstructor = Constructor; + enumerator.promise = new Constructor(noop); + + if (enumerator._validateInput(input)) { + enumerator._input = input; + enumerator.length = input.length; + enumerator._remaining = input.length; + + enumerator._init(); + + if (enumerator.length === 0) { + fulfill(enumerator.promise, enumerator._result); + } else { + enumerator.length = enumerator.length || 0; + enumerator._enumerate(); + if (enumerator._remaining === 0) { + fulfill(enumerator.promise, enumerator._result); + } + } + } else { + reject(enumerator.promise, enumerator._validationError()); + } +} + +Enumerator.prototype._validateInput = function(input) { + return isArray(input); +}; + +Enumerator.prototype._validationError = function() { + return new Error('Array Methods must be provided an Array'); +}; + +Enumerator.prototype._init = function() { + this._result = new Array(this.length); +}; + +export default Enumerator; + +Enumerator.prototype._enumerate = function() { + var enumerator = this; + + var length = enumerator.length; + var promise = enumerator.promise; + var input = enumerator._input; + + for (var i = 0; promise._state === PENDING && i < length; i++) { + enumerator._eachEntry(input[i], i); + } +}; + +Enumerator.prototype._eachEntry = function(entry, i) { + var enumerator = this; + var c = enumerator._instanceConstructor; + + if (isMaybeThenable(entry)) { + if (entry.constructor === c && entry._state !== PENDING) { + entry._onerror = null; + enumerator._settledAt(entry._state, i, entry._result); + } else { + enumerator._willSettleAt(c.resolve(entry), i); + } + } else { + enumerator._remaining--; + enumerator._result[i] = entry; + } +}; + +Enumerator.prototype._settledAt = function(state, i, value) { + var enumerator = this; + var promise = enumerator.promise; + + if (promise._state === PENDING) { + enumerator._remaining--; + + if (state === REJECTED) { + reject(promise, value); + } else { + enumerator._result[i] = value; + } + } + + if (enumerator._remaining === 0) { + fulfill(promise, enumerator._result); + } +}; + +Enumerator.prototype._willSettleAt = function(promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function(value) { + enumerator._settledAt(FULFILLED, i, value); + }, function(reason) { + enumerator._settledAt(REJECTED, i, reason); + }); +}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js new file mode 100644 index 0000000..6696dfc --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js @@ -0,0 +1,26 @@ +/*global self*/ +import Promise from './promise'; + +export default function polyfill() { + var local; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { + return; + } + + local.Promise = Promise; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js new file mode 100644 index 0000000..78fe2ca --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js @@ -0,0 +1,408 @@ +import { + isFunction +} from './utils'; + +import { + noop, + subscribe, + initializePromise, + invokeCallback, + FULFILLED, + REJECTED +} from './-internal'; + +import asap from './asap'; + +import all from './promise/all'; +import race from './promise/race'; +import Resolve from './promise/resolve'; +import Reject from './promise/reject'; + +var counter = 0; + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +export default Promise; +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise’s eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + var promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this._id = counter++; + this._state = undefined; + this._result = undefined; + this._subscribers = []; + + if (noop !== resolver) { + if (!isFunction(resolver)) { + needsResolver(); + } + + if (!(this instanceof Promise)) { + needsNew(); + } + + initializePromise(this, resolver); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = Resolve; +Promise.reject = Reject; + +Promise.prototype = { + constructor: Promise, + +/** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + var result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + var author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} +*/ + then: function(onFulfillment, onRejection) { + var parent = this; + var state = parent._state; + + if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { + return this; + } + + var child = new this.constructor(noop); + var result = parent._result; + + if (state) { + var callback = arguments[state - 1]; + asap(function(){ + invokeCallback(state, child, callback, result); + }); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; + }, + +/** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} +*/ + 'catch': function(onRejection) { + return this.then(null, onRejection); + } +}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js new file mode 100644 index 0000000..03033f0 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js @@ -0,0 +1,52 @@ +import Enumerator from '../enumerator'; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = resolve(2); + var promise3 = resolve(3); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + var promise1 = resolve(1); + var promise2 = reject(new Error("2")); + var promise3 = reject(new Error("3")); + var promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +export default function all(entries) { + return new Enumerator(this, entries).promise; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js new file mode 100644 index 0000000..0d7ff13 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js @@ -0,0 +1,104 @@ +import { + isArray +} from "../utils"; + +import { + noop, + resolve, + reject, + subscribe, + PENDING +} from '../-internal'; + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + var promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + var promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +export default function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + var promise = new Constructor(noop); + + if (!isArray(entries)) { + reject(promise, new TypeError('You must pass an array to race.')); + return promise; + } + + var length = entries.length; + + function onFulfillment(value) { + resolve(promise, value); + } + + function onRejection(reason) { + reject(promise, reason); + } + + for (var i = 0; promise._state === PENDING && i < length; i++) { + subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); + } + + return promise; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js new file mode 100644 index 0000000..63b86cb --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js @@ -0,0 +1,46 @@ +import { + noop, + reject as _reject +} from '../-internal'; + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +export default function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js new file mode 100644 index 0000000..201a545 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js @@ -0,0 +1,48 @@ +import { + noop, + resolve as _resolve +} from '../-internal'; + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + var promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + var promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +export default function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js new file mode 100644 index 0000000..31ec6f9 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js @@ -0,0 +1,22 @@ +export function objectOrFunction(x) { + return typeof x === 'function' || (typeof x === 'object' && x !== null); +} + +export function isFunction(x) { + return typeof x === 'function'; +} + +export function isMaybeThenable(x) { + return typeof x === 'object' && x !== null; +} + +var _isArray; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +export var isArray = _isArray; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/package.json new file mode 100644 index 0000000..6fc9a80 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/package.json @@ -0,0 +1,88 @@ +{ + "name": "es6-promise", + "namespace": "es6-promise", + "version": "2.1.1", + "description": "A lightweight library that provides tools for organizing asynchronous code", + "main": "dist/es6-promise.js", + "directories": { + "lib": "lib" + }, + "files": [ + "dist", + "lib" + ], + "devDependencies": { + "bower": "^1.3.9", + "brfs": "0.0.8", + "broccoli-es3-safe-recast": "0.0.8", + "broccoli-es6-module-transpiler": "^0.5.0", + "broccoli-jshint": "^0.5.1", + "broccoli-merge-trees": "^0.1.4", + "broccoli-replace": "^0.2.0", + "broccoli-stew": "0.0.6", + "broccoli-uglify-js": "^0.1.3", + "broccoli-watchify": "^0.2.0", + "ember-cli": "^0.2.2", + "ember-publisher": "0.0.7", + "git-repo-version": "0.0.2", + "json3": "^3.3.2", + "minimatch": "^2.0.1", + "mocha": "^1.20.1", + "promises-aplus-tests-phantom": "^2.1.0-revise", + "release-it": "0.0.10" + }, + "scripts": { + "build": "ember build", + "start": "ember s", + "test": "ember test", + "test:server": "ember test --server", + "test:node": "ember build && mocha ./dist/test/browserify", + "lint": "jshint lib", + "prepublish": "ember build --environment production", + "dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive" + }, + "repository": { + "type": "git", + "url": "git://github.com/jakearchibald/ES6-Promises.git" + }, + "bugs": { + "url": "https://github.com/jakearchibald/ES6-Promises/issues" + }, + "browser": { + "vertx": false + }, + "keywords": [ + "promises", + "futures" + ], + "author": { + "name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors", + "url": "Conversion to ES6 API by Jake Archibald" + }, + "license": "MIT", + "spm": { + "main": "dist/es6-promise.js" + }, + "gitHead": "02cf697c50856f0cd3785f425a2cf819af0e521c", + "homepage": "https://github.com/jakearchibald/ES6-Promises", + "_id": "es6-promise@2.1.1", + "_shasum": "03e8f3c7297928e5478d6ab1d0643251507bdedd", + "_from": "es6-promise@2.1.1", + "_npmVersion": "2.5.1", + "_nodeVersion": "0.12.1", + "_npmUser": { + "name": "jaffathecake", + "email": "jaffathecake@gmail.com" + }, + "maintainers": [ + { + "name": "jaffathecake", + "email": "jaffathecake@gmail.com" + } + ], + "dist": { + "shasum": "03e8f3c7297928e5478d6ab1d0643251507bdedd", + "tarball": "http://registry.npmjs.org/es6-promise/-/es6-promise-2.1.1.tgz" + }, + "_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-2.1.1.tgz" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md new file mode 100644 index 0000000..a21da87 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md @@ -0,0 +1,246 @@ +1.2.14 09-28-2015 +----------------- +- NODE-547 only emit error if there are any listeners. +- Fixed APM issue with issuing readConcern. + +1.2.13 09-18-2015 +----------------- +- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. + +1.2.12 09-08-2015 +----------------- +- NODE-541 Added initial support for readConcern. + +1.2.11 08-31-2015 +----------------- +- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. +- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. +- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). + +1.2.10 08-14-2015 +----------------- +- Added missing Mongos.prototype.parserType function. + +1.2.9 08-05-2015 +---------------- +- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. +- NODE-518 connectTimeoutMS is doubled in 2.0.39. + +1.2.8 07-24-2015 +----------------- +- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. + +1.2.7 07-16-2015 +----------------- +- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. + +1.2.6 07-14-2015 +----------------- +- NODE-505 Query fails to find records that have a 'result' property with an array value. + +1.2.5 07-14-2015 +----------------- +- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. + +1.2.4 07-07-2015 +----------------- +- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. + +1.2.3 06-26-2015 +----------------- +- Minor bug fixes. + +1.2.2 06-22-2015 +----------------- +- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). + +1.2.1 06-17-2015 +----------------- +- Ensure serializeFunctions passed down correctly to wire protocol. + +1.2.0 06-17-2015 +----------------- +- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. +- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. +- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. +- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. +- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. + +1.1.33 05-31-2015 +----------------- +- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. + +1.1.32 05-20-2015 +----------------- +- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) + +1.1.31 05-19-2015 +----------------- +- Minor fixes for issues with re-authentication of mongos. + +1.1.30 05-18-2015 +----------------- +- Correctly emit 'all' event when primary + all secondaries have connected. + +1.1.29 05-17-2015 +----------------- +- NODE-464 Only use a single socket against arbiters and hidden servers. +- Ensure we filter out hidden servers from any server queries. + +1.1.28 05-12-2015 +----------------- +- Fixed buffer compare for electionId for < node 12.0.2 + +1.1.27 05-12-2015 +----------------- +- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. + +1.1.26 05-06-2015 +----------------- +- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. +- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. + +1.1.25 04-24-2015 +----------------- +- Handle lack of callback in crud operations when returning error on application closed. + +1.1.24 04-22-2015 +----------------- +- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. + +1.1.23 04-15-2015 +----------------- +- Standardizing mongoErrors and its API (Issue #14) +- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) +- remove mkdirp and rimraf dependencies (Issue #12) +- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) +- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) +- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) + +1.1.22 04-10-2015 +----------------- +- Minor refactorings in cursor code to make extending the cursor simpler. +- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. + +1.1.21 03-26-2015 +----------------- +- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. + +1.1.20 03-24-2015 +----------------- +- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. + +1.1.19 03-21-2015 +----------------- +- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. + +1.1.18 03-17-2015 +----------------- +- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. + +1.1.17 03-16-2015 +----------------- +- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. + +1.1.16 03-06-2015 +----------------- +- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. + +1.1.15 03-04-2015 +----------------- +- Removed check for type in replset pickserver function. + +1.1.14 02-26-2015 +----------------- +- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads + +1.1.13 02-24-2015 +----------------- +- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) + +1.1.12 02-16-2015 +----------------- +- Fixed cursor transforms for buffered document reads from cursor. + +1.1.11 02-02-2015 +----------------- +- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. + +1.1.10 31-01-2015 +----------------- +- Added tranforms.doc option to cursor to allow for pr. document transformations. + +1.1.9 21-01-2015 +---------------- +- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. +- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. +- Don't treat findOne() as a command cursor. +- Refactored out state changes into methods to simplify read the next method. + +1.1.8 09-12-2015 +---------------- +- Stripped out Object.defineProperty for performance reasons +- Applied more performance optimizations. +- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit + +1.1.7 18-12-2014 +---------------- +- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. + +1.1.6 18-12-2014 +---------------- +- Server manager fixed to support 2.2.X servers for travis test matrix. + +1.1.5 17-12-2014 +---------------- +- Fall back to errmsg when creating MongoError for command errors + +1.1.4 17-12-2014 +---------------- +- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. +- Fixed variable leak in scram. +- Fixed server manager to deal better with killing processes. +- Bumped bson to 0.2.16. + +1.1.3 01-12-2014 +---------------- +- Fixed error handling issue with nonce generation in mongocr. +- Fixed issues with restarting servers when using ssl. +- Using strict for all classes. +- Cleaned up any escaping global variables. + +1.1.2 20-11-2014 +---------------- +- Correctly encoding UTF8 collection names on wire protocol messages. +- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. + +1.1.1 14-11-2014 +---------------- +- Refactored code to use prototype instead of privileged methods. +- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. +- Several deopt optimizations for v8 to improve performance and reduce GC pauses. + +1.0.5 29-10-2014 +---------------- +- Fixed issue with wrong namespace being created for command cursors. + +1.0.4 24-10-2014 +---------------- +- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. + +1.0.3 21-10-2014 +---------------- +- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. + +1.0.2 07-10-2014 +---------------- +- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. +- fixed issue with replset_state logging. + +1.0.1 07-10-2014 +---------------- +- Dependency issue solved + +1.0.0 07-10-2014 +---------------- +- Initial release of mongodb-core diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE new file mode 100644 index 0000000..ad410e1 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + 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. \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile new file mode 100644 index 0000000..36e1202 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile @@ -0,0 +1,11 @@ +NODE = node +NPM = npm +JSDOC = jsdoc +name = all + +generate_docs: + # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md + hugo -s docs/reference -d ../../public + $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api + cp -R ./public/api/scripts ./public/. + cp -R ./public/api/styles ./public/. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/README.md new file mode 100644 index 0000000..1c9e4c8 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/README.md @@ -0,0 +1,225 @@ +# Description + +The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. + +## MongoDB Node.JS Core Driver + +| what | where | +|---------------|------------------------------------------------| +| documentation | http://mongodb.github.io/node-mongodb-native/ | +| apidoc | http://mongodb.github.io/node-mongodb-native/ | +| source | https://github.com/christkv/mongodb-core | +| mongodb | http://www.mongodb.org/ | + +### Blogs of Engineers involved in the driver +- Christian Kvalheim [@christkv](https://twitter.com/christkv) + +### Bugs / Feature Requests + +Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a +case in our issue management tool, JIRA: + +- Create an account and login . +- Navigate to the NODE project . +- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. + +Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the +Core Server (i.e. SERVER) project are **public**. + +### Questions and Bug Reports + + * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native + * jira: http://jira.mongodb.org/ + +### Change Log + +http://jira.mongodb.org/browse/NODE + +# QuickStart + +The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. + +## Create the package.json file + +Let's create a directory where our application will live. In our case we will put this under our projects directory. + +``` +mkdir myproject +cd myproject +``` + +Create a **package.json** using your favorite text editor and fill it in. + +```json +{ + "name": "myproject", + "version": "1.0.0", + "description": "My first project", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/christkv/myfirstproject.git" + }, + "dependencies": { + "mongodb-core": "~1.0" + }, + "author": "Christian Kvalheim", + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/myfirstproject/issues" + }, + "homepage": "https://github.com/christkv/myfirstproject" +} +``` + +Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. + +``` +npm install +``` + +You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. + +Booting up a MongoDB Server +--------------------------- +Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). + +``` +mongod --dbpath=/data --port 27017 +``` + +You should see the **mongod** process start up and print some status information. + +## Connecting to MongoDB + +Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. + +First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + test.done(); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. + +```js +var Server = require('mongodb-core').Server + , assert = require('assert'); + +// Set up server connection +var server = new Server({ + host: 'localhost' + , port: 27017 + , reconnect: true + , reconnectInterval: 50 +}); + +// Add event listeners +server.on('connect', function(_server) { + console.log('connected'); + + // Execute the ismaster command + _server.command('system.$cmd', {ismaster: true}, function(err, result) { + + // Perform a document insert + _server.insert('myproject.inserts1', [{a:1}, {a:2}], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(2, results.result.n); + + // Perform a document update + _server.update('myproject.inserts1', [{ + q: {a: 1}, u: {'$set': {b:1}} + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Remove a document + _server.remove('myproject.inserts1', [{ + q: {a: 1}, limit: 1 + }], { + writeConcern: {w:1}, ordered:true + }, function(err, results) { + assert.equal(null, err); + assert.equal(1, results.result.n); + + // Get a document + var cursor = _server.cursor('integration_tests.inserts_example4', { + find: 'integration_tests.example4' + , query: {a:1} + }); + + // Get the first document + cursor.next(function(err, doc) { + assert.equal(null, err); + assert.equal(2, doc.a); + + // Execute the ismaster command + _server.command("system.$cmd" + , {ismaster: true}, function(err, result) { + assert.equal(null, err) + _server.destroy(); + }); + }); + }); + }); + + test.done(); + }); +}); + +server.on('close', function() { + console.log('closed'); +}); + +server.on('reconnect', function() { + console.log('reconnect'); +}); + +// Start connection +server.connect(); +``` + +The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. + +* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. +* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. +* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. +* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. +* `command`, Executes a command against MongoDB and returns the result. +* `auth`, Authenticates the current topology using a supported authentication scheme. + +The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. + +## Next steps + +The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md new file mode 100644 index 0000000..fe03ea0 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md @@ -0,0 +1,18 @@ +Testing setup +============= + +Single Server +------------- +mongod --dbpath=./db + +Replicaset +---------- +mongo --nodb +var x = new ReplSetTest({"useHostName":"false", "nodes" : {node0 : {}, node1 : {}, node2 : {}}}) +x.startSet(); +var config = x.getReplSetConfig() +x.initiate(config); + +Mongos +------ +var s = new ShardingTest( "auth1", 1 , 0 , 2 , {rs: true, noChunkSize : true}); \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json new file mode 100644 index 0000000..c5eca92 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json @@ -0,0 +1,60 @@ +{ + "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], + "source": { + "include": [ + "test/tests/functional/operation_example_tests.js", + "lib/topologies/mongos.js", + "lib/topologies/command_result.js", + "lib/topologies/read_preference.js", + "lib/topologies/replset.js", + "lib/topologies/server.js", + "lib/topologies/session.js", + "lib/topologies/replset_state.js", + "lib/connection/logger.js", + "lib/connection/connection.js", + "lib/cursor.js", + "lib/error.js", + "node_modules/bson/lib/bson/binary.js", + "node_modules/bson/lib/bson/code.js", + "node_modules/bson/lib/bson/db_ref.js", + "node_modules/bson/lib/bson/double.js", + "node_modules/bson/lib/bson/long.js", + "node_modules/bson/lib/bson/objectid.js", + "node_modules/bson/lib/bson/symbol.js", + "node_modules/bson/lib/bson/timestamp.js", + "node_modules/bson/lib/bson/max_key.js", + "node_modules/bson/lib/bson/min_key.js" + ] + }, + "templates": { + "cleverLinks": true, + "monospaceLinks": true, + "default": { + "outputSourceFiles" : true + }, + "applicationName": "Node.js MongoDB Driver API", + "disqus": true, + "googleAnalytics": "UA-29229787-1", + "openGraph": { + "title": "", + "type": "website", + "image": "", + "site_name": "", + "url": "" + }, + "meta": { + "title": "", + "description": "", + "keyword": "" + }, + "linenums": true + }, + "markdown": { + "parser": "gfm", + "hardwrap": true, + "tags": ["examples"] + }, + "examples": { + "indent": 4 + } +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/index.js new file mode 100644 index 0000000..8f10860 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/index.js @@ -0,0 +1,18 @@ +module.exports = { + MongoError: require('./lib/error') + , Server: require('./lib/topologies/server') + , ReplSet: require('./lib/topologies/replset') + , Mongos: require('./lib/topologies/mongos') + , Logger: require('./lib/connection/logger') + , Cursor: require('./lib/cursor') + , ReadPreference: require('./lib/topologies/read_preference') + , BSON: require('bson') + // Raw operations + , Query: require('./lib/connection/commands').Query + // Auth mechanisms + , MongoCR: require('./lib/auth/mongocr') + , X509: require('./lib/auth/x509') + , Plain: require('./lib/auth/plain') + , GSSAPI: require('./lib/auth/gssapi') + , ScramSHA1: require('./lib/auth/scram') +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js new file mode 100644 index 0000000..c442b9b --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js @@ -0,0 +1,244 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require('kerberos').Kerberos + // Authentication process for Mongo + MongoAuthProcess = require('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new GSSAPI authentication mechanism + * @class + * @return {GSSAPI} A cursor instance + */ +var GSSAPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.auth = function(server, pool, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + GSSAPIInitialize(db, username, password, db, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// +// Initialize step +var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, server, connection, callback) { + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); + + // Perform initialization + mongo_auth_process.init(username, password, function(err, context) { + if(err) return callback(err, false); + + // Perform the first step + mongo_auth_process.transition('', function(err, payload) { + if(err) return callback(err, false); + + // Call the next db step + MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback) { + // Build the sasl start command + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: payload + , autoAuthorize: 1 + }; + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Execute mongodb transition + mongo_auth_process.transition(r.result.payload, function(err, payload) { + if(err) return callback(err, false); + + // MongoDB API Second Step + MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +// +// Perform first step against mongodb +var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + // Call next transition for kerberos + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err, false); + + // Call the last and third step + MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); + }); + }); +} + +var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { + // Build final command + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + mongo_auth_process.transition(null, function(err, payload) { + if(err) return callback(err, null); + callback(null, r); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +GSSAPI.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = GSSAPI; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js new file mode 100644 index 0000000..d0e9f59 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js @@ -0,0 +1,160 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new MongoCR authentication mechanism + * @class + * @return {MongoCR} A cursor instance + */ +var MongoCR = function() { + this.authStore = []; +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var executeMongoCR = function(connection) { + // Let's start the process + server.command(f("%s.$cmd", db) + , { getnonce: 1 } + , { connection: connection }, function(err, r) { + var nonce = null; + var key = null; + + // Adjust the number of connections left + // Get nonce + if(err == null) { + nonce = r.result.nonce; + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + var hash_password = md5.digest('hex'); + // Final key + md5 = crypto.createHash('md5'); + md5.update(nonce + username + hash_password); + key = md5.digest('hex'); + } + + // Execute command + server.command(f("%s.$cmd", db) + , { authenticate: 1, user: username, nonce: nonce, key:key} + , { connection: connection }, function(err, r) { + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + }); + } + + // Get the connection + executeMongoCR(connections.shift()); + } +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +MongoCR.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = MongoCR; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js new file mode 100644 index 0000000..31ce872 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js @@ -0,0 +1,150 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new Plain authentication mechanism + * @class + * @return {Plain} A cursor instance + */ +var Plain = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Create payload + var payload = new Binary(f("\x00%s\x00%s", username, password)); + + // Let's start the sasl process + var command = { + saslStart: 1 + , mechanism: 'PLAIN' + , payload: payload + , autoAuthorize: 1 + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +Plain.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = Plain; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js new file mode 100644 index 0000000..fe96637 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js @@ -0,0 +1,317 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , Binary = require('bson').Binary + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new ScramSHA1 authentication mechanism + * @class + * @return {ScramSHA1} A cursor instance + */ +var ScramSHA1 = function() { + this.authStore = []; +} + +var parsePayload = function(payload) { + var dict = {}; + var parts = payload.split(','); + + for(var i = 0; i < parts.length; i++) { + var valueParts = parts[i].split('='); + dict[valueParts[0]] = valueParts[1]; + } + + return dict; +} + +var passwordDigest = function(username, password) { + if(typeof username != 'string') throw new MongoError("username must be a string"); + if(typeof password != 'string') throw new MongoError("password must be a string"); + if(password.length == 0) throw new MongoError("password cannot be empty"); + // Use node md5 generator + var md5 = crypto.createHash('md5'); + // Generate keys used for authentication + md5.update(username + ":mongo:" + password); + return md5.digest('hex'); +} + +// XOR two buffers +var xor = function(a, b) { + if (!Buffer.isBuffer(a)) a = new Buffer(a) + if (!Buffer.isBuffer(b)) b = new Buffer(b) + var res = [] + if (a.length > b.length) { + for (var i = 0; i < b.length; i++) { + res.push(a[i] ^ b[i]) + } + } else { + for (var i = 0; i < a.length; i++) { + res.push(a[i] ^ b[i]) + } + } + return new Buffer(res); +} + +// Create a final digest +var hi = function(data, salt, iterations) { + // Create digest + var digest = function(msg) { + var hmac = crypto.createHmac('sha1', data); + hmac.update(msg); + return new Buffer(hmac.digest('base64'), 'base64'); + } + + // Create variables + salt = Buffer.concat([salt, new Buffer('\x00\x00\x00\x01')]) + var ui = digest(salt); + var u1 = ui; + + for(var i = 0; i < iterations - 1; i++) { + u1 = digest(u1); + ui = xor(ui, u1); + } + + return ui; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var executeScram = function(connection) { + // Clean up the user + username = username.replace('=', "=3D").replace(',', '=2C'); + + // Create a random nonce + var nonce = crypto.randomBytes(24).toString('base64'); + // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' + var firstBare = f("n=%s,r=%s", username, nonce); + + // Build command structure + var cmd = { + saslStart: 1 + , mechanism: 'SCRAM-SHA-1' + , payload: new Binary(f("n,,%s", firstBare)) + , autoAuthorize: 1 + } + + // Handle the error + var handleError = function(err, r) { + if(err) { + numberOfValidConnections = numberOfValidConnections - 1; + errorObject = err; return false; + } else if(r.result['$err']) { + errorObject = r.result; return false; + } else if(r.result['errmsg']) { + errorObject = r.result; return false; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + return true + } + + // Finish up + var finish = function(_count, _numberOfValidConnections) { + if(_count == 0 && _numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(_count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + } + + var handleEnd = function(_err, _r) { + // Handle any error + handleError(_err, _r) + // Adjust the number of connections + count = count - 1; + // Execute the finish + finish(count, numberOfValidConnections); + } + + // Execute start sasl command + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + + // Do we have an error, handle it + if(handleError(err, r) == false) { + count = count - 1; + + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + return callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); + return callback(errorObject, false); + } + + return; + } + + // Get the dictionary + var dict = parsePayload(r.result.payload.value()) + + // Unpack dictionary + var iterations = parseInt(dict.i, 10); + var salt = dict.s; + var rnonce = dict.r; + + // Set up start of proof + var withoutProof = f("c=biws,r=%s", rnonce); + var passwordDig = passwordDigest(username, password); + var saltedPassword = hi(passwordDig + , new Buffer(salt, 'base64') + , iterations); + + // Create the client key + var hmac = crypto.createHmac('sha1', saltedPassword); + hmac.update(new Buffer("Client Key")); + var clientKey = new Buffer(hmac.digest('base64'), 'base64'); + + // Create the stored key + var hash = crypto.createHash('sha1'); + hash.update(clientKey); + var storedKey = new Buffer(hash.digest('base64'), 'base64'); + + // Create the authentication message + var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(','); + + // Create client signature + var hmac = crypto.createHmac('sha1', storedKey); + hmac.update(new Buffer(authMsg)); + var clientSig = new Buffer(hmac.digest('base64'), 'base64'); + + // Create client proof + var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64')); + + // Create client final + var clientFinal = [withoutProof, clientProof].join(','); + + // Generate server key + var hmac = crypto.createHmac('sha1', saltedPassword); + hmac.update(new Buffer('Server Key')) + var serverKey = new Buffer(hmac.digest('base64'), 'base64'); + + // Generate server signature + var hmac = crypto.createHmac('sha1', serverKey); + hmac.update(new Buffer(authMsg)) + var serverSig = new Buffer(hmac.digest('base64'), 'base64'); + + // + // Create continue message + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Binary(new Buffer(clientFinal)) + } + + // + // Execute sasl continue + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + if(r && r.result.done == false) { + var cmd = { + saslContinue: 1 + , conversationId: r.result.conversationId + , payload: new Buffer(0) + } + + server.command(f("%s.$cmd", db) + , cmd, { connection: connection }, function(err, r) { + handleEnd(err, r); + }); + } else { + handleEnd(err, r); + } + }); + }); + } + + // Get the connection + executeScram(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +ScramSHA1.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + + +module.exports = ScramSHA1; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js new file mode 100644 index 0000000..177ede5 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js @@ -0,0 +1,234 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password, options) { + this.db = db; + this.username = username; + this.password = password; + this.options = options; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +// Kerberos class +var Kerberos = null; +var MongoAuthProcess = null; + +// Try to grab the Kerberos class +try { + Kerberos = require('kerberos').Kerberos + // Authentication process for Mongo + MongoAuthProcess = require('kerberos').processes.MongoAuthProcess +} catch(err) {} + +/** + * Creates a new SSPI authentication mechanism + * @class + * @return {SSPI} A cursor instance + */ +var SSPI = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.auth = function(server, pool, db, username, password, options, callback) { + var self = this; + // We don't have the Kerberos library + if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); + var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Start Auth process for a connection + SSIPAuthenticate(username, password, gssapiServiceName, server, connection, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r && typeof r == 'object' && r.result['$err']) { + errorObject = r.result; + } else if(r && typeof r == 'object' && r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password, options)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +var SSIPAuthenticate = function(username, password, gssapiServiceName, server, connection, callback) { + // Build Authentication command to send to MongoDB + var command = { + saslStart: 1 + , mechanism: 'GSSAPI' + , payload: '' + , autoAuthorize: 1 + }; + + // Create authenticator + var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); + + // Execute first sasl step + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.init(username, password, function(err) { + if(err) return callback(err); + + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err); + + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.transition(doc.payload, function(err, payload) { + if(err) return callback(err); + + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + mongo_auth_process.transition(doc.payload, function(err, payload) { + // Perform the next step against mongod + var command = { + saslContinue: 1 + , conversationId: doc.conversationId + , payload: payload + }; + + // Execute the command + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + if(err) return callback(err, false); + var doc = r.result; + + if(doc.done) return callback(null, true); + callback(new Error("Authentication failed"), false); + }); + }); + }); + }); + }); + }); + }); + }); +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +SSPI.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = SSPI; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js new file mode 100644 index 0000000..641990e --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js @@ -0,0 +1,145 @@ +"use strict"; + +var f = require('util').format + , crypto = require('crypto') + , MongoError = require('../error'); + +var AuthSession = function(db, username, password) { + this.db = db; + this.username = username; + this.password = password; +} + +AuthSession.prototype.equal = function(session) { + return session.db == this.db + && session.username == this.username + && session.password == this.password; +} + +/** + * Creates a new X509 authentication mechanism + * @class + * @return {X509} A cursor instance + */ +var X509 = function() { + this.authStore = []; +} + +/** + * Authenticate + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {string} db Name of the database + * @param {string} username Username + * @param {string} password Password + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.auth = function(server, pool, db, username, password, callback) { + var self = this; + // Get all the connections + var connections = pool.getAll(); + // Total connections + var count = connections.length; + if(count == 0) return callback(null, null); + + // Valid connections + var numberOfValidConnections = 0; + var credentialsValid = false; + var errorObject = null; + + // For each connection we need to authenticate + while(connections.length > 0) { + // Execute MongoCR + var execute = function(connection) { + // Let's start the sasl process + var command = { + authenticate: 1 + , mechanism: 'MONGODB-X509' + , user: username + }; + + // Let's start the process + server.command("$external.$cmd" + , command + , { connection: connection }, function(err, r) { + // Adjust count + count = count - 1; + + // If we have an error + if(err) { + errorObject = err; + } else if(r.result['$err']) { + errorObject = r.result; + } else if(r.result['errmsg']) { + errorObject = r.result; + } else { + credentialsValid = true; + numberOfValidConnections = numberOfValidConnections + 1; + } + + // We have authenticated all connections + if(count == 0 && numberOfValidConnections > 0) { + // Store the auth details + addAuthSession(self.authStore, new AuthSession(db, username, password)); + // Return correct authentication + callback(null, true); + } else if(count == 0) { + if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); + callback(errorObject, false); + } + }); + } + + // Get the connection + execute(connections.shift()); + } +} + +// Add to store only if it does not exist +var addAuthSession = function(authStore, session) { + var found = false; + + for(var i = 0; i < authStore.length; i++) { + if(authStore[i].equal(session)) { + found = true; + break; + } + } + + if(!found) authStore.push(session); +} + +/** + * Re authenticate pool + * @method + * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on + * @param {Pool} pool Connection pool for this topology + * @param {authResultCallback} callback The callback to return the result from the authentication + * @return {object} + */ +X509.prototype.reauthenticate = function(server, pool, callback) { + var count = this.authStore.length; + if(count == 0) return callback(null, null); + // Iterate over all the auth details stored + for(var i = 0; i < this.authStore.length; i++) { + this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { + count = count - 1; + // Done re-authenticating + if(count == 0) { + callback(null, null); + } + }); + } +} + +/** + * This is a result from a authentication strategy + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {boolean} result The result of the authentication process + */ + +module.exports = X509; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js new file mode 100644 index 0000000..05023b4 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js @@ -0,0 +1,519 @@ +"use strict"; + +var f = require('util').format + , Long = require('bson').Long + , setProperty = require('./utils').setProperty + , getProperty = require('./utils').getProperty + , getSingleProperty = require('./utils').getSingleProperty; + +// Incrementing request id +var _requestId = 0; + +// Wire command operation ids +var OP_QUERY = 2004; +var OP_GETMORE = 2005; +var OP_KILL_CURSORS = 2007; + +// Query flags +var OPTS_NONE = 0; +var OPTS_TAILABLE_CURSOR = 2; +var OPTS_SLAVE = 4; +var OPTS_OPLOG_REPLAY = 8; +var OPTS_NO_CURSOR_TIMEOUT = 16; +var OPTS_AWAIT_DATA = 32; +var OPTS_EXHAUST = 64; +var OPTS_PARTIAL = 128; + +// Response flags +var CURSOR_NOT_FOUND = 0; +var QUERY_FAILURE = 2; +var SHARD_CONFIG_STALE = 4; +var AWAIT_CAPABLE = 8; + +/************************************************************** + * QUERY + **************************************************************/ +var Query = function(bson, ns, query, options) { + var self = this; + // Basic options needed to be passed in + if(ns == null) throw new Error("ns must be specified for query"); + if(query == null) throw new Error("query must be specified for query"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new Error("namespace cannot contain a null character"); + } + + // Basic options + this.bson = bson; + this.ns = ns; + this.query = query; + + // Ensure empty options + this.options = options || {}; + + // Additional options + this.numberToSkip = options.numberToSkip || 0; + this.numberToReturn = options.numberToReturn || 0; + this.returnFieldSelector = options.returnFieldSelector || null; + this.requestId = _requestId++; + + // Serialization option + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.batchSize = self.numberToReturn; + + // Flags + this.tailable = false; + this.slaveOk = false; + this.oplogReply = false; + this.noCursorTimeout = false; + this.awaitData = false; + this.exhaust = false; + this.partial = false; +} + +// +// Assign a new request Id +Query.prototype.incRequestId = function() { + this.requestId = _requestId++; +} + +// +// Assign a new request Id +Query.nextRequestId = function() { + return _requestId + 1; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +Query.prototype.toBin = function() { + var self = this; + var buffers = []; + var projection = null; + + // Set up the flags + var flags = 0; + if(this.tailable) flags |= OPTS_TAILABLE_CURSOR; + if(this.slaveOk) flags |= OPTS_SLAVE; + if(this.oplogReply) flags |= OPTS_OPLOG_REPLAY; + if(this.noCursorTimeout) flags |= OPTS_NO_CURSOR_TIMEOUT; + if(this.awaitData) flags |= OPTS_AWAIT_DATA; + if(this.exhaust) flags |= OPTS_EXHAUST; + if(this.partial) flags |= OPTS_PARTIAL; + + // If batchSize is different to self.numberToReturn + if(self.batchSize != self.numberToReturn) self.numberToReturn = self.batchSize; + + // Allocate write protocol header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(self.ns) + 1 // namespace + + 4 // numberToSkip + + 4 // numberToReturn + ); + + // Add header to buffers + buffers.push(header); + + // Serialize the query + var query = self.bson.serialize(this.query + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + + // Add query document + buffers.push(query); + + if(self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { + // Serialize the projection document + projection = self.bson.serialize(this.returnFieldSelector, this.checkKeys, true, this.serializeFunctions, this.ignoreUndefined); + // Add projection document + buffers.push(projection); + } + + // Total message size + var totalLength = header.length + query.length + (projection ? projection.length : 0); + + // Set up the index + var index = 4; + + // Write total document length + header[3] = (totalLength >> 24) & 0xff; + header[2] = (totalLength >> 16) & 0xff; + header[1] = (totalLength >> 8) & 0xff; + header[0] = (totalLength) & 0xff; + + // Write header information requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // Write header information responseTo + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write header information OP_QUERY + header[index + 3] = (OP_QUERY >> 24) & 0xff; + header[index + 2] = (OP_QUERY >> 16) & 0xff; + header[index + 1] = (OP_QUERY >> 8) & 0xff; + header[index] = (OP_QUERY) & 0xff; + index = index + 4; + + // Write header information flags + header[index + 3] = (flags >> 24) & 0xff; + header[index + 2] = (flags >> 16) & 0xff; + header[index + 1] = (flags >> 8) & 0xff; + header[index] = (flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write header information flags numberToSkip + header[index + 3] = (this.numberToSkip >> 24) & 0xff; + header[index + 2] = (this.numberToSkip >> 16) & 0xff; + header[index + 1] = (this.numberToSkip >> 8) & 0xff; + header[index] = (this.numberToSkip) & 0xff; + index = index + 4; + + // Write header information flags numberToReturn + header[index + 3] = (this.numberToReturn >> 24) & 0xff; + header[index + 2] = (this.numberToReturn >> 16) & 0xff; + header[index + 1] = (this.numberToReturn >> 8) & 0xff; + header[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +Query.getRequestId = function() { + return ++_requestId; +} + +/************************************************************** + * GETMORE + **************************************************************/ +var GetMore = function(bson, ns, cursorId, opts) { + opts = opts || {}; + this.numberToReturn = opts.numberToReturn || 0; + this.requestId = _requestId++; + this.bson = bson; + this.ns = ns; + this.cursorId = cursorId; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +GetMore.prototype.toBin = function() { + var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); + // Create command buffer + var index = 0; + // Allocate buffer + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_GETMORE); + _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; + _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; + _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; + _buffer[index] = (OP_GETMORE) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + _buffer.write(this.ns, index, 'utf8') + 1; + _buffer[index - 1] = 0; + + // Write batch size + // index = write32bit(index, _buffer, numberToReturn); + _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; + _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; + _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; + _buffer[index] = (this.numberToReturn) & 0xff; + index = index + 4; + + // Write cursor id + // index = write32bit(index, _buffer, cursorId.getLowBits()); + _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorId.getHighBits()); + _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorId.getHighBits()) & 0xff; + index = index + 4; + + // Return buffer + return _buffer; +} + +/************************************************************** + * KILLCURSOR + **************************************************************/ +var KillCursor = function(bson, cursorIds) { + this.requestId = _requestId++; + this.cursorIds = cursorIds; +} + +// +// Uses a single allocated buffer for the process, avoiding multiple memory allocations +KillCursor.prototype.toBin = function() { + var length = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); + + // Create command buffer + var index = 0; + var _buffer = new Buffer(length); + + // Write header information + // index = write32bit(index, _buffer, length); + _buffer[index + 3] = (length >> 24) & 0xff; + _buffer[index + 2] = (length >> 16) & 0xff; + _buffer[index + 1] = (length >> 8) & 0xff; + _buffer[index] = (length) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, requestId); + _buffer[index + 3] = (this.requestId >> 24) & 0xff; + _buffer[index + 2] = (this.requestId >> 16) & 0xff; + _buffer[index + 1] = (this.requestId >> 8) & 0xff; + _buffer[index] = (this.requestId) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, OP_KILL_CURSORS); + _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; + _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; + _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; + _buffer[index] = (OP_KILL_CURSORS) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, 0); + _buffer[index + 3] = (0 >> 24) & 0xff; + _buffer[index + 2] = (0 >> 16) & 0xff; + _buffer[index + 1] = (0 >> 8) & 0xff; + _buffer[index] = (0) & 0xff; + index = index + 4; + + // Write batch size + // index = write32bit(index, _buffer, this.cursorIds.length); + _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; + _buffer[index] = (this.cursorIds.length) & 0xff; + index = index + 4; + + // Write all the cursor ids into the array + for(var i = 0; i < this.cursorIds.length; i++) { + // Write cursor id + // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); + _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getLowBits()) & 0xff; + index = index + 4; + + // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); + _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; + _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; + _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; + _buffer[index] = (this.cursorIds[i].getHighBits()) & 0xff; + index = index + 4; + } + + // Return buffer + return _buffer; +} + +var Response = function(bson, data, opts) { + opts = opts || {promoteLongs: true}; + this.parsed = false; + + // + // Parse Header + // + this.index = 0; + this.raw = data; + this.data = data; + this.bson = bson; + this.opts = opts; + + // Read the message length + this.length = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the request id for this reply + this.requestId = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Fetch the id of the request that triggered the response + this.responseTo = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Skip op-code field + this.index = this.index + 4; + + // Unpack flags + this.responseFlags = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the cursor + var lowBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + var highBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + // Create long object + this.cursorId = new Long(lowBits, highBits); + + // Unpack the starting from + this.startingFrom = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Unpack the number of objects returned + this.numberReturned = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; + this.index = this.index + 4; + + // Preallocate document array + this.documents = new Array(this.numberReturned); + + // Flag values + this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) != 0; + this.queryFailure = (this.responseFlags & QUERY_FAILURE) != 0; + this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) != 0; + this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) != 0; + this.promoteLongs = typeof opts.promoteLongs == 'boolean' ? opts.promoteLongs : true; +} + +Response.prototype.isParsed = function() { + return this.parsed; +} + +// Validation buffers +var firstBatch = new Buffer('firstBatch', 'utf8'); +var nextBatch = new Buffer('nextBatch', 'utf8'); +var cursorId = new Buffer('id', 'utf8').toString('hex'); + +var documentBuffers = { + firstBatch: firstBatch.toString('hex'), + nextBatch: nextBatch.toString('hex') +}; + +Response.prototype.parse = function(options) { + // Don't parse again if not needed + if(this.parsed) return; + options = options || {}; + + // Allow the return of raw documents instead of parsing + var raw = options.raw || false; + var documentsReturnedIn = options.documentsReturnedIn || null; + + // + // Single document and documentsReturnedIn set + // + if(this.numberReturned == 1 && documentsReturnedIn != null && raw) { + // Calculate the bson size + var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Slice out the buffer containing the command result document + var document = this.data.slice(this.index, this.index + bsonSize); + // Set up field we wish to keep as raw + var fieldsAsRaw = {} + fieldsAsRaw[documentsReturnedIn] = true; + // Set up the options + var _options = {promoteLongs: this.opts.promoteLongs, fieldsAsRaw: fieldsAsRaw}; + + // Deserialize but keep the array of documents in non-parsed form + var doc = this.bson.deserialize(document, _options); + + // Get the documents + this.documents = doc.cursor[documentsReturnedIn]; + this.numberReturned = this.documents.length; + // Ensure we have a Long valie cursor id + this.cursorId = typeof doc.cursor.id == 'number' + ? Long.fromNumber(doc.cursor.id) + : doc.cursor.id; + + // Adjust the index + this.index = this.index + bsonSize; + + // Set as parsed + this.parsed = true + return; + } + + // + // Parse Body + // + for(var i = 0; i < this.numberReturned; i++) { + var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; + // Parse options + var _options = {promoteLongs: this.opts.promoteLongs}; + + // If we have raw results specified slice the return document + if(raw) { + this.documents[i] = this.data.slice(this.index, this.index + bsonSize); + } else { + this.documents[i] = this.bson.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); + } + + // Adjust the index + this.index = this.index + bsonSize; + } + + // Set parsed + this.parsed = true; +} + +module.exports = { + Query: Query + , GetMore: GetMore + , Response: Response + , KillCursor: KillCursor +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js new file mode 100644 index 0000000..217e58a --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js @@ -0,0 +1,462 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , net = require('net') + , tls = require('tls') + , f = require('util').format + , getSingleProperty = require('./utils').getSingleProperty + , debugOptions = require('./utils').debugOptions + , Response = require('./commands').Response + , MongoError = require('../error') + , Logger = require('./logger'); + +var _id = 0; +var debugFields = ['host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay' + , 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert' + , 'rejectUnauthorized', 'promoteLongs']; + +/** + * Creates a new Connection instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Connection#connect + * @fires Connection#close + * @fires Connection#error + * @fires Connection#timeout + * @fires Connection#parseError + * @return {Connection} A cursor instance + */ +var Connection = function(options) { + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + // Identification information + this.id = _id++; + // Logger instance + this.logger = Logger('Connection', options); + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Get bson parser + this.bson = options.bson; + // Grouping tag used for debugging purposes + this.tag = options.tag; + // Message handler + this.messageHandler = options.messageHandler; + + // Max BSON message size + this.maxBsonMessageSize = options.maxBsonMessageSize || (1024 * 1024 * 16 * 4); + // Debug information + if(this.logger.isDebug()) this.logger.debug(f('creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)))); + + // Default options + this.port = options.port || 27017; + this.host = options.host || 'localhost'; + this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; + this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0; + this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; + this.connectionTimeout = options.connectionTimeout || 0; + this.socketTimeout = options.socketTimeout || 0; + + // If connection was destroyed + this.destroyed = false; + + // Check if we have a domain socket + this.domainSocket = this.host.indexOf('\/') != -1; + + // Serialize commands using function + this.singleBufferSerializtion = typeof options.singleBufferSerializtion == 'boolean' ? options.singleBufferSerializtion : true; + this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; + + // SSL options + this.ca = options.ca || null; + this.cert = options.cert || null; + this.key = options.key || null; + this.passphrase = options.passphrase || null; + this.ssl = typeof options.ssl == 'boolean' ? options.ssl : false; + this.rejectUnauthorized = typeof options.rejectUnauthorized == 'boolean' ? options.rejectUnauthorized : true + + // If ssl not enabled + if(!this.ssl) this.rejectUnauthorized = false; + + // Response options + this.responseOptions = { + promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true + } + + // Flushing + this.flushing = false; + this.queue = []; + + // Internal state + this.connection = null; + this.writeStream = null; +} + +inherits(Connection, EventEmitter); + +// +// Connection handlers +var errorHandler = function(self) { + return function(err) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err))); + // Emit the error + if(self.listeners('error').length > 0) self.emit("error", MongoError.create(err), self); + } +} + +var timeoutHandler = function(self) { + return function() { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); + // Emit timeout error + self.emit("timeout" + , MongoError.create(f("connection %s to %s:%s timed out", self.id, self.host, self.port)) + , self); + } +} + +var closeHandler = function(self) { + return function(hadError) { + // Debug information + if(self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); + // Emit close event + if(!hadError) { + self.emit("close" + , MongoError.create(f("connection %s to %s:%s closed", self.id, self.host, self.port)) + , self); + } + } +} + +var dataHandler = function(self) { + return function(data) { + // Parse until we are done with the data + while(data.length > 0) { + // If we still have bytes to read on the current message + if(self.bytesRead > 0 && self.sizeOfMessage > 0) { + // Calculate the amount of remaining bytes + var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; + // Check if the current chunk contains the rest of the message + if(remainingBytesToRead > data.length) { + // Copy the new data into the exiting buffer (should have been allocated when we know the message size) + data.copy(self.buffer, self.bytesRead); + // Adjust the number of bytes read so it point to the correct index in the buffer + self.bytesRead = self.bytesRead + data.length; + + // Reset state of buffer + data = new Buffer(0); + } else { + // Copy the missing part of the data into our current buffer + data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); + // Slice the overflow into a new buffer that we will then re-parse + data = data.slice(remainingBytesToRead); + + // Emit current complete message + try { + var emitBuffer = self.buffer; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Emit the buffer + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } catch(err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + } + } + } else { + // Stub buffer is kept in case we don't get enough bytes to determine the + // size of the message (< 4 bytes) + if(self.stubBuffer != null && self.stubBuffer.length > 0) { + // If we have enough bytes to determine the message size let's do it + if(self.stubBuffer.length + data.length > 4) { + // Prepad the data + var newData = new Buffer(self.stubBuffer.length + data.length); + self.stubBuffer.copy(newData, 0); + data.copy(newData, self.stubBuffer.length); + // Reassign for parsing + data = newData; + + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + + } else { + + // Add the the bytes to the stub buffer + var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); + // Copy existing stub buffer + self.stubBuffer.copy(newStubBuffer, 0); + // Copy missing part of the data + data.copy(newStubBuffer, self.stubBuffer.length); + // Exit parsing loop + data = new Buffer(0); + } + } else { + if(data.length > 4) { + // Retrieve the message size + // var sizeOfMessage = data.readUInt32LE(0); + var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; + // If we have a negative sizeOfMessage emit error and return + if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ + sizeOfMessage: sizeOfMessage, + bytesRead: self.bytesRead, + stubBuffer: self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + return; + } + + // Ensure that the size of message is larger than 0 and less than the max allowed + if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage > data.length) { + self.buffer = new Buffer(sizeOfMessage); + // Copy all the data into the buffer + data.copy(self.buffer, 0); + // Update bytes read + self.bytesRead = data.length; + // Update sizeOfMessage + self.sizeOfMessage = sizeOfMessage; + // Ensure stub buffer is null + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + + } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage == data.length) { + try { + var emitBuffer = data; + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + // Emit the message + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } catch (err) { + var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ + sizeOfMessage:self.sizeOfMessage, + bytesRead:self.bytesRead, + stubBuffer:self.stubBuffer}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + } + } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { + var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ + sizeOfMessage:sizeOfMessage, + bytesRead:0, + buffer:null, + stubBuffer:null}}; + // We got a parse Error fire it off then keep going + self.emit("parseError", errorObject, self); + + // Clear out the state of the parser + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Exit parsing loop + data = new Buffer(0); + } else { + var emitBuffer = data.slice(0, sizeOfMessage); + // Reset state of buffer + self.buffer = null; + self.sizeOfMessage = 0; + self.bytesRead = 0; + self.stubBuffer = null; + // Copy rest of message + data = data.slice(sizeOfMessage); + // Emit the message + self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); + } + } else { + // Create a buffer that contains the space for the non-complete message + self.stubBuffer = new Buffer(data.length) + // Copy the data to the stub buffer + data.copy(self.stubBuffer, 0); + // Exit parsing loop + data = new Buffer(0); + } + } + } + } + } +} + +/** + * Connect + * @method + */ +Connection.prototype.connect = function(_options) { + var self = this; + _options = _options || {}; + // Check if we are overriding the promoteLongs + if(typeof _options.promoteLongs == 'boolean') { + self.responseOptions.promoteLongs = _options.promoteLongs; + } + + // Create new connection instance + self.connection = self.domainSocket + ? net.createConnection(self.host) + : net.createConnection(self.port, self.host); + + // Set the options for the connection + self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); + self.connection.setTimeout(self.connectionTimeout); + self.connection.setNoDelay(self.noDelay); + + // If we have ssl enabled + if(self.ssl) { + var sslOptions = { + socket: self.connection + , rejectUnauthorized: self.rejectUnauthorized + } + + if(self.ca) sslOptions.ca = self.ca; + if(self.cert) sslOptions.cert = self.cert; + if(self.key) sslOptions.key = self.key; + if(self.passphrase) sslOptions.passphrase = self.passphrase; + + // Attempt SSL connection + self.connection = tls.connect(self.port, self.host, sslOptions, function() { + // Error on auth or skip + if(self.connection.authorizationError && self.rejectUnauthorized) { + return self.emit("error", self.connection.authorizationError, self, {ssl:true}); + } + + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // We are done emit connect + self.emit('connect', self); + }); + self.connection.setTimeout(self.connectionTimeout); + } else { + self.connection.on('connect', function() { + // Set socket timeout instead of connection timeout + self.connection.setTimeout(self.socketTimeout); + // Emit connect event + self.emit('connect', self); + }); + } + + // Add handlers for events + self.connection.once('error', errorHandler(self)); + self.connection.once('timeout', timeoutHandler(self)); + self.connection.once('close', closeHandler(self)); + self.connection.on('data', dataHandler(self)); +} + +/** + * Destroy connection + * @method + */ +Connection.prototype.destroy = function() { + if(this.connection) this.connection.destroy(); + this.destroyed = true; +} + +/** + * Write to connection + * @method + * @param {Command} command Command to write out need to implement toBin and toBinUnified + */ +Connection.prototype.write = function(buffer) { + // Debug log + if(this.logger.isDebug()) this.logger.debug(f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port)); + // Write out the command + if(!Array.isArray(buffer)) return this.connection.write(buffer, 'binary'); + // Iterate over all buffers and write them in order to the socket + for(var i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); +} + +/** + * Return id of connection as a string + * @method + * @return {string} + */ +Connection.prototype.toString = function() { + return "" + this.id; +} + +/** + * Return json object of connection + * @method + * @return {object} + */ +Connection.prototype.toJSON = function() { + return {id: this.id, host: this.host, port: this.port}; +} + +/** + * Is the connection connected + * @method + * @return {boolean} + */ +Connection.prototype.isConnected = function() { + if(this.destroyed) return false; + return !this.connection.destroyed && this.connection.writable; +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Connection#connect + * @type {Connection} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Connection#close + * @type {Connection} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Connection#error + * @type {Connection} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Connection#timeout + * @type {Connection} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Connection#parseError + * @type {Connection} + */ + +module.exports = Connection; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js new file mode 100644 index 0000000..69c6f93 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js @@ -0,0 +1,196 @@ +"use strict"; + +var f = require('util').format + , MongoError = require('../error'); + +// Filters for classes +var classFilters = {}; +var filteredClasses = {}; +var level = null; +// Save the process id +var pid = process.pid; +// current logger +var currentLogger = null; + +/** + * Creates a new Logger instance + * @class + * @param {string} className The Class name associated with the logging instance + * @param {object} [options=null] Optional settings. + * @param {Function} [options.logger=null] Custom logger function; + * @param {string} [options.loggerLevel=error] Override default global log level. + * @return {Logger} a Logger instance. + */ +var Logger = function(className, options) { + if(!(this instanceof Logger)) return new Logger(className, options); + options = options || {}; + + // Current reference + var self = this; + this.className = className; + + // Current logger + if(currentLogger == null && options.logger) { + currentLogger = options.logger; + } else if(currentLogger == null) { + currentLogger = console.log; + } + + // Set level of logging, default is error + if(level == null) { + level = options.loggerLevel || 'error'; + } + + // Add all class names + if(filteredClasses[this.className] == null) classFilters[this.className] = true; +} + +/** + * Log a message at the debug level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.debug = function(message, object) { + if(this.isDebug() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); + var state = { + type: 'debug', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +} + +/** + * Log a message at the info level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.info = function(message, object) { + if(this.isInfo() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); + var state = { + type: 'info', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Log a message at the error level + * @method + * @param {string} message The message to log + * @param {object} object additional meta data to log + * @return {null} + */ +Logger.prototype.error = function(message, object) { + if(this.isError() + && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) + || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { + var dateTime = new Date().getTime(); + var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); + var state = { + type: 'error', message: message, className: this.className, pid: pid, date: dateTime + }; + if(object) state.meta = object; + currentLogger(msg, state); + } +}, + +/** + * Is the logger set at info level + * @method + * @return {boolean} + */ +Logger.prototype.isInfo = function() { + return level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at error level + * @method + * @return {boolean} + */ +Logger.prototype.isError = function() { + return level == 'error' || level == 'info' || level == 'debug'; +}, + +/** + * Is the logger set at debug level + * @method + * @return {boolean} + */ +Logger.prototype.isDebug = function() { + return level == 'debug'; +} + +/** + * Resets the logger to default settings, error and no filtered classes + * @method + * @return {null} + */ +Logger.reset = function() { + level = 'error'; + filteredClasses = {}; +} + +/** + * Get the current logger function + * @method + * @return {function} + */ +Logger.currentLogger = function() { + return currentLogger; +} + +/** + * Set the current logger function + * @method + * @param {function} logger Logger function. + * @return {null} + */ +Logger.setCurrentLogger = function(logger) { + if(typeof logger != 'function') throw new MongoError("current logger must be a function"); + currentLogger = logger; +} + +/** + * Set what classes to log. + * @method + * @param {string} type The type of filter (currently only class) + * @param {string[]} values The filters to apply + * @return {null} + */ +Logger.filter = function(type, values) { + if(type == 'class' && Array.isArray(values)) { + filteredClasses = {}; + + values.forEach(function(x) { + filteredClasses[x] = true; + }); + } +} + +/** + * Set the current log level + * @method + * @param {string} level Set current log level (debug, info, error) + * @return {null} + */ +Logger.setLevel = function(_level) { + if(_level != 'info' && _level != 'error' && _level != 'debug') throw new Error(f("%s is an illegal logging level", _level)); + level = _level; +} + +module.exports = Logger; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js new file mode 100644 index 0000000..dd13707 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js @@ -0,0 +1,275 @@ +"use strict"; + +var inherits = require('util').inherits + , EventEmitter = require('events').EventEmitter + , Connection = require('./connection') + , Query = require('./commands').Query + , Logger = require('./logger') + , f = require('util').format; + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +var _id = 0; + +/** + * Creates a new Pool instance + * @class + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passPhrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @fires Pool#connect + * @fires Pool#close + * @fires Pool#error + * @fires Pool#timeout + * @fires Pool#parseError + * @return {Pool} A cursor instance + */ +var Pool = function(options) { + var self = this; + // Add event listener + EventEmitter.call(this); + // Set empty if no options passed + this.options = options || {}; + this.size = typeof options.size == 'number' ? options.size : 5; + // Message handler + this.messageHandler = options.messageHandler; + // No bson parser passed in + if(!options.bson) throw new Error("must pass in valid bson parser"); + // Contains all connections + this.connections = []; + this.state = DISCONNECTED; + // Round robin index + this.index = 0; + this.dead = false; + // Logger instance + this.logger = Logger('Pool', options); + // Pool id + this.id = _id++; + // Grouping tag used for debugging purposes + this.tag = options.tag; +} + +inherits(Pool, EventEmitter); + +var errorHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('error', err, self); + } + } +} + +var timeoutHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] timed out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('timeout', err, self); + } + } +} + +var closeHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] closed [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('close', err, self); + } + } +} + +var parseErrorHandler = function(self) { + return function(err, connection) { + if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); + if(!self.dead) { + self.state = DISCONNECTED; + self.dead = true; + self.destroy(); + self.emit('parseError', err, self); + } + } +} + +var connectHandler = function(self) { + return function(connection) { + self.connections.push(connection); + // We have connected to all servers + if(self.connections.length == self.size) { + self.state = CONNECTED; + // Done connecting + self.emit("connect", self); + } + } +} + +/** + * Destroy pool + * @method + */ +Pool.prototype.destroy = function() { + this.state = DESTROYED; + // Set dead + this.dead = true; + // Destroy all the connections + this.connections.forEach(function(c) { + // Destroy all event emitters + ["close", "message", "error", "timeout", "parseError", "connect"].forEach(function(e) { + c.removeAllListeners(e); + }); + + // Destroy the connection + c.destroy(); + }); +} + +var execute = null; + +try { + execute = setImmediate; +} catch(err) { + execute = process.nextTick; +} + +/** + * Connect pool + * @method + */ +Pool.prototype.connect = function(_options) { + var self = this; + // Set to connecting + this.state = CONNECTING + // No dead + this.dead = false; + + // Ensure we allow for a little time to setup connections + var wait = 1; + + // Connect all sockets + for(var i = 0; i < this.size; i++) { + setTimeout(function() { + execute(function() { + self.options.messageHandler = self.messageHandler; + var connection = new Connection(self.options); + + // Add all handlers + connection.once('close', closeHandler(self)); + connection.once('error', errorHandler(self)); + connection.once('timeout', timeoutHandler(self)); + connection.once('parseError', parseErrorHandler(self)); + connection.on('connect', connectHandler(self)); + + // Start connection + connection.connect(_options); + }); + }, wait); + + // wait for 1 miliseconds before attempting to connect, spacing out connections + wait = wait + 1; + } +} + +/** + * Get a pool connection (round-robin) + * @method + * @return {Connection} + */ +Pool.prototype.get = function() { + // if(this.dead) return null; + var connection = this.connections[this.index++]; + this.index = this.index % this.connections.length; + return connection; +} + +/** + * Get all pool connections + * @method + * @return {array} + */ +Pool.prototype.getAll = function() { + return this.connections.slice(0); +} + +/** + * Is the pool connected + * @method + * @return {boolean} + */ +Pool.prototype.isConnected = function() { + for(var i = 0; i < this.connections.length; i++) { + if(!this.connections[i].isConnected()) return false; + } + + return this.state == CONNECTED; +} + +/** + * Was the pool destroyed + * @method + * @return {boolean} + */ +Pool.prototype.isDestroyed = function() { + return this.state == DESTROYED; +} + + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Pool#connect + * @type {Pool} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Pool#close + * @type {Pool} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Pool#error + * @type {Pool} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Pool#timeout + * @type {Pool} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Pool#parseError + * @type {Pool} + */ + +module.exports = Pool; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js new file mode 100644 index 0000000..7f0b89d --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js @@ -0,0 +1,77 @@ +"use strict"; + +// Set property function +var setProperty = function(obj, prop, flag, values) { + Object.defineProperty(obj, prop.name, { + enumerable:true, + set: function(value) { + if(typeof value != 'boolean') throw new Error(f("%s required a boolean", prop.name)); + // Flip the bit to 1 + if(value == true) values.flags |= flag; + // Flip the bit to 0 if it's set, otherwise ignore + if(value == false && (values.flags & flag) == flag) values.flags ^= flag; + prop.value = value; + } + , get: function() { return prop.value; } + }); +} + +// Set property function +var getProperty = function(obj, propName, fieldName, values, func) { + Object.defineProperty(obj, propName, { + enumerable:true, + get: function() { + // Not parsed yet, parse it + if(values[fieldName] == null && obj.isParsed && !obj.isParsed()) { + obj.parse(); + } + + // Do we have a post processing function + if(typeof func == 'function') return func(values[fieldName]); + // Return raw value + return values[fieldName]; + } + }); +} + +// Set simple property +var getSingleProperty = function(obj, name, value) { + Object.defineProperty(obj, name, { + enumerable:true, + get: function() { + return value + } + }); +} + +// Shallow copy +var copy = function(fObj, tObj) { + tObj = tObj || {}; + for(var name in fObj) tObj[name] = fObj[name]; + return tObj; +} + +var debugOptions = function(debugFields, options) { + var finaloptions = {}; + debugFields.forEach(function(n) { + finaloptions[n] = options[n]; + }); + + return finaloptions; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) return callback; + return domain.bind(callback); +} + +exports.setProperty = setProperty; +exports.getProperty = getProperty; +exports.getSingleProperty = getSingleProperty; +exports.copy = copy; +exports.bindToCurrentDomain = bindToCurrentDomain; +exports.debugOptions = debugOptions; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js new file mode 100644 index 0000000..ab82818 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js @@ -0,0 +1,756 @@ +"use strict"; + +var Long = require('bson').Long + , Logger = require('./connection/logger') + , MongoError = require('./error') + , f = require('util').format; + +/** + * This is a cursor results callback + * + * @callback resultCallback + * @param {error} error An error object. Set to null if no error present + * @param {object} document + */ + +/** + * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB + * allowing for iteration over the results returned from the underlying query. + * + * **CURSORS Cannot directly be instantiated** + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * assert.equal(null, err); + * + * // Execute the write + * var cursor = _server.cursor('integration_tests.inserts_example4', { + * find: 'integration_tests.example4' + * , query: {a:1} + * }, { + * readPreference: new ReadPreference('secondary'); + * }); + * + * // Get the first document + * cursor.next(function(err, doc) { + * assert.equal(null, err); + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Cursor, not to be used directly + * @class + * @param {object} bson An instance of the BSON parser + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|Long} cmd The selector (can be a command or a cursorId) + * @param {object} [options=null] Optional settings. + * @param {object} [options.batchSize=1000] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {object} [options.transforms=null] Transform methods for the cursor results + * @param {function} [options.transforms.query] Transform the value returned from the initial query + * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next + * @param {object} topology The server topology instance. + * @param {object} topologyOptions The server topology options. + * @return {Cursor} A cursor instance + * @property {number} cursorBatchSize The current cursorBatchSize for the cursor + * @property {number} cursorLimit The current cursorLimit for the cursor + * @property {number} cursorSkip The current cursorSkip for the cursor + */ +var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { + options = options || {}; + // Cursor reference + var self = this; + // Initial query + var query = null; + + // Cursor connection + this.connection = null; + // Cursor server + this.server = null; + + // Do we have a not connected handler + this.disconnectHandler = options.disconnectHandler; + + // Set local values + this.bson = bson; + this.ns = ns; + this.cmd = cmd; + this.options = options; + this.topology = topology; + + // All internal state + this.cursorState = { + cursorId: null + , cmd: cmd + , documents: options.documents || [] + , cursorIndex: 0 + , dead: false + , killed: false + , init: false + , notified: false + , limit: options.limit || cmd.limit || 0 + , skip: options.skip || cmd.skip || 0 + , batchSize: options.batchSize || cmd.batchSize || 1000 + , currentLimit: 0 + // Result field name if not a cursor (contains the array of results) + , transforms: options.transforms + } + + // Callback controller + this.callbacks = null; + + // Logger + this.logger = Logger('Cursor', options); + + // + // Did we pass in a cursor id + if(typeof cmd == 'number') { + this.cursorState.cursorId = Long.fromNumber(cmd); + } else if(cmd instanceof Long) { + this.cursorState.cursorId = cmd; + } +} + +Cursor.prototype.setCursorBatchSize = function(value) { + this.cursorState.batchSize = value; +} + +Cursor.prototype.cursorBatchSize = function() { + return this.cursorState.batchSize; +} + +Cursor.prototype.setCursorLimit = function(value) { + this.cursorState.limit = value; +} + +Cursor.prototype.cursorLimit = function() { + return this.cursorState.limit; +} + +Cursor.prototype.setCursorSkip = function(value) { + this.cursorState.skip = value; +} + +Cursor.prototype.cursorSkip = function() { + return this.cursorState.skip; +} + +// // +// // Execute getMore command +// var execGetMore = function(self, callback) { +// } + +// +// Execute the first query +var execInitialQuery = function(self, query, cmd, options, cursorState, connection, logger, callbacks, callback) { + if(logger.isDebug()) { + logger.debug(f("issue initial query [%s] with flags [%s]" + , JSON.stringify(cmd) + , JSON.stringify(query))); + } + + var queryCallback = function(err, result) { + if(err) return callback(err); + + if(result.queryFailure) { + return callback(MongoError.create(result.documents[0]), null); + } + + // Check if we have a command cursor + if(Array.isArray(result.documents) && result.documents.length == 1 + && (!cmd.find || (cmd.find && cmd.virtual == false)) + && (result.documents[0].cursor != 'string' + || result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || Array.isArray(result.documents[0].result)) + ) { + + // We have a an error document return the error + if(result.documents[0]['$err'] + || result.documents[0]['errmsg']) { + return callback(MongoError.create(result.documents[0]), null); + } + + // We have a cursor document + if(result.documents[0].cursor != null + && typeof result.documents[0].cursor != 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if(result.documents[0].cursor.ns) { + self.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; + // If we have a firstBatch set it + if(Array.isArray(result.documents[0].cursor.firstBatch)) { + cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); + } + + // Return after processing command cursor + return callback(null, null); + } + + if(Array.isArray(result.documents[0].result)) { + cursorState.documents = result.documents[0].result; + cursorState.cursorId = Long.ZERO; + return callback(null, null); + } + } + + // Otherwise fall back to regular find path + cursorState.cursorId = result.cursorId; + cursorState.documents = result.documents; + + // Transform the results with passed in transformation method if provided + if(cursorState.transforms && typeof cursorState.transforms.query == 'function') { + cursorState.documents = cursorState.transforms.query(result); + } + + // Return callback + callback(null, null); + } + + // If we have a raw query decorate the function + if(options.raw || cmd.raw) { + queryCallback.raw = options.raw || cmd.raw; + } + + // Do we have documentsReturnedIn set on the query + if(typeof query.documentsReturnedIn == 'string') { + queryCallback.documentsReturnedIn = query.documentsReturnedIn; + } + + // Set up callback + callbacks.register(query.requestId, queryCallback); + + // Write the initial command out + connection.write(query.toBin()); +} + +// +// Handle callback (including any exceptions thrown) +var handleCallback = function(callback, err, result) { + try { + callback(err, result); + } catch(err) { + process.nextTick(function() { + throw err; + }); + } +} + + +// Internal methods +Cursor.prototype._find = function(callback) { + var self = this; + // execInitialQuery(self, self.query, self.cmd, self.options, self.cursorState, self.connection, self.logger, self.callbacks, function(err, r) { + if(self.logger.isDebug()) { + self.logger.debug(f("issue initial query [%s] with flags [%s]" + , JSON.stringify(self.cmd) + , JSON.stringify(self.query))); + } + + var queryCallback = function(err, result) { + if(err) return callback(err); + + if(result.queryFailure) { + return callback(MongoError.create(result.documents[0]), null); + } + + // Check if we have a command cursor + if(Array.isArray(result.documents) && result.documents.length == 1 + && (!self.cmd.find || (self.cmd.find && self.cmd.virtual == false)) + && (result.documents[0].cursor != 'string' + || result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || Array.isArray(result.documents[0].result)) + ) { + + // We have a an error document return the error + if(result.documents[0]['$err'] + || result.documents[0]['errmsg']) { + return callback(MongoError.create(result.documents[0]), null); + } + + // We have a cursor document + if(result.documents[0].cursor != null + && typeof result.documents[0].cursor != 'string') { + var id = result.documents[0].cursor.id; + // If we have a namespace change set the new namespace for getmores + if(result.documents[0].cursor.ns) { + self.ns = result.documents[0].cursor.ns; + } + // Promote id to long if needed + self.cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; + // If we have a firstBatch set it + if(Array.isArray(result.documents[0].cursor.firstBatch)) { + self.cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); + } + + // Return after processing command cursor + return callback(null, null); + } + + if(Array.isArray(result.documents[0].result)) { + self.cursorState.documents = result.documents[0].result; + self.cursorState.cursorId = Long.ZERO; + return callback(null, null); + } + } + + // Otherwise fall back to regular find path + self.cursorState.cursorId = result.cursorId; + self.cursorState.documents = result.documents; + + // Transform the results with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.query == 'function') { + self.cursorState.documents = self.cursorState.transforms.query(result); + } + + // Return callback + callback(null, null); + } + // console.log("------------------------- 2") + + // If we have a raw query decorate the function + if(self.options.raw || self.cmd.raw) { + queryCallback.raw = self.options.raw || self.cmd.raw; + } + // console.log("------------------------- 3") + + // Do we have documentsReturnedIn set on the query + if(typeof self.query.documentsReturnedIn == 'string') { + queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; + } + // console.log("------------------------- 4") + + // Set up callback + self.callbacks.register(self.query.requestId, queryCallback); + + // Write the initial command out + self.connection.write(self.query.toBin()); +// console.log("------------------------- 5") +} + +Cursor.prototype._getmore = function(callback) { + if(this.logger.isDebug()) this.logger.debug(f("schedule getMore call for query [%s]", JSON.stringify(this.query))) + // Determine if it's a raw query + var raw = this.options.raw || this.cmd.raw; + // We have a wire protocol handler + this.server.wireProtocolHandler.getMore(this.bson, this.ns, this.cursorState, this.cursorState.batchSize, raw, this.connection, this.callbacks, this.options, callback); +} + +Cursor.prototype._killcursor = function(callback) { + // Set cursor to dead + this.cursorState.dead = true; + this.cursorState.killed = true; + // Remove documents + this.cursorState.documents = []; + + // If no cursor id just return + if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) { + if(callback) callback(null, null); + return; + } + + // Execute command + this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState.cursorId, this.connection, this.callbacks, callback); +} + +/** + * Clone the cursor + * @method + * @return {Cursor} + */ +Cursor.prototype.clone = function() { + return this.topology.cursor(this.ns, this.cmd, this.options); +} + +/** + * Checks if the cursor is dead + * @method + * @return {boolean} A boolean signifying if the cursor is dead or not + */ +Cursor.prototype.isDead = function() { + return this.cursorState.dead == true; +} + +/** + * Checks if the cursor was killed by the application + * @method + * @return {boolean} A boolean signifying if the cursor was killed by the application + */ +Cursor.prototype.isKilled = function() { + return this.cursorState.killed == true; +} + +/** + * Checks if the cursor notified it's caller about it's death + * @method + * @return {boolean} A boolean signifying if the cursor notified the callback + */ +Cursor.prototype.isNotified = function() { + return this.cursorState.notified == true; +} + +/** + * Returns current buffered documents length + * @method + * @return {number} The number of items in the buffered documents + */ +Cursor.prototype.bufferedCount = function() { + return this.cursorState.documents.length - this.cursorState.cursorIndex; +} + +/** + * Returns current buffered documents + * @method + * @return {Array} An array of buffered documents + */ +Cursor.prototype.readBufferedDocuments = function(number) { + var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; + var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; + var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length); + + // Transform the doc with passed in transformation method if provided + if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') { + // Transform all the elements + for(var i = 0; i < elements.length; i++) { + elements[i] = this.cursorState.transforms.doc(elements[i]); + } + } + + // Ensure we do not return any more documents than the limit imposed + // Just return the number of elements up to the limit + if(this.cursorState.limit > 0 && (this.cursorState.currentLimit + elements.length) > this.cursorState.limit) { + elements = elements.slice(0, (this.cursorState.limit - this.cursorState.currentLimit)); + this.kill(); + } + + // Adjust current limit + this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; + this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; + + // Return elements + return elements; +} + +/** + * Kill the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.kill = function(callback) { + this._killcursor(callback); +} + +/** + * Resets the cursor + * @method + * @return {null} + */ +Cursor.prototype.rewind = function() { + if(this.cursorState.init) { + if(!this.cursorState.dead) { + this.kill(); + } + + this.cursorState.currentLimit = 0; + this.cursorState.init = false; + this.cursorState.dead = false; + this.cursorState.killed = false; + this.cursorState.notified = false; + this.cursorState.documents = []; + this.cursorState.cursorId = null; + this.cursorState.cursorIndex = 0; + } +} + +/** + * Validate if the connection is dead and return error + */ +var isConnectionDead = function(self, callback) { + if(self.connection + && !self.connection.isConnected()) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + callback(MongoError.create(f('connection to host %s:%s was destroyed', self.connection.host, self.connection.port))) + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead but was not explicitly killed by user + */ +var isCursorDeadButNotkilled = function(self, callback) { + // Cursor is dead but not marked killed, return null + if(self.cursorState.dead && !self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.killed = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Validate if the cursor is dead and was killed by user + */ +var isCursorDeadAndKilled = function(self, callback) { + if(self.cursorState.dead && self.cursorState.killed) { + handleCallback(callback, MongoError.create("cursor is dead")); + return true; + } + + return false; +} + +/** + * Validate if the cursor was killed by the user + */ +var isCursorKilled = function(self, callback) { + if(self.cursorState.killed) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); + return true; + } + + return false; +} + +/** + * Mark cursor as being dead and notified + */ +var setCursorDeadAndNotified = function(self, callback) { + self.cursorState.dead = true; + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +/** + * Mark cursor as being notified + */ +var setCursorNotified = function(self, callback) { + self.cursorState.notified = true; + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + handleCallback(callback, null, null); +} + +var nextFunction = function(self, callback) { + // We have notified about it + if(self.cursorState.notified) { + return callback(new Error('cursor is exhausted')); + } + + // Cursor is killed return null + if(isCursorKilled(self, callback)) return; + + // Cursor is dead but not marked killed, return null + if(isCursorDeadButNotkilled(self, callback)) return; + + // We have a dead and killed cursor, attempting to call next should error + if(isCursorDeadAndKilled(self, callback)) return; + + // We have just started the cursor + if(!self.cursorState.init) { + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.topology.isConnected(self.options) && self.disconnectHandler != null) { + return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); + } + + try { + // Get a server + self.server = self.topology.getServer(self.options); + // Get a connection + self.connection = self.server.getConnection(); + // Get the callbacks + self.callbacks = self.server.getCallbacks(); + } catch(err) { + return callback(err); + } + + // Set as init + self.cursorState.init = true; + + try { + // Get the right wire protocol command + self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options); + } catch(err) { + return callback(err); + } + } + + // Process exhaust messages + var processExhaustMessages = function(err, result) { + if(err) { + self.cursorState.dead = true; + self.callbacks.unregister(self.query.requestId); + return callback(err); + } + + // Concatenate all the documents + self.cursorState.documents = self.cursorState.documents.concat(result.documents); + + // If we have no documents left + if(Long.ZERO.equals(result.cursorId)) { + self.cursorState.cursorId = Long.ZERO; + self.callbacks.unregister(self.query.requestId); + return nextFunction(self, callback); + } + + // Set up next listener + self.callbacks.register(result.requestId, processExhaustMessages) + + // Initial result + if(self.cursorState.cursorId == null) { + self.cursorState.cursorId = result.cursorId; + nextFunction(self, callback); + } + } + + // If we have exhaust + if(self.cmd.exhaust && self.cursorState.cursorId == null) { + // Handle all the exhaust responses + self.callbacks.register(self.query.requestId, processExhaustMessages); + // Write the initial command out + return self.connection.write(self.query.toBin()); + } else if(self.cmd.exhaust && self.cursorState.cursorIndex < self.cursorState.documents.length) { + return handleCallback(callback, null, self.cursorState.documents[self.cursorState.cursorIndex++]); + } else if(self.cmd.exhaust && Long.ZERO.equals(self.cursorState.cursorId)) { + self.callbacks.unregister(self.query.requestId); + return setCursorNotified(self, callback); + } else if(self.cmd.exhaust) { + return setTimeout(function() { + if(Long.ZERO.equals(self.cursorState.cursorId)) return; + nextFunction(self, callback); + }, 1); + } + + // If we don't have a cursorId execute the first query + if(self.cursorState.cursorId == null) { + // Check if connection is dead and return if not possible to + // execute the query against the db + if(isConnectionDead(self, callback)) return; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // query, cmd, options, cursorState, callback + self._find(function(err, r) { + if(err) return handleCallback(callback, err, null); + if(self.cursorState.documents.length == 0 && !self.cmd.tailable && !self.cmd.awaitData) { + return setCursorNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } else if(self.cursorState.cursorIndex == self.cursorState.documents.length + && !Long.ZERO.equals(self.cursorState.cursorId)) { + // Ensure an empty cursor state + self.cursorState.documents = []; + self.cursorState.cursorIndex = 0; + + // Check if topology is destroyed + if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); + + // Check if connection is dead and return if not possible to + // execute a getmore on this connection + if(isConnectionDead(self, callback)) return; + + // Execute the next get more + self._getmore(function(err, doc) { + if(err) return handleCallback(callback, err); + if(self.cursorState.documents.length == 0 + && Long.ZERO.equals(self.cursorState.cursorId)) { + self.cursorState.dead = true; + } + + // Tailable cursor getMore result, notify owner about it + // No attempt is made here to retry, this is left to the user of the + // core module to handle to keep core simple + if(self.cursorState.documents.length == 0 && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } + + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + return setCursorDeadAndNotified(self, callback); + } + + nextFunction(self, callback); + }); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && self.cmd.tailable) { + return handleCallback(callback, MongoError.create({ + message: "No more documents in tailed cursor" + , tailable: self.cmd.tailable + , awaitData: self.cmd.awaitData + })); + } else if(self.cursorState.documents.length == self.cursorState.cursorIndex + && Long.ZERO.equals(self.cursorState.cursorId)) { + setCursorDeadAndNotified(self, callback); + } else { + if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { + // Ensure we kill the cursor on the server + self.kill(); + // Set cursor in dead and notified state + return setCursorDeadAndNotified(self, callback); + } + + // Increment the current cursor limit + self.cursorState.currentLimit += 1; + + // Get the document + var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; + + // Transform the doc with passed in transformation method if provided + if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') { + doc = self.cursorState.transforms.doc(doc); + } + + // Return the document + handleCallback(callback, null, doc); + } +} + +/** + * Retrieve the next document from the cursor + * @method + * @param {resultCallback} callback A callback function + */ +Cursor.prototype.next = function(callback) { + nextFunction(this, callback); +} + +module.exports = Cursor; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js new file mode 100644 index 0000000..4e17ef3 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js @@ -0,0 +1,44 @@ +"use strict"; + +/** + * Creates a new MongoError + * @class + * @augments Error + * @param {string} message The error message + * @return {MongoError} A MongoError instance + */ +function MongoError(message) { + this.name = 'MongoError'; + this.message = message; + Error.captureStackTrace(this, MongoError); +} + +/** + * Creates a new MongoError object + * @method + * @param {object} options The error options + * @return {MongoError} A MongoError instance + */ +MongoError.create = function(options) { + var err = null; + + if(options instanceof Error) { + err = new MongoError(options.message); + err.stack = options.stack; + } else if(typeof options == 'string') { + err = new MongoError(options); + } else { + err = new MongoError(options.message || options.errmsg || options.$err || "n/a"); + // Other options + for(var name in options) { + err[name] = options[name]; + } + } + + return err; +} + +// Extend JavaScript error +MongoError.prototype = new Error; + +module.exports = MongoError; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js new file mode 100644 index 0000000..dcceda4 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js @@ -0,0 +1,59 @@ +var fs = require('fs'); + +/* Note: because this plugin uses process.on('uncaughtException'), only one + * of these can exist at any given time. This plugin and anything else that + * uses process.on('uncaughtException') will conflict. */ +exports.attachToRunner = function(runner, outputFile) { + var smokeOutput = { results : [] }; + var runningTests = {}; + + var integraPlugin = { + beforeTest: function(test, callback) { + test.startTime = Date.now(); + runningTests[test.name] = test; + callback(); + }, + afterTest: function(test, callback) { + smokeOutput.results.push({ + status: test.status, + start: test.startTime, + end: Date.now(), + test_file: test.name, + exit_code: 0, + url: "" + }); + delete runningTests[test.name]; + callback(); + }, + beforeExit: function(obj, callback) { + fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { + callback(); + }); + } + }; + + // In case of exception, make sure we write file + process.on('uncaughtException', function(err) { + // Mark all currently running tests as failed + for (var testName in runningTests) { + smokeOutput.results.push({ + status: "fail", + start: runningTests[testName].startTime, + end: Date.now(), + test_file: testName, + exit_code: 0, + url: "" + }); + } + + // write file + fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); + + // Standard NodeJS uncaught exception handler + console.error(err.stack); + process.exit(1); + }); + + runner.plugin(integraPlugin); + return integraPlugin; +}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js new file mode 100644 index 0000000..ff7bf1b --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js @@ -0,0 +1,37 @@ +"use strict"; + +var setProperty = require('../connection/utils').setProperty + , getProperty = require('../connection/utils').getProperty + , getSingleProperty = require('../connection/utils').getSingleProperty; + +/** + * Creates a new CommandResult instance + * @class + * @param {object} result CommandResult object + * @param {Connection} connection A connection instance associated with this result + * @return {CommandResult} A cursor instance + */ +var CommandResult = function(result, connection) { + this.result = result; + this.connection = connection; +} + +/** + * Convert CommandResult to JSON + * @method + * @return {object} + */ +CommandResult.prototype.toJSON = function() { + return this.result; +} + +/** + * Convert CommandResult to String representation + * @method + * @return {string} + */ +CommandResult.prototype.toString = function() { + return JSON.stringify(this.toJSON()); +} + +module.exports = CommandResult; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js new file mode 100644 index 0000000..c54514a --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js @@ -0,0 +1,1000 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , BasicCursor = require('../cursor') + , Server = require('./server') + , Logger = require('../connection/logger') + , ReadPreference = require('./read_preference') + , Session = require('./session') + , MongoError = require('../error'); + +/** + * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is + * used to construct connections. + * + * @example + * var Mongos = require('mongodb-core').Mongos + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Mongos([{host: 'localhost', port: 30000}]); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +// Instance id +var mongosId = 0; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +var State = function(readPreferenceStrategies) { + // Internal state + this.s = { + connectedServers: [] + , disconnectedServers: [] + , readPreferenceStrategies: readPreferenceStrategies + } +} + +// +// A Mongos connected +State.prototype.connected = function(server) { + // Locate in disconnected servers and remove + this.s.disconnectedServers = this.s.disconnectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.connectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.connectedServers.push(server); +} + +// +// A Mongos disconnected +State.prototype.disconnected = function(server) { + // Locate in disconnected servers and remove + this.s.connectedServers = this.s.connectedServers.filter(function(s) { + return !s.equals(server); + }); + + var found = false; + // Check if the server exists + this.s.disconnectedServers.forEach(function(s) { + if(s.equals(server)) found = true; + }); + + // Add to disconnected list if it does not already exist + if(!found) this.s.disconnectedServers.push(server); +} + +// +// Return the list of disconnected servers +State.prototype.disconnectedServers = function() { + return this.s.disconnectedServers.slice(0); +} + +// +// Get connectedServers +State.prototype.connectedServers = function() { + return this.s.connectedServers.slice(0) +} + +// +// Get all servers +State.prototype.getAll = function() { + return this.s.connectedServers.slice(0).concat(this.s.disconnectedServers); +} + +// +// Get all connections +State.prototype.getAllConnections = function() { + var connections = []; + this.s.connectedServers.forEach(function(e) { + connections = connections.concat(e.connections()); + }); + return connections; +} + +// +// Destroy the state +State.prototype.destroy = function() { + // Destroy any connected servers + while(this.s.connectedServers.length > 0) { + var server = this.s.connectedServers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Server destroy + server.destroy(); + // Add to list of disconnected servers + this.s.disconnectedServers.push(server); + } +} + +// +// Are we connected +State.prototype.isConnected = function() { + return this.s.connectedServers.length > 0; +} + +// +// Pick a server +State.prototype.pickServer = function(readPreference) { + readPreference = readPreference || ReadPreference.primary; + + // Do we have a custom readPreference strategy, use it + if(this.s.readPreferenceStrategies != null && this.s.readPreferenceStrategies[readPreference] != null) { + return this.s.readPreferenceStrategies[readPreference].pickServer(connectedServers, readPreference); + } + + // No valid connections + if(this.s.connectedServers.length == 0) throw new MongoError("no mongos proxy available"); + // Pick first one + return this.s.connectedServers[0]; +} + +/** + * Creates a new Mongos instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {number} [options.reconnectTries=30] Reconnect retries for HA if no servers available + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Mongos} A cursor instance + * @fires Mongos#connect + * @fires Mongos#joined + * @fires Mongos#left + */ +var Mongos = function(seedlist, options) { + var self = this; + options = options || {}; + + // Add event listener + EventEmitter.call(this); + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // BSON Parser, ensure we have a single instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + // Pick the right bson parser + var bson = options.bson ? options.bson : bsonInstance; + // Add bson parser to options + options.bson = bson; + + // The Mongos state + this.s = { + // Seed list for sharding passed in + seedlist: seedlist + // Passed in options + , options: options + // Logger + , logger: Logger('Mongos', options) + // Reconnect tries + , reconnectTries: options.reconnectTries || 30 + // Ha interval + , haInterval: options.haInterval || 5000 + // Have omitted fullsetup + , fullsetup: false + // Cursor factory + , Cursor: options.cursorFactory || BasicCursor + // Current credentials used for auth + , credentials: [] + // BSON Parser + , bsonInstance: bsonInstance + , bson: bson + // Default state + , state: DISCONNECTED + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // Unique instance id + , id: mongosId++ + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Current retries left + , retriesLeft: options.reconnectTries || 30 + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + } + + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 1000; + + // Create a new state for the mongos + this.s.mongosState = new State(this.s.readPreferenceStrategies); + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.mongosState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'mongos'; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.mongosState; } + }); +} + +inherits(Mongos, EventEmitter); + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +Mongos.prototype.parserType = function() { + if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Mongos.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Mongos.prototype.lastIsMaster = function() { + var connectedServers = this.s.mongosState.connectedServers(); + if(connectedServers.length > 0) return connectedServers[0].lastIsMaster(); + return null; +} + +/** + * Initiate server connect + * @method + */ +Mongos.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setTimeout(mongosInquirer(self, self.s), self.s.haInterval); + // Additional options + if(_options) for(var name in _options) self.s.options[name] = _options[name]; + // For all entries in the seedlist build a server instance + self.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Don't emit errors + opts.emitError = true; + // Create a new Server + self.s.mongosState.disconnected(new Server(opts)); + }); + + // Get the disconnected servers + var servers = self.s.mongosState.disconnectedServers(); + + // Attempt to connect to all the servers + while(servers.length > 0) { + // Get the server + var server = servers.shift(); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, self.s, server)); + server.once('close', errorHandlerTemp(self, self.s, server)); + server.once('timeout', errorHandlerTemp(self, self.s, server)); + server.once('parseError', errorHandlerTemp(self, self.s, server)); + server.once('connect', connectHandler(self, self.s, 'connect')); + + if(self.s.logger.isInfo()) self.s.logger.info(f('connecting to server %s', server.name)); + // Attempt to connect + server.connect(); + } +} + +/** + * Destroy the server connection + * @method + */ +Mongos.prototype.destroy = function(emitClose) { + this.s.state = DESTROYED; + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + // Destroy the state + this.s.mongosState.destroy(); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Mongos.prototype.isConnected = function() { + return this.s.mongosState.isConnected(); +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Mongos.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +// +// Operations +// + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'update', ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this.s, 'remove', ns, ops, options, callback); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + var self = this; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + var server = null; + // Ensure we have no options + options = options || {}; + + // We need to execute the command on all servers + if(options.onAll) { + var servers = self.s.mongosState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(state, ns); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + + try { + // Get a primary + server = self.s.mongosState.pickServer(options.writeConcern ? ReadPreference.primary : options.readPreference); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Mongos.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Mongos.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // Authenticate against all the servers + var servers = this.s.mongosState.connectedServers().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Mongos.prototype.addReadPreferenceStrategy = function(name, strategy) { + if(this.s.readPreferenceStrategies == null) this.s.readPreferenceStrategies = {}; + this.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Mongos.prototype.addAuthProvider = function(name, provider) { + this.s.authProviders[name] = provider; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Mongos.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = this.s.mongosState.pickServer(options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Mongos.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return this.s.mongosState.pickServer(options.readPreference); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Mongos.prototype.connections = function() { + return this.s.mongosState.getAllConnections(); +} + +// +// Inquires about state changes +// +var mongosInquirer = function(self, state) { + return function() { + if(state.state == DESTROYED) return + if(state.state == CONNECTED) state.retriesLeft = state.reconnectTries; + + // If we have a disconnected site + if(state.state == DISCONNECTED && state.retriesLeft == 0) { + self.destroy(); + return self.emit('error', new MongoError(f('failed to reconnect after %s', state.reconnectTries))); + } else if(state == DISCONNECTED) { + state.retriesLeft = state.retriesLeft - 1; + } + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.mongosState.isConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // Log the information + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess running')); + + // Let's query any disconnected proxies + var disconnectedServers = state.mongosState.disconnectedServers(); + if(disconnectedServers.length == 0) return setTimeout(mongosInquirer(self, state), state.haInterval); + + // Count of connections waiting to be connected + var connectionCount = disconnectedServers.length; + if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess found %d disconnected proxies', connectionCount)); + + // Let's attempt to reconnect + while(disconnectedServers.length > 0) { + var server = disconnectedServers.shift(); + if(state.logger.isDebug()) state.logger.debug(f('attempting to connect to server %s', server.name)); + + // Remove any listeners + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, server)); + server.once('close', errorHandlerTemp(self, state, server)); + server.once('timeout', errorHandlerTemp(self, state, server)); + server.once('connect', connectHandler(self, state, 'ha')); + // Start connect + server.connect(); + } + + // Let's keep monitoring but wait for possible timeout to happen + return setTimeout(mongosInquirer(self, state), state.options.connectionTimeout + state.haInterval); + } +} + +// +// Error handler for initial connect +var errorHandlerTemp = function(self, state, server) { + return function(err, server) { + // Log the information + if(state.logger.isInfo()) state.logger.info(f('server %s disconnected with error %s', server.name, JSON.stringify(err))); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Signal disconnect of server + state.mongosState.disconnected(server); + } +} + +// +// Handlers +var errorHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', server.name, JSON.stringify(err))); + state.mongosState.disconnected(server); + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + if(state.emitError) self.emit('error', err, server); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', server.name)); + state.mongosState.disconnected(server); + + // No more servers emit close event if no entries left + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + if(state.logger.isInfo()) state.logger.info(f('server %s closed', server.name)); + state.mongosState.disconnected(server); + + // No more servers left emit close + if(state.mongosState.connectedServers().length == 0) { + state.state = DISCONNECTED; + } + + // Signal server left + self.emit('left', 'mongos', server); + } +} + +// Connect handler +var connectHandler = function(self, state, e) { + return function(server) { + if(state.logger.isInfo()) state.logger.info(f('connected to %s', server.name)); + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { + server.removeAllListeners(e); + }); + + // finish processing the server + var processNewServer = function(_server) { + // Add the server handling code + if(_server.isConnected()) { + _server.once('error', errorHandler(self, state)); + _server.once('close', closeHandler(self, state)); + _server.once('timeout', timeoutHandler(self, state)); + _server.once('parseError', timeoutHandler(self, state)); + } + + // Emit joined event + self.emit('joined', 'mongos', _server); + + // Add to list connected servers + state.mongosState.connected(_server); + + // Do we have a reconnect event + if('ha' == e && state.mongosState.connectedServers().length == 1) { + self.emit('reconnect', _server); + } + + // Full setup + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length > 0 && + !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup'); + } + + // all connected + if(state.mongosState.disconnectedServers().length == 0 && + state.mongosState.connectedServers().length == state.seedlist.length && + !state.all) { + state.all = true; + self.emit('all'); + } + + // Set connected + if(state.state == DISCONNECTED) { + state.state = CONNECTED; + self.emit('connect', self); + } + } + + // Is there an authentication process ongoing + if(state.authInProgress) { + state.authInProgressServers.push(server); + } + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(server); + + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) processNewServer(server); + }])); + } + } +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } +} + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(state, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(state, db + ".dummy"); + // Add new credentials to list + state.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(state, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < state.credentials.length; i++) { + if(state.credentials[i][1] != db) filteredCredentials.push(state.credentials[i]); + } + + // Set new list of credentials + state.credentials = filteredCredentials; +} + +var processReadPreference = function(cmd, options) { + options = options || {} + // No read preference specified + if(options.readPreference == null) return cmd; +} + +// +// Execute write operation +var executeWriteOperation = function(state, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + try { + // Get a primary + server = state.mongosState.pickServer(); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no mongos found")); + // Execute the command + server[op](ns, ops, options, callback); +} + +/** + * A mongos connect event, used to verify that the connection is up and running + * + * @event Mongos#connect + * @type {Mongos} + */ + +/** + * A server member left the mongos list + * + * @event Mongos#left + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the mongos list + * + * @event Mongos#joined + * @type {Mongos} + * @param {string} type The type of member that left (mongos) + * @param {Server} server The server object that joined + */ + +module.exports = Mongos; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js new file mode 100644 index 0000000..913ca1b --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js @@ -0,0 +1,106 @@ +"use strict"; + +var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; + +/** + * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is + * used to construct connections. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * var cursor = server.cursor('db.test' + * , {find: 'db.test', query: {}} + * , {readPreference: new ReadPreference('secondary')}); + * cursor.next(function(err, doc) { + * server.destroy(); + * }); + * }); + * + * // Start connecting + * server.connect(); + */ + +/** + * Creates a new Pool instance + * @class + * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @param {object} tags The tags object + * @param {object} [options] Additional read preference options + * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest) + * @property {object} tags The tags object + * @property {object} options Additional read preference options + * @return {ReadPreference} + */ +var ReadPreference = function(preference, tags, options) { + this.preference = preference; + this.tags = tags; + this.options = options; +} + +/** + * This needs slaveOk bit set + * @method + * @return {boolean} + */ +ReadPreference.prototype.slaveOk = function() { + return needSlaveOk.indexOf(this.preference) != -1; +} + +/** + * Are the two read preference equal + * @method + * @return {boolean} + */ +ReadPreference.prototype.equals = function(readPreference) { + return readPreference.preference == this.preference; +} + +/** + * Return JSON representation + * @method + * @return {Object} + */ +ReadPreference.prototype.toJSON = function() { + var readPreference = {mode: this.preference}; + if(Array.isArray(this.tags)) readPreference.tags = this.tags; + return readPreference; +} + +/** + * Primary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primary = new ReadPreference('primary'); +/** + * Primary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); +/** + * Secondary read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondary = new ReadPreference('secondary'); +/** + * Secondary Preferred read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); +/** + * Nearest read preference + * @method + * @return {ReadPreference} + */ +ReadPreference.nearest = new ReadPreference('nearest'); + +module.exports = ReadPreference; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js new file mode 100644 index 0000000..011c8fe --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js @@ -0,0 +1,1333 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , b = require('bson') + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , debugOptions = require('../connection/utils').debugOptions + , EventEmitter = require('events').EventEmitter + , Server = require('./server') + , ReadPreference = require('./read_preference') + , MongoError = require('../error') + , Ping = require('./strategies/ping') + , Session = require('./session') + , BasicCursor = require('../cursor') + , BSON = require('bson').native().BSON + , State = require('./replset_state') + , Logger = require('../connection/logger'); + +/** + * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is + * used to construct connecctions. + * + * @example + * var ReplSet = require('mongodb-core').ReplSet + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// +// ReplSet instance id +var replSetId = 1; + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; + +/** + * Creates a new Replset instance + * @class + * @param {array} seedlist A list of seeds for the replicaset + * @param {boolean} options.setName The Replicaset set name + * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset + * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {ReplSet} A cursor instance + * @fires ReplSet#connect + * @fires ReplSet#ha + * @fires ReplSet#joined + * @fires ReplSet#left + */ +var ReplSet = function(seedlist, options) { + var self = this; + options = options || {}; + + // Validate seedlist + if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); + // Validate list + if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); + // Validate entries + seedlist.forEach(function(e) { + if(typeof e.host != 'string' || typeof e.port != 'number') + throw new MongoError("seedlist entry must contain a host and port"); + }); + + // Add event listener + EventEmitter.call(this); + + // Set the bson instance + bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; + + // Internal state hash for the object + this.s = { + options: options + // Logger instance + , logger: Logger('ReplSet', options) + // Uniquely identify the replicaset instance + , id: replSetId++ + // Index + , index: 0 + // Ha Index + , haId: 0 + // Current credentials used for auth + , credentials: [] + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Special replicaset options + , secondaryOnlyConnectionAllowed: typeof options.secondaryOnlyConnectionAllowed == 'boolean' + ? options.secondaryOnlyConnectionAllowed : false + , haInterval: options.haInterval || 10000 + // Are we running in debug mode + , debug: typeof options.debug == 'boolean' ? options.debug : false + // The replicaset name + , setName: options.setName + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // Currently connecting servers + , connectingServers: {} + // Contains any alternate strategies for picking + , readPreferenceStrategies: {} + // Auth providers + , authProviders: {} + // All the servers + , disconnectedServers: [] + // Initial connection servers + , initialConnectionServers: [] + // High availability process running + , highAvailabilityProcessRunning: false + // Full setup + , fullsetup: false + // All servers accounted for (used for testing) + , all: false + // Seedlist + , seedlist: seedlist + // Authentication in progress + , authInProgress: false + // Servers added while auth in progress + , authInProgressServers: [] + // Minimum heartbeat frequency used if we detect a server close + , minHeartbeatFrequencyMS: 500 + } + + // Add bson parser to options + options.bson = this.s.bson; + // Set up the connection timeout for the options + options.connectionTimeout = options.connectionTimeout || 10000; + + // Replicaset state + var replState = new State(this, { + id: this.s.id, setName: this.s.setName + , connectingServers: this.s.connectingServers + , secondaryOnlyConnectionAllowed: this.s.secondaryOnlyConnectionAllowed + }); + + // Add Replicaset state to our internal state + this.s.replState = replState; + + // BSON property (find a server and pass it along) + Object.defineProperty(this, 'bson', { + enumerable: true, get: function() { + var servers = self.s.replState.getAll(); + return servers.length > 0 ? servers[0].bson : null; + } + }); + + Object.defineProperty(this, 'id', { + enumerable:true, get: function() { return self.s.id; } + }); + + Object.defineProperty(this, 'haInterval', { + enumerable:true, get: function() { return self.s.haInterval; } + }); + + Object.defineProperty(this, 'state', { + enumerable:true, get: function() { return self.s.replState; } + }); + + // + // Debug options + if(self.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'readPreferenceStrategies', { + enumerable: true, get: function() { return self.s.readPreferenceStrategies; } + }); + } + + Object.defineProperty(this, 'type', { + enumerable:true, get: function() { return 'replset'; } + }); + + // Add the ping strategy for nearest + this.addReadPreferenceStrategy('nearest', new Ping(options)); +} + +inherits(ReplSet, EventEmitter); + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +ReplSet.prototype.addReadPreferenceStrategy = function(name, func) { + this.s.readPreferenceStrategies[name] = func; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +ReplSet.prototype.addAuthProvider = function(name, provider) { + if(this.s.authProviders == null) this.s.authProviders = {}; + this.s.authProviders[name] = provider; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +ReplSet.prototype.parserType = function() { + if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +ReplSet.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +ReplSet.prototype.lastIsMaster = function() { + return this.s.replState.lastIsMaster(); +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +ReplSet.prototype.getConnection = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + var server = pickServer(this, this.s, options.readPreference); + if(server == null) return null; + // Return connection + return server.getConnection(); +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +ReplSet.prototype.connections = function() { + return this.s.replState.getAllConnections(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +ReplSet.prototype.getServer = function(options) { + // Ensure we have no options + options = options || {}; + // Pick the right server based on readPreference + return pickServer(this, this.s, options.readPreference); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { + cursorOptions = cursorOptions || {}; + var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; + return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); +} + +// +// Execute write operation +var executeWriteOperation = function(self, op, ns, ops, options, callback) { + if(typeof options == 'function') { + callback = options; + options = {}; + } + + var server = null; + // Ensure we have no options + options = options || {}; + // Get a primary + try { + server = pickServer(self, self.s, ReadPreference.primary); + if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + + // Handler + var handler = function(err, r) { + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the result + callback(err, r); + } + + // Add operationId if existing + if(callback.operationId) handler.operationId = callback.operationId; + // Execute the command + server[op](ns, ops, options, handler); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + + var server = null; + var self = this; + // Ensure we have no options + options = options || {}; + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected(options) && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // We need to execute the command on all servers + if(options.onAll) { + var servers = this.s.replState.getAll(); + var count = servers.length; + var cmdErr = null; + + for(var i = 0; i < servers.length; i++) { + servers[i].command(ns, cmd, options, function(err, r) { + count = count - 1; + // Finished executing command + if(count == 0) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); + // Return the error + callback(err, r); + } + }); + } + + return; + } + + // Pick the right server based on readPreference + try { + server = pickServer(self, self.s, options.writeConcern ? ReadPreference.primary : options.readPreference); + if(self.s.debug) self.emit('pickedServer', options.writeConcern ? ReadPreference.primary : options.readPreference, server); + } catch(err) { + return callback(err); + } + + // No server returned we had an error + if(server == null) return callback(new MongoError("no server found")); + // Execute the command + server.command(ns, cmd, options, function(err, r) { + // Was it a logout command clear any credentials + if(cmd.logout) clearCredentials(self.s, ns); + // We have a no master error, immediately refresh the view of the replicaset + if(notMasterError(r) || notMasterError(err)) { + replicasetInquirer(self, self.s, true)(); + } + // Return the error + callback(err, r); + }); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + executeWriteOperation(this, 'remove', ns, ops, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + executeWriteOperation(this, 'insert', ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +ReplSet.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!this.isConnected() && this.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return this.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + executeWriteOperation(this, 'update', ns, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +ReplSet.prototype.auth = function(mechanism, db) { + var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(this.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // Authenticate against all the servers + var servers = this.s.replState.getAll().slice(0); + var count = servers.length; + // Correct authentication + var authenticated = true; + var authErr = null; + // Set auth in progress + this.s.authInProgress = true; + + // Authenticate against all servers + while(servers.length > 0) { + var server = servers.shift(); + + // Arguments without a callback + var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); + // Create arguments + var finalArguments = argsWithoutCallback.concat([function(err, r) { + count = count - 1; + if(err) authErr = err; + if(!r) authenticated = false; + + // We are done + if(count == 0) { + // We have more servers that are not authenticated, let's authenticate + if(self.s.authInProgressServers.length > 0) { + self.s.authInProgressServers = []; + return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); + } + + // Auth is done + self.s.authInProgress = false; + // Add successful credentials + if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); + // Return the auth error + if(authErr) return callback(authErr, false); + // Successfully authenticated session + callback(null, new Session({}, self)); + } + }]); + + // Execute the auth + server.auth.apply(server, finalArguments); + } +} + +ReplSet.prototype.state = function() { + return this.s.replState.state; +} + +/** + * Ensure single socket connections to arbiters and hidden servers + * @method + */ +var handleIsmaster = function(self) { + return function(ismaster, _server) { + if(ismaster.arbiterOnly) { + _server.s.options.size = 1; + } else if(ismaster.hidden) { + _server.s.options.size = 1; + } + } +} + +/** + * Initiate server connect + * @method + */ +ReplSet.prototype.connect = function(_options) { + var self = this; + // Start replicaset inquiry process + setTimeout(replicasetInquirer(this, this.s, false), this.s.haInterval); + // Additional options + if(_options) for(var name in _options) this.s.options[name] = _options[name]; + + // Set the state as connecting + this.s.replState.state = CONNECTING; + + // No fullsetup reached + this.s.fullsetup = false; + + // For all entries in the seedlist build a server instance + this.s.seedlist.forEach(function(e) { + // Clone options + var opts = cloneOptions(self.s.options); + // Add host and port + opts.host = e.host; + opts.port = e.port; + opts.reconnect = false; + opts.readPreferenceStrategies = self.s.readPreferenceStrategies; + opts.emitError = true; + if(self.s.tag) opts.tag = self.s.tag; + // Share the auth store + opts.authProviders = self.s.authProviders; + // Create a new Server + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Add to list of disconnected servers + self.s.disconnectedServers.push(server); + // Add to list of inflight Connections + self.s.initialConnectionServers.push(server); + }); + + // Attempt to connect to all the servers + while(this.s.disconnectedServers.length > 0) { + // Get the server + var server = this.s.disconnectedServers.shift(); + + // Set up the event handlers + server.once('error', errorHandlerTemp(this, this.s, 'error')); + server.once('close', errorHandlerTemp(this, this.s, 'close')); + server.once('timeout', errorHandlerTemp(this, this.s, 'timeout')); + server.once('connect', connectHandler(this, this.s)); + + // Attempt to connect + server.connect(); + } +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +ReplSet.prototype.isConnected = function(options) { + options = options || {}; + // If we specified a read preference check if we are connected to something + // than can satisfy this + if(options.readPreference + && options.readPreference.equals(ReadPreference.secondary)) + return this.s.replState.isSecondaryConnected(); + + if(options.readPreference + && options.readPreference.equals(ReadPreference.primary)) + return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); + + if(this.s.secondaryOnlyConnectionAllowed + && this.s.replState.isSecondaryConnected()) return true; + return this.s.replState.isPrimaryConnected(); +} + +/** + * Figure out if the replicaset instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +ReplSet.prototype.isDestroyed = function() { + return this.s.replState.state == DESTROYED; +} + +/** + * Destroy the server connection + * @method + */ +ReplSet.prototype.destroy = function(emitClose) { + var self = this; + if(this.s.logger.isInfo()) this.s.logger.info(f('[%s] destroyed', this.s.id)); + this.s.replState.state = DESTROYED; + + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + + // Destroy state + this.s.replState.destroy(); + + // Clear out any listeners + var events = ['timeout', 'error', 'close', 'joined', 'left']; + events.forEach(function(e) { + self.removeAllListeners(e); + }); +} + +/** + * A replset connect event, used to verify that the connection is up and running + * + * @event ReplSet#connect + * @type {ReplSet} + */ + +/** + * The replset high availability event + * + * @event ReplSet#ha + * @type {function} + * @param {string} type The stage in the high availability event (start|end) + * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only + * @param {number} data.id The id for this high availability request + * @param {object} data.state An object containing the information about the current replicaset + */ + +/** + * A server member left the replicaset + * + * @event ReplSet#left + * @type {function} + * @param {string} type The type of member that left (primary|secondary|arbiter) + * @param {Server} server The server object that left + */ + +/** + * A server member joined the replicaset + * + * @event ReplSet#joined + * @type {function} + * @param {string} type The type of member that joined (primary|secondary|arbiter) + * @param {Server} server The server object that joined + */ + +// +// Inquires about state changes +// + +// Add the new credential for a db, removing the old +// credential from the cache +var addCredentials = function(s, db, argsWithoutCallback) { + // Remove any credentials for the db + clearCredentials(s, db + ".dummy"); + // Add new credentials to list + s.credentials.push(argsWithoutCallback); +} + +// Clear out credentials for a namespace +var clearCredentials = function(s, ns) { + var db = ns.split('.')[0]; + var filteredCredentials = []; + + // Filter out all credentials for the db the user is logging out off + for(var i = 0; i < s.credentials.length; i++) { + if(s.credentials[i][1] != db) filteredCredentials.push(s.credentials[i]); + } + + // Set new list of credentials + s.credentials = filteredCredentials; +} + +// +// Filter serves by tags +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tags = readPreference.tags; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) filteredServers.push(servers[i]); + } + + // Returned filtered servers + return filteredServers; +} + +// +// Pick a server based on readPreference +var pickServer = function(self, s, readPreference) { + // If no read Preference set to primary by default + readPreference = readPreference || ReadPreference.primary; + + // Do we have a custom readPreference strategy, use it + if(s.readPreferenceStrategies != null && s.readPreferenceStrategies[readPreference.preference] != null) { + if(s.readPreferenceStrategies[readPreference.preference] == null) throw new MongoError(f("cannot locate read preference handler for %s", readPreference.preference)); + var server = s.readPreferenceStrategies[readPreference.preference].pickServer(s.replState, readPreference); + if(s.debug) self.emit('pickedServer', readPreference, server); + return server; + } + + // Filter out any hidden secondaries + var secondaries = s.replState.secondaries.filter(function(server) { + if(server.lastIsMaster().hidden) return false; + return true; + }); + + // Check if we can satisfy and of the basic read Preferences + if(readPreference.equals(ReadPreference.secondary) + && secondaries.length == 0) + throw new MongoError("no secondary server available"); + + if(readPreference.equals(ReadPreference.secondaryPreferred) + && secondaries.length == 0 + && s.replState.primary == null) + throw new MongoError("no secondary or primary server available"); + + if(readPreference.equals(ReadPreference.primary) + && s.replState.primary == null) + throw new MongoError("no primary server available"); + + // Secondary + if(readPreference.equals(ReadPreference.secondary)) { + s.index = (s.index + 1) % secondaries.length; + return secondaries[s.index]; + } + + // Secondary preferred + if(readPreference.equals(ReadPreference.secondaryPreferred)) { + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + } + + return s.replState.primary; + } + + // Primary preferred + if(readPreference.equals(ReadPreference.primaryPreferred)) { + if(s.replState.primary) return s.replState.primary; + + if(secondaries.length > 0) { + // Apply tags if present + var servers = filterByTags(readPreference, secondaries); + // If have a matching server pick one otherwise fall through to primary + if(servers.length > 0) { + s.index = (s.index + 1) % servers.length; + return servers[s.index]; + } + + // Throw error a we have not valid secondary or primary servers + throw new MongoError("no secondary or primary server available"); + } + } + + // Return the primary + return s.replState.primary; +} + +var replicasetInquirer = function(self, state, norepeat) { + return function() { + if(state.replState.state == DESTROYED) return + // Process already running don't rerun + if(state.highAvailabilityProcessRunning) return; + // Started processes + state.highAvailabilityProcessRunning = true; + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring process running %s', state.id, JSON.stringify(state.replState))); + + // Unique HA id to identify the current look running + var localHaId = state.haId++; + + // Clean out any failed connection attempts + state.connectingServers = {}; + + // Controls if we are doing a single inquiry or repeating + norepeat = typeof norepeat == 'boolean' ? norepeat : false; + + // If we have a primary and a disconnect handler, execute + // buffered operations + if(state.replState.isPrimaryConnected() && state.replState.isSecondaryConnected() && state.disconnectHandler) { + state.disconnectHandler.execute(); + } + + // Emit replicasetInquirer + self.emit('ha', 'start', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + + // Let's process all the disconnected servers + while(state.disconnectedServers.length > 0) { + // Get the first disconnected server + var server = state.disconnectedServers.shift(); + if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring attempting to connect to %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + // Attempt to connect + server.connect(); + } + + // Cleanup state (removed disconnected servers) + state.replState.clean(); + + // We need to query all servers + var servers = state.replState.getAll(); + var serversLeft = servers.length; + + // If no servers and we are not destroyed keep pinging + if(servers.length == 0 && state.replState.state == CONNECTED) { + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Restart ha process + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + + // + // ismaster for Master server + var primaryIsMaster = null; + + // Kill the server connection if it hangs + var timeoutServer = function(_server) { + return setTimeout(function() { + if(_server.isConnected()) { + _server.connections()[0].connection.destroy(); + } + }, self.s.options.connectionTimeout); + } + + // + // Inspect a specific servers ismaster + var inspectServer = function(server) { + if(state.replState.state == DESTROYED) return; + // Did we get a server + if(server && server.isConnected()) { + // Get the timeout id + var timeoutId = timeoutServer(server); + // Execute ismaster + server.command('system.$cmd', {ismaster:true}, function(err, r) { + // Clear out the timeoutServer + clearTimeout(timeoutId); + // If the state was destroyed + if(state.replState.state == DESTROYED) return; + // Count down the number of servers left + serversLeft = serversLeft - 1; + // If we have an error but still outstanding server request return + if(err && serversLeft > 0) return; + // We had an error and have no more servers to inspect, schedule a new check + if(err && serversLeft == 0) { + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunnfing + state.highAvailabilityProcessRunning = false; + // Return the replicasetInquirer + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + + // Let all the read Preferences do things to the servers + var rPreferencesCount = Object.keys(state.readPreferenceStrategies).length; + + // Handle the primary + var ismaster = r.result; + if(state.logger.isDebug()) state.logger.debug(f('[%s] monitoring process ismaster %s', state.id, JSON.stringify(ismaster))); + + // Update the replicaset state + state.replState.update(ismaster, server); + + // Add any new servers + if(err == null && ismaster.ismaster && Array.isArray(ismaster.hosts)) { + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + // Process all the hsots + processHosts(self, state, hosts); + } + + // No read Preferences strategies + if(rPreferencesCount == 0) { + // Don't schedule a new inquiry + if(serversLeft > 0) return; + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + + // No servers left to query, execute read preference strategies + if(serversLeft == 0) { + // Go over all the read preferences + for(var name in state.readPreferenceStrategies) { + state.readPreferenceStrategies[name].ha(self, state.replState, function() { + rPreferencesCount = rPreferencesCount - 1; + + if(rPreferencesCount == 0) { + // Add any new servers in primary ismaster + if(err == null + && ismaster.ismaster + && Array.isArray(ismaster.hosts)) { + processHosts(self, state, ismaster.hosts); + } + + // Emit ha process end + self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); + // Ended highAvailabilityProcessRunning + state.highAvailabilityProcessRunning = false; + // Let's keep monitoring + if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); + return; + } + }); + } + } + }); + } + } + + // Call ismaster on all servers + for(var i = 0; i < servers.length; i++) { + inspectServer(servers[i]); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + + // If all servers are accounted for and we have not sent the all event + if(state.replState.primary != null && self.lastIsMaster() + && Array.isArray(self.lastIsMaster().hosts) && !state.all) { + var length = 1 + state.replState.secondaries.length; + // If we have all secondaries + primary + if(length == self.lastIsMaster().hosts.length + 1) { + state.all = true; + self.emit('all', self); + } + } + } +} + +// Error handler for initial connect +var errorHandlerTemp = function(self, state, event) { + return function(err, server) { + // Log the information + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s disconnected', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + + // Connection is destroyed, ignore + if(state.replState.state == DESTROYED) return; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Push to list of disconnected servers + addToListIfNotExist(state.disconnectedServers, server); + + // End connection operation if we have no legal replicaset state + if(state.initialConnectionServers == 0 && state.replState.state == CONNECTING) { + if((state.secondaryOnlyConnectionAllowed && !state.replState.isSecondaryConnected() && !state.replState.isPrimaryConnected()) + || (!state.secondaryOnlyConnectionAllowed && !state.replState.isPrimaryConnected())) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) + return self.emit('error', new MongoError('no valid seed servers in list')); + } + } + + // If the number of disconnected servers is equal to + // the number of seed servers we cannot connect + if(state.disconnectedServers.length == state.seedlist.length && state.replState.state == CONNECTING) { + if(state.emitError && self.listeners('error').length > 0) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); + + if(self.listeners('error').length > 0) + self.emit('error', new MongoError('no valid seed servers in list')); + } + } + } +} + +// Connect handler +var connectHandler = function(self, state) { + return function(server) { + if(state.logger.isInfo()) state.logger.info(f('[%s] connected to %s', state.id, server.name)); + // Destroyed connection + if(state.replState.state == DESTROYED) { + server.destroy(false, false); + return; + } + + // Filter out any connection servers + state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { + return server.name != _server.name; + }); + + // Process the new server + var processNewServer = function() { + // Discover any additional servers + var ismaster = server.lastIsMaster(); + + var events = ['error', 'close', 'timeout', 'connect', 'message']; + // Remove any non used handlers + events.forEach(function(e) { + server.removeAllListeners(e); + }) + + // Clean up + delete state.connectingServers[server.name]; + // Update the replicaset state, destroy if not added + if(!state.replState.update(ismaster, server)) { + return server.destroy(); + } + + // Add the server handling code + if(server.isConnected()) { + server.on('error', errorHandler(self, state)); + server.on('close', closeHandler(self, state)); + server.on('timeout', timeoutHandler(self, state)); + } + + // Hosts to process + var hosts = ismaster.hosts; + // Add arbiters to list of hosts if we have any + if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); + if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); + + // Add any new servers + processHosts(self, state, hosts); + + // If have the server instance already destroy it + if(state.initialConnectionServers.length == 0 && Object.keys(state.connectingServers).length == 0 + && !state.replState.isPrimaryConnected() && !state.secondaryOnlyConnectionAllowed && state.replState.state == CONNECTING) { + if(state.logger.isInfo()) state.logger.info(f('[%s] no primary found in replicaset', state.id)); + self.emit('error', new MongoError("no primary found in replicaset")); + return self.destroy(); + } + + // If no more initial servers and new scheduled servers to connect + if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { + state.fullsetup = true; + self.emit('fullsetup', self); + } + } + + // Save up new members to be authenticated against + if(self.s.authInProgress) { + self.s.authInProgressServers.push(server); + } + + // No credentials just process server + if(state.credentials.length == 0) return processNewServer(); + // Do we have credentials, let's apply them all + var count = state.credentials.length; + // Apply the credentials + for(var i = 0; i < state.credentials.length; i++) { + server.auth.apply(server, state.credentials[i].concat([function(err, r) { + count = count - 1; + if(count == 0) processNewServer(); + }])); + } + } +} + +// +// Detect if we need to add new servers +var processHosts = function(self, state, hosts) { + if(state.replState.state == DESTROYED) return; + if(Array.isArray(hosts)) { + // Check any hosts exposed by ismaster + for(var i = 0; i < hosts.length; i++) { + // If not found we need to create a new connection + if(!state.replState.contains(hosts[i])) { + if(state.connectingServers[hosts[i]] == null && !inInitialConnectingServers(self, state, hosts[i])) { + if(state.logger.isInfo()) state.logger.info(f('[%s] scheduled server %s for connection', state.id, hosts[i])); + // Make sure we know what is trying to connect + state.connectingServers[hosts[i]] = hosts[i]; + // Connect the server + connectToServer(self, state, hosts[i].split(':')[0], parseInt(hosts[i].split(':')[1], 10)); + } + } + } + } +} + +var inInitialConnectingServers = function(self, state, address) { + for(var i = 0; i < state.initialConnectionServers.length; i++) { + if(state.initialConnectionServers[i].name == address) return true; + } + return false; +} + +// Connect to a new server +var connectToServer = function(self, state, host, port) { + var opts = cloneOptions(state.options); + opts.host = host; + opts.port = port; + opts.reconnect = false; + opts.readPreferenceStrategies = state.readPreferenceStrategies; + if(state.tag) opts.tag = state.tag; + // Share the auth store + opts.authProviders = state.authProviders; + opts.emitError = true; + // Create a new server instance + var server = new Server(opts); + // Handle the ismaster + server.on('ismaster', handleIsmaster(self)); + // Set up the event handlers + server.once('error', errorHandlerTemp(self, state, 'error')); + server.once('close', errorHandlerTemp(self, state, 'close')); + server.once('timeout', errorHandlerTemp(self, state, 'timeout')); + server.once('connect', connectHandler(self, state)); + // Attempt to connect + server.connect(); +} + +// +// Add server to the list if it does not exist +var addToListIfNotExist = function(list, server) { + var found = false; + + // Remove any non used handlers + ['error', 'close', 'timeout', 'connect'].forEach(function(e) { + server.removeAllListeners(e); + }) + + // Check if the server already exists + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) found = true; + } + + if(!found) { + list.push(server); + } + + return found; +} + +var errorHandler = function(self, state) { + return function(err, server) { + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s errored out with %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name, JSON.stringify(err))); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + if(found && state.emitError && self.listeners('error').length > 0) self.emit('error', err, server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + replicasetInquirer(self, self.s, true)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var timeoutHandler = function(self, state) { + return function(err, server) { + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s timed out', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + replicasetInquirer(self, self.s, true)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +var closeHandler = function(self, state) { + return function(err, server) { + if(state.replState.state == DESTROYED) return; + if(state.logger.isInfo()) state.logger.info(f('[%s] server %s closed', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); + var found = addToListIfNotExist(state.disconnectedServers, server); + if(!found) self.emit('left', state.replState.remove(server), server); + + // Fire off a detection of missing server using minHeartbeatFrequencyMS + setTimeout(function() { + replicasetInquirer(self, self.s, true)(); + }, self.s.minHeartbeatFrequencyMS); + } +} + +// +// Validate if a non-master or recovering error +var notMasterError = function(r) { + // Get result of any + var result = r && r.result ? r.result : r; + + // Explore if we have a not master error + if(result && (result.err == 'not master' + || result.errmsg == 'not master' || (result['$err'] && result['$err'].indexOf('not master or secondary') != -1) + || (result['$err'] && result['$err'].indexOf("not master and slaveOk=false") != -1) + || result.errmsg == 'node is recovering')) { + return true; + } + + return false; +} + +module.exports = ReplSet; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js new file mode 100644 index 0000000..951a043 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js @@ -0,0 +1,483 @@ +"use strict"; + +var Logger = require('../connection/logger') + , f = require('util').format + , ObjectId = require('bson').ObjectId + , MongoError = require('../error'); + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +/** + * Creates a new Replicaset State object + * @class + * @property {object} primary Primary property + * @property {array} secondaries List of secondaries + * @property {array} arbiters List of arbiters + * @return {State} A cursor instance + */ +var State = function(replSet, options) { + this.replSet = replSet; + this.options = options; + this.secondaries = []; + this.arbiters = []; + this.passives = []; + this.primary = null; + // Initial state is disconnected + this.state = DISCONNECTED; + // Current electionId + this.electionId = null; + // Get a logger instance + this.logger = Logger('ReplSet', options); + // Unpacked options + this.id = options.id; + this.setName = options.setName; + this.connectingServers = options.connectingServers; + this.secondaryOnlyConnectionAllowed = options.secondaryOnlyConnectionAllowed; +} + +/** + * Is there a secondary connected + * @method + * @return {boolean} + */ +State.prototype.isSecondaryConnected = function() { + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].isConnected()) return true; + } + + return false; +} + +/** + * Is there a primary connection + * @method + * @return {boolean} + */ +State.prototype.isPrimaryConnected = function() { + return this.primary != null && this.primary.isConnected(); +} + +/** + * Is the given address the primary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPrimary = function(address) { + if(this.primary == null) return false; + return this.primary && this.primary.equals(address); +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isSecondary = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Is the given address a secondary + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.isPassive = function(address) { + // Check if the server is a secondary at the moment + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) { + return true; + } + } + + return false; +} + +/** + * Does the replicaset contain this server + * @method + * @param {string} address Server address + * @return {boolean} + */ +State.prototype.contains = function(address) { + if(this.primary && this.primary.equals(address)) return true; + for(var i = 0; i < this.secondaries.length; i++) { + if(this.secondaries[i].equals(address)) return true; + } + + for(var i = 0; i < this.arbiters.length; i++) { + if(this.arbiters[i].equals(address)) return true; + } + + for(var i = 0; i < this.passives.length; i++) { + if(this.passives[i].equals(address)) return true; + } + + return false; +} + +/** + * Clean out all dead connections + * @method + */ +State.prototype.clean = function() { + if(this.primary != null && !this.primary.isConnected()) { + this.primary = null; + } + + // Filter out disconnected servers + this.secondaries = this.secondaries.filter(function(s) { + return s.isConnected(); + }); + + // Filter out disconnected servers + this.arbiters = this.arbiters.filter(function(s) { + return s.isConnected(); + }); +} + +/** + * Destroy state + * @method + */ +State.prototype.destroy = function() { + this.state = DESTROYED; + if(this.primary) this.primary.destroy(); + this.secondaries.forEach(function(s) { + s.destroy(); + }); +} + +/** + * Remove server from state + * @method + * @param {Server} Server to remove + * @return {string} Returns type of server removed (primary|secondary) + */ +State.prototype.remove = function(server) { + if(this.primary && this.primary.equals(server)) { + this.primary = null; + } + + var length = this.arbiters.length; + // Filter out the server from the arbiters + this.arbiters = this.arbiters.filter(function(s) { + return !s.equals(server); + }); + if(this.arbiters.length < length) return 'arbiter'; + + var length = this.passives.length; + // Filter out the server from the passives + this.passives = this.passives.filter(function(s) { + return !s.equals(server); + }); + + // We have removed a passive + if(this.passives.length < length) { + // Ensure we removed it from the list of secondaries as well if it exists + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + } + + // Filter out the server from the secondaries + this.secondaries = this.secondaries.filter(function(s) { + return !s.equals(server); + }); + + // Get the isMaster + var isMaster = server.lastIsMaster(); + // Return primary if the server was primary + if(isMaster.ismaster) return 'primary'; + if(isMaster.secondary) return 'secondary'; + if(isMaster.passive) return 'passive'; + return 'arbiter'; +} + +/** + * Get the server by name + * @method + * @param {string} address Server address + * @return {Server} + */ +State.prototype.get = function(server) { + var found = false; + // All servers to search + var servers = this.primary ? [this.primary] : []; + servers = servers.concat(this.secondaries); + // Locate the server + for(var i = 0; i < servers.length; i++) { + if(servers[i].equals(server)) { + return servers[i]; + } + } +} + +/** + * Get all the servers in the set + * @method + * @return {array} + */ +State.prototype.getAll = function() { + var servers = []; + if(this.primary) servers.push(this.primary); + return servers.concat(this.secondaries); +} + +/** + * All raw connections + * @method + * @return {array} + */ +State.prototype.getAllConnections = function() { + var connections = []; + if(this.primary) connections = connections.concat(this.primary.connections()); + this.secondaries.forEach(function(s) { + connections = connections.concat(s.connections()); + }) + + return connections; +} + +/** + * Return JSON object + * @method + * @return {object} + */ +State.prototype.toJSON = function() { + return { + primary: this.primary ? this.primary.lastIsMaster().me : null + , secondaries: this.secondaries.map(function(s) { + return s.lastIsMaster().me + }) + } +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +State.prototype.lastIsMaster = function() { + if(this.primary) return this.primary.lastIsMaster(); + if(this.secondaries.length > 0) return this.secondaries[0].lastIsMaster(); + return {}; +} + +/** + * Promote server to primary + * @method + * @param {Server} server Server we wish to promote + */ +State.prototype.promotePrimary = function(server) { + var currentServer = this.get(server); + // Server does not exist in the state, add it as new primary + if(currentServer == null) { + this.primary = server; + return; + } + + // We found a server, make it primary and remove it from the secondaries + // Remove the server first + this.remove(currentServer); + // Set as primary + this.primary = currentServer; +} + +var add = function(list, server) { + // Check if the server is a secondary at the moment + for(var i = 0; i < list.length; i++) { + if(list[i].equals(server)) return false; + } + + list.push(server); + return true; +} + +/** + * Add server to list of secondaries + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addSecondary = function(server) { + return add(this.secondaries, server); +} + +/** + * Add server to list of arbiters + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addArbiter = function(server) { + return add(this.arbiters, server); +} + +/** + * Add server to list of passives + * @method + * @param {Server} server Server we wish to add + */ +State.prototype.addPassive = function(server) { + return add(this.passives, server); +} + +var compareObjectIds = function(id1, id2) { + var a = new Buffer(id1.toHexString(), 'hex'); + var b = new Buffer(id2.toHexString(), 'hex'); + + if(a === b) { + return 0; + } + + if(typeof Buffer.compare === 'function') { + return Buffer.compare(a, b); + } + + var x = a.length; + var y = b.length; + var len = Math.min(x, y); + + for (var i = 0; i < len; i++) { + if (a[i] !== b[i]) { + break; + } + } + + if (i !== len) { + x = a[i]; + y = b[i]; + } + + return x < y ? -1 : y < x ? 1 : 0; +} + +/** + * Update the state given a specific ismaster result + * @method + * @param {object} ismaster IsMaster result + * @param {Server} server IsMaster Server source + */ +State.prototype.update = function(ismaster, server) { + var self = this; + // Not in a known connection valid state + if(!ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { + // Remove the state + var result = self.remove(server); + if(self.state == CONNECTED) { + if(self.logger.isInfo()) self.logger.info(f('[%s] removing %s from set', self.id, ismaster.me)); + self.replSet.emit('left', self.remove(server), server); + } + + return false; + } + + // Set the setName if it's not set from the first server + if(self.setName == null && ismaster.setName) { + if(self.logger.isInfo()) self.logger.info(f('[%s] setting setName to %s', self.id, ismaster.setName)); + self.setName = ismaster.setName; + } + + // Check if the replicaset name matches the provided one + if(ismaster.setName && self.setName != ismaster.setName) { + if(self.logger.isError()) self.logger.error(f('[%s] server in replset %s is not part of the specified setName %s', self.id, ismaster.setName, self.setName)); + self.remove(server); + self.replSet.emit('error', new MongoError("provided setName for Replicaset Connection does not match setName found in server seedlist")); + return false; + } + + // Log information + if(self.logger.isInfo()) self.logger.info(f('[%s] updating replicaset state %s', self.id, JSON.stringify(this))); + + // It's a master set it + if(ismaster.ismaster && self.setName == ismaster.setName && !self.isPrimary(ismaster.me)) { + // Check if the electionId is not null + if(ismaster.electionId instanceof ObjectId && self.electionId instanceof ObjectId) { + if(compareObjectIds(self.electionId, ismaster.electionId) == -1) { + self.electionId = ismaster.electionId; + } else if(compareObjectIds(self.electionId, ismaster.electionId) == 0) { + self.electionId = ismaster.electionId; + } else { + return false; + } + } + + // Initial electionId + if(ismaster.electionId instanceof ObjectId && self.electionId == null) { + self.electionId = ismaster.electionId; + } + + // Promote to primary + self.promotePrimary(server); + // Log change of primary + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to primary', self.id, ismaster.me)); + // Emit primary + self.replSet.emit('joined', 'primary', this.primary); + + // We are connected + if(self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } else { + self.state = CONNECTED; + self.replSet.emit('reconnect', server); + } + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.arbiterOnly) { + if(self.addArbiter(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to arbiter', self.id, ismaster.me)); + self.replSet.emit('joined', 'arbiter', server); + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary && ismaster.passive) { + if(self.addPassive(server) && self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to passive', self.id, ismaster.me)); + self.replSet.emit('joined', 'passive', server); + + // If we have secondaryOnlyConnectionAllowed and just a passive it's + // still a valid connection + if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } + + return true; + }; + + return false; + } else if(!ismaster.ismaster && self.setName == ismaster.setName + && ismaster.secondary) { + if(self.addSecondary(server)) { + if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to secondary', self.id, ismaster.me)); + self.replSet.emit('joined', 'secondary', server); + + if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { + self.state = CONNECTED; + self.replSet.emit('connect', self.replSet); + } + + return true; + }; + + return false; + } + + // Return update applied + return true; +} + +module.exports = State; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js new file mode 100644 index 0000000..0fae9ea --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js @@ -0,0 +1,1230 @@ + "use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain + , EventEmitter = require('events').EventEmitter + , Pool = require('../connection/pool') + , b = require('bson') + , Query = require('../connection/commands').Query + , MongoError = require('../error') + , ReadPreference = require('./read_preference') + , BasicCursor = require('../cursor') + , CommandResult = require('./command_result') + , getSingleProperty = require('../connection/utils').getSingleProperty + , getProperty = require('../connection/utils').getProperty + , debugOptions = require('../connection/utils').debugOptions + , BSON = require('bson').native().BSON + , PreTwoSixWireProtocolSupport = require('../wireprotocol/2_4_support') + , TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support') + , ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support') + , Session = require('./session') + , Logger = require('../connection/logger') + , MongoCR = require('../auth/mongocr') + , X509 = require('../auth/x509') + , Plain = require('../auth/plain') + , GSSAPI = require('../auth/gssapi') + , SSPI = require('../auth/sspi') + , ScramSHA1 = require('../auth/scram'); + +/** + * @fileOverview The **Server** class is a class that represents a single server topology and is + * used to construct connections. + * + * @example + * var Server = require('mongodb-core').Server + * , ReadPreference = require('mongodb-core').ReadPreference + * , assert = require('assert'); + * + * var server = new Server({host: 'localhost', port: 27017}); + * // Wait for the connection event + * server.on('connect', function(server) { + * server.destroy(); + * }); + * + * // Start connecting + * server.connect(); + */ + +// All bson types +var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; +// BSON parser +var bsonInstance = null; +// Server instance id +var serverId = 0; +// Callbacks instance id +var callbackId = 0; + +// Single store for all callbacks +var Callbacks = function() { + // EventEmitter.call(this); + var self = this; + // Callbacks + this.callbacks = {}; + // Set the callbacks id + this.id = callbackId++; + // Set the type to server + this.type = 'server'; +} + +// +// Clone the options +var cloneOptions = function(options) { + var opts = {}; + for(var name in options) { + opts[name] = options[name]; + } + return opts; +} + +// +// Flush all callbacks +Callbacks.prototype.flush = function(err) { + for(var id in this.callbacks) { + if(!isNaN(parseInt(id, 10))) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, null); + } + } +} + +Callbacks.prototype.emit = function(id, err, value) { + var callback = this.callbacks[id]; + delete this.callbacks[id]; + callback(err, value); +} + +Callbacks.prototype.raw = function(id) { + if(this.callbacks[id] == null) return false; + return this.callbacks[id].raw == true ? true : false +} + +Callbacks.prototype.documentsReturnedIn = function(id) { + if(this.callbacks[id] == null) return false; + return typeof this.callbacks[id].documentsReturnedIn == 'string' ? this.callbacks[id].documentsReturnedIn : null; +} + +Callbacks.prototype.unregister = function(id) { + delete this.callbacks[id]; +} + +Callbacks.prototype.register = function(id, callback) { + this.callbacks[id] = bindToCurrentDomain(callback); +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) return callback; + return domain.bind(callback); +} + +var DISCONNECTED = 'disconnected'; +var CONNECTING = 'connecting'; +var CONNECTED = 'connected'; +var DESTROYED = 'destroyed'; + +// Supports server +var supportsServer = function(_s) { + return _s.ismaster && typeof _s.ismaster.minWireVersion == 'number'; +} + +// +// createWireProtocolHandler +var createWireProtocolHandler = function(result) { + // 3.2 wire protocol handler + if(result && result.maxWireVersion >= 4) { + return new ThreeTwoWireProtocolSupport(new TwoSixWireProtocolSupport()); + } + + // 2.6 wire protocol handler + if(result && result.maxWireVersion >= 2) { + return new TwoSixWireProtocolSupport(); + } + + // 2.4 or earlier wire protocol handler + return new PreTwoSixWireProtocolSupport(); +} + +// +// Reconnect server +var reconnectServer = function(self, state) { + // If the current reconnect retries is 0 stop attempting to reconnect + if(state.currentReconnectRetry == 0) { + return self.destroy(true, true); + } + + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + + // Set status to connecting + state.state = CONNECTING; + // Create a new Pool + state.pool = new Pool(state.options); + // error handler + var reconnectErrorHandler = function(err) { + state.state = DISCONNECTED; + // Destroy the pool + state.pool.destroy(); + // Adjust the number of retries + state.currentReconnectRetry = state.currentReconnectRetry - 1; + // No more retries + if(state.currentReconnectRetry <= 0) { + self.state = DESTROYED; + self.emit('error', f('failed to connect to %s:%s after %s retries', state.options.host, state.options.port, state.reconnectTries)); + } else { + setTimeout(function() { + reconnectServer(self, state); + }, state.reconnectInterval); + } + } + + // + // Attempt to connect + state.pool.once('connect', function() { + // Reset retries + state.currentReconnectRetry = state.reconnectTries; + + // Remove any non used handlers + var events = ['error', 'close', 'timeout', 'parseError']; + events.forEach(function(e) { + state.pool.removeAllListeners(e); + }); + + // Set connected state + state.state = CONNECTED; + + // Add proper handlers + state.pool.once('error', reconnectErrorHandler); + state.pool.once('close', closeHandler(self, state)); + state.pool.once('timeout', timeoutHandler(self, state)); + state.pool.once('parseError', fatalErrorHandler(self, state)); + + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return self.emit('reconnect', self); + + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return self.emit('reconnect', self); + } + }); + } + }); + + // + // Handle connection failure + state.pool.once('error', errorHandler(self, state)); + state.pool.once('close', errorHandler(self, state)); + state.pool.once('timeout', errorHandler(self, state)); + state.pool.once('parseError', errorHandler(self, state)); + + // Connect pool + state.pool.connect(); +} + +// +// Handlers +var messageHandler = function(self, state) { + return function(response, connection) { + try { + // Parse the message + response.parse({raw: state.callbacks.raw(response.responseTo), documentsReturnedIn: state.callbacks.documentsReturnedIn(response.responseTo)}); + if(state.logger.isDebug()) state.logger.debug(f('message [%s] received from %s', response.raw.toString('hex'), self.name)); + state.callbacks.emit(response.responseTo, null, response); + } catch (err) { + state.callbacks.flush(new MongoError(err)); + self.destroy(); + } + } +} + +var errorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Destroy all connections + self.destroy(); + // Emit error event + if(state.emitError && self.listeners('error').length > 0) self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + } +} + +var fatalErrorHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); + // Emit error event + if(self.listeners('error').length > 0) self.emit('error', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } +} + +var timeoutHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'timeout', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s timed out', self.name)); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s timed out", self.name))); + // Emit error event + self.emit('timeout', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } +} + +var closeHandler = function(self, state) { + return function(err, connection) { + if(state.state == DISCONNECTED || state.state == DESTROYED) return; + // Set disconnected state + state.state = DISCONNECTED; + + if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'close', [self]); + if(state.logger.isInfo()) state.logger.info(f('server %s closed', self.name)); + // Flush out all the callbacks + if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); + // Emit error event + self.emit('close', err, self); + // If we specified the driver to reconnect perform it + if(state.reconnect) setTimeout(function() { + // state.currentReconnectRetry = state.reconnectTries, + reconnectServer(self, state) + }, state.reconnectInterval); + // Destroy all connections + self.destroy(); + } +} + +var connectHandler = function(self, state) { + // Apply all stored authentications + var applyAuthentications = function(callback) { + // We need to ensure we have re-authenticated + var keys = Object.keys(state.authProviders); + if(keys.length == 0) return callback(null, null); + + // Execute all providers + var count = keys.length; + // Iterate over keys + for(var i = 0; i < keys.length; i++) { + state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { + count = count - 1; + // We are done, emit reconnect event + if(count == 0) { + return callback(null, null); + } + }); + } + } + + return function(connection) { + // Apply any applyAuthentications + applyAuthentications(function() { + + // Execute an ismaster + self.command('system.$cmd', {ismaster:true}, function(err, r) { + if(err) { + state.state = DISCONNECTED; + return self.emit('close', err, self); + } + + // Set the current ismaster + if(!err) { + state.ismaster = r.result; + } + + // Emit the ismaster + self.emit('ismaster', r.result, self); + + // Determine the wire protocol handler + state.wireProtocolHandler = createWireProtocolHandler(state.ismaster); + + // Set the wireProtocolHandler + state.options.wireProtocolHandler = state.wireProtocolHandler; + + // Log the ismaster if available + if(state.logger.isInfo()) state.logger.info(f('server %s connected with ismaster [%s]', self.name, JSON.stringify(r.result))); + + // Validate if we it's a server we can connect to + if(!supportsServer(state) && state.wireProtocolHandler == null) { + state.state = DISCONNECTED + return self.emit('error', new MongoError("non supported server version"), self); + } + + // Set the details + if(state.ismaster && state.ismaster.me) state.serverDetails.name = state.ismaster.me; + + // No read preference strategies just emit connect + if(state.readPreferenceStrategies == null) { + state.state = CONNECTED; + return self.emit('connect', self); + } + + // Signal connect to all readPreferences + notifyStrategies(self, self.s, 'connect', [self], function(err, result) { + state.state = CONNECTED; + return self.emit('connect', self); + }); + }); + }); + } +} + +var slaveOk = function(r) { + if(r) return r.slaveOk() + return false; +} + +// +// Execute readPreference Strategies +var notifyStrategies = function(self, state, op, params, callback) { + if(typeof callback != 'function') { + // Notify query start to any read Preference strategies + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + strat[op].apply(strat, params); + } + } + // Finish up + return; + } + + // Execute the async callbacks + var nPreferences = Object.keys(state.readPreferenceStrategies).length; + if(nPreferences == 0) return callback(null, null); + for(var name in state.readPreferenceStrategies) { + if(state.readPreferenceStrategies[name][op]) { + var strat = state.readPreferenceStrategies[name]; + // Add a callback to params + var cParams = params.slice(0); + cParams.push(function(err, r) { + nPreferences = nPreferences - 1; + if(nPreferences == 0) { + callback(null, null); + } + }) + // Execute the readPreference + strat[op].apply(strat, cParams); + } + } +} + +var debugFields = ['reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host' + , 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout' + , 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs']; + +/** + * Creates a new Server instance + * @class + * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection + * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times + * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries + * @param {boolean} [options.emitError=false] Server will emit errors events + * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors + * @param {string} options.host The server host + * @param {number} options.port The server port + * @param {number} [options.size=5] Server connection pool size + * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled + * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled + * @param {boolean} [options.noDelay=true] TCP Connection no delay + * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting + * @param {number} [options.socketTimeout=0] TCP Socket timeout setting + * @param {boolean} [options.ssl=false] Use SSL for connection + * @param {Buffer} [options.ca] SSL Certificate store binary buffer + * @param {Buffer} [options.cert] SSL Certificate binary buffer + * @param {Buffer} [options.key] SSL Key file binary buffer + * @param {string} [options.passphrase] SSL Certificate pass phrase + * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates + * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits + * @return {Server} A cursor instance + * @fires Server#connect + * @fires Server#close + * @fires Server#error + * @fires Server#timeout + * @fires Server#parseError + * @fires Server#reconnect + */ +var Server = function(options) { + var self = this; + + // Add event listener + EventEmitter.call(this); + + // BSON Parser, ensure we have a single instance + if(bsonInstance == null) { + bsonInstance = new BSON(bsonTypes); + } + + // Reconnect retries + var reconnectTries = options.reconnectTries || 30; + + // Keeps all the internal state of the server + this.s = { + // Options + options: options + // Contains all the callbacks + , callbacks: new Callbacks() + // Logger + , logger: Logger('Server', options) + // Server state + , state: DISCONNECTED + // Reconnect option + , reconnect: typeof options.reconnect == 'boolean' ? options.reconnect : true + , reconnectTries: reconnectTries + , reconnectInterval: options.reconnectInterval || 1000 + // Swallow or emit errors + , emitError: typeof options.emitError == 'boolean' ? options.emitError : false + // Current state + , currentReconnectRetry: reconnectTries + // Contains the ismaster + , ismaster: null + // Contains any alternate strategies for picking + , readPreferenceStrategies: options.readPreferenceStrategies + // Auth providers + , authProviders: options.authProviders || {} + // Server instance id + , id: serverId++ + // Grouping tag used for debugging purposes + , tag: options.tag + // Do we have a not connected handler + , disconnectHandler: options.disconnectHandler + // wireProtocolHandler methods + , wireProtocolHandler: options.wireProtocolHandler || new PreTwoSixWireProtocolSupport() + // Factory overrides + , Cursor: options.cursorFactory || BasicCursor + // BSON Parser, ensure we have a single instance + , bsonInstance: bsonInstance + // Pick the right bson parser + , bson: options.bson ? options.bson : bsonInstance + // Internal connection pool + , pool: null + // Server details + , serverDetails: { + host: options.host + , port: options.port + , name: options.port ? f("%s:%s", options.host, options.port) : options.host + } + } + + // Reference state + var s = this.s; + + // Add bson parser to options + options.bson = s.bson; + + // Set error properties + getProperty(this, 'name', 'name', s.serverDetails, {}); + getProperty(this, 'bson', 'bson', s.options, {}); + getProperty(this, 'wireProtocolHandler', 'wireProtocolHandler', s.options, {}); + getSingleProperty(this, 'id', s.id); + + // Add auth providers + this.addAuthProvider('mongocr', new MongoCR()); + this.addAuthProvider('x509', new X509()); + this.addAuthProvider('plain', new Plain()); + this.addAuthProvider('gssapi', new GSSAPI()); + this.addAuthProvider('sspi', new SSPI()); + this.addAuthProvider('scram-sha-1', new ScramSHA1()); +} + +inherits(Server, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} type Type of BSON parser to use (c++ or js) + */ +Server.prototype.setBSONParserType = function(type) { + var nBSON = null; + + if(type == 'c++') { + nBSON = require('bson').native().BSON; + } else if(type == 'js') { + nBSON = require('bson').pure().BSON; + } else { + throw new MongoError(f("% parser not supported", type)); + } + + this.s.options.bson = new nBSON(bsonTypes); +} + +/** + * Returns the last known ismaster document for this server + * @method + * @return {object} + */ +Server.prototype.lastIsMaster = function() { + return this.s.ismaster; +} + +/** + * Initiate server connect + * @method + */ +Server.prototype.connect = function(_options) { + var self = this; + // Set server specific settings + _options = _options || {} + // Set the promotion + if(typeof _options.promoteLongs == 'boolean') { + self.s.options.promoteLongs = _options.promoteLongs; + } + + // Destroy existing pool + if(self.s.pool) { + self.s.pool.destroy(); + self.s.pool = null; + } + + // Set the state to connection + self.s.state = CONNECTING; + // Create a new connection pool + if(!self.s.pool) { + self.s.options.messageHandler = messageHandler(self, self.s); + self.s.pool = new Pool(self.s.options); + } + + // Add all the event handlers + self.s.pool.once('timeout', timeoutHandler(self, self.s)); + self.s.pool.once('close', closeHandler(self, self.s)); + self.s.pool.once('error', errorHandler(self, self.s)); + self.s.pool.once('connect', connectHandler(self, self.s)); + self.s.pool.once('parseError', fatalErrorHandler(self, self.s)); + + // Connect the pool + self.s.pool.connect(); +} + +/** + * Destroy the server connection + * @method + */ +Server.prototype.destroy = function(emitClose, emitDestroy) { + var self = this; + if(self.s.logger.isDebug()) self.s.logger.debug(f('destroy called on server %s', self.name)); + // Emit close + if(emitClose && self.listeners('close').length > 0) self.emit('close', self); + + // Emit destroy event + if(emitDestroy) self.emit('destroy', self); + // Set state as destroyed + self.s.state = DESTROYED; + // Close the pool + self.s.pool.destroy(); + // Flush out all the callbacks + if(self.s.callbacks) self.s.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); +} + +/** + * Figure out if the server is connected + * @method + * @return {boolean} + */ +Server.prototype.isConnected = function() { + var self = this; + if(self.s.pool) return self.s.pool.isConnected(); + return false; +} + +/** + * Figure out if the server instance was destroyed by calling destroy + * @method + * @return {boolean} + */ +Server.prototype.isDestroyed = function() { + return this.s.state == DESTROYED; +} + +var executeSingleOperation = function(self, ns, cmd, queryOptions, options, onAll, callback) { + // Create a query instance + var query = new Query(self.s.bson, ns, cmd, queryOptions); + + // Set slave OK + query.slaveOk = slaveOk(options.readPreference); + + // Notify query start to any read Preference strategies + if(self.s.readPreferenceStrategies != null) + notifyStrategies(self, self.s, 'startOperation', [self, query, new Date()]); + + // Get a connection (either passed or from the pool) + var connection = options.connection || self.s.pool.get(); + + // Double check if we have a valid connection + if(!connection.isConnected()) { + return callback(new MongoError(f("no connection available to server %s", self.name))); + } + + // Print cmd and execution connection if in debug mode for logging + if(self.s.logger.isDebug()) { + var json = connection.toJSON(); + self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(cmd), json.id, json.host, json.port)); + } + + // Execute multiple queries + if(onAll) { + var connections = self.s.pool.getAll(); + var total = connections.length; + // We have an error + var error = null; + // Execute on all connections + for(var i = 0; i < connections.length; i++) { + try { + query.incRequestId(); + connections[i].write(query.toBin()); + } catch(err) { + total = total - 1; + if(total == 0) return callback(MongoError.create(err)); + } + + // Register the callback + self.s.callbacks.register(query.requestId, function(err, result) { + if(err) error = err; + total = total - 1; + + // Done + if(total == 0) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, error, result, new Date()]); + if(error) return callback(MongoError.create(error)); + // Execute callback, catch and rethrow if needed + try { callback(null, new CommandResult(result.documents[0], connections)); } + catch(err) { process.nextTick(function() { throw err}); } + } + }); + } + + return; + } + + // Execute a single command query + try { + connection.write(query.toBin()); + } catch(err) { + return callback(MongoError.create(err)); + } + + // Register the callback + self.s.callbacks.register(query.requestId, function(err, result) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); + if(err) return callback(err); + if(result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || result.documents[0]['err'] + || result.documents[0]['code']) return callback(MongoError.create(result.documents[0])); + // Execute callback, catch and rethrow if needed + try { callback(null, new CommandResult(result.documents[0], connection)); } + catch(err) { process.nextTick(function() { throw err}); } + }); +} + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Connection} [options.connection] Specify connection object to execute command against + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.command = function(ns, cmd, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Ensure we have no options + options = options || {}; + // Do we have a read Preference it need to be of type ReadPreference + if(options.readPreference && !(options.readPreference instanceof ReadPreference)) { + throw new Error("readPreference must be an instance of ReadPreference"); + } + + // Debug log + if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command [%s] against %s', JSON.stringify({ + ns: ns, cmd: cmd, options: debugOptions(debugFields, options) + }), self.name)); + + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('command', ns, cmd, options, callback); + } + + // If we have no connection error + if(!self.s.pool.isConnected()) return callback(new MongoError(f("no connection available to server %s", self.name))); + + // Execute on all connections + var onAll = typeof options.onAll == 'boolean' ? options.onAll : false; + + // Check keys + var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys: false; + + // Serialize function + var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + + // Ignore undefined values + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + + // Query options + var queryOptions = { + numberToSkip: 0, numberToReturn: -1, checkKeys: checkKeys + }; + + // Set up the serialize functions and ignore undefined + if(serializeFunctions) queryOptions.serializeFunctions = serializeFunctions; + if(ignoreUndefined) queryOptions.ignoreUndefined = ignoreUndefined; + + // Single operation execution + if(!Array.isArray(cmd)) { + return executeSingleOperation(self, ns, cmd, queryOptions, options, onAll, callback); + } + + // Build commands for each of the instances + var queries = new Array(cmd.length); + for(var i = 0; i < cmd.length; i++) { + queries[i] = new Query(self.s.bson, ns, cmd[i], queryOptions); + queries[i].slaveOk = slaveOk(options.readPreference); + } + + // Notify query start to any read Preference strategies + if(self.s.readPreferenceStrategies != null) + notifyStrategies(self, self.s, 'startOperation', [self, queries, new Date()]); + + // Get a connection (either passed or from the pool) + var connection = options.connection || self.s.pool.get(); + + // Double check if we have a valid connection + if(!connection.isConnected()) { + return callback(new MongoError(f("no connection available to server %s", self.name))); + } + + // Print cmd and execution connection if in debug mode for logging + if(self.s.logger.isDebug()) { + var json = connection.toJSON(); + self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(queries), json.id, json.host, json.port)); + } + + // Canceled operations + var canceled = false; + // Number of operations left + var operationsLeft = queries.length; + // Results + var results = []; + + // We need to nest the callbacks + for(var i = 0; i < queries.length; i++) { + // Get the query object + var query = queries[i]; + + // Execute a single command query + try { + connection.write(query.toBin()); + } catch(err) { + return callback(MongoError.create(err)); + } + + // Register the callback + self.s.callbacks.register(query.requestId, function(err, result) { + // If it's canceled ignore the operation + if(canceled) return; + // Update the current index + operationsLeft = operationsLeft - 1; + + // If we have an error cancel the operation + if(err) { + canceled = true; + return callback(err); + } + + // Return the result + if(result.documents[0]['$err'] + || result.documents[0]['errmsg'] + || result.documents[0]['err'] + || result.documents[0]['code']) { + + // Set to canceled + canceled = true; + // Return the error + return callback(MongoError.create(result.documents[0])); + } + + // Push results + results.push(result.documents[0]); + + // We are done, return the result + if(operationsLeft == 0) { + // Notify end of command + notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); + + // Turn into command results + var commandResults = new Array(results.length); + for(var i = 0; i < results.length; i++) { + commandResults[i] = new CommandResult(results[i], connection); + } + + // Execute callback, catch and rethrow if needed + try { callback(null, commandResults); } + catch(err) { process.nextTick(function() { throw err}); } + } + }); + } +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.insert = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('insert', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.insert(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.update = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('update', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.update(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.remove = function(ns, ops, options, callback) { + if(typeof options == 'function') callback = options, options = {}; + var self = this; + if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); + // Topology is not connected, save the call in the provided store to be + // Executed at some point when the handler deems it's reconnected + if(!self.isConnected() && self.s.disconnectHandler != null) { + callback = bindToCurrentDomain(callback); + return self.s.disconnectHandler.add('remove', ns, ops, options, callback); + } + + // Setup the docs as an array + ops = Array.isArray(ops) ? ops : [ops]; + // Execute write + return self.s.wireProtocolHandler.remove(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); +} + +/** + * Authenticate using a specified mechanism + * @method + * @param {string} mechanism The Auth mechanism we are invoking + * @param {string} db The db we are invoking the mechanism against + * @param {...object} param Parameters for the specific mechanism + * @param {authResultCallback} callback A callback function + */ +Server.prototype.auth = function(mechanism, db) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + var callback = args.pop(); + + // If we don't have the mechanism fail + if(self.s.authProviders[mechanism] == null && mechanism != 'default') + throw new MongoError(f("auth provider %s does not exist", mechanism)); + + // If we have the default mechanism we pick mechanism based on the wire + // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr + if(mechanism == 'default' && self.s.ismaster && self.s.ismaster.maxWireVersion >= 3) { + mechanism = 'scram-sha-1'; + } else if(mechanism == 'default') { + mechanism = 'mongocr'; + } + + // Actual arguments + var finalArguments = [self, self.s.pool, db].concat(args.slice(0)).concat([function(err, r) { + if(err) return callback(err); + if(!r) return callback(new MongoError('could not authenticate')); + callback(null, new Session({}, self)); + }]); + + // Let's invoke the auth mechanism + self.s.authProviders[mechanism].auth.apply(self.s.authProviders[mechanism], finalArguments); +} + +// +// Plugin methods +// + +/** + * Add custom read preference strategy + * @method + * @param {string} name Name of the read preference strategy + * @param {object} strategy Strategy object instance + */ +Server.prototype.addReadPreferenceStrategy = function(name, strategy) { + var self = this; + if(self.s.readPreferenceStrategies == null) self.s.readPreferenceStrategies = {}; + self.s.readPreferenceStrategies[name] = strategy; +} + +/** + * Add custom authentication mechanism + * @method + * @param {string} name Name of the authentication mechanism + * @param {object} provider Authentication object instance + */ +Server.prototype.addAuthProvider = function(name, provider) { + var self = this; + self.s.authProviders[name] = provider; +} + +/** + * Compare two server instances + * @method + * @param {Server} server Server to compare equality against + * @return {boolean} + */ +Server.prototype.equals = function(server) { + if(typeof server == 'string') return server == this.name; + return server.name == this.name; +} + +/** + * All raw connections + * @method + * @return {Connection[]} + */ +Server.prototype.connections = function() { + return this.s.pool.getAll(); +} + +/** + * Get server + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Server} + */ +Server.prototype.getServer = function(options) { + return this; +} + +/** + * Get connection + * @method + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @return {Connection} + */ +Server.prototype.getConnection = function(options) { + return this.s.pool.get(); +} + +/** + * Get callbacks object + * @method + * @return {Callbacks} + */ +Server.prototype.getCallbacks = function() { + return this.s.callbacks; +} + +/** + * Name of BSON parser currently used + * @method + * @return {string} + */ +Server.prototype.parserType = function() { + var s = this.s; + if(s.options.bson.serialize.toString().indexOf('[native code]') != -1) + return 'c++'; + return 'js'; +} + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it + * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. + * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. + * @param {opResultCallback} callback A callback function + */ +Server.prototype.cursor = function(ns, cmd, cursorOptions) { + var s = this.s; + cursorOptions = cursorOptions || {}; + // Set up final cursor type + var FinalCursor = cursorOptions.cursorFactory || s.Cursor; + // Return the cursor + return new FinalCursor(s.bson, ns, cmd, cursorOptions, this, s.options); +} + +/** + * A server connect event, used to verify that the connection is up and running + * + * @event Server#connect + * @type {Server} + */ + +/** + * The server connection closed, all pool connections closed + * + * @event Server#close + * @type {Server} + */ + +/** + * The server connection caused an error, all pool connections closed + * + * @event Server#error + * @type {Server} + */ + +/** + * The server connection timed out, all pool connections closed + * + * @event Server#timeout + * @type {Server} + */ + +/** + * The driver experienced an invalid message, all pool connections closed + * + * @event Server#parseError + * @type {Server} + */ + +/** + * The server reestablished the connection + * + * @event Server#reconnect + * @type {Server} + */ + +/** + * This is an insert result callback + * + * @callback opResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {CommandResult} command result + */ + +/** + * This is an authentication result callback + * + * @callback authResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Session} an authenticated session + */ + +module.exports = Server; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js new file mode 100644 index 0000000..032c3c5 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js @@ -0,0 +1,93 @@ +"use strict"; + +var inherits = require('util').inherits + , f = require('util').format + , EventEmitter = require('events').EventEmitter; + +/** + * Creates a new Authentication Session + * @class + * @param {object} [options] Options for the session + * @param {{Server}|{ReplSet}|{Mongos}} topology The topology instance underpinning the session + */ +var Session = function(options, topology) { + this.options = options; + this.topology = topology; + + // Add event listener + EventEmitter.call(this); +} + +inherits(Session, EventEmitter); + +/** + * Execute a command + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {object} cmd The command hash + * @param {object} [options.readPreference] Specify read preference if command supports it + * @param {object} [options.connection] Specify connection object to execute command against + * @param {opResultCallback} callback A callback function + */ +Session.prototype.command = function(ns, cmd, options, callback) { + this.topology.command(ns, cmd, options, callback); +} + +/** + * Insert one or more documents + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of documents to insert + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.insert = function(ns, ops, options, callback) { + this.topology.insert(ns, ops, options, callback); +} + +/** + * Perform one or more update operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of updates + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.update = function(ns, ops, options, callback) { + this.topology.update(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {array} ops An array of removes + * @param {boolean} [options.ordered=true] Execute in order or out of order + * @param {object} [options.writeConcern={}] Write concern for the operation + * @param {opResultCallback} callback A callback function + */ +Session.prototype.remove = function(ns, ops, options, callback) { + this.topology.remove(ns, ops, options, callback); +} + +/** + * Perform one or more remove operations + * @method + * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) + * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId + * @param {object} [options.batchSize=0] Batchsize for the operation + * @param {array} [options.documents=[]] Initial documents list for cursor + * @param {boolean} [options.tailable=false] Tailable flag set + * @param {boolean} [options.oplogReply=false] oplogReply flag set + * @param {boolean} [options.awaitdata=false] awaitdata flag set + * @param {boolean} [options.exhaust=false] exhaust flag set + * @param {boolean} [options.partial=false] partial flag set + * @param {opResultCallback} callback A callback function + */ +Session.prototype.cursor = function(ns, cmd, options) { + return this.topology.cursor(ns, cmd, options); +} + +module.exports = Session; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js new file mode 100644 index 0000000..3a7b460 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js @@ -0,0 +1,276 @@ +"use strict"; + +var Logger = require('../../connection/logger') + , EventEmitter = require('events').EventEmitter + , inherits = require('util').inherits + , f = require('util').format; + +/** + * Creates a new Ping read preference strategy instance + * @class + * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers + * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) + * @return {Ping} A cursor instance + */ +var Ping = function(options) { + // Add event listener + EventEmitter.call(this); + + // Contains the ping state + this.s = { + // Contains all the ping data + pings: {} + // Set no options if none provided + , options: options || {} + // Logger + , logger: Logger('Ping', options) + // Ping interval + , pingInterval: options.pingInterval || 10000 + , acceptableLatency: options.acceptableLatency || 15 + // Debug options + , debug: typeof options.debug == 'boolean' ? options.debug : false + // Index + , index: 0 + // Current ping time + , lastPing: null + + } + + // Log the options set + if(this.s.logger.isDebug()) this.s.logger.debug(f('ping strategy interval [%s], acceptableLatency [%s]', this.s.pingInterval, this.s.acceptableLatency)); + + // If we have enabled debug + if(this.s.debug) { + // Add access to the read Preference Strategies + Object.defineProperty(this, 'data', { + enumerable: true, get: function() { return this.s.pings; } + }); + } +} + +inherits(Ping, EventEmitter); + +/** + * @ignore + */ +var filterByTags = function(readPreference, servers) { + if(readPreference.tags == null) return servers; + var filteredServers = []; + var tags = readPreference.tags; + + // Iterate over all the servers + for(var i = 0; i < servers.length; i++) { + var serverTag = servers[i].lastIsMaster().tags || {}; + // Did we find the a matching server + var found = true; + // Check if the server is valid + for(var name in tags) { + if(serverTag[name] != tags[name]) found = false; + } + + // Add to candidate list + if(found) filteredServers.push(servers[i]); + } + + // Returned filtered servers + return filteredServers; +} + +/** + * Pick a server + * @method + * @param {State} set The current replicaset state object + * @param {ReadPreference} readPreference The current readPreference object + * @param {readPreferenceResultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.pickServer = function(set, readPreference) { + var self = this; + // Only get primary and secondaries as seeds + var seeds = {}; + var servers = []; + if(set.primary) { + servers.push(set.primary); + } + + for(var i = 0; i < set.secondaries.length; i++) { + servers.push(set.secondaries[i]); + } + + // Filter by tags + servers = filterByTags(readPreference, servers); + + // Transform the list + var serverList = []; + // for(var name in seeds) { + for(var i = 0; i < servers.length; i++) { + serverList.push({name: servers[i].name, time: self.s.pings[servers[i].name] || 0}); + } + + // Sort by time + serverList.sort(function(a, b) { + return a.time > b.time; + }); + + // Locate lowest time (picked servers are lowest time + acceptable Latency margin) + var lowest = serverList.length > 0 ? serverList[0].time : 0; + + // Filter by latency + serverList = serverList.filter(function(s) { + return s.time <= lowest + self.s.acceptableLatency; + }); + + // No servers, default to primary + if(serverList.length == 0 && set.primary) { + if(self.s.logger.isInfo()) self.s.logger.info(f('picked primary server [%s]', set.primary.name)); + return set.primary; + } else if(serverList.length == 0) { + return null + } + + // We picked first server + if(self.s.logger.isInfo()) self.s.logger.info(f('picked server [%s] with ping latency [%s]', serverList[0].name, serverList[0].time)); + + // Add to the index + self.s.index = self.s.index + 1; + // Select the index + self.s.index = self.s.index % serverList.length; + // Return the first server of the sorted and filtered list + return set.get(serverList[self.s.index].name); +} + +/** + * Start of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {object} query The operation running + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.startOperation = function(server, query, date) { +} + +/** + * End of an operation + * @method + * @param {Server} server The server the operation is running against + * @param {error} err An error from the operation + * @param {object} result The result from the operation + * @param {Date} date The start time of the operation + * @return {object} + */ +Ping.prototype.endOperation = function(server, err, result, date) { +} + +/** + * High availability process running + * @method + * @param {State} set The current replicaset state object + * @param {resultCallback} callback The callback to return the result from the function + * @return {object} + */ +Ping.prototype.ha = function(topology, state, callback) { + var self = this; + var servers = state.getAll(); + var count = servers.length; + + // No servers return + if(servers.length == 0) return callback(null, null); + + // Return if we have not yet reached the ping interval + if(self.s.lastPing != null) { + var diff = new Date().getTime() - self.s.lastPing.getTime(); + if(diff < self.s.pingInterval) return callback(null, null); + } + + // Execute operation + var operation = function(_server) { + var start = new Date(); + // Execute ping against server + _server.command('system.$cmd', {ismaster:1}, function(err, r) { + count = count - 1; + var time = new Date().getTime() - start.getTime(); + self.s.pings[_server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('ha latency for server [%s] is [%s] ms', _server.name, time)); + // We are done with all the servers + if(count == 0) { + // Emit ping event + topology.emit('ping', err, r ? r.result : null); + // Update the last ping time + self.s.lastPing = new Date(); + // Return + callback(null, null); + } + }); + } + + // Let's ping all servers + while(servers.length > 0) { + operation(servers.shift()); + } +} + +var removeServer = function(self, server) { + delete self.s.pings[server.name]; +} + +/** + * Server connection closed + * @method + * @param {Server} server The server that closed + */ +Ping.prototype.close = function(server) { + removeServer(this, server); +} + +/** + * Server connection errored out + * @method + * @param {Server} server The server that errored out + */ +Ping.prototype.error = function(server) { + removeServer(this, server); +} + +/** + * Server connection timeout + * @method + * @param {Server} server The server that timed out + */ +Ping.prototype.timeout = function(server) { + removeServer(this, server); +} + +/** + * Server connection happened + * @method + * @param {Server} server The server that connected + * @param {resultCallback} callback The callback to return the result from the function + */ +Ping.prototype.connect = function(server, callback) { + var self = this; + // Get the command start date + var start = new Date(); + // Execute ping against server + server.command('system.$cmd', {ismaster:1}, function(err, r) { + var time = new Date().getTime() - start.getTime(); + self.s.pings[server.name] = time; + // Log info for debug + if(self.s.logger.isDebug()) self.s.logger.debug(f('connect latency for server [%s] is [%s] ms', server.name, time)); + // Set last ping + self.s.lastPing = new Date(); + // Done, return + callback(null, null); + }); +} + +/** + * This is a result from a readPreference strategy + * + * @callback readPreferenceResultCallback + * @param {error} error An error object. Set to null if no error present + * @param {Server} server The server picked by the strategy + */ + +module.exports = Ping; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js new file mode 100644 index 0000000..e2e6a67 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js @@ -0,0 +1,559 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +// Write concern fields +var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync']; + +var WireProtocol = function() {} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var legacy = typeof options.legacy == 'boolean' ? options.legacy : false; + ops = Array.isArray(ops) ? ops :[ops]; + + // If we have more than a 1000 ops fails + if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000")); + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + options = options || {}; + // Default is ordered execution + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + ops = Array.isArray(ops) ? ops :[ops]; + + // Write concern + var writeConcern = options.writeConcern || {w:1}; + + // We are unordered + if(!ordered || writeConcern.w == 0) { + return executeUnordered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); + } + + return executeOrdered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(connection && connection.isConnected()) connection.write(killCursor.toBin()); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + connection.write(getMore.toBin()); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + // If we have explain, return a single document and close cursor + if(cmd.explain) { + numberToReturn = -1; + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; + if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; + if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + finalCmd['$readPreference'] = readPreference.toJSON(); + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +var hasWriteConcern = function(writeConcern) { + if(writeConcern.w + || writeConcern.wtimeout + || writeConcern.j == true + || writeConcern.fsync == true + || Object.keys(writeConcern).length == 0) { + return true; + } + return false; +} + +var cloneWriteConcern = function(writeConcern) { + var wc = {}; + if(writeConcern.w != null) wc.w = writeConcern.w; + if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout; + if(writeConcern.j != null) wc.j = writeConcern.j; + if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync; + return wc; +} + +// +// Aggregate up all the results +// +var aggregateWriteOperationResults = function(opType, ops, results, connection) { + var finalResult = { ok: 1, n: 0 } + + // Map all the results coming back + for(var i = 0; i < results.length; i++) { + var result = results[i]; + var op = ops[i]; + + if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) { + finalResult.upserted = []; + } + + // Push the upserted document to the list of upserted values + if(result.upserted) { + finalResult.upserted.push({index: i, _id: result.upserted}); + } + + // We have an upsert where we passed in a _id + if(result.updatedExisting == false && result.n == 1 && result.upserted == null) { + finalResult.upserted.push({index: i, _id: op.q._id}); + } + + // We have an insert command + if(result.ok == 1 && opType == 'insert' && result.err == null) { + finalResult.n = finalResult.n + 1; + } + + // We have a command error + if(result != null && result.ok == 0 || result.err || result.errmsg) { + if(result.ok == 0) finalResult.ok = 0; + finalResult.code = result.code; + finalResult.errmsg = result.errmsg || result.err || result.errMsg; + + // Check if we have a write error + if(result.code == 11000 + || result.code == 11001 + || result.code == 12582 + || result.code == 16544 + || result.code == 16538 + || result.code == 16542 + || result.code == 14 + || result.code == 13511) { + if(finalResult.writeErrors == null) finalResult.writeErrors = []; + finalResult.writeErrors.push({ + index: i + , code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + }); + } else { + finalResult.writeConcernError = { + code: result.code + , errmsg: result.errmsg || result.err || result.errMsg + } + } + } else if(typeof result.n == 'number') { + finalResult.n += result.n; + } else { + finalResult.n += 1; + } + + // Result as expected + if(result != null && result.lastOp) finalResult.lastOp = result.lastOp; + } + + // Return finalResult aggregated results + return new CommandResult(finalResult, connection); +} + +// +// Execute all inserts in an ordered manner +// +var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + var _ops = ops.slice(0); + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Collect all the getLastErrors + var getLastErrors = []; + + // Execute an operation + var executeOp = function(list, _callback) { + // Get a pool connection + var connection = pool.get(); + // No more items in the list + if(list.length == 0) return _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + + // Get the first operation + var doc = list.shift(); + + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options); + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + + // Get the db name + var db = ns.split('.').shift(); + + // Error out if no connection available + if(connection == null) + return _callback(new MongoError("no connection available")); + + try { + // Execute the insert + connection.write(op.toBin()); + + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var i = 0; i < writeConcernFields.length; i++) { + if(writeConcern[writeConcernFields[i]] != null) + getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]]; + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Write the lastError message + connection.write(getLastErrorOp.toBin()); + // Register the callback + callbacks.register(getLastErrorOp.requestId, function(err, result) { + if(err) return callback(err); + // Get the document + var doc = result.documents[0]; + // Save the getLastError document + getLastErrors.push(doc); + // If we have an error terminate + if(doc.ok == 0 || doc.err || doc.errmsg) return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + // Execute the next op in the list + executeOp(list, callback); + }); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors.push({ ok: 1, errmsg: err.message, code: 14 }); + // Return due to an error + return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + } + } + + // Execute the operations + executeOp(_ops, callback); +} + +var executeUnordered = function(opType, command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + // Bind to current domain + callback = bindToCurrentDomain(callback); + // Total operations to write + var totalOps = ops.length; + // Collect all the getLastErrors + var getLastErrors = []; + // Write concern + var optionWriteConcern = options.writeConcern || {w:1}; + // Final write concern + var writeConcern = cloneWriteConcern(optionWriteConcern); + // Driver level error + var error; + + // Execute all the operations + for(var i = 0; i < ops.length; i++) { + // Create an insert command + var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options); + // Get db name + var db = ns.split('.').shift(); + + // Get a pool connection + var connection = pool.get(); + + // Error out if no connection available + if(connection == null) + return _callback(new MongoError("no connection available")); + + try { + // Execute the insert + connection.write(op.toBin()); + // If write concern 0 don't fire getLastError + if(hasWriteConcern(writeConcern)) { + var getLastErrorCmd = {getlasterror: 1}; + // Merge all the fields + for(var j = 0; j < writeConcernFields.length; j++) { + if(writeConcern[writeConcernFields[j]] != null) + getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]]; + } + + // Create a getLastError command + var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); + // Write the lastError message + connection.write(getLastErrorOp.toBin()); + + // Give the result from getLastError the right index + var callbackOp = function(_index) { + return function(err, result) { + if(err) error = err; + // Update the number of operations executed + totalOps = totalOps - 1; + // Save the getLastError document + if(!err) getLastErrors[_index] = result.documents[0]; + // Check if we are done + if(totalOps == 0) { + if(error) return callback(error); + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + } + } + } + + // Register the callback + callbacks.register(getLastErrorOp.requestId, callbackOp(i)); + } + } catch(err) { + if(typeof err == 'string') err = new MongoError(err); + // Update the number of operations executed + totalOps = totalOps - 1; + // We have a serialization error, rewrite as a write error to have same behavior as modern + // write commands + getLastErrors[i] = { ok: 1, errmsg: err.message, code: 14 }; + // Check if we are done + if(totalOps == 0) { + callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); + } + } + } + + // Empty w:0 return + if(writeConcern + && writeConcern.w == 0 && callback) { + callback(null, null); + } +} + +module.exports = WireProtocol; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js new file mode 100644 index 0000000..b1d1d46 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js @@ -0,0 +1,291 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +var WireProtocol = function() {} + +// +// Execute a write operation +var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern || {}; + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + writeCommand.writeConcern = writeConcern; + + // Options object + var opts = {}; + if(type == 'insert') opts.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; + if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; + // Execute command + topology.command(f("%s.$cmd", d), writeCommand, opts, callback); +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { + // Create a kill cursor command + var killCursor = new KillCursor(bson, [cursorId]); + // Execute the kill cursor command + if(connection && connection.isConnected()) connection.write(killCursor.toBin()); + // Set cursor to 0 + cursorId = Long.ZERO; + // Return to caller + if(callback) callback(null, null); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { + // Create getMore command + var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.cursorId == 'number' + ? Long.fromNumber(r.cursorId) + : r.cursorId; + + // Set all the values + cursorState.documents = r.documents; + cursorState.cursorId = cursorId; + + // Return + callback(null); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Register a callback + callbacks.register(getMore.requestId, queryCallback); + // Write out the getMore command + connection.write(getMore.toBin()); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + return setupClassicFind(bson, ns, cmd, cursorState, topology, options) + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// +// Execute a find command +var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + var numberToReturn = 0; + + // Unpack the limit and batchSize values + if(cursorState.limit == 0) { + numberToReturn = cursorState.batchSize; + } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { + numberToReturn = cursorState.limit; + } else { + numberToReturn = cursorState.batchSize; + } + + var numberToSkip = cursorState.skip || 0; + // Build actual find command + var findCmd = {}; + // Using special modifier + var usesSpecialModifier = false; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + usesSpecialModifier = true; + } + + // Add special modifiers to the query + if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; + if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; + if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; + if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; + if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; + if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; + if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; + if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; + if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; + if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; + + // If we have explain, return a single document and close cursor + if(cmd.explain) { + numberToReturn = -1; + usesSpecialModifier = true; + findCmd['$explain'] = true; + } + + // If we have a special modifier + if(usesSpecialModifier) { + findCmd['$query'] = cmd.query; + } else { + findCmd = cmd.query; + } + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) { + cmd = copy(cmd); + delete cmd['readConcern']; + } + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, ns, findCmd, { + numberToSkip: numberToSkip, numberToReturn: numberToReturn + , checkKeys: false, returnFieldSelector: cmd.fields + , serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Set up the option bits for wire protocol + if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; + if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; + if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; + if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; + if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; + if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + finalCmd['$readPreference'] = readPreference.toJSON(); + } + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Throw on majority readConcern passed in + if(cmd.readConcern && cmd.readConcern.level != 'local') { + throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); + } + + // Remove readConcern, ensure no failing commands + if(cmd.readConcern) delete cmd['readConcern']; + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +module.exports = WireProtocol; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js new file mode 100644 index 0000000..c5e61aa --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js @@ -0,0 +1,494 @@ +"use strict"; + +var Insert = require('./commands').Insert + , Update = require('./commands').Update + , Remove = require('./commands').Remove + , Query = require('../connection/commands').Query + , copy = require('../connection/utils').copy + , KillCursor = require('../connection/commands').KillCursor + , GetMore = require('../connection/commands').GetMore + , Query = require('../connection/commands').Query + , ReadPreference = require('../topologies/read_preference') + , f = require('util').format + , CommandResult = require('../topologies/command_result') + , MongoError = require('../error') + , Long = require('bson').Long; + +var WireProtocol = function(legacyWireProtocol) { + this.legacyWireProtocol = legacyWireProtocol; +} + +// +// Execute a write operation +var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { + if(ops.length == 0) throw new MongoError("insert must contain at least one document"); + if(typeof options == 'function') { + callback = options; + options = {}; + } + + // Split the ns up to get db and collection + var p = ns.split("."); + var d = p.shift(); + // Options + var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; + var writeConcern = options.writeConcern || {}; + // return skeleton + var writeCommand = {}; + writeCommand[type] = p.join('.'); + writeCommand[opsField] = ops; + writeCommand.ordered = ordered; + writeCommand.writeConcern = writeConcern; + + // Do we have bypassDocumentValidation set, then enable it on the write command + if(typeof options.bypassDocumentValidation == 'boolean') { + writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; + } + + // Options object + var opts = {}; + if(type == 'insert') opts.checkKeys = true; + // Ensure we support serialization of functions + if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; + if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; + // Execute command + topology.command(f("%s.$cmd", d), writeCommand, opts, callback); +} + +// +// Needs to support legacy mass insert as well as ordered/unordered legacy +// emulation +// +WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); +} + +WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'update', 'updates', ns, ops, options, callback); +} + +WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { + executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); +} + +WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + // Create getMore command + var killcursorCmd = { + killCursors: parts.join('.'), + cursors: [cursorId] + } + + // Build Query object + var query = new Query(bson, commandns, killcursorCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = true; + + // Execute the kill cursor command + if(connection && connection.isConnected()) { + connection.write(query.toBin()); + } + + // Kill cursor callback + var killCursorCallback = function(err, r) { + if(err) { + if(typeof callback != 'function') return; + return callback(err); + } + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + if(typeof callback != 'function') return; + return callback(new MongoError("cursor killed or timed out"), null); + } + + if(!Array.isArray(r.documents) || r.documents.length == 0) { + if(typeof callback != 'function') return; + return callback(new MongoError(f('invalid getMore result returned for cursor id %s', cursorState.cursorId))); + } + + // Return the result + if(typeof callback == 'function') { + callback(null, r.documents[0]); + } + } + + // Register a callback + callbacks.register(query.requestId, killCursorCallback); +} + +WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Check if we have an maxTimeMS set + var maxTimeMS = typeof cursorState.cmd.maxTimeMS == 'number' ? cursorState.cmd.maxTimeMS : 3000; + + // Create getMore command + var getMoreCmd = { + getMore: cursorState.cursorId, + collection: parts.join('.'), + batchSize: batchSize, + maxTimeMS: maxTimeMS + } + + // Build Query object + var query = new Query(bson, commandns, getMoreCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Query callback + var queryCallback = function(err, r) { + if(err) return callback(err); + + // If we have a timed out query or a cursor that was killed + if((r.responseFlags & (1 << 0)) != 0) { + return callback(new MongoError("cursor killed or timed out"), null); + } + + if(!Array.isArray(r.documents) || r.documents.length == 0) + return callback(new MongoError(f('invalid getMore result returned for cursor id %s', cursorState.cursorId))); + + // Raw, return all the extracted documents + if(raw) { + cursorState.documents = r.documents; + cursorState.cursorId = r.cursorId; + return callback(null, r.documents); + } + + // Ensure we have a Long valie cursor id + var cursorId = typeof r.documents[0].cursor.id == 'number' + ? Long.fromNumber(r.documents[0].cursor.id) + : r.documents[0].cursor.id; + + // Set all the values + cursorState.documents = r.documents[0].cursor.nextBatch; + cursorState.cursorId = cursorId; + + // Return the result + callback(null, r.documents[0]); + } + + // If we have a raw query decorate the function + if(raw) { + queryCallback.raw = raw; + } + + // Add the result field needed + queryCallback.documentsReturnedIn = 'nextBatch'; + + // Register a callback + callbacks.register(query.requestId, queryCallback); + // Write out the getMore command + connection.write(query.toBin()); +} + +WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { + // Establish type of command + if(cmd.find) { + if(cmd.exhaust) { + return this.legacyWireProtocol.command(bson, ns, cmd, cursorState, topology, options); + } + + // Create the find command + var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options) + // Mark the cmd as virtual + cmd.virtual = false; + // Signal the documents are in the firstBatch value + query.documentsReturnedIn = 'firstBatch'; + // Return the query + return query; + } else if(cursorState.cursorId != null) { + } else if(cmd) { + return setupCommand(bson, ns, cmd, cursorState, topology, options); + } else { + throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); + } +} + +// // Command +// { +// find: ns +// , query: +// , limit: +// , fields: +// , skip: +// , hint: +// , explain: +// , snapshot: +// , batchSize: +// , returnKey: +// , maxScan: +// , min: +// , max: +// , showDiskLoc: +// , comment: +// , maxTimeMS: +// , raw: +// , readPreference: +// , tailable: +// , oplogReplay: +// , noCursorTimeout: +// , awaitdata: +// , exhaust: +// , partial: +// } + +// FIND/GETMORE SPEC +// { +// “find”: , +// “filter”: { ... }, +// “sort”: { ... }, +// “projection”: { ... }, +// “hint”: { ... }, +// “skip”: , +// “limit”: , +// “batchSize”: , +// “singleBatch”: , +// “comment”: , +// “maxScan”: , +// “maxTimeMS”: , +// “max”: { ... }, +// “min”: { ... }, +// “returnKey”: , +// “showRecordId”: , +// “snapshot”: , +// “tailable”: , +// “oplogReplay”: , +// “noCursorTimeout”: , +// “awaitData”: , +// “partial”: , +// “$readPreference”: { ... } +// } + +// +// Execute a find command +var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Ensure we have at least some options + options = options || {}; + // Set the optional batchSize + cursorState.batchSize = cmd.batchSize || cursorState.batchSize; + + // Build command namespace + var parts = ns.split(/\./); + // Command namespace + var commandns = f('%s.$cmd', parts.shift()); + + // Build actual find command + var findCmd = { + find: parts.join('.') + }; + + // I we provided a filter + if(cmd.query) findCmd.filter = cmd.query; + + // Sort value + var sortValue = cmd.sort; + + // Handle issue of sort being an Array + if(Array.isArray(sortValue)) { + var sortObject = {}; + + if(sortValue.length > 0 && !Array.isArray(sortValue[0])) { + var sortDirection = sortValue[1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[0]] = sortDirection; + } else { + for(var i = 0; i < sortValue.length; i++) { + var sortDirection = sortValue[i][1]; + // Translate the sort order text + if(sortDirection == 'asc') { + sortDirection = 1; + } else if(sortDirection == 'desc') { + sortDirection = -1; + } + + // Set the sort order + sortObject[sortValue[i][0]] = sortDirection; + } + } + + sortValue = sortObject; + }; + + // Add sort to command + if(cmd.sort) findCmd.sort = sortValue; + // Add a projection to the command + if(cmd.fields) findCmd.projection = cmd.fields; + // Add a hint to the command + if(cmd.hint) findCmd.hint = cmd.hint; + // Add a skip + if(cmd.skip) findCmd.skip = cmd.skip; + // Add a limit + if(cmd.limit) findCmd.limit = cmd.limit; + // Add a batchSize + if(cmd.batchSize) findCmd.batchSize = cmd.batchSize; + + // Check if we wish to have a singleBatch + if(cmd.limit < 0) { + findCmd.limit = Math.abs(cmd.limit); + findCmd.singleBatch = true; + } + + // If we have comment set + if(cmd.comment) findCmd.comment = cmd.comment; + + // If we have maxScan + if(cmd.maxScan) findCmd.maxScan = cmd.maxScan; + + // If we have maxTimeMS set + if(cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; + + // If we have min + if(cmd.min) findCmd.min = cmd.min; + + // If we have max + if(cmd.max) findCmd.max = cmd.max; + + // If we have returnKey set + if(cmd.returnKey) findCmd.returnKey = cmd.returnKey; + + // If we have showDiskLoc set + if(cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; + + // If we have snapshot set + if(cmd.snapshot) findCmd.snapshot = cmd.snapshot; + + // If we have tailable set + if(cmd.tailable) findCmd.tailable = cmd.tailable; + + // If we have oplogReplay set + if(cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; + + // If we have noCursorTimeout set + if(cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; + + // If we have awaitData set + if(cmd.awaitData) findCmd.awaitData = cmd.awaitData; + if(cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; + + // If we have partial set + if(cmd.partial) findCmd.partial = cmd.partial; + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + findCmd['$readPreference'] = readPreference.toJSON(); + } + + // If we have explain, we need to rewrite the find command + // to wrap it in the explain command + if(cmd.explain) { + findCmd = { + explain: findCmd + } + } + + // Did we provide a readConcern + if(cmd.readConcern) findCmd.readConcern = cmd.readConcern; + + // Set up the serialize and ignoreUndefined fields + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, commandns, findCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, returnFieldSelector: null + , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +// +// Set up a command cursor +var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { + var readPreference = options.readPreference || new ReadPreference('primary'); + if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); + if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); + + // Set empty options object + options = options || {} + + // Final query + var finalCmd = {}; + for(var name in cmd) { + finalCmd[name] = cmd[name]; + } + + // Build command namespace + var parts = ns.split(/\./); + + // We have a Mongos topology, check if we need to add a readPreference + if(topology.type == 'mongos' && readPreference) { + finalCmd['$readPreference'] = readPreference.toJSON(); + } + + // Serialize functions + var serializeFunctions = typeof options.serializeFunctions == 'boolean' + ? options.serializeFunctions : false; + + // Set up the serialize and ignoreUndefined fields + var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' + ? options.ignoreUndefined : false; + + // Build Query object + var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { + numberToSkip: 0, numberToReturn: -1 + , checkKeys: false, serializeFunctions: serializeFunctions + , ignoreUndefined: ignoreUndefined + }); + + // Set query flags + query.slaveOk = readPreference.slaveOk(); + + // Return the query + return query; +} + +/** + * @ignore + */ +var bindToCurrentDomain = function(callback) { + var domain = process.domain; + if(domain == null || callback == null) { + return callback; + } else { + return domain.bind(callback); + } +} + +module.exports = WireProtocol; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js new file mode 100644 index 0000000..9c665ee --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js @@ -0,0 +1,357 @@ +"use strict"; + +var MongoError = require('../error'); + +// Wire command operation ids +var OP_UPDATE = 2001; +var OP_INSERT = 2002; +var OP_DELETE = 2006; + +var Insert = function(requestId, ismaster, bson, ns, documents, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + if(!Array.isArray(documents) || documents.length == 0) throw new MongoError("documents array must contain at least one document to insert"); + + // Validate that we are not passing 0x00 in the colletion name + if(!!~ns.indexOf("\x00")) { + throw new MongoError("namespace cannot contain a null character"); + } + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.documents = documents; + this.ismaster = ismaster; + + // Ensure empty options + options = options || {}; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; + this.continueOnError = typeof options.continueOnError == 'boolean' ? options.continueOnError : false; + // Set flags + this.flags = this.continueOnError ? 1 : 0; +} + +// To Binary +Insert.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // Flags + + Buffer.byteLength(this.ns) + 1 // namespace + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize all the documents + for(var i = 0; i < this.documents.length; i++) { + var buffer = this.bson.serialize(this.documents[i] + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + + // Document is larger than maxBsonObjectSize, terminate serialization + if(buffer.length > this.ismaster.maxBsonObjectSize) { + throw new MongoError("Document exceeds maximum allowed bson size of " + this.ismaster.maxBsonObjectSize + " bytes"); + } + + // Add to total length of wire protocol message + totalLength = totalLength + buffer.length; + // Add to buffer + buffers.push(buffer); + } + + // Command is larger than maxMessageSizeBytes terminate serialization + if(totalLength > this.ismaster.maxMessageSizeBytes) { + throw new MongoError("Command exceeds maximum message size of " + this.ismaster.maxMessageSizeBytes + " bytes"); + } + + // Add all the metadata + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_INSERT >> 24) & 0xff; + header[index + 2] = (OP_INSERT >> 16) & 0xff; + header[index + 1] = (OP_INSERT >> 8) & 0xff; + header[index] = (OP_INSERT) & 0xff; + index = index + 4; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Return the buffers + return buffers; +} + +var Update = function(requestId, ismaster, bson, ns, update, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.upsert = typeof update[0].upsert == 'boolean' ? update[0].upsert : false; + this.multi = typeof update[0].multi == 'boolean' ? update[0].multi : false; + this.q = update[0].q; + this.u = update[0].u; + + // Create flag value + this.flags = this.upsert ? 1 : 0; + this.flags = this.multi ? this.flags | 2 : this.flags; +} + +// To Binary +Update.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Serialize the update + var update = this.bson.serialize(this.u + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(update); + totalLength = totalLength + update.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_UPDATE >> 24) & 0xff; + header[index + 2] = (OP_UPDATE >> 16) & 0xff; + header[index + 1] = (OP_UPDATE >> 8) & 0xff; + header[index] = (OP_UPDATE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Flags + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +var Remove = function(requestId, ismaster, bson, ns, remove, options) { + // Basic options needed to be passed in + if(ns == null) throw new MongoError("ns must be specified for query"); + + // Ensure empty options + options = options || {}; + + // Set internal + this.requestId = requestId; + this.bson = bson; + this.ns = ns; + this.ismaster = ismaster; + + // Unpack options + this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; + this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; + this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; + + // Unpack the update document + this.limit = typeof remove[0].limit == 'number' ? remove[0].limit : 1; + this.q = remove[0].q; + + // Create flag value + this.flags = this.limit == 1 ? 1 : 0; +} + +// To Binary +Remove.prototype.toBin = function() { + // Contains all the buffers to be written + var buffers = []; + + // Header buffer + var header = new Buffer( + 4 * 4 // Header + + 4 // ZERO + + Buffer.byteLength(this.ns) + 1 // namespace + + 4 // Flags + ); + + // Add header to buffers + buffers.push(header); + + // Total length of the message + var totalLength = header.length; + + // Serialize the selector + var selector = this.bson.serialize(this.q + , this.checkKeys + , true + , this.serializeFunctions + , 0, this.ignoreUndefined); + buffers.push(selector); + totalLength = totalLength + selector.length; + + // Index in header buffer + var index = 0; + + // Write header length + header[index + 3] = (totalLength >> 24) & 0xff; + header[index + 2] = (totalLength >> 16) & 0xff; + header[index + 1] = (totalLength >> 8) & 0xff; + header[index] = (totalLength) & 0xff; + index = index + 4; + + // Write header requestId + header[index + 3] = (this.requestId >> 24) & 0xff; + header[index + 2] = (this.requestId >> 16) & 0xff; + header[index + 1] = (this.requestId >> 8) & 0xff; + header[index] = (this.requestId) & 0xff; + index = index + 4; + + // No flags + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Operation + header[index + 3] = (OP_DELETE >> 24) & 0xff; + header[index + 2] = (OP_DELETE >> 16) & 0xff; + header[index + 1] = (OP_DELETE >> 8) & 0xff; + header[index] = (OP_DELETE) & 0xff; + index = index + 4; + + // Write ZERO + header[index + 3] = (0 >> 24) & 0xff; + header[index + 2] = (0 >> 16) & 0xff; + header[index + 1] = (0 >> 8) & 0xff; + header[index] = (0) & 0xff; + index = index + 4; + + // Write collection name + index = index + header.write(this.ns, index, 'utf8') + 1; + header[index - 1] = 0; + + // Write ZERO + header[index + 3] = (this.flags >> 24) & 0xff; + header[index + 2] = (this.flags >> 16) & 0xff; + header[index + 1] = (this.flags >> 8) & 0xff; + header[index] = (this.flags) & 0xff; + index = index + 4; + + // Return the buffers + return buffers; +} + +module.exports = { + Insert: Insert + , Update: Update + , Remove: Remove +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY new file mode 100644 index 0000000..ecf5994 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY @@ -0,0 +1,113 @@ +0.4.16 2015-10-07 +----------------- +- Fixed issue with return statement in Map.js. + +0.4.15 2015-10-06 +----------------- +- Exposed Map correctly via index.js file. + +0.4.14 2015-10-06 +----------------- +- Exposed Map correctly via bson.js file. + +0.4.13 2015-10-06 +----------------- +- Added ES6 Map type serialization as well as a polyfill for ES5. + +0.4.12 2015-09-18 +----------------- +- Made ignore undefined an optional parameter. + +0.4.11 2015-08-06 +----------------- +- Minor fix for invalid key checking. + +0.4.10 2015-08-06 +----------------- +- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. +- Some performance improvements by in lining code. + +0.4.9 2015-08-06 +---------------- +- Undefined fields are omitted from serialization in objects. + +0.4.8 2015-07-14 +---------------- +- Fixed size validation to ensure we can deserialize from dumped files. + +0.4.7 2015-06-26 +---------------- +- Added ability to instruct deserializer to return raw BSON buffers for named array fields. +- Minor deserialization optimization by moving inlined function out. + +0.4.6 2015-06-17 +---------------- +- Fixed serializeWithBufferAndIndex bug. + +0.4.5 2015-06-17 +---------------- +- Removed any references to the shared buffer to avoid non GC collectible bson instances. + +0.4.4 2015-06-17 +---------------- +- Fixed rethrowing of error when not RangeError. + +0.4.3 2015-06-17 +---------------- +- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. + +0.4.2 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.1 2015-06-16 +---------------- +- More fixes for corrupt Bson + +0.4.0 2015-06-16 +---------------- +- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. +- Removed bson-ext extension dependency for now. + +0.3.2 2015-03-27 +---------------- +- Removed node-gyp from install script in package.json. + +0.3.1 2015-03-27 +---------------- +- Return pure js version on native() call if failed to initialize. + +0.3.0 2015-03-26 +---------------- +- Pulled out all C++ code into bson-ext and made it an optional dependency. + +0.2.21 2015-03-21 +----------------- +- Updated Nan to 1.7.0 to support io.js and node 0.12.0 + +0.2.19 2015-02-16 +----------------- +- Updated Nan to 1.6.2 to support io.js and node 0.12.0 + +0.2.18 2015-01-20 +----------------- +- Updated Nan to 1.5.1 to support io.js + +0.2.16 2014-12-17 +----------------- +- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's + +0.2.12 2014-08-24 +----------------- +- Fixes for fortify review of c++ extension +- toBSON correctly allows returns of non objects + +0.2.3 2013-10-01 +---------------- +- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) +- Fixed issue where corrupt CString's could cause endless loop +- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) + +0.1.4 2012-09-25 +---------------- +- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md new file mode 100644 index 0000000..56327c2 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md @@ -0,0 +1,69 @@ +Javascript + C++ BSON parser +============================ + +This BSON parser is primarily meant to be used with the `mongodb` node.js driver. +However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser. +The current build is located in the `browser_build/bson.js` file. + +A simple example of how to use BSON in the browser: + +```html + + + + + + + + +``` + +A simple example of how to use BSON in `node.js`: + +```javascript +var bson = require("bson"); +var BSON = new bson.BSONPure.BSON(); +var Long = bson.BSONPure.Long; + +var doc = {long: Long.fromNumber(100)} + +// Serialize a document +var data = BSON.serialize(doc, false, true, false); +console.log("data:", data); + +// Deserialize the resulting Buffer +var doc_2 = BSON.deserialize(data); +console.log("doc_2:", doc_2); +``` + +The API consists of two simple methods to serialize/deserialize objects to/from BSON format: + + * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** + * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports + + * BSON.deserialize(buffer, options, isArray) + * Options + * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * @param {TypedArray/Array} a TypedArray/Array containing the BSON data + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js new file mode 100644 index 0000000..555aa79 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js @@ -0,0 +1,1574 @@ +var Long = require('../lib/bson/long').Long + , Double = require('../lib/bson/double').Double + , Timestamp = require('../lib/bson/timestamp').Timestamp + , ObjectID = require('../lib/bson/objectid').ObjectID + , Symbol = require('../lib/bson/symbol').Symbol + , Code = require('../lib/bson/code').Code + , MinKey = require('../lib/bson/min_key').MinKey + , MaxKey = require('../lib/bson/max_key').MaxKey + , DBRef = require('../lib/bson/db_ref').DBRef + , Binary = require('../lib/bson/binary').Binary + , BinaryParser = require('../lib/bson/binary_parser').BinaryParser + , writeIEEE754 = require('../lib/bson/float_parser').writeIEEE754 + , readIEEE754 = require('../lib/bson/float_parser').readIEEE754 + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * Create a new BSON instance + * + * @class + * @return {BSON} instance of BSON Parser. + */ +function BSON () {}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_UNDEFINED + **/ +BSON.BSON_DATA_UNDEFINED = 6; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions) { + var isBuffer = typeof Buffer !== 'undefined'; + + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + switch(typeof value) { + case 'string': + return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + case 'undefined': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + case 'boolean': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else if(serializeFunctions) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; + } + } + } + + return 0; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { + // Default setting false + serializeFunctions = serializeFunctions == null ? false : serializeFunctions; + // Write end information (length of the object) + var size = buffer.length; + // Write the size of the object + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; +} + +/** + * @ignore + * @api private + */ +var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { + if(object.toBSON) { + if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); + object = object.toBSON(); + if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); + } + + // Process the object + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Serialize the object + for(var key in object) { + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + // dollars and dots ok + BSON.checkKey(key, !checkKeys); + } + + // Pack the element + index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); + } + } + + // Write zero + buffer[index++] = 0; + return index; +} + +var stringToBytes = function(str) { + var ch, st, re = []; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re.concat( st.reverse() ); + } + // return an array of bytes + return re; +} + +var numberOfBytes = function(str) { + var ch, st, re = 0; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re + st.length; + } + // return an array of bytes + return re; +} + +/** + * @ignore + * @api private + */ +var writeToTypedArray = function(buffer, string, index) { + var bytes = stringToBytes(string); + for(var i = 0; i < bytes.length; i++) { + buffer[index + i] = bytes[i]; + } + return bytes.length; +} + +/** + * @ignore + * @api private + */ +var supportsBuffer = typeof Buffer != 'undefined'; + +/** + * @ignore + * @api private + */ +var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { + + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + var startIndex = index; + + switch(typeof value) { + case 'string': + // console.log("+++++++++++ index string:: " + index) + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; + // console.log("====== key :: " + name + " size ::" + size) + // Write the size of the string to buffer + buffer[index + 3] = (size >> 24) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index] = size & 0xff; + // Ajust the index + index = index + 4; + // Write the string + supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + // Return index + return index; + case 'number': + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + case 'undefined': + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + case 'boolean': + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + case 'object': + if(value === null || value instanceof MinKey || value instanceof MaxKey + || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + // console.log("+++++++++++ index OBJECTID:: " + index) + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write objectid + supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); + // Ajust index + index = index + 12; + return index; + } else if(value instanceof Date || isDate(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + // Write the type + buffer[index++] = value instanceof Long || value['_bsontype'] == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(value instanceof Double || value['_bsontype'] == 'Double') { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.code.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize + 4; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.code.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); + // Ajust index + index = index + value.position; + return index; + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(value.value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + // Message size + var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); + // Serialize the object + var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write zero for object + buffer[endIndex++] = 0x00; + // Return the end index + return endIndex; + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Adjust the index + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); + // Write size + var size = endIndex - index; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return endIndex; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + buffer.write(value.source, index, 'utf8'); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = new Buffer(scopeSize); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize - 4; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + scopeObjectBuffer.copy(buffer, index, 0, scopeSize); + + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else if(serializeFunctions) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } + } + + // If no value to serialize + return index; +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + // Throw error if we are trying serialize an illegal type + if(object == null || typeof object != 'object' || Array.isArray(object)) + throw new Error("Only javascript objects supported"); + + // Emoty target buffer + var buffer = null; + // Calculate the size of the object + var size = BSON.calculateObjectSize(object, serializeFunctions); + // Fetch the best available type for storing the binary data + if(buffer = typeof Buffer != 'undefined') { + buffer = new Buffer(size); + asBuffer = true; + } else if(typeof Uint8Array != 'undefined') { + buffer = new Uint8Array(new ArrayBuffer(size)); + } else { + buffer = new Array(size); + } + + // If asBuffer is false use typed arrays + BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); + // console.log("++++++++++++++++++++++++++++++++++++ OLDJS :: " + buffer.length) + // console.log(buffer.toString('hex')) + // console.log(buffer.toString('ascii')) + return buffer; +} + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Crc state variables shared by function + * + * @ignore + * @api private + */ +var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + +/** + * CRC32 hash method, Fast and enough versitility for our usage + * + * @ignore + * @api private + */ +var crc32 = function(string, start, end) { + var crc = 0 + var x = 0; + var y = 0; + crc = crc ^ (-1); + + for(var i = start, iTop = end; i < iTop;i++) { + y = (crc ^ string[i]) & 0xFF; + x = table[y]; + crc = (crc >>> 8) ^ x; + } + + return crc ^ (-1); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = BSON.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +/** + * Convert Uint8Array to String + * + * @ignore + * @api private + */ +var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { + return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); +} + +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + + return result; +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.deserialize = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + // Reads in a C style string + var readCStyleString = function() { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Grab utf8 encoded string + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); + // Update index position + index = i + 1; + // Return string + return string; + } + + // Create holding object + var object = isArray ? [] : {}; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var name = readCStyleString(); + // Switch on the type + switch(elementType) { + case BSON.BSON_DATA_OID: + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + break; + case BSON.BSON_DATA_STRING: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_INT: + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + break; + case BSON.BSON_DATA_NUMBER: + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + break; + case BSON.BSON_DATA_DATE: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + break; + case BSON.BSON_DATA_BOOLEAN: + // Parse the boolean value + object[name] = buffer[index++] == 1; + break; + case BSON.BSON_DATA_UNDEFINED: + case BSON.BSON_DATA_NULL: + // Parse the boolean value + object[name] = null; + break; + case BSON.BSON_DATA_BINARY: + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + break; + case BSON.BSON_DATA_ARRAY: + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, true); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_OBJECT: + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_REGEXP: + // Create the regexp + var source = readCStyleString(); + var regExpOptions = readCStyleString(); + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + break; + case BSON.BSON_DATA_LONG: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + break; + case BSON.BSON_DATA_SYMBOL: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_TIMESTAMP: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + break; + case BSON.BSON_DATA_MIN_KEY: + // Parse the object + object[name] = new MinKey(); + break; + case BSON.BSON_DATA_MAX_KEY: + // Parse the object + object[name] = new MaxKey(); + break; + case BSON.BSON_DATA_CODE: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Function string + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_CODE_W_SCOPE: + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Javascript function + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + + // Add string to object + break; + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Check if key name is valid. + * + * @ignore + * @api private + */ +BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { + if (!key.length) return; + // Check if we have a legal key for the object + if (!!~key.indexOf("\x00")) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + if (!dollarsAndDotsOk) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return BSON.deserialize(data, options); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { + return BSON.calculateObjectSize(object, serializeFunctions); +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { + return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); +} + +/** + * @ignore + * @api private + */ +module.exports = BSON; +module.exports.Code = Code; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js new file mode 100644 index 0000000..f19e44f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js @@ -0,0 +1,429 @@ +/// reduced to ~ 410 LOCs (parser only 300 vs. 1400+) with (some, needed) BSON classes "inlined". +/// Compare ~ 4,300 (22KB vs. 157KB) in browser build at: https://github.com/mongodb/js-bson/blob/master/browser_build/bson.js + +module.exports.calculateObjectSize = calculateObjectSize; + +function calculateObjectSize(object) { + var totalLength = (4 + 1); /// handles the obj.length prefix + terminating '0' ?! + for(var key in object) { /// looks like it handles arrays under the same for...in loop!? + totalLength += calculateElement(key, object[key]) + } + return totalLength; +} + +function calculateElement(name, value) { + var len = 1; /// always starting with 1 for the data type byte! + if (name) len += Buffer.byteLength(name, 'utf8') + 1; /// cstring: name + '0' termination + + if (value === undefined || value === null) return len; /// just the type byte plus name cstring + switch( value.constructor ) { /// removed all checks 'isBuffer' if Node.js Buffer class is present!? + + case ObjectID: /// we want these sorted from most common case to least common/deprecated; + return len + 12; + case String: + return len + 4 + Buffer.byteLength(value, 'utf8') +1; /// + case Number: + if (Math.floor(value) === value) { /// case: integer; pos.# more common, '&&' stops if 1st fails! + if ( value <= 2147483647 && value >= -2147483647 ) // 32 bit + return len + 4; + else return len + 8; /// covers Long-ish JS integers as Longs! + } else return len + 8; /// 8+1 --- covers Double & std. float + case Boolean: + return len + 1; + + case Array: + case Object: + return len + calculateObjectSize(value); + + case Buffer: /// replaces the entire Binary class! + return len + 4 + value.length + 1; + + case Regex: /// these are handled as strings by serializeFast() later, hence 'gim' opts = 3 + 1 chars + return len + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) +1; + case Date: + case Long: + case Timestamp: + case Double: + return len + 8; + + case MinKey: + case MaxKey: + return len; /// these two return the type byte and name cstring only! + } + return 0; +} + +module.exports.serializeFast = serializeFast; +module.exports.serialize = function(object, checkKeys, asBuffer, serializeFunctions, index) { + var buffer = new Buffer(calculateObjectSize(object)); + return serializeFast(object, checkKeys, buffer, 0); +} + +function serializeFast(object, checkKeys, buffer, i) { /// set checkKeys = false in query(..., options object to save performance IFF you're certain your keys are safe/system-set! + var size = buffer.length; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; /// these get overwritten later! + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + if (object.constructor === Array) { /// any need to checkKeys here?!? since we're doing for rather than for...in, should be safe from extra (non-numeric) keys added to the array?! + for(var j = 0; j < object.length; j++) { + i = packElement(j.toString(), object[j], checkKeys, buffer, i); + } + } else { /// checkKeys is needed if any suspicion of end-user key tampering/"injection" (a la SQL) + for(var key in object) { /// mostly there should never be direct access to them!? + if (checkKeys && (key.indexOf('\x00') >= 0 || key === '$where') ) { /// = "no script"?!; could add back key.indexOf('$') or maybe check for 'eval'?! +/// took out: || key.indexOf('.') >= 0... Don't we allow dot notation queries?! + console.log('checkKeys error: '); + return new Error('Illegal object key!'); + } + i = packElement(key, object[key], checkKeys, buffer, i); /// checkKeys pass needed for recursion! + } + } + buffer[i++] = 0; /// write terminating zero; !we do NOT -1 the index increase here as original does! + return i; +} + +function packElement(name, value, checkKeys, buffer, i) { /// serializeFunctions removed! checkKeys needed for Array & Object cases pass through (calling serializeFast recursively!) + if (value === undefined || value === null){ + buffer[i++] = 10; /// = BSON.BSON_DATA_NULL; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; /// buffer.write(...) returns bytesWritten! + return i; + } + switch(value.constructor) { + + case ObjectID: + buffer[i++] = 7; /// = BSON.BSON_DATA_OID; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// i += buffer.write(value.id, i, 'binary'); /// OLD: writes a String to a Buffer; 'binary' deprecated!! + value.id.copy(buffer, i); /// NEW ObjectID version has this.id = Buffer at the ready! + return i += 12; + + case String: + buffer[i++] = 2; /// = BSON.BSON_DATA_STRING; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + + var size = Buffer.byteLength(value) + 1; /// includes the terminating '0'!? + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + i += buffer.write(value, i, 'utf8'); buffer[i++] = 0; + return i; + + case Number: + if ( ~~(value) === value) { /// double-Tilde is equiv. to Math.floor(value) + if ( value <= 2147483647 && value >= -2147483647){ /// = BSON.BSON_INT32_MAX / MIN asf. + buffer[i++] = 16; /// = BSON.BSON_DATA_INT; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + buffer[i++] = value & 0xff; buffer[i++] = (value >> 8) & 0xff; + buffer[i++] = (value >> 16) & 0xff; buffer[i++] = (value >> 24) & 0xff; + +// Else large-ish JS int!? to Long!? + } else { /// if (value <= BSON.JS_INT_MAX && value >= BSON.JS_INT_MIN){ /// 9007199254740992 asf. + buffer[i++] = 18; /// = BSON.BSON_DATA_LONG; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var lowBits = ( value % 4294967296 ) | 0, highBits = ( value / 4294967296 ) | 0; + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + } + } else { /// we have a float / Double + buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); + buffer.writeDoubleLE(value, i); i += 8; + } + return i; + + case Boolean: + buffer[i++] = 8; /// = BSON.BSON_DATA_BOOLEAN; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + buffer[i++] = value ? 1 : 0; + return i; + + case Array: + case Object: + buffer[i++] = value.constructor === Array ? 4 : 3; /// = BSON.BSON_DATA_ARRAY / _OBJECT; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + + var endIndex = serializeFast(value, checkKeys, buffer, i); /// + 4); no longer needed b/c serializeFast writes a temp 4 bytes for length + var size = endIndex - i; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + return endIndex; + + /// case Binary: /// is basically identical unless special/deprecated options! + case Buffer: /// solves ALL of our Binary needs without the BSON.Binary class!? + buffer[i++] = 5; /// = BSON.BSON_DATA_BINARY; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var size = value.length; + buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; + buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; + + buffer[i++] = 0; /// write BSON.BSON_BINARY_SUBTYPE_DEFAULT; + value.copy(buffer, i); ///, 0, size); << defaults to sourceStart=0, sourceEnd=sourceBuffer.length); + i += size; + return i; + + case RegExp: + buffer[i++] = 11; /// = BSON.BSON_DATA_REGEXP; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + i += buffer.write(value.source, i, 'utf8'); buffer[i++] = 0x00; + + if (value.global) buffer[i++] = 0x73; // s = 'g' for JS Regex! + if (value.ignoreCase) buffer[i++] = 0x69; // i + if (value.multiline) buffer[i++] = 0x6d; // m + buffer[i++] = 0x00; + return i; + + case Date: + buffer[i++] = 9; /// = BSON.BSON_DATA_DATE; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var millis = value.getTime(); + var lowBits = ( millis % 4294967296 ) | 0, highBits = ( millis / 4294967296 ) | 0; + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + return i; + + case Long: + case Timestamp: + buffer[i++] = value.constructor === Long ? 18 : 17; /// = BSON.BSON_DATA_LONG / _TIMESTAMP + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + var lowBits = value.getLowBits(), highBits = value.getHighBits(); + + buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; + buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; + buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; + buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; + return i; + + case Double: + buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; + i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; +/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); i += 8; + buffer.writeDoubleLE(value, i); i += 8; + return i + + case MinKey: /// = BSON.BSON_DATA_MINKEY; + buffer[i++] = 127; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + return i; + case MaxKey: /// = BSON.BSON_DATA_MAXKEY; + buffer[i++] = 255; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; + return i; + + } /// end of switch + return i; /// ?! If no value to serialize +} + + +module.exports.deserializeFast = deserializeFast; + +function deserializeFast(buffer, i, isArray){ //// , options, isArray) { //// no more options! + if (buffer.length < 5) return new Error('Corrupt bson message < 5 bytes long'); /// from 'throw' + var elementType, tempindex = 0, name; + var string, low, high; /// = lowBits / highBits + /// using 'i' as the index to keep the lines shorter: + i || ( i = 0 ); /// for parseResponse it's 0; set to running index in deserialize(object/array) recursion + var object = isArray ? [] : {}; /// needed for type ARRAY recursion later! + var size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + if(size < 5 || size > buffer.length) return new Error('Corrupt BSON message'); +/// 'size' var was not used by anything after this, so we can reuse it + + while(true) { // While we have more left data left keep parsing + elementType = buffer[i++]; // Read the type + if (elementType === 0) break; // If we get a zero it's the last byte, exit + + tempindex = i; /// inlined readCStyleString & removed extra i= buffer.length) return new Error('Corrupt BSON document: illegal CString') + name = buffer.toString('utf8', i, tempindex); + i = tempindex + 1; /// Update index position to after the string + '0' termination + + switch(elementType) { + + case 7: /// = BSON.BSON_DATA_OID: + var buf = new Buffer(12); + buffer.copy(buf, 0, i, i += 12 ); /// copy 12 bytes from the current 'i' offset into fresh Buffer + object[name] = new ObjectID(buf); ///... & attach to the new ObjectID instance + break; + + case 2: /// = BSON.BSON_DATA_STRING: + size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; + object[name] = buffer.toString('utf8', i, i += size -1 ); + i++; break; /// need to get the '0' index "tick-forward" back! + + case 16: /// = BSON.BSON_DATA_INT: // Decode the 32bit value + object[name] = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; break; + + case 1: /// = BSON.BSON_DATA_NUMBER: // Decode the double value + object[name] = buffer.readDoubleLE(i); /// slightly faster depending on dec.points; a LOT cleaner + /// OLD: object[name] = readIEEE754(buffer, i, 'little', 52, 8); + i += 8; break; + + case 8: /// = BSON.BSON_DATA_BOOLEAN: + object[name] = buffer[i++] == 1; break; + + case 6: /// = BSON.BSON_DATA_UNDEFINED: /// deprecated + case 10: /// = BSON.BSON_DATA_NULL: + object[name] = null; break; + + case 4: /// = BSON.BSON_DATA_ARRAY + size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; /// NO 'i' increment since the size bytes are reread during the recursion! + object[name] = deserializeFast(buffer, i, true ); /// pass current index & set isArray = true + i += size; break; + case 3: /// = BSON.BSON_DATA_OBJECT: + size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; + object[name] = deserializeFast(buffer, i, false ); /// isArray = false => Object + i += size; break; + + case 5: /// = BSON.BSON_DATA_BINARY: // Decode the size of the binary blob + size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + buffer[i++]; /// Skip, as we assume always default subtype, i.e. 0! + object[name] = buffer.slice(i, i += size); /// creates a new Buffer "slice" view of the same memory! + break; + + case 9: /// = BSON.BSON_DATA_DATE: /// SEE notes below on the Date type vs. other options... + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + object[name] = new Date( high * 4294967296 + (low < 0 ? low + 4294967296 : low) ); break; + + case 18: /// = BSON.BSON_DATA_LONG: /// usage should be somewhat rare beyond parseResponse() -> cursorId, where it is handled inline, NOT as part of deserializeFast(returnedObjects); get lowBits, highBits: + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + + size = high * 4294967296 + (low < 0 ? low + 4294967296 : low); /// from long.toNumber() + if (size < JS_INT_MAX && size > JS_INT_MIN) object[name] = size; /// positive # more likely! + else object[name] = new Long(low, high); break; + + case 127: /// = BSON.BSON_DATA_MIN_KEY: /// do we EVER actually get these BACK from MongoDB server?! + object[name] = new MinKey(); break; + case 255: /// = BSON.BSON_DATA_MAX_KEY: + object[name] = new MaxKey(); break; + + case 17: /// = BSON.BSON_DATA_TIMESTAMP: /// somewhat obscure internal BSON type; MongoDB uses it for (pseudo) high-res time timestamp (past millisecs precision is just a counter!) in the Oplog ts: field, etc. + low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; + object[name] = new Timestamp(low, high); break; + +/// case 11: /// = RegExp is skipped; we should NEVER be getting any from the MongoDB server!? + } /// end of switch(elementType) + } /// end of while(1) + return object; // Return the finalized object +} + + +function MinKey() { this._bsontype = 'MinKey'; } /// these are merely placeholders/stubs to signify the type!? + +function MaxKey() { this._bsontype = 'MaxKey'; } + +function Long(low, high) { + this._bsontype = 'Long'; + this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. +} +Long.prototype.getLowBits = function(){ return this.low_; } +Long.prototype.getHighBits = function(){ return this.high_; } + +Long.prototype.toNumber = function(){ + return this.high_ * 4294967296 + (this.low_ < 0 ? this.low_ + 4294967296 : this.low_); +} +Long.fromNumber = function(num){ + return new Long(num % 4294967296, num / 4294967296); /// |0 is forced in the constructor! +} +function Double(value) { + this._bsontype = 'Double'; + this.value = value; +} +function Timestamp(low, high) { + this._bsontype = 'Timestamp'; + this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. +} +Timestamp.prototype.getLowBits = function(){ return this.low_; } +Timestamp.prototype.getHighBits = function(){ return this.high_; } + +/////////////////////////////// ObjectID ///////////////////////////////// +/// machine & proc IDs stored as 1 string, b/c Buffer shouldn't be held for long periods (could use SlowBuffer?!) + +var MACHINE = parseInt(Math.random() * 0xFFFFFF, 10); +var PROCESS = process.pid % 0xFFFF; +var MACHINE_AND_PROC = encodeIntBE(MACHINE, 3) + encodeIntBE(PROCESS, 2); /// keep as ONE string, ready to go. + +function encodeIntBE(data, bytes){ /// encode the bytes to a string + var result = ''; + if (bytes >= 4){ result += String.fromCharCode(Math.floor(data / 0x1000000)); data %= 0x1000000; } + if (bytes >= 3){ result += String.fromCharCode(Math.floor(data / 0x10000)); data %= 0x10000; } + if (bytes >= 2){ result += String.fromCharCode(Math.floor(data / 0x100)); data %= 0x100; } + result += String.fromCharCode(Math.floor(data)); + return result; +} +var _counter = ~~(Math.random() * 0xFFFFFF); /// double-tilde is equivalent to Math.floor() +var checkForHex = new RegExp('^[0-9a-fA-F]{24}$'); + +function ObjectID(id) { + this._bsontype = 'ObjectID'; + if (!id){ this.id = createFromScratch(); /// base case, DONE. + } else { + if (id.constructor === Buffer){ + this.id = id; /// case of + } else if (id.constructor === String) { + if ( id.length === 24 && checkForHex.test(id) ) { + this.id = new Buffer(id, 'hex'); + } else { + this.id = new Error('Illegal/faulty Hexadecimal string supplied!'); /// changed from 'throw' + } + } else if (id.constructor === Number) { + this.id = createFromTime(id); /// this is what should be the only interface for this!? + } + } +} +function createFromScratch() { + var buf = new Buffer(12), i = 0; + var ts = ~~(Date.now()/1000); /// 4 bytes timestamp in seconds, BigEndian notation! + buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; + buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; + + buf.write(MACHINE_AND_PROC, i, 5, 'utf8'); i += 5; /// write 3 bytes + 2 bytes MACHINE_ID and PROCESS_ID + _counter = ++_counter % 0xFFFFFF; /// 3 bytes internal _counter for subsecond resolution; BigEndian + buf[i++] = (_counter >> 16) & 0xFF; + buf[i++] = (_counter >> 8) & 0xFF; + buf[i++] = (_counter) & 0xFF; + return buf; +} +function createFromTime(ts) { + ts || ( ts = ~~(Date.now()/1000) ); /// 4 bytes timestamp in seconds only + var buf = new Buffer(12), i = 0; + buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; + buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; + + for (;i < 12; ++i) buf[i] = 0x00; /// indeces 4 through 11 (8 bytes) get filled up with nulls + return buf; +} +ObjectID.prototype.toHexString = function toHexString() { + return this.id.toString('hex'); +} +ObjectID.prototype.getTimestamp = function getTimestamp() { + return this.id.readUIntBE(0, 4); +} +ObjectID.prototype.getTimestampDate = function getTimestampDate() { + var ts = new Date(); + ts.setTime(this.id.readUIntBE(0, 4) * 1000); + return ts; +} +ObjectID.createPk = function createPk () { ///?override if a PrivateKey factory w/ unique factors is warranted?! + return new ObjectID(); +} +ObjectID.prototype.toJSON = function toJSON() { + return "ObjectID('" +this.id.toString('hex')+ "')"; +} + +/// module.exports.BSON = BSON; /// not needed anymore!? exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.Long = Long; /// ?! we really don't want to do the complicated Long math anywhere for now!? + +//module.exports.Double = Double; +//module.exports.Timestamp = Timestamp; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js new file mode 100644 index 0000000..8e942dd --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js @@ -0,0 +1,4843 @@ +var bson = (function(){ + + var pkgmap = {}, + global = {}, + nativeRequire = typeof require != 'undefined' && require, + lib, ties, main, async; + + function exports(){ return main(); }; + + exports.main = exports; + exports.module = module; + exports.packages = pkgmap; + exports.pkg = pkg; + exports.require = function require(uri){ + return pkgmap.main.index.require(uri); + }; + + + ties = {}; + + aliases = {}; + + + return exports; + +function join() { + return normalize(Array.prototype.join.call(arguments, "/")); +}; + +function normalize(path) { + var ret = [], parts = path.split('/'), cur, prev; + + var i = 0, l = parts.length-1; + for (; i <= l; i++) { + cur = parts[i]; + + if (cur === "." && prev !== undefined) continue; + + if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { + ret.pop(); + prev = ret.slice(-1)[0]; + } else { + if (prev === ".") ret.pop(); + ret.push(cur); + prev = cur; + } + } + + return ret.join("/"); +}; + +function dirname(path) { + return path && path.substr(0, path.lastIndexOf("/")) || "."; +}; + +function findModule(workingModule, uri){ + var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), + moduleIndexId = join(moduleId, 'index'), + pkg = workingModule.pkg, + module; + + var i = pkg.modules.length, + id; + + while(i-->0){ + id = pkg.modules[i].id; + + if(id==moduleId || id == moduleIndexId){ + module = pkg.modules[i]; + break; + } + } + + return module; +} + +function newRequire(callingModule){ + function require(uri){ + var module, pkg; + + if(/^\./.test(uri)){ + module = findModule(callingModule, uri); + } else if ( ties && ties.hasOwnProperty( uri ) ) { + return ties[uri]; + } else if ( aliases && aliases.hasOwnProperty( uri ) ) { + return require(aliases[uri]); + } else { + pkg = pkgmap[uri]; + + if(!pkg && nativeRequire){ + try { + pkg = nativeRequire(uri); + } catch (nativeRequireError) {} + + if(pkg) return pkg; + } + + if(!pkg){ + throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); + } + + module = pkg.index; + } + + if(!module){ + throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); + } + + module.parent = callingModule; + return module.call(); + }; + + + return require; +} + + +function module(parent, id, wrapper){ + var mod = { pkg: parent, id: id, wrapper: wrapper }, + cached = false; + + mod.exports = {}; + mod.require = newRequire(mod); + + mod.call = function(){ + if(cached) { + return mod.exports; + } + + cached = true; + + global.require = mod.require; + + mod.wrapper(mod, mod.exports, global, global.require); + return mod.exports; + }; + + if(parent.mainModuleId == mod.id){ + parent.index = mod; + parent.parents.length === 0 && ( main = mod.call ); + } + + parent.modules.push(mod); +} + +function pkg(/* [ parentId ...], wrapper */){ + var wrapper = arguments[ arguments.length - 1 ], + parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), + ctx = wrapper(parents); + + + pkgmap[ctx.name] = ctx; + + arguments.length == 1 && ( pkgmap.main = ctx ); + + return function(modules){ + var id; + for(id in modules){ + module(ctx, id, modules[id]); + } + }; +} + + +}(this)); + +bson.pkg(function(parents){ + + return { + 'name' : 'bson', + 'mainModuleId' : 'bson', + 'modules' : [], + 'parents' : parents + }; + +})({ 'binary': function(module, exports, global, require, undefined){ + /** + * Module dependencies. + */ +if(typeof window === 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +// Binary default subtype +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + * @api private + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for(var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +} + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + * @api private + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class Represents the Binary BSON type. + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Grid} + */ +function Binary(buffer, subType) { + if(!(this instanceof Binary)) return new Binary(buffer, subType); + + this._bsontype = 'Binary'; + + if(buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if(buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if(typeof buffer == 'string') { + // Different ways of writing the length of the string for the different types + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(buffer); + } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error("only String, Buffer, Uint8Array or Array accepted"); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if(typeof Uint8Array != 'undefined'){ + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +}; + +/** + * Updates this binary with byte_value. + * + * @param {Character} byte_value a single byte we wish to write. + * @api public + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); + if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); + + // Decode the byte value once + var decoded_byte = null; + if(typeof byte_value == 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if(byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if(this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + var buffer = null; + // Create a new buffer (typed or normal array) + if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for(var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. + * @param {Number} offset specify the binary of where to write the content. + * @api public + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset == 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if(this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) + // Copy the content + for(var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length + } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, 'binary', offset); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length; + } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' + || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if(typeof string == 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @param {Number} position read from the given position in the Binary. + * @param {Number} length the number of bytes to read. + * @return {Buffer} + * @api public + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 + ? length + : this.position; + + // Let's return the data based on the type we have + if(this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for(var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @return {String} + * @api public + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // If it's a node.js buffer object + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if(asRaw) { + // we support the slice command use it + if(this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for(var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @return {Number} the length of the binary. + * @api public + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + * @api private + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +} + +/** + * @ignore + * @api private + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +} + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +exports.Binary = Binary; + + +}, + + + +'binary_parser': function(module, exports, global, require, undefined){ + /** + * Binary Parser. + * Jonas Raoni Soares Silva + * http://jsfromhell.com/classes/binary-parser [v1.0] + */ +var chr = String.fromCharCode; + +var maxBits = []; +for (var i = 0; i < 64; i++) { + maxBits[i] = Math.pow(2, i); +} + +function BinaryParser (bigEndian, allowExceptions) { + if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); + + this.bigEndian = bigEndian; + this.allowExceptions = allowExceptions; +}; + +BinaryParser.warn = function warn (msg) { + if (this.allowExceptions) { + throw new Error(msg); + } + + return 1; +}; + +BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { + var b = new this.Buffer(this.bigEndian, data); + + b.checkBuffer(precisionBits + exponentBits + 1); + + var bias = maxBits[exponentBits - 1] - 1 + , signal = b.readBits(precisionBits + exponentBits, 1) + , exponent = b.readBits(precisionBits, exponentBits) + , significand = 0 + , divisor = 2 + , curByte = b.buffer.length + (-precisionBits >> 3) - 1; + + do { + for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); + } while (precisionBits -= startBit); + + return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); +}; + +BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { + var b = new this.Buffer(this.bigEndian || forceBigEndian, data) + , x = b.readBits(0, bits) + , max = maxBits[bits]; //max = Math.pow( 2, bits ); + + return signed && x >= max / 2 + ? x - max + : x; +}; + +BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { + var bias = maxBits[exponentBits - 1] - 1 + , minExp = -bias + 1 + , maxExp = bias + , minUnnormExp = minExp - precisionBits + , n = parseFloat(data) + , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 + , exp = 0 + , len = 2 * bias + 1 + precisionBits + 3 + , bin = new Array(len) + , signal = (n = status !== 0 ? 0 : n) < 0 + , intPart = Math.floor(n = Math.abs(n)) + , floatPart = n - intPart + , lastBit + , rounded + , result + , i + , j; + + for (i = len; i; bin[--i] = 0); + + for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); + + for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); + + for (i = -1; ++i < len && !bin[i];); + + if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { + if (!(rounded = bin[lastBit])) { + for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); + } + + for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); + } + + for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); + + if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { + ++i; + } else if (exp < minExp) { + exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); + i = bias + 1 - (exp = minExp - 1); + } + + if (intPart || status !== 0) { + this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); + exp = maxExp + 1; + i = bias + 2; + + if (status == -Infinity) { + signal = 1; + } else if (isNaN(status)) { + bin[i] = 1; + } + } + + for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); + + for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { + n += (1 << j) * result.charAt(--i); + if (j == 7) { + r[r.length] = String.fromCharCode(n); + n = 0; + } + } + + r[r.length] = n + ? String.fromCharCode(n) + : ""; + + return (this.bigEndian ? r.reverse() : r).join(""); +}; + +BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { + var max = maxBits[bits]; + + if (data >= max || data < -(max / 2)) { + this.warn("encodeInt::overflow"); + data = 0; + } + + if (data < 0) { + data += max; + } + + for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); + + for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); + + return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); +}; + +BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; +BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; +BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; +BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; +BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; +BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; +BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; +BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; +BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; +BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; +BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; +BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; +BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; +BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; +BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; +BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; + +// Factor out the encode so it can be shared by add_header and push_int32 +BinaryParser.encode_int32 = function encode_int32 (number, asArray) { + var a, b, c, d, unsigned; + unsigned = (number < 0) ? (number + 0x100000000) : number; + a = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + b = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + c = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + d = Math.floor(unsigned); + return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); +}; + +BinaryParser.encode_int64 = function encode_int64 (number) { + var a, b, c, d, e, f, g, h, unsigned; + unsigned = (number < 0) ? (number + 0x10000000000000000) : number; + a = Math.floor(unsigned / 0xffffffffffffff); + unsigned &= 0xffffffffffffff; + b = Math.floor(unsigned / 0xffffffffffff); + unsigned &= 0xffffffffffff; + c = Math.floor(unsigned / 0xffffffffff); + unsigned &= 0xffffffffff; + d = Math.floor(unsigned / 0xffffffff); + unsigned &= 0xffffffff; + e = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + f = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + g = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + h = Math.floor(unsigned); + return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); +}; + +/** + * UTF8 methods + */ + +// Take a raw binary string and return a utf8 string +BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { + var len = binaryStr.length + , decoded = '' + , i = 0 + , c = 0 + , c1 = 0 + , c2 = 0 + , c3; + + while (i < len) { + c = binaryStr.charCodeAt(i); + if (c < 128) { + decoded += String.fromCharCode(c); + i++; + } else if ((c > 191) && (c < 224)) { + c2 = binaryStr.charCodeAt(i+1); + decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = binaryStr.charCodeAt(i+1); + c3 = binaryStr.charCodeAt(i+2); + decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; + } + } + + return decoded; +}; + +// Encode a cstring +BinaryParser.encode_cstring = function encode_cstring (s) { + return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); +}; + +// Take a utf8 string and return a binary string +BinaryParser.encode_utf8 = function encode_utf8 (s) { + var a = "" + , c; + + for (var n = 0, len = s.length; n < len; n++) { + c = s.charCodeAt(n); + + if (c < 128) { + a += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + a += String.fromCharCode((c>>6) | 192) ; + a += String.fromCharCode((c&63) | 128); + } else { + a += String.fromCharCode((c>>12) | 224); + a += String.fromCharCode(((c>>6) & 63) | 128); + a += String.fromCharCode((c&63) | 128); + } + } + + return a; +}; + +BinaryParser.hprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } + } + + process.stdout.write("\n\n"); +}; + +BinaryParser.ilprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +BinaryParser.hlprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +/** + * BinaryParser buffer constructor. + */ +function BinaryParserBuffer (bigEndian, buffer) { + this.bigEndian = bigEndian || 0; + this.buffer = []; + this.setBuffer(buffer); +}; + +BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { + var l, i, b; + + if (data) { + i = l = data.length; + b = this.buffer = new Array(l); + for (; i; b[l - i] = data.charCodeAt(--i)); + this.bigEndian && b.reverse(); + } +}; + +BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { + return this.buffer.length >= -(-neededBits >> 3); +}; + +BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { + if (!this.hasNeededBits(neededBits)) { + throw new Error("checkBuffer::missing bytes"); + } +}; + +BinaryParserBuffer.prototype.readBits = function readBits (start, length) { + //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) + + function shl (a, b) { + for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); + return a; + } + + if (start < 0 || length <= 0) { + return 0; + } + + this.checkBuffer(start + length); + + var offsetLeft + , offsetRight = start % 8 + , curByte = this.buffer.length - ( start >> 3 ) - 1 + , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) + , diff = curByte - lastByte + , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); + + for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); + + return sum; +}; + +/** + * Expose. + */ +BinaryParser.Buffer = BinaryParserBuffer; + +exports.BinaryParser = BinaryParser; + +}, + + + +'bson': function(module, exports, global, require, undefined){ + var Long = require('./long').Long + , Double = require('./double').Double + , Timestamp = require('./timestamp').Timestamp + , ObjectID = require('./objectid').ObjectID + , Symbol = require('./symbol').Symbol + , Code = require('./code').Code + , MinKey = require('./min_key').MinKey + , MaxKey = require('./max_key').MaxKey + , DBRef = require('./db_ref').DBRef + , Binary = require('./binary').Binary + , BinaryParser = require('./binary_parser').BinaryParser + , writeIEEE754 = require('./float_parser').writeIEEE754 + , readIEEE754 = require('./float_parser').readIEEE754 + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +/** + * Create a new BSON instance + * + * @class Represents the BSON Parser + * @return {BSON} instance of BSON Parser. + */ +function BSON () {}; + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions) { + var isBuffer = typeof Buffer !== 'undefined'; + + switch(typeof value) { + case 'string': + return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } + case 'undefined': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + case 'boolean': + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); + } else if(serializeFunctions) { + return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; + } + } + } + + return 0; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { + // Default setting false + serializeFunctions = serializeFunctions == null ? false : serializeFunctions; + // Write end information (length of the object) + var size = buffer.length; + // Write the size of the object + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; +} + +/** + * @ignore + * @api private + */ +var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { + // Process the object + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Serialize the object + for(var key in object) { + // Check the key and throw error if it's illegal + if (key != '$db' && key != '$ref' && key != '$id') { + // dollars and dots ok + BSON.checkKey(key, !checkKeys); + } + + // Pack the element + index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); + } + } + + // Write zero + buffer[index++] = 0; + return index; +} + +var stringToBytes = function(str) { + var ch, st, re = []; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re.concat( st.reverse() ); + } + // return an array of bytes + return re; +} + +var numberOfBytes = function(str) { + var ch, st, re = 0; + for (var i = 0; i < str.length; i++ ) { + ch = str.charCodeAt(i); // get char + st = []; // set up "stack" + do { + st.push( ch & 0xFF ); // push byte to stack + ch = ch >> 8; // shift value down by 1 byte + } + while ( ch ); + // add stack contents to result + // done because chars have "wrong" endianness + re = re + st.length; + } + // return an array of bytes + return re; +} + +/** + * @ignore + * @api private + */ +var writeToTypedArray = function(buffer, string, index) { + var bytes = stringToBytes(string); + for(var i = 0; i < bytes.length; i++) { + buffer[index + i] = bytes[i]; + } + return bytes.length; +} + +/** + * @ignore + * @api private + */ +var supportsBuffer = typeof Buffer != 'undefined'; + +/** + * @ignore + * @api private + */ +var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { + var startIndex = index; + + switch(typeof value) { + case 'string': + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; + // Write the size of the string to buffer + buffer[index + 3] = (size >> 24) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index] = size & 0xff; + // Ajust the index + index = index + 4; + // Write the string + supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + // Return index + return index; + case 'number': + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; + case 'undefined': + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + case 'boolean': + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; + case 'object': + if(value === null || value instanceof MinKey || value instanceof MaxKey + || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + return index; + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write objectid + supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); + // Ajust index + index = index + 12; + return index; + } else if(value instanceof Date || isDate(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; + } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + // Write the type + buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; + } else if(value instanceof Double || value['_bsontype'] == 'Double') { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.code.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize + 4; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.code.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); + // Ajust index + index = index + value.position; + return index; + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate size + var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + buffer.write(value.value, index, 'utf8'); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + // Message size + var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); + // Serialize the object + var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write zero for object + buffer[endIndex++] = 0x00; + // Return the end index + return endIndex; + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Adjust the index + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); + // Write size + var size = endIndex - index; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + return endIndex; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + + // Write the regular expression string + buffer.write(value.source, index, 'utf8'); + // Adjust the index + index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Calculate the scope size + var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); + // Function string + var functionString = value.toString(); + // Function Size + var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + + // Calculate full size of the object + var totalSize = 4 + codeSize + scopeSize; + + // Write the total size of the object + buffer[index++] = totalSize & 0xff; + buffer[index++] = (totalSize >> 8) & 0xff; + buffer[index++] = (totalSize >> 16) & 0xff; + buffer[index++] = (totalSize >> 24) & 0xff; + + // Write the size of the string to buffer + buffer[index++] = codeSize & 0xff; + buffer[index++] = (codeSize >> 8) & 0xff; + buffer[index++] = (codeSize >> 16) & 0xff; + buffer[index++] = (codeSize >> 24) & 0xff; + + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + codeSize - 1; + // Write zero + buffer[index++] = 0; + // Serialize the scope object + var scopeObjectBuffer = new Buffer(scopeSize); + // Execute the serialization into a seperate buffer + serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); + + // Adjusted scope Size (removing the header) + var scopeDocSize = scopeSize - 4; + // Write scope object size + buffer[index++] = scopeDocSize & 0xff; + buffer[index++] = (scopeDocSize >> 8) & 0xff; + buffer[index++] = (scopeDocSize >> 16) & 0xff; + buffer[index++] = (scopeDocSize >> 24) & 0xff; + + // Write the scopeObject into the buffer + scopeObjectBuffer.copy(buffer, index, 0, scopeSize); + + // Adjust index, removing the empty size of the doc (5 bytes 0000000005) + index = index + scopeDocSize - 5; + // Write trailing zero + buffer[index++] = 0; + return index + } else if(serializeFunctions) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Function string + var functionString = value.toString(); + // Function Size + var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the string + supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); + // Update index + index = index + size - 1; + // Write zero + buffer[index++] = 0; + return index; + } + } + } + + // If no value to serialize + return index; +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + // Throw error if we are trying serialize an illegal type + if(object == null || typeof object != 'object' || Array.isArray(object)) + throw new Error("Only javascript objects supported"); + + // Emoty target buffer + var buffer = null; + // Calculate the size of the object + var size = BSON.calculateObjectSize(object, serializeFunctions); + // Fetch the best available type for storing the binary data + if(buffer = typeof Buffer != 'undefined') { + buffer = new Buffer(size); + asBuffer = true; + } else if(typeof Uint8Array != 'undefined') { + buffer = new Uint8Array(new ArrayBuffer(size)); + } else { + buffer = new Array(size); + } + + // If asBuffer is false use typed arrays + BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); + return buffer; +} + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Crc state variables shared by function + * + * @ignore + * @api private + */ +var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; + +/** + * CRC32 hash method, Fast and enough versitility for our usage + * + * @ignore + * @api private + */ +var crc32 = function(string, start, end) { + var crc = 0 + var x = 0; + var y = 0; + crc = crc ^ (-1); + + for(var i = start, iTop = end; i < iTop;i++) { + y = (crc ^ string[i]) & 0xFF; + x = table[y]; + crc = (crc >>> 8) ^ x; + } + + return crc ^ (-1); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = BSON.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +/** + * Convert Uint8Array to String + * + * @ignore + * @api private + */ +var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { + return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); +} + +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + + return result; +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.deserialize = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] || true; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + // Reads in a C style string + var readCStyleString = function() { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00) { i++ } + // Grab utf8 encoded string + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); + // Update index position + index = i + 1; + // Return string + return string; + } + + // Create holding object + var object = isArray ? [] : {}; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var name = readCStyleString(); + // Switch on the type + switch(elementType) { + case BSON.BSON_DATA_OID: + var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + break; + case BSON.BSON_DATA_STRING: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_INT: + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + break; + case BSON.BSON_DATA_NUMBER: + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + break; + case BSON.BSON_DATA_DATE: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + break; + case BSON.BSON_DATA_BOOLEAN: + // Parse the boolean value + object[name] = buffer[index++] == 1; + break; + case BSON.BSON_DATA_NULL: + // Parse the boolean value + object[name] = null; + break; + case BSON.BSON_DATA_BINARY: + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + break; + case BSON.BSON_DATA_ARRAY: + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, true); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_OBJECT: + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Set the array to the object + object[name] = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + break; + case BSON.BSON_DATA_REGEXP: + // Create the regexp + var source = readCStyleString(); + var regExpOptions = readCStyleString(); + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + break; + case BSON.BSON_DATA_LONG: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + break; + case BSON.BSON_DATA_SYMBOL: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_TIMESTAMP: + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + break; + case BSON.BSON_DATA_MIN_KEY: + // Parse the object + object[name] = new MinKey(); + break; + case BSON.BSON_DATA_MAX_KEY: + // Parse the object + object[name] = new MaxKey(); + break; + case BSON.BSON_DATA_CODE: + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Function string + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + break; + case BSON.BSON_DATA_CODE_W_SCOPE: + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Javascript function + var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = BSON.deserialize(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + + // Add string to object + break; + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Check if key name is valid. + * + * @ignore + * @api private + */ +BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { + if (!key.length) return; + // Check if we have a legal key for the object + if (!!~key.indexOf("\x00")) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + if (!dollarsAndDotsOk) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } +}; + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return BSON.deserialize(data, options); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { + return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { + return BSON.calculateObjectSize(object, serializeFunctions); +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { + return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); +} + +/** + * @ignore + * @api private + */ +exports.Code = Code; +exports.Symbol = Symbol; +exports.BSON = BSON; +exports.DBRef = DBRef; +exports.Binary = Binary; +exports.ObjectID = ObjectID; +exports.Long = Long; +exports.Timestamp = Timestamp; +exports.Double = Double; +exports.MinKey = MinKey; +exports.MaxKey = MaxKey; + +}, + + + +'code': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON Code type. + * + * @class Represents the BSON Code type. + * @param {String|Function} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +function Code(code, scope) { + if(!(this instanceof Code)) return new Code(code, scope); + + this._bsontype = 'Code'; + this.code = code; + this.scope = scope == null ? {} : scope; +}; + +/** + * @ignore + * @api private + */ +Code.prototype.toJSON = function() { + return {scope:this.scope, code:this.code}; +} + +exports.Code = Code; +}, + + + +'db_ref': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON DBRef type. + * + * @class Represents the BSON DBRef type. + * @param {String} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {String} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +}; + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + '$ref':this.namespace, + '$id':this.oid, + '$db':this.db == null ? '' : this.db + }; +} + +exports.DBRef = DBRef; +}, + + + +'double': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON Double type. + * + * @class Represents the BSON Double type. + * @param {Number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if(!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @return {Number} returns the wrapped double number. + * @api public + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + * @api private + */ +Double.prototype.toJSON = function() { + return this.value; +} + +exports.Double = Double; +}, + + + +'float_parser': function(module, exports, global, require, undefined){ + // Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, m, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : (nBytes - 1), + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, m, c, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = bBE ? (nBytes-1) : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e+eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754; +}, + + + +'index': function(module, exports, global, require, undefined){ + try { + exports.BSONPure = require('./bson'); + exports.BSONNative = require('../../ext'); +} catch(err) { + // do nothing +} + +[ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + exports[i] = module[i]; + } +}); + +// Exports all the classes for the NATIVE JS BSON Parser +exports.native = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long' + , '../../ext' +].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + // Return classes list + return classes; +} + +// Exports all the classes for the PURE JS BSON Parser +exports.pure = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './symbol' + , './timestamp' + , './long' + , '././bson'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + // Return classes list + return classes; +} + +}, + + + +'long': function(module, exports, global, require, undefined){ + // 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class Represents the BSON Long type. + * @param {Number} low the low (signed) 32 bits of the Long. + * @param {Number} high the high (signed) 32 bits of the Long. + */ +function Long(low, high) { + if(!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @api private + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @api private + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {Number} the value, assuming it is a 32-bit integer. + * @api public + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @return {Number} the closest floating-point representation to this value. + * @api public + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @return {String} the JSON representation. + * @api public + */ +Long.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @param {Number} [opt_radix] the radix in which the text should be written. + * @return {String} the textual representation of this value. + * @api public + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @return {Number} the high 32-bits as a signed value. + * @api public + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @return {Number} the low 32-bits as a signed value. + * @api public + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @return {Number} the low 32-bits as an unsigned value. + * @api public + */ +Long.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. + * @api public + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @return {Boolean} whether this value is zero. + * @api public + */ +Long.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @return {Boolean} whether this value is negative. + * @api public + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @return {Boolean} whether this value is odd. + * @api public + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Long equals the other + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long equals the other + * @api public + */ +Long.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Long does not equal the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long does not equal the other. + * @api public + */ +Long.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Long is less than the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is less than the other. + * @api public + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is less than or equal to the other. + * @api public + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is greater than the other. + * @api public + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @param {Long} other Long to compare against. + * @return {Boolean} whether this Long is greater than or equal to the other. + * @api public + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @param {Long} other Long to compare against. + * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + * @api public + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @return {Long} the negation of this value. + * @api public + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + * @api public + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + * @api public + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + * @api public + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && + other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + * @api public + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || + other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + * @api public + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @return {Long} the bitwise-NOT of this value. + * @api public + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + * @api public + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + * @api public + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + * @api public + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + * @api public + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + * @api public + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Long.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + * @api public + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @param {Number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @param {Number} value the number in question. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long( + (value % Long.TWO_PWR_32_DBL_) | 0, + (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @param {Number} lowBits the low 32-bits. + * @param {Number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @param {String} str the textual representation of the Long. + * @param {Number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + * @api public + */ +Long.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @api private + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @api private + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @api private + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = + Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @api private + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +exports.Long = Long; +}, + + + +'max_key': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON MaxKey type. + * + * @class Represents the BSON MaxKey type. + * @return {MaxKey} + */ +function MaxKey() { + if(!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +exports.MaxKey = MaxKey; +}, + + + +'min_key': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON MinKey type. + * + * @class Represents the BSON MinKey type. + * @return {MinKey} + */ +function MinKey() { + if(!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +exports.MinKey = MinKey; +}, + + + +'objectid': function(module, exports, global, require, undefined){ + /** + * Module dependencies. + */ +var BinaryParser = require('./binary_parser').BinaryParser; + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + */ +var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); + +/** +* Create a new ObjectID instance +* +* @class Represents the BSON ObjectID type +* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @return {Object} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id, _hex) { + if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); + + this._bsontype = 'ObjectID'; + var __id = null; + + // Throw an error if it's not a valid setup + if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + // Generate id based on the input + if(id == null || typeof id == 'number') { + // convert to 12 byte binary string + this.id = this.generate(id); + } else if(id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } else if(checkForHexRegExp.test(id)) { + return ObjectID.createFromHexString(id); + } else { + throw new Error("Value passed in is not a valid 24 character hex string"); + } + + if(ObjectID.cacheHexString) this.__id = this.toHexString(); +}; + +// Allow usage of ObjectId as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @return {String} return the 24 byte hex string representation. +* @api public +*/ +ObjectID.prototype.toHexString = function() { + if(ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @return {Number} returns next index value. +* @api private +*/ +ObjectID.prototype.get_inc = function() { + return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @return {Number} returns next index value. +* @api private +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id string used in ObjectID's +* +* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {String} return the 12 byte id binary string. +* @api private +*/ +ObjectID.prototype.generate = function(time) { + if ('number' == typeof time) { + var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); + /* for time-based ObjectID the bytes following the time will be zeroed */ + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + } else { + var unixTime = parseInt(Date.now()/1000,10); + var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + } + + return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @return {String} return the 24 byte hex string representation. +* @api private +*/ +ObjectID.prototype.toString = function() { + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @api private +*/ +ObjectID.prototype.inspect = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @api private +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @param {Object} otherID ObjectID instance to compare against. +* @return {Bool} the result of comparing two ObjectID's +* @api public +*/ +ObjectID.prototype.equals = function equals (otherID) { + var id = (otherID instanceof ObjectID || otherID.toHexString) + ? otherID.id + : ObjectID.createFromHexString(otherID).id; + + return this.id === id; +} + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @return {Date} the generation date +* @api public +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); + return timestamp; +} + +/** +* @ignore +* @api private +*/ +ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); + +ObjectID.createPk = function createPk () { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @param {Number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +* @api public +*/ +ObjectID.createFromTime = function createFromTime (time) { + var id = BinaryParser.encodeInt(time, 32, true, true) + + BinaryParser.encodeInt(0, 64, true, true); + return new ObjectID(id); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +* @api public +*/ +ObjectID.createFromHexString = function createFromHexString (hexString) { + // Throw an error if it's not a valid setup + if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + var len = hexString.length; + + if(len > 12*2) { + throw new Error('Id cannot be longer than 12 bytes'); + } + + var result = '' + , string + , number; + + for (var index = 0; index < len; index += 2) { + string = hexString.substr(index, 2); + number = parseInt(string, 16); + result += BinaryParser.fromByte(number); + } + + return new ObjectID(result, hexString); +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, "generationTime", { + enumerable: true + , get: function () { + return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); + } + , set: function (value) { + var value = BinaryParser.encodeInt(value, 32, true, true); + this.id = value + this.id.substr(4); + // delete this.__id; + this.toHexString(); + } +}); + +/** + * Expose. + */ +exports.ObjectID = ObjectID; +exports.ObjectId = ObjectID; + +}, + + + +'symbol': function(module, exports, global, require, undefined){ + /** + * A class representation of the BSON Symbol type. + * + * @class Represents the BSON Symbol type. + * @param {String} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if(!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @return {String} returns the wrapped string. + * @api public + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + * @api private + */ +Symbol.prototype.toString = function() { + return this.value; +} + +/** + * @ignore + * @api private + */ +Symbol.prototype.inspect = function() { + return this.value; +} + +/** + * @ignore + * @api private + */ +Symbol.prototype.toJSON = function() { + return this.value; +} + +exports.Symbol = Symbol; +}, + + + +'timestamp': function(module, exports, global, require, undefined){ + // 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class Represents the BSON Timestamp type. + * @param {Number} low the low (signed) 32 bits of the Timestamp. + * @param {Number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if(!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @api private + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @api private + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {Number} the value, assuming it is a 32-bit integer. + * @api public + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @return {Number} the closest floating-point representation to this value. + * @api public + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @return {String} the JSON representation. + * @api public + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @param {Number} [opt_radix] the radix in which the text should be written. + * @return {String} the textual representation of this value. + * @api public + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @return {Number} the high 32-bits as a signed value. + * @api public + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @return {Number} the low 32-bits as a signed value. + * @api public + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @return {Number} the low 32-bits as an unsigned value. + * @api public + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. + * @api public + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @return {Boolean} whether this value is zero. + * @api public + */ +Timestamp.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @return {Boolean} whether this value is negative. + * @api public + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @return {Boolean} whether this value is odd. + * @api public + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp equals the other + * @api public + */ +Timestamp.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp does not equal the other. + * @api public + */ +Timestamp.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is less than the other. + * @api public + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is less than or equal to the other. + * @api public + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is greater than the other. + * @api public + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} whether this Timestamp is greater than or equal to the other. + * @api public + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @param {Timestamp} other Timestamp to compare against. + * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + * @api public + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @return {Timestamp} the negation of this value. + * @api public + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + * @api public + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + * @api public + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + * @api public + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && + other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + * @api public + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || + other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + * @api public + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @return {Timestamp} the bitwise-NOT of this value. + * @api public + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + * @api public + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + * @api public + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + * @api public + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + * @api public + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + * @api public + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Timestamp.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @param {Number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + * @api public + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @param {Number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @param {Number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @param {Number} lowBits the low 32-bits. + * @param {Number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @param {String} str the textual representation of the Timestamp. + * @param {Number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + * @api public + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @api private + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @api private + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = + Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @api private + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +exports.Timestamp = Timestamp; +}, + + }); + + +if(typeof module != 'undefined' && module.exports ){ + module.exports = bson; + + if( !module.parent ){ + bson(); + } +} + +if(typeof window != 'undefined' && typeof require == 'undefined'){ + window.require = bson.require; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json new file mode 100644 index 0000000..3ebb587 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json @@ -0,0 +1,8 @@ +{ "name" : "bson" +, "description" : "A bson parser for node.js and the browser" +, "main": "../lib/bson/bson" +, "directories" : { "lib" : "../lib/bson" } +, "engines" : { "node" : ">=0.6.0" } +, "licenses" : [ { "type" : "Apache License, Version 2.0" + , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js new file mode 100644 index 0000000..ef74b16 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js @@ -0,0 +1,344 @@ +/** + * Module dependencies. + * @ignore + */ +if(typeof window === 'undefined') { + var Buffer = require('buffer').Buffer; // TODO just use global Buffer +} + +/** + * A class representation of the BSON Binary type. + * + * Sub types + * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. + * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. + * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. + * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. + * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. + * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. + * + * @class + * @param {Buffer} buffer a buffer object containing the binary data. + * @param {Number} [subType] the option binary type. + * @return {Binary} + */ +function Binary(buffer, subType) { + if(!(this instanceof Binary)) return new Binary(buffer, subType); + + this._bsontype = 'Binary'; + + if(buffer instanceof Number) { + this.sub_type = buffer; + this.position = 0; + } else { + this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; + this.position = 0; + } + + if(buffer != null && !(buffer instanceof Number)) { + // Only accept Buffer, Uint8Array or Arrays + if(typeof buffer == 'string') { + // Different ways of writing the length of the string for the different types + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(buffer); + } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { + this.buffer = writeStringToArray(buffer); + } else { + throw new Error("only String, Buffer, Uint8Array or Array accepted"); + } + } else { + this.buffer = buffer; + } + this.position = buffer.length; + } else { + if(typeof Buffer != 'undefined') { + this.buffer = new Buffer(Binary.BUFFER_SIZE); + } else if(typeof Uint8Array != 'undefined'){ + this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); + } else { + this.buffer = new Array(Binary.BUFFER_SIZE); + } + // Set position to start of buffer + this.position = 0; + } +}; + +/** + * Updates this binary with byte_value. + * + * @method + * @param {string} byte_value a single byte we wish to write. + */ +Binary.prototype.put = function put(byte_value) { + // If it's a string and a has more than one character throw an error + if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); + if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); + + // Decode the byte value once + var decoded_byte = null; + if(typeof byte_value == 'string') { + decoded_byte = byte_value.charCodeAt(0); + } else if(byte_value['length'] != null) { + decoded_byte = byte_value[0]; + } else { + decoded_byte = byte_value; + } + + if(this.buffer.length > this.position) { + this.buffer[this.position++] = decoded_byte; + } else { + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + // Create additional overflow buffer + var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); + // Combine the two buffers together + this.buffer.copy(buffer, 0, 0, this.buffer.length); + this.buffer = buffer; + this.buffer[this.position++] = decoded_byte; + } else { + var buffer = null; + // Create a new buffer (typed or normal array) + if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); + } else { + buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); + } + + // We need to copy all the content to the new array + for(var i = 0; i < this.buffer.length; i++) { + buffer[i] = this.buffer[i]; + } + + // Reassign the buffer + this.buffer = buffer; + // Write the byte + this.buffer[this.position++] = decoded_byte; + } + } +}; + +/** + * Writes a buffer or string to the binary. + * + * @method + * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. + * @param {number} offset specify the binary of where to write the content. + * @return {null} + */ +Binary.prototype.write = function write(string, offset) { + offset = typeof offset == 'number' ? offset : this.position; + + // If the buffer is to small let's extend the buffer + if(this.buffer.length < offset + string.length) { + var buffer = null; + // If we are in node.js + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + buffer = new Buffer(this.buffer.length + string.length); + this.buffer.copy(buffer, 0, 0, this.buffer.length); + } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { + // Create a new buffer + buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) + // Copy the content + for(var i = 0; i < this.position; i++) { + buffer[i] = this.buffer[i]; + } + } + + // Assign the new buffer + this.buffer = buffer; + } + + if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { + string.copy(this.buffer, offset, 0, string.length); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length + } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { + this.buffer.write(string, offset, 'binary'); + this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; + // offset = string.length; + } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' + || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string[i]; + } + + this.position = offset > this.position ? offset : this.position; + } else if(typeof string == 'string') { + for(var i = 0; i < string.length; i++) { + this.buffer[offset++] = string.charCodeAt(i); + } + + this.position = offset > this.position ? offset : this.position; + } +}; + +/** + * Reads **length** bytes starting at **position**. + * + * @method + * @param {number} position read from the given position in the Binary. + * @param {number} length the number of bytes to read. + * @return {Buffer} + */ +Binary.prototype.read = function read(position, length) { + length = length && length > 0 + ? length + : this.position; + + // Let's return the data based on the type we have + if(this.buffer['slice']) { + return this.buffer.slice(position, position + length); + } else { + // Create a buffer to keep the result + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); + for(var i = 0; i < length; i++) { + buffer[i] = this.buffer[position++]; + } + } + // Return the buffer + return buffer; +}; + +/** + * Returns the value of this binary as a string. + * + * @method + * @return {string} + */ +Binary.prototype.value = function value(asRaw) { + asRaw = asRaw == null ? false : asRaw; + + // Optimize to serialize for the situation where the data == size of buffer + if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) + return this.buffer; + + // If it's a node.js buffer object + if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { + return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); + } else { + if(asRaw) { + // we support the slice command use it + if(this.buffer['slice'] != null) { + return this.buffer.slice(0, this.position); + } else { + // Create a new buffer to copy content to + var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); + // Copy content + for(var i = 0; i < this.position; i++) { + newBuffer[i] = this.buffer[i]; + } + // Return the buffer + return newBuffer; + } + } else { + return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); + } + } +}; + +/** + * Length. + * + * @method + * @return {number} the length of the binary. + */ +Binary.prototype.length = function length() { + return this.position; +}; + +/** + * @ignore + */ +Binary.prototype.toJSON = function() { + return this.buffer != null ? this.buffer.toString('base64') : ''; +} + +/** + * @ignore + */ +Binary.prototype.toString = function(format) { + return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; +} + +/** + * Binary default subtype + * @ignore + */ +var BSON_BINARY_SUBTYPE_DEFAULT = 0; + +/** + * @ignore + */ +var writeStringToArray = function(data) { + // Create a buffer + var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); + // Write the content to the buffer + for(var i = 0; i < data.length; i++) { + buffer[i] = data.charCodeAt(i); + } + // Write the string to the buffer + return buffer; +} + +/** + * Convert Array ot Uint8Array to Binary String + * + * @ignore + */ +var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { + var result = ""; + for(var i = startIndex; i < endIndex; i++) { + result = result + String.fromCharCode(byteArray[i]); + } + return result; +}; + +Binary.BUFFER_SIZE = 256; + +/** + * Default BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_DEFAULT = 0; +/** + * Function BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_FUNCTION = 1; +/** + * Byte Array BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_BYTE_ARRAY = 2; +/** + * OLD UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID_OLD = 3; +/** + * UUID BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_UUID = 4; +/** + * MD5 BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_MD5 = 5; +/** + * User BSON type + * + * @classconstant SUBTYPE_DEFAULT + **/ +Binary.SUBTYPE_USER_DEFINED = 128; + +/** + * Expose. + */ +module.exports = Binary; +module.exports.Binary = Binary; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js new file mode 100644 index 0000000..d2fc811 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js @@ -0,0 +1,385 @@ +/** + * Binary Parser. + * Jonas Raoni Soares Silva + * http://jsfromhell.com/classes/binary-parser [v1.0] + */ +var chr = String.fromCharCode; + +var maxBits = []; +for (var i = 0; i < 64; i++) { + maxBits[i] = Math.pow(2, i); +} + +function BinaryParser (bigEndian, allowExceptions) { + if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); + + this.bigEndian = bigEndian; + this.allowExceptions = allowExceptions; +}; + +BinaryParser.warn = function warn (msg) { + if (this.allowExceptions) { + throw new Error(msg); + } + + return 1; +}; + +BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { + var b = new this.Buffer(this.bigEndian, data); + + b.checkBuffer(precisionBits + exponentBits + 1); + + var bias = maxBits[exponentBits - 1] - 1 + , signal = b.readBits(precisionBits + exponentBits, 1) + , exponent = b.readBits(precisionBits, exponentBits) + , significand = 0 + , divisor = 2 + , curByte = b.buffer.length + (-precisionBits >> 3) - 1; + + do { + for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); + } while (precisionBits -= startBit); + + return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); +}; + +BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { + var b = new this.Buffer(this.bigEndian || forceBigEndian, data) + , x = b.readBits(0, bits) + , max = maxBits[bits]; //max = Math.pow( 2, bits ); + + return signed && x >= max / 2 + ? x - max + : x; +}; + +BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { + var bias = maxBits[exponentBits - 1] - 1 + , minExp = -bias + 1 + , maxExp = bias + , minUnnormExp = minExp - precisionBits + , n = parseFloat(data) + , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 + , exp = 0 + , len = 2 * bias + 1 + precisionBits + 3 + , bin = new Array(len) + , signal = (n = status !== 0 ? 0 : n) < 0 + , intPart = Math.floor(n = Math.abs(n)) + , floatPart = n - intPart + , lastBit + , rounded + , result + , i + , j; + + for (i = len; i; bin[--i] = 0); + + for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); + + for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); + + for (i = -1; ++i < len && !bin[i];); + + if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { + if (!(rounded = bin[lastBit])) { + for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); + } + + for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); + } + + for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); + + if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { + ++i; + } else if (exp < minExp) { + exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); + i = bias + 1 - (exp = minExp - 1); + } + + if (intPart || status !== 0) { + this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); + exp = maxExp + 1; + i = bias + 2; + + if (status == -Infinity) { + signal = 1; + } else if (isNaN(status)) { + bin[i] = 1; + } + } + + for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); + + for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { + n += (1 << j) * result.charAt(--i); + if (j == 7) { + r[r.length] = String.fromCharCode(n); + n = 0; + } + } + + r[r.length] = n + ? String.fromCharCode(n) + : ""; + + return (this.bigEndian ? r.reverse() : r).join(""); +}; + +BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { + var max = maxBits[bits]; + + if (data >= max || data < -(max / 2)) { + this.warn("encodeInt::overflow"); + data = 0; + } + + if (data < 0) { + data += max; + } + + for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); + + for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); + + return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); +}; + +BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; +BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; +BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; +BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; +BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; +BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; +BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; +BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; +BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; +BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; +BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; +BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; +BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; +BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; +BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; +BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; +BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; +BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; + +// Factor out the encode so it can be shared by add_header and push_int32 +BinaryParser.encode_int32 = function encode_int32 (number, asArray) { + var a, b, c, d, unsigned; + unsigned = (number < 0) ? (number + 0x100000000) : number; + a = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + b = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + c = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + d = Math.floor(unsigned); + return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); +}; + +BinaryParser.encode_int64 = function encode_int64 (number) { + var a, b, c, d, e, f, g, h, unsigned; + unsigned = (number < 0) ? (number + 0x10000000000000000) : number; + a = Math.floor(unsigned / 0xffffffffffffff); + unsigned &= 0xffffffffffffff; + b = Math.floor(unsigned / 0xffffffffffff); + unsigned &= 0xffffffffffff; + c = Math.floor(unsigned / 0xffffffffff); + unsigned &= 0xffffffffff; + d = Math.floor(unsigned / 0xffffffff); + unsigned &= 0xffffffff; + e = Math.floor(unsigned / 0xffffff); + unsigned &= 0xffffff; + f = Math.floor(unsigned / 0xffff); + unsigned &= 0xffff; + g = Math.floor(unsigned / 0xff); + unsigned &= 0xff; + h = Math.floor(unsigned); + return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); +}; + +/** + * UTF8 methods + */ + +// Take a raw binary string and return a utf8 string +BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { + var len = binaryStr.length + , decoded = '' + , i = 0 + , c = 0 + , c1 = 0 + , c2 = 0 + , c3; + + while (i < len) { + c = binaryStr.charCodeAt(i); + if (c < 128) { + decoded += String.fromCharCode(c); + i++; + } else if ((c > 191) && (c < 224)) { + c2 = binaryStr.charCodeAt(i+1); + decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); + i += 2; + } else { + c2 = binaryStr.charCodeAt(i+1); + c3 = binaryStr.charCodeAt(i+2); + decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); + i += 3; + } + } + + return decoded; +}; + +// Encode a cstring +BinaryParser.encode_cstring = function encode_cstring (s) { + return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); +}; + +// Take a utf8 string and return a binary string +BinaryParser.encode_utf8 = function encode_utf8 (s) { + var a = "" + , c; + + for (var n = 0, len = s.length; n < len; n++) { + c = s.charCodeAt(n); + + if (c < 128) { + a += String.fromCharCode(c); + } else if ((c > 127) && (c < 2048)) { + a += String.fromCharCode((c>>6) | 192) ; + a += String.fromCharCode((c&63) | 128); + } else { + a += String.fromCharCode((c>>12) | 224); + a += String.fromCharCode(((c>>6) & 63) | 128); + a += String.fromCharCode((c&63) | 128); + } + } + + return a; +}; + +BinaryParser.hprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + process.stdout.write(number + " ") + } + } + + process.stdout.write("\n\n"); +}; + +BinaryParser.ilprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(10) + : s.charCodeAt(i).toString(10); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +BinaryParser.hlprint = function hprint (s) { + var number; + + for (var i = 0, len = s.length; i < len; i++) { + if (s.charCodeAt(i) < 32) { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '); + } else { + number = s.charCodeAt(i) <= 15 + ? "0" + s.charCodeAt(i).toString(16) + : s.charCodeAt(i).toString(16); + require('util').debug(number+' : '+ s.charAt(i)); + } + } +}; + +/** + * BinaryParser buffer constructor. + */ +function BinaryParserBuffer (bigEndian, buffer) { + this.bigEndian = bigEndian || 0; + this.buffer = []; + this.setBuffer(buffer); +}; + +BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { + var l, i, b; + + if (data) { + i = l = data.length; + b = this.buffer = new Array(l); + for (; i; b[l - i] = data.charCodeAt(--i)); + this.bigEndian && b.reverse(); + } +}; + +BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { + return this.buffer.length >= -(-neededBits >> 3); +}; + +BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { + if (!this.hasNeededBits(neededBits)) { + throw new Error("checkBuffer::missing bytes"); + } +}; + +BinaryParserBuffer.prototype.readBits = function readBits (start, length) { + //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) + + function shl (a, b) { + for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); + return a; + } + + if (start < 0 || length <= 0) { + return 0; + } + + this.checkBuffer(start + length); + + var offsetLeft + , offsetRight = start % 8 + , curByte = this.buffer.length - ( start >> 3 ) - 1 + , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) + , diff = curByte - lastByte + , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); + + for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); + + return sum; +}; + +/** + * Expose. + */ +BinaryParser.Buffer = BinaryParserBuffer; + +exports.BinaryParser = BinaryParser; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js new file mode 100644 index 0000000..36f0057 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js @@ -0,0 +1,323 @@ +// "use strict" + +var writeIEEE754 = require('./float_parser').writeIEEE754, + readIEEE754 = require('./float_parser').readIEEE754, + Map = require('./map'), + Long = require('./long').Long, + Double = require('./double').Double, + Timestamp = require('./timestamp').Timestamp, + ObjectID = require('./objectid').ObjectID, + BSONRegExp = require('./regexp').BSONRegExp, + Symbol = require('./symbol').Symbol, + Code = require('./code').Code, + MinKey = require('./min_key').MinKey, + MaxKey = require('./max_key').MaxKey, + DBRef = require('./db_ref').DBRef, + Binary = require('./binary').Binary; + +// Parts of the parser +var deserialize = require('./parser/deserializer'), + serializer = require('./parser/serializer'), + calculateObjectSize = require('./parser/calculate_size'); + +/** + * @ignore + * @api private + */ +// Max Size +var MAXSIZE = (1024*1024*17); +// Max Document Buffer size +var buffer = new Buffer(MAXSIZE); + +var BSON = function() { +} + +/** + * Serialize a Javascript object. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Buffer} returns the Buffer object containing the serialized object. + * @api public + */ +BSON.prototype.serialize = function serialize(object, checkKeys, asBuffer, serializeFunctions, index, ignoreUndefined) { + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, index || 0, 0, serializeFunctions, ignoreUndefined); + // Create the final buffer + var finishedBuffer = new Buffer(serializationIndex); + // Copy into the finished buffer + buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); + // Return the buffer + return finishedBuffer; +} + +/** + * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. + * + * @param {Object} object the Javascript object to serialize. + * @param {Boolean} checkKeys the serializer will check if keys are valid. + * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. + * @param {Number} index the index in the buffer where we wish to start serializing into. + * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. + * @return {Number} returns the new write index in the Buffer. + * @api public + */ +BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, finalBuffer, startIndex, serializeFunctions, ignoreUndefined) { + // Attempt to serialize + var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); + buffer.copy(finalBuffer, startIndex, 0, serializationIndex); + // Return the index + return startIndex + serializationIndex - 1; +} + +/** + * Deserialize data as BSON. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. + * @param {Object} [options] additional options used for the deserialization. + * @param {Boolean} [isArray] ignore used for recursive parsing. + * @return {Object} returns the deserialized Javascript Object. + * @api public + */ +BSON.prototype.deserialize = function(data, options) { + return deserialize(data, options); +} + +/** + * Calculate the bson size for a passed in Javascript object. + * + * @param {Object} object the Javascript object to calculate the BSON byte size for. + * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. + * @return {Number} returns the number of bytes the BSON object will take up. + * @api public + */ +BSON.prototype.calculateObjectSize = function(object, serializeFunctions, ignoreUndefined) { + return calculateObjectSize(object, serializeFunctions, ignoreUndefined); +} + +/** + * Deserialize stream data as BSON documents. + * + * Options + * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. + * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. + * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. + * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits + * + * @param {Buffer} data the buffer containing the serialized set of BSON documents. + * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. + * @param {Number} numberOfDocuments number of documents to deserialize. + * @param {Array} documents an array where to store the deserialized documents. + * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. + * @param {Object} [options] additional options used for the deserialization. + * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. + * @api public + */ +BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { + // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); + options = options != null ? options : {}; + var index = startIndex; + // Loop over all documents + for(var i = 0; i < numberOfDocuments; i++) { + // Find size of the document + var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; + // Update options with index + options['index'] = index; + // Parse the document at this point + documents[docStartIndex + i] = this.deserialize(data, options); + // Adjust index by the document size + index = index + size; + } + + // Return object containing end index of parsing and list of documents + return index; +} + +/** + * @ignore + * @api private + */ +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// Return BSON +module.exports = BSON; +module.exports.Code = Code; +module.exports.Map = Map; +module.exports.Symbol = Symbol; +module.exports.BSON = BSON; +module.exports.DBRef = DBRef; +module.exports.Binary = Binary; +module.exports.ObjectID = ObjectID; +module.exports.Long = Long; +module.exports.Timestamp = Timestamp; +module.exports.Double = Double; +module.exports.MinKey = MinKey; +module.exports.MaxKey = MaxKey; +module.exports.BSONRegExp = BSONRegExp; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js new file mode 100644 index 0000000..83a42c9 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js @@ -0,0 +1,24 @@ +/** + * A class representation of the BSON Code type. + * + * @class + * @param {(string|function)} code a string or function. + * @param {Object} [scope] an optional scope for the function. + * @return {Code} + */ +var Code = function Code(code, scope) { + if(!(this instanceof Code)) return new Code(code, scope); + this._bsontype = 'Code'; + this.code = code; + this.scope = scope == null ? {} : scope; +}; + +/** + * @ignore + */ +Code.prototype.toJSON = function() { + return {scope:this.scope, code:this.code}; +} + +module.exports = Code; +module.exports.Code = Code; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js new file mode 100644 index 0000000..06789a6 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js @@ -0,0 +1,32 @@ +/** + * A class representation of the BSON DBRef type. + * + * @class + * @param {string} namespace the collection name. + * @param {ObjectID} oid the reference ObjectID. + * @param {string} [db] optional db name, if omitted the reference is local to the current db. + * @return {DBRef} + */ +function DBRef(namespace, oid, db) { + if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); + + this._bsontype = 'DBRef'; + this.namespace = namespace; + this.oid = oid; + this.db = db; +}; + +/** + * @ignore + * @api private + */ +DBRef.prototype.toJSON = function() { + return { + '$ref':this.namespace, + '$id':this.oid, + '$db':this.db == null ? '' : this.db + }; +} + +module.exports = DBRef; +module.exports.DBRef = DBRef; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js new file mode 100644 index 0000000..09ed222 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js @@ -0,0 +1,33 @@ +/** + * A class representation of the BSON Double type. + * + * @class + * @param {number} value the number we want to represent as a double. + * @return {Double} + */ +function Double(value) { + if(!(this instanceof Double)) return new Double(value); + + this._bsontype = 'Double'; + this.value = value; +} + +/** + * Access the number value. + * + * @method + * @return {number} returns the wrapped double number. + */ +Double.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Double.prototype.toJSON = function() { + return this.value; +} + +module.exports = Double; +module.exports.Double = Double; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js new file mode 100644 index 0000000..6fca392 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js @@ -0,0 +1,121 @@ +// Copyright (c) 2008, Fair Oaks Labs, Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// +// +// Modifications to writeIEEE754 to support negative zeroes made by Brian White + +var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { + var e, m, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + nBits = -7, + i = bBE ? 0 : (nBytes - 1), + d = bBE ? 1 : -1, + s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity); + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; + +var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { + var e, m, c, + bBE = (endian === 'big'), + eLen = nBytes * 8 - mLen - 1, + eMax = (1 << eLen) - 1, + eBias = eMax >> 1, + rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), + i = bBE ? (nBytes-1) : 0, + d = bBE ? -1 : 1, + s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e+eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); + + buffer[offset + i - d] |= s * 128; +}; + +exports.readIEEE754 = readIEEE754; +exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js new file mode 100644 index 0000000..f4147b2 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js @@ -0,0 +1,86 @@ +try { + exports.BSONPure = require('./bson'); + exports.BSONNative = require('bson-ext'); +} catch(err) { +} + +[ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './symbol' + , './timestamp' + , './long'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + exports[i] = module[i]; + } +}); + +// Exports all the classes for the PURE JS BSON Parser +exports.pure = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './symbol' + , './timestamp' + , './long' + , '././bson'].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + // Return classes list + return classes; +} + +// Exports all the classes for the NATIVE JS BSON Parser +exports.native = function() { + var classes = {}; + // Map all the classes + [ './binary_parser' + , './binary' + , './code' + , './map' + , './db_ref' + , './double' + , './max_key' + , './min_key' + , './objectid' + , './regexp' + , './symbol' + , './timestamp' + , './long' + ].forEach(function (path) { + var module = require('./' + path); + for (var i in module) { + classes[i] = module[i]; + } + }); + + // Catch error and return no classes found + try { + classes['BSON'] = require('bson-ext') + } catch(err) { + return exports.pure(); + } + + // Return classes list + return classes; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js new file mode 100644 index 0000000..6f18885 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js @@ -0,0 +1,856 @@ +// 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * Defines a Long class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Long". This + * implementation is derived from LongLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Longs. + * + * The internal representation of a Long is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Long. + * @param {number} high the high (signed) 32 bits of the Long. + * @return {Long} + */ +function Long(low, high) { + if(!(this instanceof Long)) return new Long(low, high); + + this._bsontype = 'Long'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @method + * @return {number} the value, assuming it is a 32-bit integer. + */ +Long.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Long.prototype.toNumber = function() { + return this.high_ * Long.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Long.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Long.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + // We need to change the Long value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixLong = Long.fromNumber(radix); + var div = this.div(radixLong); + var rem = div.multiply(radixLong).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Long.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Long.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Long.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Long. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Long. + */ +Long.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Long.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Long.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Long.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Long.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Long equals the other + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long equals the other + */ +Long.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Long does not equal the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long does not equal the other. + */ +Long.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Long is less than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than the other. + */ +Long.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Long is less than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is less than or equal to the other. + */ +Long.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Long is greater than the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than the other. + */ +Long.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Long is greater than or equal to the other. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} whether this Long is greater than or equal to the other. + */ +Long.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Long with the given one. + * + * @method + * @param {Long} other Long to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Long.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Long} the negation of this value. + */ +Long.prototype.negate = function() { + if (this.equals(Long.MIN_VALUE)) { + return Long.MIN_VALUE; + } else { + return this.not().add(Long.ONE); + } +}; + +/** + * Returns the sum of this and the given Long. + * + * @method + * @param {Long} other Long to add to this one. + * @return {Long} the sum of this and the given Long. + */ +Long.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Long. + * + * @method + * @param {Long} other Long to subtract from this. + * @return {Long} the difference of this and the given Long. + */ +Long.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Long. + * + * @method + * @param {Long} other Long to multiply with this. + * @return {Long} the product of this and the other. + */ +Long.prototype.multiply = function(other) { + if (this.isZero()) { + return Long.ZERO; + } else if (other.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } else if (other.equals(Long.MIN_VALUE)) { + return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Longs are small, use float multiplication + if (this.lessThan(Long.TWO_PWR_24_) && + other.lessThan(Long.TWO_PWR_24_)) { + return Long.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Long divided by the given one. + * + * @method + * @param {Long} other Long by which to divide. + * @return {Long} this Long divided by the given one. + */ +Long.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Long.ZERO; + } + + if (this.equals(Long.MIN_VALUE)) { + if (other.equals(Long.ONE) || + other.equals(Long.NEG_ONE)) { + return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Long.ZERO)) { + return other.isNegative() ? Long.ONE : Long.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Long.MIN_VALUE)) { + return Long.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Long.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Long.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Long.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Long.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Long modulo the given one. + * + * @method + * @param {Long} other Long by which to mod. + * @return {Long} this Long modulo the given one. + */ +Long.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Long} the bitwise-NOT of this value. + */ +Long.prototype.not = function() { + return Long.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to AND. + * @return {Long} the bitwise-AND of this and the other. + */ +Long.prototype.and = function(other) { + return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to OR. + * @return {Long} the bitwise-OR of this and the other. + */ +Long.prototype.or = function(other) { + return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Long and the given one. + * + * @method + * @param {Long} other the Long with which to XOR. + * @return {Long} the bitwise-XOR of this and the other. + */ +Long.prototype.xor = function(other) { + return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Long with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the left by the given amount. + */ +Long.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Long.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Long.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount. + */ +Long.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Long.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Long.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Long.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Long.fromBits(high, 0); + } else { + return Long.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Long representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Long} the corresponding Long value. + */ +Long.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Long.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Long(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Long.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Long} the corresponding Long value. + */ +Long.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Long.ZERO; + } else if (value <= -Long.TWO_PWR_63_DBL_) { + return Long.MIN_VALUE; + } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { + return Long.MAX_VALUE; + } else if (value < 0) { + return Long.fromNumber(-value).negate(); + } else { + return new Long( + (value % Long.TWO_PWR_32_DBL_) | 0, + (value / Long.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Long} the corresponding Long value. + */ +Long.fromBits = function(lowBits, highBits) { + return new Long(lowBits, highBits); +}; + +/** + * Returns a Long representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Long. + * @param {number} opt_radix the radix in which the text is written. + * @return {Long} the corresponding Long value. + */ +Long.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Long.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Long.fromNumber(Math.pow(radix, 8)); + + var result = Long.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Long.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Long.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Long.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Long representations of small integer values. + * @type {Object} + * @ignore + */ +Long.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Long.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; + +/** @type {Long} */ +Long.ZERO = Long.fromInt(0); + +/** @type {Long} */ +Long.ONE = Long.fromInt(1); + +/** @type {Long} */ +Long.NEG_ONE = Long.fromInt(-1); + +/** @type {Long} */ +Long.MAX_VALUE = + Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Long} */ +Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); + +/** + * @type {Long} + * @ignore + */ +Long.TWO_PWR_24_ = Long.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Long; +module.exports.Long = Long; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js new file mode 100644 index 0000000..f53c8c1 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js @@ -0,0 +1,126 @@ +"use strict" + +// We have an ES6 Map available, return the native instance +if(typeof global.Map !== 'undefined') { + module.exports = global.Map; + module.exports.Map = global.Map; +} else { + // We will return a polyfill + var Map = function(array) { + this._keys = []; + this._values = {}; + + for(var i = 0; i < array.length; i++) { + if(array[i] == null) continue; // skip null and undefined + var entry = array[i]; + var key = entry[0]; + var value = entry[1]; + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + } + } + + Map.prototype.clear = function() { + this._keys = []; + this._values = {}; + } + + Map.prototype.delete = function(key) { + var value = this._values[key]; + if(value == null) return false; + // Delete entry + delete this._values[key]; + // Remove the key from the ordered keys list + this._keys.splice(value.i, 1); + return true; + } + + Map.prototype.entries = function() { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? [key, self._values[key].v] : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.forEach = function(callback, self) { + self = self || this; + + for(var i = 0; i < this._keys.length; i++) { + var key = this._keys[i]; + // Call the forEach callback + callback.call(self, this._values[key].v, key, self); + } + } + + Map.prototype.get = function(key) { + return this._values[key] ? this._values[key].v : undefined; + } + + Map.prototype.has = function(key) { + return this._values[key] != null; + } + + Map.prototype.keys = function(key) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? key : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + Map.prototype.set = function(key, value) { + if(this._values[key]) { + this._values[key].v = value; + return this; + } + + // Add the key to the list of keys in order + this._keys.push(key); + // Add the key and value to the values dictionary with a point + // to the location in the ordered keys list + this._values[key] = {v: value, i: this._keys.length - 1}; + return this; + } + + Map.prototype.values = function(key, value) { + var self = this; + var index = 0; + + return { + next: function() { + var key = self._keys[index++]; + return { + value: key !== undefined ? self._values[key].v : undefined, + done: key !== undefined ? false : true + } + } + }; + } + + // Last ismaster + Object.defineProperty(Map.prototype, 'size', { + enumerable:true, + get: function() { return this._keys.length; } + }); + + module.exports = Map; + module.exports.Map = Map; +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js new file mode 100644 index 0000000..03ee9cd --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MaxKey type. + * + * @class + * @return {MaxKey} A MaxKey instance + */ +function MaxKey() { + if(!(this instanceof MaxKey)) return new MaxKey(); + + this._bsontype = 'MaxKey'; +} + +module.exports = MaxKey; +module.exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js new file mode 100644 index 0000000..5e120fb --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js @@ -0,0 +1,14 @@ +/** + * A class representation of the BSON MinKey type. + * + * @class + * @return {MinKey} A MinKey instance + */ +function MinKey() { + if(!(this instanceof MinKey)) return new MinKey(); + + this._bsontype = 'MinKey'; +} + +module.exports = MinKey; +module.exports.MinKey = MinKey; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js new file mode 100644 index 0000000..3ddcb14 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js @@ -0,0 +1,273 @@ +/** + * Module dependencies. + * @ignore + */ +var BinaryParser = require('./binary_parser').BinaryParser; + +/** + * Machine id. + * + * Create a random 3-byte value (i.e. unique for this + * process). Other drivers use a md5 of the machine id here, but + * that would mean an asyc call to gethostname, so we don't bother. + * @ignore + */ +var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); + +// Regular expression that checks for hex value +var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); + +/** +* Create a new ObjectID instance +* +* @class +* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. +* @property {number} generationTime The generation time of this ObjectId instance +* @return {ObjectID} instance of ObjectID. +*/ +var ObjectID = function ObjectID(id) { + if(!(this instanceof ObjectID)) return new ObjectID(id); + if((id instanceof ObjectID)) return id; + + this._bsontype = 'ObjectID'; + var __id = null; + var valid = ObjectID.isValid(id); + + // Throw an error if it's not a valid setup + if(!valid && id != null){ + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + } else if(valid && typeof id == 'string' && id.length == 24) { + return ObjectID.createFromHexString(id); + } else if(id == null || typeof id == 'number') { + // convert to 12 byte binary string + this.id = this.generate(id); + } else if(id != null && id.length === 12) { + // assume 12 byte string + this.id = id; + } + + if(ObjectID.cacheHexString) this.__id = this.toHexString(); +}; + +// Allow usage of ObjectId as well as ObjectID +var ObjectId = ObjectID; + +// Precomputed hex table enables speedy hex string conversion +var hexTable = []; +for (var i = 0; i < 256; i++) { + hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); +} + +/** +* Return the ObjectID id as a 24 byte hex string representation +* +* @method +* @return {string} return the 24 byte hex string representation. +*/ +ObjectID.prototype.toHexString = function() { + if(ObjectID.cacheHexString && this.__id) return this.__id; + + var hexString = ''; + + for (var i = 0; i < this.id.length; i++) { + hexString += hexTable[this.id.charCodeAt(i)]; + } + + if(ObjectID.cacheHexString) this.__id = hexString; + return hexString; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.get_inc = function() { + return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; +}; + +/** +* Update the ObjectID index used in generating new ObjectID's on the driver +* +* @method +* @return {number} returns next index value. +* @ignore +*/ +ObjectID.prototype.getInc = function() { + return this.get_inc(); +}; + +/** +* Generate a 12 byte id string used in ObjectID's +* +* @method +* @param {number} [time] optional parameter allowing to pass in a second based timestamp. +* @return {string} return the 12 byte id binary string. +*/ +ObjectID.prototype.generate = function(time) { + if ('number' != typeof time) { + time = parseInt(Date.now()/1000,10); + } + + var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); + /* for time-based ObjectID the bytes following the time will be zeroed */ + var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); + var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid % 0xFFFF); + var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); + + return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; +}; + +/** +* Converts the id into a 24 byte hex string for printing +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toString = function() { + return this.toHexString(); +}; + +/** +* Converts to a string representation of this Id. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.inspect = ObjectID.prototype.toString; + +/** +* Converts to its JSON representation. +* +* @return {String} return the 24 byte hex string representation. +* @ignore +*/ +ObjectID.prototype.toJSON = function() { + return this.toHexString(); +}; + +/** +* Compares the equality of this ObjectID with `otherID`. +* +* @method +* @param {object} otherID ObjectID instance to compare against. +* @return {boolean} the result of comparing two ObjectID's +*/ +ObjectID.prototype.equals = function equals (otherID) { + if(otherID == null) return false; + var id = (otherID instanceof ObjectID || otherID.toHexString) + ? otherID.id + : ObjectID.createFromHexString(otherID).id; + + return this.id === id; +} + +/** +* Returns the generation date (accurate up to the second) that this ID was generated. +* +* @method +* @return {date} the generation date +*/ +ObjectID.prototype.getTimestamp = function() { + var timestamp = new Date(); + timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); + return timestamp; +} + +/** +* @ignore +*/ +ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); + +/** +* @ignore +*/ +ObjectID.createPk = function createPk () { + return new ObjectID(); +}; + +/** +* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. +* +* @method +* @param {number} time an integer number representing a number of seconds. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromTime = function createFromTime (time) { + var id = BinaryParser.encodeInt(time, 32, true, true) + + BinaryParser.encodeInt(0, 64, true, true); + return new ObjectID(id); +}; + +/** +* Creates an ObjectID from a hex string representation of an ObjectID. +* +* @method +* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. +* @return {ObjectID} return the created ObjectID +*/ +ObjectID.createFromHexString = function createFromHexString (hexString) { + // Throw an error if it's not a valid setup + if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) + throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); + + var len = hexString.length; + + if(len > 12*2) { + throw new Error('Id cannot be longer than 12 bytes'); + } + + var result = '' + , string + , number; + + for (var index = 0; index < len; index += 2) { + string = hexString.substr(index, 2); + number = parseInt(string, 16); + result += BinaryParser.fromByte(number); + } + + return new ObjectID(result, hexString); +}; + +/** +* Checks if a value is a valid bson ObjectId +* +* @method +* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. +*/ +ObjectID.isValid = function isValid(id) { + if(id == null) return false; + + if(typeof id == 'number') + return true; + if(typeof id == 'string') { + return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id)); + } + return false; +}; + +/** +* @ignore +*/ +Object.defineProperty(ObjectID.prototype, "generationTime", { + enumerable: true + , get: function () { + return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); + } + , set: function (value) { + var value = BinaryParser.encodeInt(value, 32, true, true); + this.id = value + this.id.substr(4); + // delete this.__id; + this.toHexString(); + } +}); + +/** + * Expose. + */ +module.exports = ObjectID; +module.exports.ObjectID = ObjectID; +module.exports.ObjectId = ObjectID; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js new file mode 100644 index 0000000..03513f3 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js @@ -0,0 +1,310 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754 + , readIEEE754 = require('../float_parser').readIEEE754 + , Long = require('../long').Long + , Double = require('../double').Double + , Timestamp = require('../timestamp').Timestamp + , ObjectID = require('../objectid').ObjectID + , Symbol = require('../symbol').Symbol + , BSONRegExp = require('../regexp').BSONRegExp + , Code = require('../code').Code + , MinKey = require('../min_key').MinKey + , MaxKey = require('../max_key').MaxKey + , DBRef = require('../db_ref').DBRef + , Binary = require('../binary').Binary; + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { + var totalLength = (4 + 1); + + if(Array.isArray(object)) { + for(var i = 0; i < object.length; i++) { + totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) + } + } else { + // If we have toBSON defined, override the current object + if(object.toBSON) { + object = object.toBSON(); + } + + // Calculate size + for(var key in object) { + totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined) + } + } + + return totalLength; +} + +/** + * @ignore + * @api private + */ +function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { + // If we have toBSON defined, override the current object + if(value && value.toBSON){ + value = value.toBSON(); + } + + switch(typeof value) { + case 'string': + return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; + case 'number': + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + } else { // 64 bit + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } + case 'undefined': + if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + return 0; + case 'boolean': + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 1); + case 'object': + if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); + } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); + } else if(value instanceof Date || isDate(value)) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 4 + 1) + value.length; + } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp + || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); + } else if(value instanceof Code || value['_bsontype'] == 'Code') { + // Calculate size depending on the availability of a scope + if(value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; + } + } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { + // Check what kind of subtype we have + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); + } + } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; + } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { + // Set up correct object for serialization + var ordered_values = { + '$ref': value.namespace + , '$id' : value.oid + }; + + // Add db reference if it exists + if(null != value.db) { + ordered_values['$db'] = value.db; + } + + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); + } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 + + Buffer.byteLength(value.options, 'utf8') + 1 + } else { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; + } + case 'function': + // WTF for 0.4.X where typeof /someregexp/ === 'function' + if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 + + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 + } else { + if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); + } else if(serializeFunctions) { + return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; + } + } + } + + return 0; +} + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = calculateObjectSize; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js new file mode 100644 index 0000000..5f1cc10 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js @@ -0,0 +1,544 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754, + readIEEE754 = require('../float_parser').readIEEE754, + f = require('util').format, + Long = require('../long').Long, + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + BSONRegExp = require('../regexp').BSONRegExp, + Binary = require('../binary').Binary; + +var deserialize = function(buffer, options, isArray) { + var index = 0; + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || buffer.length < size) { + throw new Error("corrupt bson message"); + } + + // Illegal end value + if(buffer[size - 1] != 0) { + throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); + } + + // Start deserializtion + return deserializeObject(buffer, options, isArray); +} + +// Reads in a C style string +var readCStyleStringSpecial = function(buffer, index) { + // Get the start search index + var i = index; + // Locate the end of the c string + while(buffer[i] !== 0x00 && i < buffer.length) { + i++ + } + // If are at the end of the buffer there is a problem with the document + if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") + // Grab utf8 encoded string + var string = buffer.toString('utf8', index, i); + // Update index position + index = i + 1; + // Return string + return {s: string, i: index}; +} + +var deserializeObject = function(buffer, options, isArray) { + // Options + options = options == null ? {} : options; + var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; + var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; + var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; + var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; + var fieldsAsRaw = options['fieldsAsRaw'] == null ? {} : options['fieldsAsRaw']; + // Return BSONRegExp objects instead of native regular expressions + var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; + + // Validate that we have at least 4 bytes of buffer + if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); + + // Set up index + var index = typeof options['index'] == 'number' ? options['index'] : 0; + + // Read the document size + var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + + // Ensure buffer is valid size + if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); + + // Create holding object + var object = isArray ? [] : {}; + + // While we have more left data left keep parsing + while(true) { + // Read the type + var elementType = buffer[index++]; + // If we get a zero it's the last byte, exit + if(elementType == 0) break; + // Read the name of the field + var r = readCStyleStringSpecial(buffer, index); + var name = r.s; + index = r.i; + + // Switch on the type + if(elementType == BSON.BSON_DATA_OID) { + var string = buffer.toString('binary', index, index + 12); + // Decode the oid + object[name] = new ObjectID(string); + // Update index + index = index + 12; + } else if(elementType == BSON.BSON_DATA_STRING) { + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Validate if string Size is larger than the actual provided buffer + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Add string to object + object[name] = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_INT) { + // Decode the 32bit value + object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } else if(elementType == BSON.BSON_DATA_NUMBER) { + // Decode the double value + object[name] = readIEEE754(buffer, index, 'little', 52, 8); + // Update the index + index = index + 8; + } else if(elementType == BSON.BSON_DATA_DATE) { + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set date object + object[name] = new Date(new Long(lowBits, highBits).toNumber()); + } else if(elementType == BSON.BSON_DATA_BOOLEAN) { + // Parse the boolean value + object[name] = buffer[index++] == 1; + } else if(elementType == BSON.BSON_DATA_UNDEFINED || elementType == BSON.BSON_DATA_NULL) { + // Parse the boolean value + object[name] = null; + } else if(elementType == BSON.BSON_DATA_BINARY) { + // Decode the size of the binary blob + var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Decode the subtype + var subType = buffer[index++]; + // Decode as raw Buffer object if options specifies it + if(buffer['slice'] != null) { + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Slice the data + object[name] = new Binary(buffer.slice(index, index + binarySize), subType); + } else { + var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); + // If we have subtype 2 skip the 4 bytes for the size + if(subType == Binary.SUBTYPE_BYTE_ARRAY) { + binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + } + // Copy the data + for(var i = 0; i < binarySize; i++) { + _buffer[i] = buffer[index + i]; + } + // Create the binary object + object[name] = new Binary(_buffer, subType); + } + // Update the index + index = index + binarySize; + } else if(elementType == BSON.BSON_DATA_ARRAY) { + options['index'] = index; + // Decode the size of the array document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + var arrayOptions = options; + + // All elements of array to be returned as raw bson + if(fieldsAsRaw[name]) { + arrayOptions = {}; + for(var n in options) arrayOptions[n] = options[n]; + arrayOptions['raw'] = true; + } + + // Set the array to the object + object[name] = deserializeObject(buffer, arrayOptions, true); + // Adjust the index + index = index + objectSize; + } else if(elementType == BSON.BSON_DATA_OBJECT) { + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Validate if string Size is larger than the actual provided buffer + if(objectSize <= 0 || objectSize > (buffer.length - index)) throw new Error("bad embedded document length in bson"); + + // We have a raw value + if(options['raw']) { + // Set the array to the object + object[name] = buffer.slice(index, index + objectSize); + } else { + // Set the array to the object + object[name] = deserializeObject(buffer, options, false); + } + + // Adjust the index + index = index + objectSize; + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { + // Create the regexp + var r = readCStyleStringSpecial(buffer, index); + var source = r.s; + index = r.i; + + var r = readCStyleStringSpecial(buffer, index); + var regExpOptions = r.s; + index = r.i; + + // For each option add the corresponding one for javascript + var optionsArray = new Array(regExpOptions.length); + + // Parse options + for(var i = 0; i < regExpOptions.length; i++) { + switch(regExpOptions[i]) { + case 'm': + optionsArray[i] = 'm'; + break; + case 's': + optionsArray[i] = 'g'; + break; + case 'i': + optionsArray[i] = 'i'; + break; + } + } + + object[name] = new RegExp(source, optionsArray.join('')); + } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { + // Create the regexp + var r = readCStyleStringSpecial(buffer, index); + var source = r.s; + index = r.i; + + var r = readCStyleStringSpecial(buffer, index); + var regExpOptions = r.s; + index = r.i; + + // Set the object + object[name] = new BSONRegExp(source, regExpOptions); + } else if(elementType == BSON.BSON_DATA_LONG) { + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Create long object + var long = new Long(lowBits, highBits); + // Promote the long if possible + if(promoteLongs) { + object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; + } else { + object[name] = long; + } + } else if(elementType == BSON.BSON_DATA_SYMBOL) { + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Validate if string Size is larger than the actual provided buffer + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Add string to object + object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); + // Update parse index position + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_TIMESTAMP) { + // Unpack the low and high bits + var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Set the object + object[name] = new Timestamp(lowBits, highBits); + } else if(elementType == BSON.BSON_DATA_MIN_KEY) { + // Parse the object + object[name] = new MinKey(); + } else if(elementType == BSON.BSON_DATA_MAX_KEY) { + // Parse the object + object[name] = new MaxKey(); + } else if(elementType == BSON.BSON_DATA_CODE) { + // Read the content of the field + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Validate if string Size is larger than the actual provided buffer + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Function string + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + } else { + object[name] = new Code(functionString, {}); + } + + // Update parse index position + index = index + stringSize; + } else if(elementType == BSON.BSON_DATA_CODE_W_SCOPE) { + // Read the content of the field + var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; + // Validate if string Size is larger than the actual provided buffer + if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); + // Javascript function + var functionString = buffer.toString('utf8', index, index + stringSize - 1); + // Update parse index position + index = index + stringSize; + // Parse the element + options['index'] = index; + // Decode the size of the object document + var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; + // Decode the scope object + var scopeObject = deserializeObject(buffer, options, false); + // Adjust the index + index = index + objectSize; + + // If we are evaluating the functions + if(evalFunctions) { + // Contains the value we are going to set + var value = null; + // If we have cache enabled let's look for the md5 of the function in the cache + if(cacheFunctions) { + var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; + // Got to do this to avoid V8 deoptimizing the call due to finding eval + object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); + } else { + // Set directly + object[name] = isolateEval(functionString); + } + + // Set the scope on the object + object[name].scope = scopeObject; + } else { + object[name] = new Code(functionString, scopeObject); + } + } + } + + // Check if we have a db ref object + if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); + + // Return the final objects + return object; +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEvalWithHash = function(functionCache, hash, functionString, object) { + // Contains the value we are going to set + var value = null; + + // Check for cache hit, eval if missing and return cached function + if(functionCache[hash] == null) { + eval("value = " + functionString); + functionCache[hash] = value; + } + // Set the object + return functionCache[hash].bind(object); +} + +/** + * Ensure eval is isolated. + * + * @ignore + * @api private + */ +var isolateEval = function(functionString) { + // Contains the value we are going to set + var value = null; + // Eval the function + eval("value = " + functionString); + return value; +} + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = deserialize diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js new file mode 100644 index 0000000..285e45b --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js @@ -0,0 +1,909 @@ +"use strict" + +var writeIEEE754 = require('../float_parser').writeIEEE754, + readIEEE754 = require('../float_parser').readIEEE754, + Long = require('../long').Long, + Map = require('../map'), + Double = require('../double').Double, + Timestamp = require('../timestamp').Timestamp, + ObjectID = require('../objectid').ObjectID, + Symbol = require('../symbol').Symbol, + Code = require('../code').Code, + BSONRegExp = require('../regexp').BSONRegExp, + MinKey = require('../min_key').MinKey, + MaxKey = require('../max_key').MaxKey, + DBRef = require('../db_ref').DBRef, + Binary = require('../binary').Binary; + +var regexp = /\x00/ + +// To ensure that 0.4 of node works correctly +var isDate = function isDate(d) { + return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; +} + +var isRegExp = function isRegExp(d) { + return Object.prototype.toString.call(d) === '[object RegExp]'; +} + +var serializeString = function(buffer, key, value, index) { + // Encode String type + buffer[index++] = BSON.BSON_DATA_STRING; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes + 1; + buffer[index - 1] = 0; + // Write the string + var size = buffer.write(value, index + 4, 'utf8'); + // Write the size of the string to buffer + buffer[index + 3] = (size + 1 >> 24) & 0xff; + buffer[index + 2] = (size + 1 >> 16) & 0xff; + buffer[index + 1] = (size + 1 >> 8) & 0xff; + buffer[index] = size + 1 & 0xff; + // Update index + index = index + 4 + size; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeNumber = function(buffer, key, value, index) { + // We have an integer value + if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // If the value fits in 32 bits encode as int, if it fits in a double + // encode it as a double, otherwise long + if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { + // Set int type 32 bits or less + buffer[index++] = BSON.BSON_DATA_INT; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the int value + buffer[index++] = value & 0xff; + buffer[index++] = (value >> 8) & 0xff; + buffer[index++] = (value >> 16) & 0xff; + buffer[index++] = (value >> 24) & 0xff; + } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } else { + // Set long type + buffer[index++] = BSON.BSON_DATA_LONG; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var longVal = Long.fromNumber(value); + var lowBits = longVal.getLowBits(); + var highBits = longVal.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + } + } else { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + } + + return index; +} + +var serializeUndefined = function(buffer, key, value, index) { + // Set long type + buffer[index++] = BSON.BSON_DATA_NULL; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +var serializeBoolean = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BOOLEAN; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Encode the boolean value + buffer[index++] = value ? 1 : 0; + return index; +} + +var serializeDate = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_DATE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the date + var dateInMilis = Long.fromNumber(value.getTime()); + var lowBits = dateInMilis.getLowBits(); + var highBits = dateInMilis.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +var serializeRegExp = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Adjust the index + index = index + buffer.write(value.source, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the parameters + if(value.global) buffer[index++] = 0x73; // s + if(value.ignoreCase) buffer[index++] = 0x69; // i + if(value.multiline) buffer[index++] = 0x6d; // m + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +var serializeBSONRegExp = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_REGEXP; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Adjust the index + index = index + buffer.write(value.pattern, index, 'utf8'); + // Write zero + buffer[index++] = 0x00; + // Write the options + index = index + buffer.write(value.options, index, 'utf8'); + // Add ending zero + buffer[index++] = 0x00; + return index; +} + +var serializeMinMax = function(buffer, key, value, index) { + // Write the type of either min or max key + if(value === null) { + buffer[index++] = BSON.BSON_DATA_NULL; + } else if(value instanceof MinKey) { + buffer[index++] = BSON.BSON_DATA_MIN_KEY; + } else { + buffer[index++] = BSON.BSON_DATA_MAX_KEY; + } + + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + return index; +} + +var serializeObjectId = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OID; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Write the objectId into the shared buffer + buffer.write(value.id, index, 'binary') + + // Ajust index + return index + 12; +} + +var serializeBuffer = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Get size of the buffer (current write point) + var size = value.length; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the default subtype + buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; + // Copy the content form the binary field to the buffer + value.copy(buffer, index, 0, size); + // Adjust the index + index = index + size; + return index; +} + +var serializeObject = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { + // Write the type + buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); + // Write size + var size = endIndex - index; + return endIndex; +} + +var serializeLong = function(buffer, key, value, index) { + // Write the type + buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the date + var lowBits = value.getLowBits(); + var highBits = value.getHighBits(); + // Encode low bits + buffer[index++] = lowBits & 0xff; + buffer[index++] = (lowBits >> 8) & 0xff; + buffer[index++] = (lowBits >> 16) & 0xff; + buffer[index++] = (lowBits >> 24) & 0xff; + // Encode high bits + buffer[index++] = highBits & 0xff; + buffer[index++] = (highBits >> 8) & 0xff; + buffer[index++] = (highBits >> 16) & 0xff; + buffer[index++] = (highBits >> 24) & 0xff; + return index; +} + +var serializeDouble = function(buffer, key, value, index) { + // Encode as double + buffer[index++] = BSON.BSON_DATA_NUMBER; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write float + writeIEEE754(buffer, value, index, 'little', 52, 8); + // Ajust index + index = index + 8; + return index; +} + +var serializeFunction = function(buffer, key, value, index, checkKeys, depth) { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + return index; +} + +var serializeCode = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { + if(value.scope != null && Object.keys(value.scope).length > 0) { + // Write the type + buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + // Starting index + var startIndex = index; + + // Serialize the function + // Get the function string + var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); + // Index adjustment + index = index + 4; + // Write string into buffer + var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = codeSize & 0xff; + buffer[index + 1] = (codeSize >> 8) & 0xff; + buffer[index + 2] = (codeSize >> 16) & 0xff; + buffer[index + 3] = (codeSize >> 24) & 0xff; + // Write end 0 + buffer[index + 4 + codeSize - 1] = 0; + // Write the + index = index + codeSize + 4; + + // + // Serialize the scope value + var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined) + index = endIndex - 1; + + // Writ the total + var totalSize = endIndex - startIndex; + + // Write the total size of the object + buffer[startIndex++] = totalSize & 0xff; + buffer[startIndex++] = (totalSize >> 8) & 0xff; + buffer[startIndex++] = (totalSize >> 16) & 0xff; + buffer[startIndex++] = (totalSize >> 24) & 0xff; + // Write trailing zero + buffer[index++] = 0; + } else { + buffer[index++] = BSON.BSON_DATA_CODE; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Function string + var functionString = value.code.toString(); + // Write the string + var size = buffer.write(functionString, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0; + } + + return index; +} + +var serializeBinary = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_BINARY; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Extract the buffer + var data = value.value(true); + // Calculate size + var size = value.position; + // Write the size of the string to buffer + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + // Write the subtype to the buffer + buffer[index++] = value.sub_type; + + // If we have binary type 2 the 4 first bytes are the size + if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { + buffer[index++] = size & 0xff; + buffer[index++] = (size >> 8) & 0xff; + buffer[index++] = (size >> 16) & 0xff; + buffer[index++] = (size >> 24) & 0xff; + } + + // Write the data to the object + data.copy(buffer, index, 0, value.position); + // Adjust the index + index = index + value.position; + return index; +} + +var serializeSymbol = function(buffer, key, value, index) { + // Write the type + buffer[index++] = BSON.BSON_DATA_SYMBOL; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + // Write the string + var size = buffer.write(value.value, index + 4, 'utf8') + 1; + // Write the size of the string to buffer + buffer[index] = size & 0xff; + buffer[index + 1] = (size >> 8) & 0xff; + buffer[index + 2] = (size >> 16) & 0xff; + buffer[index + 3] = (size >> 24) & 0xff; + // Update index + index = index + 4 + size - 1; + // Write zero + buffer[index++] = 0x00; + return index; +} + +var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions) { + // Write the type + buffer[index++] = BSON.BSON_DATA_OBJECT; + // Number of written bytes + var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); + + // Encode the name + index = index + numberOfWrittenBytes; + buffer[index++] = 0; + + var startIndex = index; + var endIndex; + + // Serialize object + if(null != value.db) { + endIndex = serializeInto(buffer, { + '$ref': value.namespace + , '$id' : value.oid + , '$db' : value.db + }, false, index, depth + 1, serializeFunctions); + } else { + endIndex = serializeInto(buffer, { + '$ref': value.namespace + , '$id' : value.oid + }, false, index, depth + 1, serializeFunctions); + } + + // Calculate object size + var size = endIndex - startIndex; + // Write the size + buffer[startIndex++] = size & 0xff; + buffer[startIndex++] = (size >> 8) & 0xff; + buffer[startIndex++] = (size >> 16) & 0xff; + buffer[startIndex++] = (size >> 24) & 0xff; + // Set index + return endIndex; +} + +var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined) { + startingIndex = startingIndex || 0; + + // Start place to serialize into + var index = startingIndex + 4; + var self = this; + + // Special case isArray + if(Array.isArray(object)) { + // Get object keys + for(var i = 0; i < object.length; i++) { + var key = "" + i; + var value = object[i]; + + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + var type = typeof value; + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(type == 'undefined' || value == null) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else if(object instanceof Map) { + var iterator = object.entries(); + var done = false; + + while(!done) { + // Unpack the next entry + var entry = iterator.next(); + done = entry.done; + // Are we done, then skip and terminate + if(done) continue; + + // Get the entry values + var key = entry.value[0]; + var value = entry.value[1]; + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + + if (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + // console.log("---------------------------------------------------") + // console.dir("key = " + key) + // console.dir("value = " + value) + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } else { + // Did we provide a custom serialization method + if(object.toBSON) { + if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); + object = object.toBSON(); + if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); + } + + // Iterate over all the keys + for(var key in object) { + var value = object[key]; + // Is there an override value + if(value && value.toBSON) { + if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); + value = value.toBSON(); + } + + // Check the type of the value + var type = typeof value; + + // Check the key and throw error if it's illegal + if(key != '$db' && key != '$ref' && key != '$id') { + if (key.match(regexp) != null) { + // The BSON spec doesn't allow keys with null bytes because keys are + // null-terminated. + throw Error("key " + key + " must not contain null bytes"); + } + + if (checkKeys) { + if('$' == key[0]) { + throw Error("key " + key + " must not start with '$'"); + } else if (!!~key.indexOf('.')) { + throw Error("key " + key + " must not contain '.'"); + } + } + } + + if(type == 'string') { + index = serializeString(buffer, key, value, index); + } else if(type == 'number') { + index = serializeNumber(buffer, key, value, index); + } else if(type == 'boolean') { + index = serializeBoolean(buffer, key, value, index); + } else if(value instanceof Date || isDate(value)) { + index = serializeDate(buffer, key, value, index); + } else if(value === undefined && ignoreUndefined == true) { + } else if(value === null || value === undefined) { + index = serializeUndefined(buffer, key, value, index); + } else if(value['_bsontype'] == 'ObjectID') { + index = serializeObjectId(buffer, key, value, index); + } else if(Buffer.isBuffer(value)) { + index = serializeBuffer(buffer, key, value, index); + } else if(value instanceof RegExp || isRegExp(value)) { + index = serializeRegExp(buffer, key, value, index); + } else if(type == 'object' && value['_bsontype'] == null) { + index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { + index = serializeLong(buffer, key, value, index); + } else if(value['_bsontype'] == 'Double') { + index = serializeDouble(buffer, key, value, index); + } else if(value['_bsontype'] == 'Code') { + index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); + } else if(typeof value == 'function' && serializeFunctions) { + index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); + } else if(value['_bsontype'] == 'Binary') { + index = serializeBinary(buffer, key, value, index); + } else if(value['_bsontype'] == 'Symbol') { + index = serializeSymbol(buffer, key, value, index); + } else if(value['_bsontype'] == 'DBRef') { + index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); + } else if(value['_bsontype'] == 'BSONRegExp') { + index = serializeBSONRegExp(buffer, key, value, index); + } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { + index = serializeMinMax(buffer, key, value, index); + } + } + } + + // Final padding byte for object + buffer[index++] = 0x00; + + // Final size + var size = index - startingIndex; + // Write the size of the object + buffer[startingIndex++] = size & 0xff; + buffer[startingIndex++] = (size >> 8) & 0xff; + buffer[startingIndex++] = (size >> 16) & 0xff; + buffer[startingIndex++] = (size >> 24) & 0xff; + return index; +} + +var BSON = {}; + +/** + * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 + * + * @ignore + * @api private + */ +var functionCache = BSON.functionCache = {}; + +/** + * Number BSON Type + * + * @classconstant BSON_DATA_NUMBER + **/ +BSON.BSON_DATA_NUMBER = 1; +/** + * String BSON Type + * + * @classconstant BSON_DATA_STRING + **/ +BSON.BSON_DATA_STRING = 2; +/** + * Object BSON Type + * + * @classconstant BSON_DATA_OBJECT + **/ +BSON.BSON_DATA_OBJECT = 3; +/** + * Array BSON Type + * + * @classconstant BSON_DATA_ARRAY + **/ +BSON.BSON_DATA_ARRAY = 4; +/** + * Binary BSON Type + * + * @classconstant BSON_DATA_BINARY + **/ +BSON.BSON_DATA_BINARY = 5; +/** + * ObjectID BSON Type + * + * @classconstant BSON_DATA_OID + **/ +BSON.BSON_DATA_OID = 7; +/** + * Boolean BSON Type + * + * @classconstant BSON_DATA_BOOLEAN + **/ +BSON.BSON_DATA_BOOLEAN = 8; +/** + * Date BSON Type + * + * @classconstant BSON_DATA_DATE + **/ +BSON.BSON_DATA_DATE = 9; +/** + * null BSON Type + * + * @classconstant BSON_DATA_NULL + **/ +BSON.BSON_DATA_NULL = 10; +/** + * RegExp BSON Type + * + * @classconstant BSON_DATA_REGEXP + **/ +BSON.BSON_DATA_REGEXP = 11; +/** + * Code BSON Type + * + * @classconstant BSON_DATA_CODE + **/ +BSON.BSON_DATA_CODE = 13; +/** + * Symbol BSON Type + * + * @classconstant BSON_DATA_SYMBOL + **/ +BSON.BSON_DATA_SYMBOL = 14; +/** + * Code with Scope BSON Type + * + * @classconstant BSON_DATA_CODE_W_SCOPE + **/ +BSON.BSON_DATA_CODE_W_SCOPE = 15; +/** + * 32 bit Integer BSON Type + * + * @classconstant BSON_DATA_INT + **/ +BSON.BSON_DATA_INT = 16; +/** + * Timestamp BSON Type + * + * @classconstant BSON_DATA_TIMESTAMP + **/ +BSON.BSON_DATA_TIMESTAMP = 17; +/** + * Long BSON Type + * + * @classconstant BSON_DATA_LONG + **/ +BSON.BSON_DATA_LONG = 18; +/** + * MinKey BSON Type + * + * @classconstant BSON_DATA_MIN_KEY + **/ +BSON.BSON_DATA_MIN_KEY = 0xff; +/** + * MaxKey BSON Type + * + * @classconstant BSON_DATA_MAX_KEY + **/ +BSON.BSON_DATA_MAX_KEY = 0x7f; + +/** + * Binary Default Type + * + * @classconstant BSON_BINARY_SUBTYPE_DEFAULT + **/ +BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; +/** + * Binary Function Type + * + * @classconstant BSON_BINARY_SUBTYPE_FUNCTION + **/ +BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; +/** + * Binary Byte Array Type + * + * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY + **/ +BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; +/** + * Binary UUID Type + * + * @classconstant BSON_BINARY_SUBTYPE_UUID + **/ +BSON.BSON_BINARY_SUBTYPE_UUID = 3; +/** + * Binary MD5 Type + * + * @classconstant BSON_BINARY_SUBTYPE_MD5 + **/ +BSON.BSON_BINARY_SUBTYPE_MD5 = 4; +/** + * Binary User Defined Type + * + * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED + **/ +BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; + +// BSON MAX VALUES +BSON.BSON_INT32_MAX = 0x7FFFFFFF; +BSON.BSON_INT32_MIN = -0x80000000; + +BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; +BSON.BSON_INT64_MIN = -Math.pow(2, 63); + +// JS MAX PRECISE VALUES +BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. +BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. + +// Internal long versions +var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. +var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. + +module.exports = serializeInto; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js new file mode 100644 index 0000000..6b148b2 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js @@ -0,0 +1,30 @@ +/** + * A class representation of the BSON RegExp type. + * + * @class + * @return {BSONRegExp} A MinKey instance + */ +function BSONRegExp(pattern, options) { + if(!(this instanceof BSONRegExp)) return new BSONRegExp(); + + // Execute + this._bsontype = 'BSONRegExp'; + this.pattern = pattern; + this.options = options; + + // Validate options + for(var i = 0; i < options.length; i++) { + if(!(this.options[i] == 'i' + || this.options[i] == 'm' + || this.options[i] == 'x' + || this.options[i] == 'l' + || this.options[i] == 's' + || this.options[i] == 'u' + )) { + throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); + } + } +} + +module.exports = BSONRegExp; +module.exports.BSONRegExp = BSONRegExp; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js new file mode 100644 index 0000000..7681a4d --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js @@ -0,0 +1,47 @@ +/** + * A class representation of the BSON Symbol type. + * + * @class + * @deprecated + * @param {string} value the string representing the symbol. + * @return {Symbol} + */ +function Symbol(value) { + if(!(this instanceof Symbol)) return new Symbol(value); + this._bsontype = 'Symbol'; + this.value = value; +} + +/** + * Access the wrapped string value. + * + * @method + * @return {String} returns the wrapped string. + */ +Symbol.prototype.valueOf = function() { + return this.value; +}; + +/** + * @ignore + */ +Symbol.prototype.toString = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.inspect = function() { + return this.value; +} + +/** + * @ignore + */ +Symbol.prototype.toJSON = function() { + return this.value; +} + +module.exports = Symbol; +module.exports.Symbol = Symbol; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js new file mode 100644 index 0000000..7718caf --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js @@ -0,0 +1,856 @@ +// 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. +// +// Copyright 2009 Google Inc. All Rights Reserved + +/** + * This type is for INTERNAL use in MongoDB only and should not be used in applications. + * The appropriate corresponding type is the JavaScript Date type. + * + * Defines a Timestamp class for representing a 64-bit two's-complement + * integer value, which faithfully simulates the behavior of a Java "Timestamp". This + * implementation is derived from TimestampLib in GWT. + * + * Constructs a 64-bit two's-complement integer, given its low and high 32-bit + * values as *signed* integers. See the from* functions below for more + * convenient ways of constructing Timestamps. + * + * The internal representation of a Timestamp is the two given signed, 32-bit values. + * We use 32-bit pieces because these are the size of integers on which + * Javascript performs bit-operations. For operations like addition and + * multiplication, we split each number into 16-bit pieces, which can easily be + * multiplied within Javascript's floating-point representation without overflow + * or change in sign. + * + * In the algorithms below, we frequently reduce the negative case to the + * positive case by negating the input(s) and then post-processing the result. + * Note that we must ALWAYS check specially whether those values are MIN_VALUE + * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + * a positive number, it overflows back into a negative). Not handling this + * case would often result in infinite recursion. + * + * @class + * @param {number} low the low (signed) 32 bits of the Timestamp. + * @param {number} high the high (signed) 32 bits of the Timestamp. + */ +function Timestamp(low, high) { + if(!(this instanceof Timestamp)) return new Timestamp(low, high); + this._bsontype = 'Timestamp'; + /** + * @type {number} + * @ignore + */ + this.low_ = low | 0; // force into 32 signed bits. + + /** + * @type {number} + * @ignore + */ + this.high_ = high | 0; // force into 32 signed bits. +}; + +/** + * Return the int value. + * + * @return {number} the value, assuming it is a 32-bit integer. + */ +Timestamp.prototype.toInt = function() { + return this.low_; +}; + +/** + * Return the Number value. + * + * @method + * @return {number} the closest floating-point representation to this value. + */ +Timestamp.prototype.toNumber = function() { + return this.high_ * Timestamp.TWO_PWR_32_DBL_ + + this.getLowBitsUnsigned(); +}; + +/** + * Return the JSON value. + * + * @method + * @return {string} the JSON representation. + */ +Timestamp.prototype.toJSON = function() { + return this.toString(); +} + +/** + * Return the String value. + * + * @method + * @param {number} [opt_radix] the radix in which the text should be written. + * @return {string} the textual representation of this value. + */ +Timestamp.prototype.toString = function(opt_radix) { + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + // We need to change the Timestamp value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixTimestamp = Timestamp.fromNumber(radix); + var div = this.div(radixTimestamp); + var rem = div.multiply(radixTimestamp).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } + + // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); + + var rem = this; + var result = ''; + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); + var digits = intval.toString(radix); + + rem = remDiv; + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + result = '' + digits + result; + } + } +}; + +/** + * Return the high 32-bits value. + * + * @method + * @return {number} the high 32-bits as a signed value. + */ +Timestamp.prototype.getHighBits = function() { + return this.high_; +}; + +/** + * Return the low 32-bits value. + * + * @method + * @return {number} the low 32-bits as a signed value. + */ +Timestamp.prototype.getLowBits = function() { + return this.low_; +}; + +/** + * Return the low unsigned 32-bits value. + * + * @method + * @return {number} the low 32-bits as an unsigned value. + */ +Timestamp.prototype.getLowBitsUnsigned = function() { + return (this.low_ >= 0) ? + this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; +}; + +/** + * Returns the number of bits needed to represent the absolute value of this Timestamp. + * + * @method + * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. + */ +Timestamp.prototype.getNumBitsAbs = function() { + if (this.isNegative()) { + if (this.equals(Timestamp.MIN_VALUE)) { + return 64; + } else { + return this.negate().getNumBitsAbs(); + } + } else { + var val = this.high_ != 0 ? this.high_ : this.low_; + for (var bit = 31; bit > 0; bit--) { + if ((val & (1 << bit)) != 0) { + break; + } + } + return this.high_ != 0 ? bit + 33 : bit + 1; + } +}; + +/** + * Return whether this value is zero. + * + * @method + * @return {boolean} whether this value is zero. + */ +Timestamp.prototype.isZero = function() { + return this.high_ == 0 && this.low_ == 0; +}; + +/** + * Return whether this value is negative. + * + * @method + * @return {boolean} whether this value is negative. + */ +Timestamp.prototype.isNegative = function() { + return this.high_ < 0; +}; + +/** + * Return whether this value is odd. + * + * @method + * @return {boolean} whether this value is odd. + */ +Timestamp.prototype.isOdd = function() { + return (this.low_ & 1) == 1; +}; + +/** + * Return whether this Timestamp equals the other + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp equals the other + */ +Timestamp.prototype.equals = function(other) { + return (this.high_ == other.high_) && (this.low_ == other.low_); +}; + +/** + * Return whether this Timestamp does not equal the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp does not equal the other. + */ +Timestamp.prototype.notEquals = function(other) { + return (this.high_ != other.high_) || (this.low_ != other.low_); +}; + +/** + * Return whether this Timestamp is less than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than the other. + */ +Timestamp.prototype.lessThan = function(other) { + return this.compare(other) < 0; +}; + +/** + * Return whether this Timestamp is less than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is less than or equal to the other. + */ +Timestamp.prototype.lessThanOrEqual = function(other) { + return this.compare(other) <= 0; +}; + +/** + * Return whether this Timestamp is greater than the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than the other. + */ +Timestamp.prototype.greaterThan = function(other) { + return this.compare(other) > 0; +}; + +/** + * Return whether this Timestamp is greater than or equal to the other. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} whether this Timestamp is greater than or equal to the other. + */ +Timestamp.prototype.greaterThanOrEqual = function(other) { + return this.compare(other) >= 0; +}; + +/** + * Compares this Timestamp with the given one. + * + * @method + * @param {Timestamp} other Timestamp to compare against. + * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. + */ +Timestamp.prototype.compare = function(other) { + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + if (thisNeg && !otherNeg) { + return -1; + } + if (!thisNeg && otherNeg) { + return 1; + } + + // at this point, the signs are the same, so subtraction will not overflow + if (this.subtract(other).isNegative()) { + return -1; + } else { + return 1; + } +}; + +/** + * The negation of this value. + * + * @method + * @return {Timestamp} the negation of this value. + */ +Timestamp.prototype.negate = function() { + if (this.equals(Timestamp.MIN_VALUE)) { + return Timestamp.MIN_VALUE; + } else { + return this.not().add(Timestamp.ONE); + } +}; + +/** + * Returns the sum of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to add to this one. + * @return {Timestamp} the sum of this and the given Timestamp. + */ +Timestamp.prototype.add = function(other) { + // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 + b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns the difference of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to subtract from this. + * @return {Timestamp} the difference of this and the given Timestamp. + */ +Timestamp.prototype.subtract = function(other) { + return this.add(other.negate()); +}; + +/** + * Returns the product of this and the given Timestamp. + * + * @method + * @param {Timestamp} other Timestamp to multiply with this. + * @return {Timestamp} the product of this and the other. + */ +Timestamp.prototype.multiply = function(other) { + if (this.isZero()) { + return Timestamp.ZERO; + } else if (other.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } else if (other.equals(Timestamp.MIN_VALUE)) { + return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().multiply(other.negate()); + } else { + return this.negate().multiply(other).negate(); + } + } else if (other.isNegative()) { + return this.multiply(other.negate()).negate(); + } + + // If both Timestamps are small, use float multiplication + if (this.lessThan(Timestamp.TWO_PWR_24_) && + other.lessThan(Timestamp.TWO_PWR_24_)) { + return Timestamp.fromNumber(this.toNumber() * other.toNumber()); + } + + // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + var a48 = this.high_ >>> 16; + var a32 = this.high_ & 0xFFFF; + var a16 = this.low_ >>> 16; + var a00 = this.low_ & 0xFFFF; + + var b48 = other.high_ >>> 16; + var b32 = other.high_ & 0xFFFF; + var b16 = other.low_ >>> 16; + var b00 = other.low_ & 0xFFFF; + + var c48 = 0, c32 = 0, c16 = 0, c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xFFFF; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xFFFF; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xFFFF; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xFFFF; + return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); +}; + +/** + * Returns this Timestamp divided by the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to divide. + * @return {Timestamp} this Timestamp divided by the given one. + */ +Timestamp.prototype.div = function(other) { + if (other.isZero()) { + throw Error('division by zero'); + } else if (this.isZero()) { + return Timestamp.ZERO; + } + + if (this.equals(Timestamp.MIN_VALUE)) { + if (other.equals(Timestamp.ONE) || + other.equals(Timestamp.NEG_ONE)) { + return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + var approx = halfThis.div(other).shiftLeft(1); + if (approx.equals(Timestamp.ZERO)) { + return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; + } else { + var rem = this.subtract(other.multiply(approx)); + var result = approx.add(rem.div(other)); + return result; + } + } + } else if (other.equals(Timestamp.MIN_VALUE)) { + return Timestamp.ZERO; + } + + if (this.isNegative()) { + if (other.isNegative()) { + return this.negate().div(other.negate()); + } else { + return this.negate().div(other).negate(); + } + } else if (other.isNegative()) { + return this.div(other.negate()).negate(); + } + + // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + var res = Timestamp.ZERO; + var rem = this; + while (rem.greaterThanOrEqual(other)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); + + // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); + + // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + var approxRes = Timestamp.fromNumber(approx); + var approxRem = approxRes.multiply(other); + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Timestamp.fromNumber(approx); + approxRem = approxRes.multiply(other); + } + + // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + if (approxRes.isZero()) { + approxRes = Timestamp.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + return res; +}; + +/** + * Returns this Timestamp modulo the given one. + * + * @method + * @param {Timestamp} other Timestamp by which to mod. + * @return {Timestamp} this Timestamp modulo the given one. + */ +Timestamp.prototype.modulo = function(other) { + return this.subtract(this.div(other).multiply(other)); +}; + +/** + * The bitwise-NOT of this value. + * + * @method + * @return {Timestamp} the bitwise-NOT of this value. + */ +Timestamp.prototype.not = function() { + return Timestamp.fromBits(~this.low_, ~this.high_); +}; + +/** + * Returns the bitwise-AND of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to AND. + * @return {Timestamp} the bitwise-AND of this and the other. + */ +Timestamp.prototype.and = function(other) { + return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); +}; + +/** + * Returns the bitwise-OR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to OR. + * @return {Timestamp} the bitwise-OR of this and the other. + */ +Timestamp.prototype.or = function(other) { + return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); +}; + +/** + * Returns the bitwise-XOR of this Timestamp and the given one. + * + * @method + * @param {Timestamp} other the Timestamp with which to XOR. + * @return {Timestamp} the bitwise-XOR of this and the other. + */ +Timestamp.prototype.xor = function(other) { + return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); +}; + +/** + * Returns this Timestamp with bits shifted to the left by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the left by the given amount. + */ +Timestamp.prototype.shiftLeft = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var low = this.low_; + if (numBits < 32) { + var high = this.high_; + return Timestamp.fromBits( + low << numBits, + (high << numBits) | (low >>> (32 - numBits))); + } else { + return Timestamp.fromBits(0, low << (numBits - 32)); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount. + */ +Timestamp.prototype.shiftRight = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >> numBits); + } else { + return Timestamp.fromBits( + high >> (numBits - 32), + high >= 0 ? 0 : -1); + } + } +}; + +/** + * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. + * + * @method + * @param {number} numBits the number of bits by which to shift. + * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. + */ +Timestamp.prototype.shiftRightUnsigned = function(numBits) { + numBits &= 63; + if (numBits == 0) { + return this; + } else { + var high = this.high_; + if (numBits < 32) { + var low = this.low_; + return Timestamp.fromBits( + (low >>> numBits) | (high << (32 - numBits)), + high >>> numBits); + } else if (numBits == 32) { + return Timestamp.fromBits(high, 0); + } else { + return Timestamp.fromBits(high >>> (numBits - 32), 0); + } + } +}; + +/** + * Returns a Timestamp representing the given (32-bit) integer value. + * + * @method + * @param {number} value the 32-bit integer in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromInt = function(value) { + if (-128 <= value && value < 128) { + var cachedObj = Timestamp.INT_CACHE_[value]; + if (cachedObj) { + return cachedObj; + } + } + + var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); + if (-128 <= value && value < 128) { + Timestamp.INT_CACHE_[value] = obj; + } + return obj; +}; + +/** + * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * + * @method + * @param {number} value the number in question. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromNumber = function(value) { + if (isNaN(value) || !isFinite(value)) { + return Timestamp.ZERO; + } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MIN_VALUE; + } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { + return Timestamp.MAX_VALUE; + } else if (value < 0) { + return Timestamp.fromNumber(-value).negate(); + } else { + return new Timestamp( + (value % Timestamp.TWO_PWR_32_DBL_) | 0, + (value / Timestamp.TWO_PWR_32_DBL_) | 0); + } +}; + +/** + * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. + * + * @method + * @param {number} lowBits the low 32-bits. + * @param {number} highBits the high 32-bits. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromBits = function(lowBits, highBits) { + return new Timestamp(lowBits, highBits); +}; + +/** + * Returns a Timestamp representation of the given string, written using the given radix. + * + * @method + * @param {string} str the textual representation of the Timestamp. + * @param {number} opt_radix the radix in which the text is written. + * @return {Timestamp} the corresponding Timestamp value. + */ +Timestamp.fromString = function(str, opt_radix) { + if (str.length == 0) { + throw Error('number format error: empty string'); + } + + var radix = opt_radix || 10; + if (radix < 2 || 36 < radix) { + throw Error('radix out of range: ' + radix); + } + + if (str.charAt(0) == '-') { + return Timestamp.fromString(str.substring(1), radix).negate(); + } else if (str.indexOf('-') >= 0) { + throw Error('number format error: interior "-" character: ' + str); + } + + // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); + + var result = Timestamp.ZERO; + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + if (size < 8) { + var power = Timestamp.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Timestamp.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Timestamp.fromNumber(value)); + } + } + return result; +}; + +// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the +// from* methods on which they depend. + + +/** + * A cache of the Timestamp representations of small integer values. + * @type {Object} + * @ignore + */ +Timestamp.INT_CACHE_ = {}; + +// NOTE: the compiler should inline these constant values below and then remove +// these variables, so there should be no runtime penalty for these. + +/** + * Number used repeated below in calculations. This must appear before the + * first call to any from* function below. + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_16_DBL_ = 1 << 16; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_24_DBL_ = 1 << 24; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; + +/** + * @type {number} + * @ignore + */ +Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; + +/** @type {Timestamp} */ +Timestamp.ZERO = Timestamp.fromInt(0); + +/** @type {Timestamp} */ +Timestamp.ONE = Timestamp.fromInt(1); + +/** @type {Timestamp} */ +Timestamp.NEG_ONE = Timestamp.fromInt(-1); + +/** @type {Timestamp} */ +Timestamp.MAX_VALUE = + Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); + +/** @type {Timestamp} */ +Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); + +/** + * @type {Timestamp} + * @ignore + */ +Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); + +/** + * Expose. + */ +module.exports = Timestamp; +module.exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json new file mode 100644 index 0000000..1eb5b0a --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json @@ -0,0 +1,70 @@ +{ + "name": "bson", + "description": "A bson parser for node.js and the browser", + "keywords": [ + "mongodb", + "bson", + "parser" + ], + "version": "0.4.16", + "author": { + "name": "Christian Amor Kvalheim", + "email": "christkv@gmail.com" + }, + "contributors": [], + "repository": { + "type": "git", + "url": "git://github.com/mongodb/js-bson.git" + }, + "bugs": { + "url": "https://github.com/mongodb/js-bson/issues" + }, + "devDependencies": { + "nodeunit": "0.9.0", + "gleak": "0.2.3", + "one": "2.X.X", + "benchmark": "1.0.0", + "colors": "1.1.0" + }, + "config": { + "native": false + }, + "main": "./lib/bson/index", + "directories": { + "lib": "./lib/bson" + }, + "engines": { + "node": ">=0.6.19" + }, + "scripts": { + "test": "nodeunit ./test/node" + }, + "browser": "lib/bson/bson.js", + "license": "Apache-2.0", + "gitHead": "4166146d0539a050946c1cae9188f274dd751ed9", + "homepage": "https://github.com/mongodb/js-bson", + "_id": "bson@0.4.16", + "_shasum": "e78fb993535123851f857fb83c7f68b1cd7e6caa", + "_from": "bson@>=0.4.0 <0.5.0", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "octave", + "email": "chinsay@gmail.com" + }, + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "e78fb993535123851f857fb83c7f68b1cd7e6caa", + "tarball": "http://registry.npmjs.org/bson/-/bson-0.4.16.tgz" + }, + "_resolved": "https://registry.npmjs.org/bson/-/bson-0.4.16.tgz" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js new file mode 100644 index 0000000..c707cfc --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js @@ -0,0 +1,21 @@ + +var gleak = require('gleak')(); +gleak.ignore('AssertionError'); +gleak.ignore('testFullSpec_param_found'); +gleak.ignore('events'); +gleak.ignore('Uint8Array'); +gleak.ignore('Uint8ClampedArray'); +gleak.ignore('TAP_Global_Harness'); +gleak.ignore('setImmediate'); +gleak.ignore('clearImmediate'); + +gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); +gleak.ignore('DTRACE_NET_STREAM_END'); +gleak.ignore('DTRACE_NET_SOCKET_READ'); +gleak.ignore('DTRACE_NET_SOCKET_WRITE'); +gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); +gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); +gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); +gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); + +module.exports = gleak; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml new file mode 100644 index 0000000..b0fb9f4 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml @@ -0,0 +1,20 @@ +language: node_js +node_js: + - "0.8" + - "0.10" + - "0.12" + - "iojs-v1.8.4" + - "iojs-v2.5.0" + - "iojs-v3.3.0" + - "4" +addons: + apt: + sources: + - ubuntu-toolchain-r-test + packages: + - g++-4.8 +before_install: + - '[ "${TRAVIS_NODE_VERSION}" != "0.8" ] || npm install -g npm@1.4.28' + - if [[ $TRAVIS_OS_NAME == "linux" ]]; then export CXX=g++-4.8; fi + - $CXX --version + - npm explore npm -g -- npm install node-gyp@latest \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md new file mode 100644 index 0000000..7428b0d --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md @@ -0,0 +1,4 @@ +kerberos +======== + +Kerberos library for node.js \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp new file mode 100644 index 0000000..6655299 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp @@ -0,0 +1,46 @@ +{ + 'targets': [ + { + 'target_name': 'kerberos', + 'cflags!': [ '-fno-exceptions' ], + 'cflags_cc!': [ '-fno-exceptions' ], + 'include_dirs': [ '> $(depfile) +# Add extra rules as in (2). +# We remove slashes and replace spaces with new lines; +# remove blank lines; +# delete the first line and append a colon to the remaining lines. +sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ + grep -v '^$$' |\ + sed -e 1d -e 's|$$|:|' \ + >> $(depfile) +rm $(depfile).raw +endef + +# Command definitions: +# - cmd_foo is the actual command to run; +# - quiet_cmd_foo is the brief-output summary of the command. + +quiet_cmd_cc = CC($(TOOLSET)) $@ +cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_cxx = CXX($(TOOLSET)) $@ +cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_touch = TOUCH $@ +cmd_touch = touch $@ + +quiet_cmd_copy = COPY $@ +# send stderr to /dev/null to ignore messages when linking directories. +cmd_copy = rm -rf "$@" && cp -af "$<" "$@" + +quiet_cmd_alink = AR($(TOOLSET)) $@ +cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) + +quiet_cmd_alink_thin = AR($(TOOLSET)) $@ +cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) + +# Due to circular dependencies between libraries :(, we wrap the +# special "figure out circular dependencies" flags around the entire +# input list during linking. +quiet_cmd_link = LINK($(TOOLSET)) $@ +cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) + +# We support two kinds of shared objects (.so): +# 1) shared_library, which is just bundling together many dependent libraries +# into a link line. +# 2) loadable_module, which is generating a module intended for dlopen(). +# +# They differ only slightly: +# In the former case, we want to package all dependent code into the .so. +# In the latter case, we want to package just the API exposed by the +# outermost module. +# This means shared_library uses --whole-archive, while loadable_module doesn't. +# (Note that --whole-archive is incompatible with the --start-group used in +# normal linking.) + +# Other shared-object link notes: +# - Set SONAME to the library filename so our binaries don't reference +# the local, absolute paths used on the link command-line. +quiet_cmd_solink = SOLINK($(TOOLSET)) $@ +cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) + +quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) + + +# Define an escape_quotes function to escape single quotes. +# This allows us to handle quotes properly as long as we always use +# use single quotes and escape_quotes. +escape_quotes = $(subst ','\'',$(1)) +# This comment is here just to include a ' to unconfuse syntax highlighting. +# Define an escape_vars function to escape '$' variable syntax. +# This allows us to read/write command lines with shell variables (e.g. +# $LD_LIBRARY_PATH), without triggering make substitution. +escape_vars = $(subst $$,$$$$,$(1)) +# Helper that expands to a shell command to echo a string exactly as it is in +# make. This uses printf instead of echo because printf's behaviour with respect +# to escape sequences is more portable than echo's across different shells +# (e.g., dash, bash). +exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' + +# Helper to compare the command we're about to run against the command +# we logged the last time we ran the command. Produces an empty +# string (false) when the commands match. +# Tricky point: Make has no string-equality test function. +# The kernel uses the following, but it seems like it would have false +# positives, where one string reordered its arguments. +# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ +# $(filter-out $(cmd_$@), $(cmd_$(1)))) +# We instead substitute each for the empty string into the other, and +# say they're equal if both substitutions produce the empty string. +# .d files contain ? instead of spaces, take that into account. +command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ + $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) + +# Helper that is non-empty when a prerequisite changes. +# Normally make does this implicitly, but we force rules to always run +# so we can check their command lines. +# $? -- new prerequisites +# $| -- order-only dependencies +prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) + +# Helper that executes all postbuilds until one fails. +define do_postbuilds + @E=0;\ + for p in $(POSTBUILDS); do\ + eval $$p;\ + E=$$?;\ + if [ $$E -ne 0 ]; then\ + break;\ + fi;\ + done;\ + if [ $$E -ne 0 ]; then\ + rm -rf "$@";\ + exit $$E;\ + fi +endef + +# do_cmd: run a command via the above cmd_foo names, if necessary. +# Should always run for a given target to handle command-line changes. +# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. +# Third argument, if non-zero, makes it do POSTBUILDS processing. +# Note: We intentionally do NOT call dirx for depfile, since it contains ? for +# spaces already and dirx strips the ? characters. +define do_cmd +$(if $(or $(command_changed),$(prereq_changed)), + @$(call exact_echo, $($(quiet)cmd_$(1))) + @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" + $(if $(findstring flock,$(word 1,$(cmd_$1))), + @$(cmd_$(1)) + @echo " $(quiet_cmd_$(1)): Finished", + @$(cmd_$(1)) + ) + @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) + @$(if $(2),$(fixup_dep)) + $(if $(and $(3), $(POSTBUILDS)), + $(call do_postbuilds) + ) +) +endef + +# Declare the "all" target first so it is the default, +# even though we don't have the deps yet. +.PHONY: all +all: + +# make looks for ways to re-generate included makefiles, but in our case, we +# don't have a direct way. Explicitly telling make that it has nothing to do +# for them makes it go faster. +%.d: ; + +# Use FORCE_DO_CMD to force a target to run. Should be coupled with +# do_cmd. +.PHONY: FORCE_DO_CMD +FORCE_DO_CMD: + +TOOLSET := target +# Suffix rules, putting all outputs into $(obj). +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# Try building from generated source, too. +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + + +ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ + $(findstring $(join ^,$(prefix)),\ + $(join ^,kerberos.target.mk)))),) + include kerberos.target.mk +endif + +quiet_cmd_regen_makefile = ACTION Regenerating $@ +cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/fmason/hub/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/fmason/.node-gyp/0.12.7/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/fmason/.node-gyp/0.12.7" "-Dmodule_root_dir=/home/fmason/hub/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos" binding.gyp +Makefile: $(srcdir)/../../../../../../../../../.node-gyp/0.12.7/common.gypi $(srcdir)/../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp + $(call do_cmd,regen_makefile) + +# "all" is a concatenation of the "all" targets from all the included +# sub-makefiles. This is just here to clarify. +all: + +# Add in dependency-tracking rules. $(all_deps) is the list of every single +# target in our tree. Only consider the ones with .d (dependency) info: +d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) +ifneq ($(d_files),) + include $(d_files) +endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d new file mode 100644 index 0000000..0bc3206 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d @@ -0,0 +1 @@ +cmd_Release/kerberos.node := rm -rf "Release/kerberos.node" && cp -af "Release/obj.target/kerberos.node" "Release/kerberos.node" diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d new file mode 100644 index 0000000..2ec56f5 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d @@ -0,0 +1 @@ +cmd_Release/obj.target/kerberos.node := g++ -shared -pthread -rdynamic -m64 -Wl,-soname=kerberos.node -o Release/obj.target/kerberos.node -Wl,--start-group Release/obj.target/kerberos/lib/kerberos.o Release/obj.target/kerberos/lib/worker.o Release/obj.target/kerberos/lib/kerberosgss.o Release/obj.target/kerberos/lib/base64.o Release/obj.target/kerberos/lib/kerberos_context.o -Wl,--end-group -lkrb5 -lgssapi_krb5 diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d new file mode 100644 index 0000000..cfee5be --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d @@ -0,0 +1,4 @@ +cmd_Release/obj.target/kerberos/lib/base64.o := cc '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/base64.o.d.raw -c -o Release/obj.target/kerberos/lib/base64.o ../lib/base64.c +Release/obj.target/kerberos/lib/base64.o: ../lib/base64.c ../lib/base64.h +../lib/base64.c: +../lib/base64.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d new file mode 100644 index 0000000..a313cb5 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d @@ -0,0 +1,71 @@ +cmd_Release/obj.target/kerberos/lib/kerberos.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos.o ../lib/kerberos.cc +Release/obj.target/kerberos/lib/kerberos.o: ../lib/kerberos.cc \ + ../lib/kerberos.h /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /usr/include/mit-krb5/gssapi/gssapi.h \ + /usr/include/mit-krb5/gssapi/gssapi_generic.h \ + /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ + /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ + /usr/include/mit-krb5/krb5/krb5.h ../node_modules/nan/nan.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ + /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ + /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ + ../node_modules/nan/nan_callbacks.h \ + ../node_modules/nan/nan_callbacks_12_inl.h \ + ../node_modules/nan/nan_maybe_pre_43_inl.h \ + ../node_modules/nan/nan_converters.h \ + ../node_modules/nan/nan_converters_pre_43_inl.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h \ + ../node_modules/nan/nan_persistent_12_inl.h \ + ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h \ + ../lib/kerberosgss.h ../lib/worker.h ../lib/kerberos_context.h +../lib/kerberos.cc: +../lib/kerberos.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/usr/include/mit-krb5/gssapi/gssapi.h: +/usr/include/mit-krb5/gssapi/gssapi_generic.h: +/usr/include/mit-krb5/gssapi/gssapi_krb5.h: +/usr/include/mit-krb5/gssapi/gssapi_ext.h: +/usr/include/mit-krb5/krb5.h: +/usr/include/mit-krb5/krb5/krb5.h: +../node_modules/nan/nan.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: +/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/src/smalloc.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: +../node_modules/nan/nan_callbacks.h: +../node_modules/nan/nan_callbacks_12_inl.h: +../node_modules/nan/nan_maybe_pre_43_inl.h: +../node_modules/nan/nan_converters.h: +../node_modules/nan/nan_converters_pre_43_inl.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: +../node_modules/nan/nan_persistent_12_inl.h: +../node_modules/nan/nan_weak.h: +../node_modules/nan/nan_object_wrap.h: +../lib/kerberosgss.h: +../lib/worker.h: +../lib/kerberos_context.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d new file mode 100644 index 0000000..fcffab4 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d @@ -0,0 +1,70 @@ +cmd_Release/obj.target/kerberos/lib/kerberos_context.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos_context.o ../lib/kerberos_context.cc +Release/obj.target/kerberos/lib/kerberos_context.o: \ + ../lib/kerberos_context.cc ../lib/kerberos_context.h \ + /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /usr/include/mit-krb5/gssapi/gssapi.h \ + /usr/include/mit-krb5/gssapi/gssapi_generic.h \ + /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ + /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ + /usr/include/mit-krb5/krb5/krb5.h ../node_modules/nan/nan.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ + /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ + /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ + ../node_modules/nan/nan_callbacks.h \ + ../node_modules/nan/nan_callbacks_12_inl.h \ + ../node_modules/nan/nan_maybe_pre_43_inl.h \ + ../node_modules/nan/nan_converters.h \ + ../node_modules/nan/nan_converters_pre_43_inl.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h \ + ../node_modules/nan/nan_persistent_12_inl.h \ + ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h \ + ../lib/kerberosgss.h +../lib/kerberos_context.cc: +../lib/kerberos_context.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/usr/include/mit-krb5/gssapi/gssapi.h: +/usr/include/mit-krb5/gssapi/gssapi_generic.h: +/usr/include/mit-krb5/gssapi/gssapi_krb5.h: +/usr/include/mit-krb5/gssapi/gssapi_ext.h: +/usr/include/mit-krb5/krb5.h: +/usr/include/mit-krb5/krb5/krb5.h: +../node_modules/nan/nan.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: +/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/src/smalloc.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: +../node_modules/nan/nan_callbacks.h: +../node_modules/nan/nan_callbacks_12_inl.h: +../node_modules/nan/nan_maybe_pre_43_inl.h: +../node_modules/nan/nan_converters.h: +../node_modules/nan/nan_converters_pre_43_inl.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: +../node_modules/nan/nan_persistent_12_inl.h: +../node_modules/nan/nan_weak.h: +../node_modules/nan/nan_object_wrap.h: +../lib/kerberosgss.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d new file mode 100644 index 0000000..d4cefbf --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d @@ -0,0 +1,16 @@ +cmd_Release/obj.target/kerberos/lib/kerberosgss.o := cc '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberosgss.o ../lib/kerberosgss.c +Release/obj.target/kerberos/lib/kerberosgss.o: ../lib/kerberosgss.c \ + ../lib/kerberosgss.h /usr/include/mit-krb5/gssapi/gssapi.h \ + /usr/include/mit-krb5/gssapi/gssapi_generic.h \ + /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ + /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ + /usr/include/mit-krb5/krb5/krb5.h ../lib/base64.h +../lib/kerberosgss.c: +../lib/kerberosgss.h: +/usr/include/mit-krb5/gssapi/gssapi.h: +/usr/include/mit-krb5/gssapi/gssapi_generic.h: +/usr/include/mit-krb5/gssapi/gssapi_krb5.h: +/usr/include/mit-krb5/gssapi/gssapi_ext.h: +/usr/include/mit-krb5/krb5.h: +/usr/include/mit-krb5/krb5/krb5.h: +../lib/base64.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d new file mode 100644 index 0000000..02da394 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d @@ -0,0 +1,57 @@ +cmd_Release/obj.target/kerberos/lib/worker.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/worker.o.d.raw -c -o Release/obj.target/kerberos/lib/worker.o ../lib/worker.cc +Release/obj.target/kerberos/lib/worker.o: ../lib/worker.cc \ + ../lib/worker.h /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ + /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ + ../node_modules/nan/nan.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ + /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ + /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ + /home/fmason/.node-gyp/0.12.7/src/node.h \ + /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ + /home/fmason/.node-gyp/0.12.7/src/node_version.h \ + ../node_modules/nan/nan_callbacks.h \ + ../node_modules/nan/nan_callbacks_12_inl.h \ + ../node_modules/nan/nan_maybe_pre_43_inl.h \ + ../node_modules/nan/nan_converters.h \ + ../node_modules/nan/nan_converters_pre_43_inl.h \ + ../node_modules/nan/nan_new.h \ + ../node_modules/nan/nan_implementation_12_inl.h \ + ../node_modules/nan/nan_persistent_12_inl.h \ + ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h +../lib/worker.cc: +../lib/worker.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: +/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: +../node_modules/nan/nan.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: +/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: +/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: +/home/fmason/.node-gyp/0.12.7/src/node.h: +/home/fmason/.node-gyp/0.12.7/src/smalloc.h: +/home/fmason/.node-gyp/0.12.7/src/node_version.h: +../node_modules/nan/nan_callbacks.h: +../node_modules/nan/nan_callbacks_12_inl.h: +../node_modules/nan/nan_maybe_pre_43_inl.h: +../node_modules/nan/nan_converters.h: +../node_modules/nan/nan_converters_pre_43_inl.h: +../node_modules/nan/nan_new.h: +../node_modules/nan/nan_implementation_12_inl.h: +../node_modules/nan/nan_persistent_12_inl.h: +../node_modules/nan/nan_weak.h: +../node_modules/nan/nan_object_wrap.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node new file mode 100755 index 0000000000000000000000000000000000000000..2bcec8ec0121131fd8bf4a7bd02d25f4198f6fc3 GIT binary patch literal 85259 zcmeFad3=;b@;^R-fC0org$3~%6&3Ix0fGTU6T-km14IIX2ZoSLAQF<8OgKa|Y!YM~ zN8^33(bW}iyb(o%AVJpyT~}Ez@T7;hinwXJZiK~9=Me(vhjN{eyJC#w&!8p zTuG^}qg?}BgQmJy)+VK<4oFE{ol<)=N9xwiHPDqn+Mbv9Oz6`kA@%H(9&0lby5zXe zopV&r{rTATj-%APL=Q4eX`M1_U%gwdHTvwRu<+ujS=PPi%3cro`y#~M6 z;rDv{-iY6u@XMc@@p}t?Z^iE&_`MUqP5AvQe(%9Af9};6*L}FI!tebCegM~p%;!gN zebjvBWi@^u!|&txeGjk&JH^*Q{m!|%c8ZrPK0U)^UXZSvf7$LkrB zZt;$7$v$T8irc=vcIm#u-+JPK0T)iWzW<80w+?#Z9N(QKE0zyG;NzYD_~wAWFSu>^ zd0(#W+q3&gr@l7(vVXh!5Bu}7e{A*MKIxf%HXJ{9MR@*236-zBx#!u?w+Fm3_n|&1 zeLkPp`onF*XWh7R_YI4mS=m-GKPzYR!5=rCwPnwbzD2uQcJ=*uVgDgRavr&q za!%G>_dV&ot8N>9$Ii8V8^&~R+jzp<6}OzS^|;4g$GE3YT6)sn+lDuGJMyVzecyWG z$;T5*-uk@c&TP*=zj|x>mOXcLfBC}KXMA?=+Rv`Nr0}(mj%(A zto-S+eYXww{i*LWFCOyN6Cbwpo$;@WW*&CTZ6%ILjix$Yy21lzj*rD(d4S91tOdIz z1I~SrjWC~|KDcxISU7iQmdYIF5by#*y=9=&dumyp3en8GcTjal)`8RMg?;9u9$=o#~-V9RFl}+8O-=apqeRN6$yZ zi6^JW(evmy{=Y7c9+Kk3&((3}^=X_qd~FlB;6K9-5YsuAJD0yG&ieW*{Gqct;T;Iy8GaY^(3yT#K%Ymudbt{>YZskqJT)xy?d7U`K_mR| z8~!AL{vgoTZq)Gm`r`Tm>x<*eepw@qG5BSOKg7GHX~cMgFE-GL*d{6HgTmFOS%b2R<|$jzUR%=nE)&ese+!;F(+#u={3 zT_ePQdbyhZsu5orJau`HYk$}IuNs8841-@$o|GnyfP2f2!oSo*$`lP_S;@~bqlaBa z500MCmG$1s)oeD7>&?9OA>VO)*9E%2*NjtO_|_I{#5ab)56JJN-?BpE+su5=bnI*R zI{NfTJ>Sc<{Si&y!|;6=bsfj4yjJ6n(HGY|(ND*H*%avcK-VFz?TJSTCCKFGEa>?t zoIEs{bC^_v_sM$i<=WNG?#Fc1^saXFFDQvjUNt}KQ9=0nv8xNKddwJN^KG{ zmt(J!jQ(9_d`EfQT))v$!2MF zxrQSCQ~z78(}?%s2mEO@{#?0A!{x?L#>CNc1<1s&CTn^pNB9ii_Hp%2*q3(9Y`5;_ znfbQY=iE5)(^XI~cR@vYLAAfI%3o06Dkv!}FLf2TsR#jN)ug=LIR^ah?#t-u>B;)_%GI+b1w81 z`G=+EmsKp9==0~4Lu*jOgi>Ewu?PA*ck-Da%kV7L`1G?2%W8a)?rCY>!t&xWUw%eAM<2L_lV^Nu}u)Jf}YG2htUlm07wN{ZVVi!HB8IUAx*bHCc z{OrQAvN?rC^F33~)b_WL;|u+TIrjAPQ(rKQ5ZvumoV;9QZ$-|fK8DD9jV+#_MZS*}q;994}^75>F#d9u8t z^cpW-V=t`iG+9g$5sbT>!o@n*S0%HhpF{{E>sBl3lxY=pc0X+f-%v*q+nqxxkf}y&niJcXdeJE^vHaFRcZO$v^1DtLRH0r z>Hd<8Sn2c5ESe0jPovnHc-oRmpN=&cV3cQZk*|{RGTl>ERZ)d#Suj$E6fB$qGrqAr zW0Rg^#n1nUV5pX>Y~C*24gFt#ZmmQPKig#2)<>Sc$CHc zc#!~=M^AIOKu4*TqVd`2(}R}b1<-wJL57pcp#D;LoIywQNk)<`oY{=>7FK5$*36w} zR-Be%!~{gavWT7G9=04@_h97=;l!&5!UUk<#ic&D5?s|+RaIV5P*#Bi0u;xrk!aoL;EkPFQgHaZ{JKuRdnVZpV2A)`bz zV8m!}&yHNG036m%3V671R;JRgP0|G?lz#EB&K08*NjQ4ODl*-iWujt28 zWrnE;v&u^6mivnHDqvq<6+?QA{5oz&RW&MRZ6K?lF8ZU&ijEe$(pY2t&&SG$k&LBJ z`Tu+{N3eXU7yl839F_*jVkFUvT|y^TT3Wk-rDlq(QYVu~wq70i>S;ySY}&~73_Yd4zSuj4 zicYwgQaoO6vyzk@TJlF=V>3BFiG z(eSc8pIo@0eN>Ar6QQE01RZA>tD}ybq}s_(cWT9s1Ziogvtsiu?b~sFJUQ@J_)+h6 zm|%v3>7-zd&W5><3LU|XB;>-!G!BZQ$G;@YkJ@`q4Ne%0h9mXbDNxmKYALcHe?7gJ zb(b-rqN>P;ac!eRoJhV!br@f|5v;0Wm!4H{Qv41{@As}+7PG zr~rikcf2u7B6L)82ddKYi)u=%d@(&8iKXWp2s&~EilZWE(q$l2WP~7Sc~RvOVP}qC zI6XOPfhPPo_h7-T&m~YI7i1Sqo>nkD-!rvfa@Hh|^eZef0#x~m3otdk%fx&vxuX=W z$SB?^`P0T_<$J~#V7Rk$vOA6zqlF?2@0wpVC%r(_;3!Hkm4#I>hVWZ3AICWhDo2jc zv_(a*6%Gs*`XVs9>tvx(bA5j9IZ$~mz#(AaTyB@4m*SdA-Oe+sb_Bu{Ll^r%Sh2*S zqw5rvRu-07I7d`!wy=o1;TR*8 zi^@5(=&;(HW1fx;W+8NFNE0?+ zVAM{v?^JLds3o;VZ0jV%SliMibUCXJ?^x|d@>C}!5VzGFS2od+V#t%XP?Fzp#E(-Z z6mlQ5BxhQIC!@-TDx@0pew$=4m~EM%=LtgGtkUpZdF2_&t^!{$yI|PKBO;%MTc3xWobJk= zIWucqPC*)^6yljP(QyPrwj*xAu!2cB({vylE+6$RC07@Dnp^{k_{>{{`ZjAfJcHkz zk8lZ2Kao#5ebbixy5o00)5;d7jTGkAu6!b${X-s6oGn3=u8T|GB-FP|yJ7_PqHO$6 z_l}MsP134w*^zq>^yucotwH%=FPAIf|B?T+Oq6Dn+?#W`+(6|Ww*+?zd%7+Mjz0;I zd4_4v1l*^z6nFTNTvr>M|BzBV$+Dm876aD|Al%(`Z=`=0*AUajd-nf$bUvQ2=;3fgh(qr2^S)5IQT&p{wZtxd2#TYwFRD_&Z5?Q_eOtMz92r2pAt z;s0#mU2SfGNYC$~I6p}i9=F~jKPeVIIf8Y$`dj!LExg;pn@1<4b&!R>$)ZoS@NNsA zVc{RJ@R=6=Nel0_@cf>M^OI-cA9Ikn&b08yTlm=)-aJwvt@AAW9Tt71g|D;li!HqK ztPh)OE&Np${Yndeg@tdl@aY!*W(#i~g^<=J3*ThXud?uWS@_i!{#gsZ#=@_*@XZ$f zdJDhV!Urt;77K44<&f5`7CvOrZ@2J^EWEPti!J=kCeARP)LQsv3twsB`{U^j{zP-K zZggAtTQo}k9c1C7nbqY=weUL2>P{IJ9*H9IlWF0jdEJHQqN4KXysNw9S$HR=vt_1* zN1}@S%(n1OzGmY*3y(w+`Kh$~skjvI{@KESZk4MuYKdUXg^Gp>R*I4+z5o(vK*}~(|tH{r03y(*6B0pO!eE$g6 z<=SfDO-h#5?G}E3MXxOUp%#9Zg}>9n@3HWQS$J1MRR4!t_#_Lz&cdfy_#-TQe+z%4 zg?C$c%}F;7vhYV+^r;s97z>|a;RjmyObdUkh4)(c<1Bohg&$<$XIl8d7JjycA7bI> zS@;tye5Hjy(ZVmb@F!XLS_^-&gAPaxGg-^BcnHE07!e?3dObb8G!h0=z zwuR5L@Z&A~Obc(H!Y{V)UJGAq;d3nfN(+C6g>SU*XIl81 zE&S~kzRAMpTKH8K-fU5%b+v_`Y|*c=@KY>&vxU#I@S83CSr&eag`aBSw_5mo3%}jM zKWyQZg>SU*yDa=P3%|$0Pq*-{u2KI#+rlSV_!$;H#lp|D@ck|PITqe+;m@`3gDm`c z7CzO&KV#uDEd2QvKGVX_vhZFDe}RS1v+ye{{7eh~Hw!=8!WUThc@}=Qg|D>mg%*CX zg`Z>LYc2eh7Jj9LFS78B7QWcR-)!N17QV^Cmst2!7JjaUUv1&%S@<;;zSP1uTlfnt z{ALS3-@O_!NEgpY0Me}2yGYCEwTvd@$kF0)I-FTZeFy!0!|0mLc3I@Y{s{M7UPqR|#{A5Uv#X zCBobqgl7x9mN2&j;XHvKCp>^~roaynK9q2(z;_d7i63?gd@JF@38x5rEn$}KVVA&H z5N639-t`OT|7XH(!rKMDm@tz>c#FVQgjuqOn+3j*@G*o}3p|JLK*CJ|pG%mfdAL#F zsf3RsTr2PygpVg&DeySLg9y(Scr@X`g!2R*Mwq2|I8)#ugij!xD)7;SPbBOXcmUy( z2&V{q5Mh?uVVA%?2@fT_>u0e);Z(xg1>XBC;55Qp1pbaNOYCs7z&i;KC%jtVPYJW6 z4mSz>K4F&9;YNYqCOndGt-!AmW+@!56!;~=8H8sGyp}La-*BG5j}snEI8)#U2#+D0 zD)8NeS+a)R0^drQrD`}u;A;u96b-uszJf4I(D1IG#Quac32ztpV!~O3w+LKCn5Aa8 zS>Ou^XA@p6@EpS92{#FRE@76A;YNX{5}rV~R^T%TPb6F^@HoO=!m|Y)O*n^ep1{Kh zpFucN;30%r3Wie!KALbYVYk2o2u~uMBJe?kS=xnN0{0}$k}kY!uh^e3OS$lNf%mQf z%n~lVMd0rUvvdnL3%rwXKH=2@e@d98SGY;w_X)G)3O5S;Her@p;aY)TCCm~lTq*EN zgl7_-E$~{x=Mc^l_;JGL63!I(0mA1IP8IlW!Yq-(Zh>zl%+e^FBJj0@SrUa^0$)Lx zrA>I(f5rZUXA|Bo@Wq4+32za&iZDxR|-6iFcVOCw!otamlDnsco^Xe31N5gtrTPG2!Kew+LKC_|Jr!1-_7Q z9pTji&mmk-xJlr12{#aK1U%gv>b(lB-cb4>VCoHxy$`aj?T>bE;0qOkNF@0J3_$WD zI1*7q@z1;-u)5Y*ll)-bMF;rB68v=it*c}&wU*YuwPwCNv+ zr4M!6OuEq6wYW_84&FoBx;+Oh>N0Bs3b+yMjRNkwS#8@XuQ$}~8clzNMZbPeS8w1Y z@A{pmdlR;J-`Z0no%{Ba&Tpf$H?XPgQ}(YNdk*@!YL55TjZH=~SO&iE?~i%C{gm6K zPQsE<^WX-vHg!t{VZ!$tO865|3c95}jBftpAl#JITDSq!;sBsAR@;_Y;Taep`N&!q ze!^$sbF_QobZ_uiLIMWM4Sb^x!vws67BvvDjbu52P2S+dw%Wy@8k6=TN&X81 z8hxZ;T3;e59z) zk`6WZosAI18|>;0Rs&kx9~K*h<>_ts(VIMemwNC&ZEZP$mxHdlJ#GH9tU&$1Cxw1# zlDDA^b@~`A5^rFe8qO=~bx16d%?cj{Od~t2Mu(iBCn;-F{lF%CPRIdr6+X1Cfqp~X zUPW}E+M-H}iUpapAR^)7{%Q;q^=tAx_@kERue`>{a}6-ROPtQ5J=pf-YKSccS*Y$Q!iL>a%-=MgBZ{R2Hp>l(d(wDLHINMwT{;q|F{U4-{BvD zFSx8BNI^<4JE@_$W{zXp(aBFw>{YitxlVOGHDS?-s*+2h;RA0=b_x{f@*hlp32gHQ zGn2^qJcP(b{b2)A$T)<1q>v{#m(bW_7a@fp9k|qx?=VWJ_c6NpdfoiPLNu>nb1yVU zS2)%a<pBe0Q8?SV~ge~XT< zM@&(F!x(khNeR)}jL_nKfoWhiS5e&aDDL^++Txb9lUK$|u3rgCBju@G{1=FtFU_b^ z2@TDG>?D6L!$$H;uQUW1NH-s%n_oh0w3hXpYDBZFKZ*4!i`0P)Il=mYH>24b$absO zW#uDi1X|LX5jFhqn_;R2O2Dc^-jMn0T%i&=^zW}io%X*xwtv(f-D>WKE`HtKd%vfe zbTI0zUgI)oXYVBVZRhsx*7vu@AFOVT8NaOE`0)SpW`#$7gS34Y=GM;s-JV+Y8}biU zqhrS3zti#G{TkzEIpdpL9GbNS3pZ7bqQheu1~#e5P^2e#kEAqp6!7B%UosmngnYa{ zLYE?`XS2GNoPwUs@TycXUQS>m+SJ9s=LUADIp}WN)9dhig&j4&k742nzsG<#{JI-{ zr&;`tj>E5~;rAV`o$@<}9W}pln_m|2hTo0Q59jv==I_k!anWnX`O%)7-=E|03$vr< zw-57(%@jZ8LSv{Ll38*_B5$=`Bz&R zVnRav4Sn@)>M(d{?Q>0Na3$BjjS@09_*dp;RRXeS(YY<{?Og4_eaIaae(fu{!dKNb z5FX{__~3I)@oE?-#s~J1=yFY@UKENJ)sLM+>BnFfX+|a0dKfP^uotrA26n3=f$psY zQ?-MiL-(fQv$XC|FJnZt1!yqL4K1!z8}WHkLtAqFPhD7@EUe^+FA84_w?mDW;dX#r z1t3Lk$k&(~cxo|5Wb3A#7&%zSyxb9ss~E@QT-4m!BZS6H`KsMJ_|B1eQm1f?)>g_TDyl>?Rka3kaTc>Ne0_6reE^nIPe`Lgn>83N%ojhQKF308 zyRI3msEMmd15FsER$^$i6gcqqhBBc-t%`X-dF$43Qt*o_Fi=i#ktp~AN0=SzGio&e z1-Ga{BG0-!(5n;CcT&TT$@Nc2w~?H}AoKz$hM!529MMIL@_)o&M)@ZQix%~S=uRvD zJ+a_ZmFR6$@f4=0n%OH>`Mtr_DF1QV7-{lHwOEnPQ9i}Am47b8;Vh~!nt0T+)K*ZG zUoK;a^1qi!?p9;4G^za0&{W^-Pf?>OoL(fSV<@)m2idWd=w6c=KKCDy6FhYwYxUmh zVf4;vNgRk4l+8QTGK$vlfxm|?<=XPN-%*R`c*{3(#Y!=qbwO5v*_WmL7`_z8){%N0 zaBm#r+VEsdFbcPY_qL;dEQY=*u(a5S}k zhEJ^@;~&oDKv=HzEjTEf`>;7|T6RNMtP<8ST`0E>f!nGC zFnba9bg8*JBKsJGkxx)+c?0iDQ(CjS5RI+x+4TjZUrykc7YCs)!k@Ys6e!{lvy$t1 zFq9L#gL|6Xz^B3Cs9ciNA_&V5TqDoXBH;c6u32@bwfPU96u6i5mskRGz!o`tBO0~* zIl&3ohc+~UAOT9qYH46FgazPJ4H8Q)1a0d}j(jLyPlWuc7%aopv{dA1A)*gQ{ydCC z`L})T7<$WWK~zCgbj8GOwU9;xE5F zpIbrR`l2%l!-6lXq?k0K`+Grht6>K3PT^%tR}S*_>~kP!=8B|}weCt)ND zXvsLk|}A#rWG364}rGs)2`mSy$SwF!nIz; z6Rx*lLds7#l>RX0VsSk}s9My!UudqA0UNH_;M%$p<7c)dKb_gDZqH?x{monVO_J&f z%OWt`k`qiEh-r37zIu;j1n!@)PivX2=3$zQ+cZC^f_W)O99LZ=WQ&v3RtO}~@MZPz zXKihv#R+n}<1K1a>liy5nz61B_CfDSYfgJ*Eyh8IkGWD`gIF)5z)AGV32AybMRI)> z=#5Yb$yf1(Us@u_{3l36?e4=ovjW{ol@quiNsE8KP=c7-%;woBepbGi1P*F7qhkv` zVcfvWDh*(6XqnC~ZE74Wr4A7zq!&s3MkmEYg-G*8QP&1I~ zNRA)uz3O&1wA1$!TyjE-k~m)G2KFMh+ct#m|xBkl_1r$sR@SaG>vLq2j6OC zfTx3ulA(5}qoP9`XHW+KWe40$eSX;?KJ^QZO9^@R)%`bNVTpu`=@`J6@$6?Y>vodF1}TaAb$hxb*B4-g*6rzk<-G&Cn) zbwpP#(uv?)fTGa!G(*NHmu)&s+24FgUs4bV1DQ=dD}XAN~?Zq=zLA^rZbe zOQHgUZ*u({jBQ1VA}#|aNkoeKOplzv5t9PtN#n;XPD#G#$A*FHF~Ls5KoDId47|<0(J=5CbgW)rqZ0;}Lusb=ds?*Zgn`XQ z_ij+rd-~(5!@$=ZQ-^^fx>Ts!iCCAvCkzy$&UL~-e~usQeb>!y@bCLRE>0M@0OPAe zgvmB0xP99I_WwZM* zob@|!KImDQJ9ybjd3Zwb=ORFDQ}19j?5rFLuBQTry(?-GQ%gA-otd?E6T@BK0h($h0-sH<#Vq@!WK2l z@cAcT!{^lx!RImDx|en14R(pdwReH!-1dmQH>f5K66|}{O>S2jJ{-jJvIC5VT#tca zc_x~FLETKpKOoLg!B`&1kJ;kx%-G0}^e2+MEhK#gB0Pli!L6hb@p2lFcD!5x9Yo+r zitQ>wVSl+vZT%oNsVll3m)^_C^`&4NP3pOUuUT=*OH$RhocI|s@k|7OZ7Rjga}9Ki zd6wST$vhu|Rm?oU#gsXT8Z%D>W7I>*SG`3S2zoKoFiNE!-oP7mU!qjnmyq0W21vcZ z98@?tz3TpZS@PARfT-JxnnvHWK|fQ|TyK=vUk2A28jX}{=a;8A8hv0t3am@M!#;)& z?3T5cuI9w}+FisV&YgpK)7RbtYQ~bNW7h9NTUNengVAZBXN2hnHI!5V><4lG@n2-xrXC_mynHto5nJ-zCVXHj zJI={>>2zDOWxL$uy8|%~5?unA>ol710>I=3XZOpgy9Dn&Pp*G2k%m6lllEiX#Y}aJ zVpH8>n$@hg^Ff*$aOVap;V)ffNua|;z+wrHhj?5e_em^}!V1CDDSsd1)SSGxQ4Ir_ z8>-Re?{1ZiMXrt@3AFJgIP#3)0Kjq>5Gj9e$3&e20h~VQ@;5iIPhBTn5(ldH@qsph zEvV2|=vr-JW3Uen6;S?iA7G-|3(z|FneumwvB4mYfO8`^t~&4ih)g}QBo zcV}%{(F9jU`MVJ1@85L!`-m=oSFAw;=yF-W2Uau#Qf_h!_P+lbH~9Dc6qlUPLMeYs zFupoU*n-a{)g6?I_JiZ*hUU#y-S8RpY;yhcP;E}oKTy}dTPc=IvmScEbV09PfhJ)a zoTNzk`-tQ{%so!tgDlaFiX3L}zD{m%4vtoKs1Gq1^WHm{fOz^+&4^MqQp)-CyiodA zvtm5GFR?J->+kWpL3sogPapj*g2#csn0(~$@f$wOd&1{n^uUD3XAt>x zW3iEs&+z$3VBz!jKf&jI#HJ2;?+roLV@CAl9cmB8r{bE}8TqfVle}=fFla$MRsVw4 znHT=OkK|o-`r~`EBf0At3`mN<3&p|AejeeO=|cXS1Z*VVVZU%GbP<7By-Eu0iZR6H zURGP*X_x=#f~NH3S*D%;@@<5FRl0o6gq1!^QV<3f0Rj>{CE_`f$*1|1L0}^a0yz~ zY^pred%^{f9``>nGteY~uTFw*U|d)TsdE~X4j&Acf{A3+Nid(Jxi)pPxWYD7D+0-e zuEC%dL{U`+b#4^(qB!j~HPJ!sR;Pj^Q|1VuWO;2+qtKDzE={gG)FFoCK;26pT4GZs zjQ2NO{(~#^E%#sJ5~>L!t3gGwfq z&X0+2i@fSel60CMk%k_Hlho}=Os+owzRJ|cx3bHAurJ-)tKi(Q&#CL@f9S7m({ShVpr)nD&MTq?ufy%O6y*w4#Ecj*7-6L z{~!$G?1z|wj(?b_6aTRORaZ_tlztfe%hK4xVqwHTsE0oLk-$3sZGjWM0wB`t`CLdog$^Hkf1xYH=zil35HTLD z#C#ZUQ#lCEfv)Hz9u1TUNjxfrSd2$spt}{dVMIJPbFKvc$8iX>R)f76+Uv7z~YM&-hhvc1w-yX&Yy-5c|8;#&0F%I zohJ?V2iaG0DpqkamfZ{eu^{x>?6;VMQ-<=-q~rz`r?e|Y(dh!TKyILRLxf|N)I|CP|6#W34)Q!Rxd^V}2pj6C%SOHRsUX0HuMg6`= z8M>H*=_&rA!!%dRIIf6j8F~b!DkXSlWoV|ckxAw=#P@0;DC(uw`AzER7yCD`CMxdOlfl1KwIeR4d ze4P>KL^BO4Gm7#U)JYBs_ve9Pv>PB}ZBqy7rq)(j`5V+hXm5SjaOr0H|68t78B7(6 zY*X($sNL$#SG6oHK$&v}yIwHQ6q@^6UCjNh0eWcq-q6=E^`3-7=?`MER8Cum=y0?*8=y7m?%c(P)2x z<+YBoK`v%fwp5^r65(81?{auw&A7j{vENF|JJIxIbq+v8J-xASQx{^Uit&s>^_J@f zm5yudf%XPWq0qG0%|UZiMZ-$ zdbpO00sdM#YpB}^h_AorK>IUP$IgNFM2;Wqy=A!@+UeWl&y1$}zE%jFlo$VCNz%Pe z0;S3TjKC%LwNAumIncfi7H|%=a0cN}x)?gCB;{ z_ruq;5C_-bqT}GD7)O0YK8&TGK~OMaG@Op%7~IC9&7khakVFlMqJ|o(eo@q629?M` z^%m&AFN;*_TQuphcw_E+ScksVD%Wq+KMd91L4}TH7Zr1!7#sf*o%kmm#9M}L#&miT z4yAv9Nm|N$5^N;?Va8PE=fYNQo&9U0mamW`9pfKDN+WU2?-HKy^zF#lgT(e4;m++ms;6G+Sf$d z>yH!6whS@ujo%;%E zz$6lVj*LesLJ%Ep#c(s{rP#8nN_U4ZC)bytd$g>=7M*3)a!ep5TQp1NF^a8*%Ve#b zkYu<@eLh17B85||iR;fntB|b{GE9|2;du}xOG|`Yw?0Cn$ZXX%PJh0Is0?IaFe<&IJ%!&080&PKBg9)0 zg}S|sg!Ow8+XJXtoWxcRZ6UGkzSs@z^i5qFO>9qsld8Z!Cb3Ner78gIB({8fmc+JK zR+4^TV=~7JNMiekc-l64T7O0pE3t8BALmXj>bHm=gr`VJO`|DYj8Bk-QLER5SwHtl zGBd`-BPIM2H0%DL6FY7JfsP$l<5Nz{1eW}+@TX3{D8CG#Z2mk)j+FFw$^oPy#`7Cz z>;A}}2fzg*`4agv6H-QC`)=V?6EQ}(3;v0oKOnuG=s`X#hK|AkkzLO(G`0`%xx^2n zAfd5ci5NpfH<1)6@LBNEIZ8baH(;jA3>bKni5utB{QMZIfKF8~#t8{_nE?+1FKk8!divD(#MjD^5@+k}{W zcn`5~_VXb>1M54&Q3C5L>+~$oB1y-5I8*im|AA*l_5(M`VB1*FJk$)9mlF=94~k`( zCR8md{DNj#2-qaUv%xaDAGjG}b3c&D4#B?PF6v}IFhcY$`++53`5XIzvoYeY?FWt{ z$9DUHE|}qO?FZbh_s|)C`-a;HtxBZ!H(Y=AU6! zgv}rV>F)`f-%HJSc{5^%I)&p0dpFle*!(Xp&VFDSIH?T$V?6qBP^v+Iov?WrK6ls; z^b>g{Y~C)uw2fi&6S}$;Hviw*56sX)a{ZKXf)fdc(rZ!ISS9SY@N@dW{m*gw8`V*u zGVAA0$lHO2olcSVwmSZ;(ej-|lDP2?c8bP7 z8BAC{1mmd735U|3KP`r3nouGBVP<4m2-t~#U}?oah%NDt9T5MjI*Wgh8}g${Q%k_o zj(<|7;lMvlif~EmC>gEiZv0cF0{=vOLZtqYc7ID2aC+6a7^#;ERf`&Kq<&D$E{bY; z20q3|mZUz2+&;MME~!HAZdZlAZNz*DcvIB!Ooo3bokfAV8|_XEeuGF@=Tc~bG5Ag) zvd&~42O>8(4^Lz)V+`i~B95s~T{a76Q%ARIMe+Q%`RUl=cMJ7wqJAHYAQd`JkI{q5 z{a9_o1g%FHn>0O!O0MUrkpz>#$*EPj#_KK~cv$C2$- zxaDUGE%kDW99|CRVG1<9>Wt_(x&Be+l*Re(=snJ&gKz6r_s4BG-PxaU112jB?SVAy;Z_ zJi1G-40Vo?>n*@Wu1!xsu04Cr^KYY&Px_!S`~d`Vo_`CC-AMe;P!(6M^~&!!fD640ZPTSz!2)MhRl!Nc!I+=1^csUB2!BFDg2bP%lc z_aLqVsq@8YerfC=n3{LWf>_j|X?zhq*!LvJE<67n>Szq(d_6s}7GF=-?`X)w`oLGV z_wMnhdV^E37s%^xz7T`=sf2oebt;XYen$o`V<(;h9~cSYRG-H=T3$-)8z5@YM2j`i zVEEBm5W3Vik43D$5g$3j=OJEH!{+<0czy!km2AXv(64q_{uN)C=MAh|43z4DE|?j; z{|Kt$zqD}Z-qr9j;Kar|)H{?1E_5Y``7}J!4U5F{SF`gs>Phg&yJn7^??%fuwmc3~ z;1r8T`q2G1Y8>?wN`DScViLzr4md{0aQ||La%;Ejs$E;qDpHRcC2BXl;=M*yAn3LnRj+s3C;=s*LHfmK)O z@$eQsYgm{ve{8gRBO0Aqqr*yem;-6N!FBTaX=nkn-&X3Tn>iG##Uq5mQG_~`Yb6+x zljqi}bD3pHth!{O>6&;I{GG5qv`b8#!hrIE9cuo|Kb1|sZ7vvFIw=1fr??I{F0NT>i zH=L@`(-YD|zVZz@jX!bz9D4%BZm*|<9**j%M0A#3FgM1ZW=l+n)zeorO?!Wu0e3Ze z`cPb4{As-?NA%QP++l~>_mI|8cL)nTtr#Aor`4ik(bEt3XzS^pG7-_!xtu8UG!-Oj z9eIS-rD*RU`tP7rf0OQ!b=ShF8a)N2$HS?TARIk${?rrWQF}e@d@!n~(?nS8DrzfdL?N7Ieazsxb14}vH1yB0Z$Fx8wy=qvDo>mg8*WK&* zXzS@=nTY6V7$*va3;~I{0slZxsZl-s6_n~y=^oM3oiLB1ry}X`a9)g_IDg9bBO2T5 z>7@tI*{r)iaiCy&fiFf+DV(#Wh{UJc#q-+fX+OBD(bJXGqt??!5*$TOPm4S3P>+Bo z_4G6?fQRzaV)Qgyd{O-AUVOCm)F2ZPJ@w>7p{Fh&Q48=7^pqFX(^62Xv!#1PPmAah z#-GMWkB2K`^u+m7Pj8^Hy`FBpKcWTowdgE;VsVU~l;|YZpZwx^?ew$_CN_F1W*@Dm z9C0Gi(^bGyjuqfZJzYf$gwiLb#^@=7SnW^C@X^-OESZSt=~EfDO})%l;Pfq8Dct>NX|JT3Rp@D)=@n5}`qZKrC2bIe#42fu zxLrFXt%ZG!l1^tIt)zkCL87EmU@1o-cv4BFbh%La2)q;3%J>HptCchpA8jRNz#UAo zTPMS|si&ZL(Rea)D7wxvJIv8JSj$)LSlnbbEdt5!W)xPlOR5;>b`7SzL90A^>uNn zJ$I`;qJeE{JBV6a1=*%P1G4oK)JJ4E5<0{?3_dq)Eo^()v<--DdysASo3?#WLbM<6 z7pNfH1E&3BwtvyOU5_j6^U)qIL3A-B&ynQQ){itvqdJrA6Qb?6#SGD?PGI|S(e|b7 z+Iz9Rd$j#L(+*>U1;z&){t_;XEi6tYxgT=g52dcA({a}$FJUUgNVuQXZG8dvSDkLC z^!^~y|4sCW_P^*}-GBM-?tdp1NA!IWZ$a_;nV(ZIQe+>T{@4)i9wP6H7>&ku?~90h z|Mx#~nnd|zAiUmbW?=g5fk`*FcvfRu;ZkFv4LOqXG$z+i!d62z3op77(RP$>gBK^) z>u(Qw8goP4K0&a}3H%G@dzNHtxj%Vk zryKf2j$X^r17CWJwlI(-yo-_5R~RN(b8}>Pz17;L20Fw056AF)tz67|6|CoRBD~uW zFu|K!JI&tao!ANQO7ixs#s;}z0Hkfb5j)c4!O-M=AP(Qnuo)V=Zx9eS67dia`gs$1 zU*Phu_CS;M&ECLM8R+c|+>j}kkXL5jkSCYWOkDiOB@b?xjStC#LzQxwUYk64R%7yD zUsLkn1*?+>*EA;&Ube*>@}%U3Lj6IK6WD{(keGS=gfEfmH{^Ij4XL1Mk+;(%L5h}! zM8MEJ9IYV*AH6|o1H{2NEDqjUu{2oQ|YiZzs5q~IQE*WDoHt*MRvN{9j5LX54p z5GKo9{#PV}6mZk-z6yFoKmVb*f!Rqd?8ewe?MQ6nn`5}yfAV+{Zx7U{Jd#rz__-A? zV$5Xw^=MZoqM`NA(H*^#JwGxhh^2 z<;4Nrb_9q2oaY9wGn2fbn(bb^d=xJtRo-BV>f`uZ%}LhG-uRoISx$?K%LZPkUzHY> zFE|NSOAjLQV+K>;fq|FQARc!$G;2-xS4Vo8c|LR;i1`M#OolJ4oz}ae<5}@-khku1 z7rrnYTDD!1wQ8a?bxV_6{@&gYUc7<^wLfverTz6G&ZV?qOSaYq-oC1_^EB2?U09R* z7J-On>l2yWpz~;}TGC-QiCWIB>So$E=-JvCo!DnaPM}S{Bo?9Td++kER&j*jWo~ba zrwJcnArDc!t~S>-a+Q}7ZN7`CcA{Hj@G_#>F*w8G>YWsvf@7sAn5w4vX*J3O zu8i>m>FyYD{J=r{kQ*o-2!7-71x$hVdIRGJ!c)c%Odb09nf!uQPJO!e{ z<2l9Lz%DDH^ZD2sNc``H=B(uFU&cENqdFUdWGV0 zUCFex+>w_xeTOMPe~oNbKR^(PzR3-I9t8Sn2B${W86;{Z5%xG(=8Lf!)kt`NkOy8$ zuK$K@b;~xp{Dn;%>rTY2F9q|01smWH%R}#fgQ9J6bL$dhbb*I_Vg1W z%IN=E>I%Px6|McerWyU!hfN&bv&vfp2?L&{@L(Z;cPv|@lA%CoHYYIAP1@}M<*9VU z3(HS)sC0A3{2Iva37j0hN=6y)a%mf;YIz=oDY5=m?Xe}|6PdV+(d-RfjCa4v+*J3! zm?0e5Tz%C~^qdz>JGcYRJl-R|kP8WHp7Z^}o16_qbloPG7TaSh& zD&bh+3#iY~*cKuRfFSFf;AQ<=?~c?jSj%C9>K#$}@~>uMooTH%G<|~?&Ecom z8%#VFGjKto&3L_OOT#MDf{&}6j}1_N!x{tOm1;fjunqEW8ezoJa<;cYx zXA}9Y#myiW0*U@V-Cd;S4;v%MFYeNS#i*Ror1V+?#Z< z9&w)-dYw#?u}_?0oZ|)vB$&yh&Bfl~`-{5Z56KPdiCw;tYPFoBF&LsWaE*1$Cirp) zlDu{ezAriI8jX>>^AzV!5%1!}@DeljFA`mtDTeReM_;G~N2-)!s*NDFT;>KCB|Hi) zW5tmKxKWJ1oPu_Ubl8#bmnWgr*0A~o{i4Y@_Wq0GJ%2|TlIP_!gkay2Wx{k8CN8ik zMY7xmrbCe~)m$@p&0Kj=CU9Pj^K3EKt-PwOunh#o!?)UnlIy<)nkL8E=Js4YO^SeL zi#OQq(0n)aT7yF7TUqJ8tt@9eFqQ;-|7pQVsPfap10h6c>`AZ!BIJtiE#1r7z7iZz zsN_Z0HcNp_=(iegP|tQVj3JnGlAy2`&U%*0ki!ZZZr)9in5?@N9ztLA9D?MWRkyv1y8RZXcRjyUsFl0( z7%&cv-2xp$xr4v6lpFqw_$u-gt#F*S!hM?11wtq%vIr>Msn7-u(olhZl1=r#SNFeG zGn%XWH-Bq0N=F9>G5Iif(3hBF_#GhZ_YrrfC-b<#+SQZK-zK;eU1O$5jk!wW`fD8A z0d?m+y02T~U{v55i3=_rq^r*F-~~uj+Wmt|Q#JNOjn#`GxHLm!H)*Ua4UFK`iDxyi zmLFtMj9;l&ryVNh->Q_z@oV*}E>?2_|1rtnX1Y`GvWyP(X{RZ;zb$RuQa)gEZx?1> zd3!9}tr-rL!o#PXJhFQBX5%vcIYHU}!4a-Iimn24UBWtHHzHWX3(`J7GHyl!8H_Qb zS@^Fvnk;-VoQrO4668hJlwF4B8W=+Xpr%ndX~&1P>Pdr)ow#bb-gW7G&{4;r^A zF%_#vUe5IzM#B=o6!`vKAUPX(KAKM$ws>m6#-;vtz1&A`xRktu)q@~bBPxtqwctA4 z&>Iae9!rsezFNq@u1x@4>Na$h)r(V!Hxto)&4ip>&*-841z9Z~_e}g`ZSoAn2?bv8 zzov5N{Hi(WMMZ#;ylV=|D~f&deN})`yldw8sw%1rX3hlEA4##B`W7=plw5fTM#b#L zK@`Z;Bo)SP^}UE((+@fT3ikzft0p~*`Wx8+w}^JDOQF=Lhw&Mf4`D1P*z5;7o)hjt zKL#BJgB}9Fp@lCOx#6Ypfjy`ckJ^IAuNtO8 zMfG@LI#>C-7|~OYw+G9EOu?F34uN;DE^Aa{;9S^L@K1s)L$&mydY|6LmgU!C!~Ow- z!}S}qi`0Mgi*qi96wvI&fjC4|H$$%QOK3v=LSlc8!7^-~+eY_Dx!4GNboS~KGBR;? zEPU@pRB@3%iMW{vqcj&X-2!Af zSx@Q~C<|d-*NP#;(O`amL~A4wNk{#`1Nqh2IPtp^WdoDEk$n@65j}{#NMSIYTRn&Q znDC!TkH>mp6Ls&N`ba$vT;bq|y(Wv9FrLV_mexomLRxiX z2^!%reIR-s7EwfG=Nm$4ZnS}N(4<}zf;%E>^ghf{R|~Tv5$Yr45yYnt50{)az150P z;d6e9)L)vOp)9>SNW+7riFO>ju`k@`d^lD3aS^^&42AU)iHvt*$r@XHx))jx`VhM= z8JM6-8fgp(Ua45T3|`ksJj+f+@N&DtIl^YV=q_+W8NL3`=o6HW;TyyV!cYAK9>EN? zk!~CsyM(g}Y=Zju{$Rvhd94c?`cc?Nxo}J#?M}pBh~VQ#p!lH=5FsLzFt6uyL`7`y zv%!Z3UE(Z*6Mv^(yvot*6um!6)=FK33kn6-PFtxzpfh8`6_^L22ZCr5e9((1;@Alr zDlF&lGr~m&hY++9buM)Tmx{QgKgB7N;96n6%>`2!MoC{qmsb2OA}zml-jt-?gp#7? z*$E)j2Yhoe52xP7`;QN%4kPE;7ostGo*ml%DXL}q+OwxmpB_N=`66rD?w#xZdt{bQ zwu4_q^_)`oQa5kWUUeC|LfqtfzD6Re?&mJv!20B?mTR@%4JDN{CO>^}R^3;49o+gv zZ{3Ej%{#l)eR_KG(|!7_JnQG=r}KXqpZs+8zV)9bW;LtCx=&L*$xkl?$cA-)9eFH8%Cu7x>ws}D?JULU%C{`;n#;ikO<#DtvnD|Fbup` zw<8r@5-vRz{S%sZCid8?Mf=mrvl55`M{vW4Ky>kj&Pv>r)pac1G={pBf9y!t*BAs8 zr=iQ*v6y%3JC2?MuiB(AUd=&NyGN-&h+gJV;aB09&iSaWWT0C8XR*}vP;DqNGqkuX z^qaG1eOs5hmIS`Rw-y%hvm z$xn|sFtc_aG8QXvZ}JQI2}0Hz(D>vR68mMh_NH_Y;a%pmK}e9#?y6 zKM;JR36^%PYa>A$IK3(a?`7AXdLRg%2jmI7wEoL3Fn40s`n`#{p>q<(_josRWm;Ap z3V)7#an}0ni5NXMbXJ!an3WeD;4S(tEBS>HY3uiO8Q)_QwpR(78f?x7r8jg@*Q_w zbztoBx$rQHSUW?JPo@Az18xo)11`hp(a;?|ANm7-Z|fnN6XEemE~U=@-WL7k_x-)C z3WOf}?`;(j?&R-n;ruEm@T0us+-!>LzQTFg01A*B!m)GY?}G86!#1^_cr4lizGi4( zbL20AWuaB>Dyz@0)bsd?q@n4}dehj3zi_hAd47;JF3wXI^;0cZL#{_eUx1HS&j5xJ zTGyNN9!R%O|Me{_3;B~}M`+QkKUp?e|1q*M@}=0$A0!K!KUQ`cVzJy@Q#nSovqUuR zw0DbKT*S^_EJGauxrS1%$lohFQXOgJvQ%itTW_%24ddMKlVAONMgz3+Rn0CKLZq?WTo^b zRi&Si=!2<8ANBU1Z+-vKX3F=WysSOpXspUGZ;Igo)b9N-X?*{sH!ovX9pF5vTz)yE zIht0*JLouv@G0zo=T=$#hKB$^O+itv$7n1c4}-YTCGPmA<(%>K|5ps~`}L0PBd9HakNL1FYiMfYQkd;JxERR4Fwj*k9U zp!kCR7ws?l9|SY#_Yr*E0BP=)1@RmD?*snS|LqXz59$91WHj-A3_$(M-I5sp=l2ZY z`|yA4cVrE`&07cO;vU=w{weAK7%tWZGl8+!z?*T`K&Fcesuva%4pBa+c>?#3LRb$o zFo0PPr>=koCUQVyk1_ZhV~^3GF!p#6b1>^65!(H|>j4X(8!AN@;K!a~fcttm23SxJ z_D4addd++d+lT+d9OyKk{_+`wE}Y%}pZY zp@#E)g%7A$#$frr!m=@L`+x0=8u10;dvHqq4a<6CyKwRI}|V9S14Z2(aiT1 zZqh`XHPMnJ5XtuyP6v_62Yv8S{2%kM^{wl7+}Ga1O2w_pAim6dlUmMspAQ({yXeh% z=r@StPqz+Z-kSu zy8kG`crZW~nTXMk#$i2x7U!Wwe!=g~OWAX`+I<wlccB=*| zHq-9#)5b(n0@mtTXW$Uv5cdoYjYz=U@yqLP&6ai7Vf( zf{Dq?Djr%!G4XvLOqu7K`;#u1K31lV?~98QIbT|7QzB3BsU(gb>ia0BAGs%Db~QLZ z!ee06$PQINS)k8}n7DeJ77e9)VnsinSo3$i8u1yT=S4;T3;kz_khG|y+KK+{C0g_x zXp*9zMY>@6&QoYLocFd9{cVheyO~Dx|9lU~IRfiM^m`}^M8A@YY&Q*vLwS@Nme%hQ zvudsX6Q3b^WmNRfpiuRKkhG{0jAmNi9W zQx=H+7M=f8jvPw=3>n%I{Y%k}7JUH8qwfVjfpTN(3#;JoLE>u5ed$sT-KO4!{FM7+ zjuT9OFI}trP0ATrC3rsx#)_(Z`FDVRMdfJ}1acojx$E&yZt&Rjk$miSQ}nUh{h^wU zkKOK8iJ*5LyUl=E|k6&+0dH%PAWGjp(66w?YlCsZ`5DdwtOR_iP?E@Qz^j< z@7ocpY*VEemT&2kzav%#Bp4Zr5oqY1pveG$2adSyzJh`aI<$Ttb0s-$n6)dPIt|{|X4=pb&=Wl^lX8{E~ zc^*io`Yx&|t@2f4^3{-`w8-bK_E(jb&vn;Sm7a*(Ab#ImUzNM0tZ*)9%8Nl)1WnE< zESm2wsVOg_KFQG<$5P^n?utrM6qdP*=AoOfd~RfX4%TrfE#FC}<$!S&`b{YHl@(`K z)X-(zw66KFn7B);-Q^W9rM^SshtSpj!tx^DugT?~=fe%2>Y6g%2Exr9!ZC)P>Z`7- zD6a;#1d_zIX#-o6tAXy^<%J7C-RZ32=_f9^tfGv8G)=&V@h2tJ=|ZvPLwe{uiF^FD-IU8{(c^SU!666p5A$Hls&t zFCDZnWAx};M82|9`AHL;HrRdMqEi1n_cZrdw-e~Hb>N$25ARx7QCi$_XflX1a7=HP z%g7gJ7=-R@6HNw*Te~SEBf5hgkDIfW;3u}1<+S4lx8oQKE-bC`*C70KF2MA1qzxpG z_&>kif9h}acDbDX9jtR{)Kn1Q*y=&YRu6U|VVyjr+BLVjx}bDHWkr?0fXi6J$PES6 zzM=vrKM7H}MDG|}acOmBS>cjs&l;VMNYAh@qZJmJj#XF%F(WyM!lEKyWh}=9^O3t3 zR3Z@T1j_U(o%zrMWT;$HP*hY{G>?IoW74j-rgiSzlXq^yJGb7QJM_+d zcfT=FwZEduSHRJWAZfMaPo(8iWOj|#YqtQBRMy} z-}H~m-?TgY+kXGgX&^m)MEb~6GDeLabLv>r(Us7pYht(V`z7`0*=zsa2PCH)c+kOp z`u?e3|3fsvfI|;E{D>pnM;(34z+;a)e$e0{C!BcF$wO1qh7FhYtZ~`nJrgE+bIv$3 zchcl3d1p<{pEmvM88gp0w{T8Tv9DzAywVHjmn|r-sJy7E+F!G9(c&c+v$K}tgrSi# z$wUv-VLETRoFwG(BkuY9;>adl`HHh)JesAjtUB9x46V`er}K6DhvU!xT73Nfo7V*l()~mEy zM7?d%Yw>|vXpy3}mR6-$AB``dwrZ>vt*^QN+I#IYXU?1h;_bcn`|ij2zL~Ypzt>)S z@3q%n`!RFQE+2}=H-jDl-3Qu?Rn#cxKG4a?uNkYvTF|#ZH`6^h$f1C;C&wgYMgjc+j^%CzIapLp?z=A4Iw69&`k>7F1y2-2qw%x)!to^dRUWx_=ly zxPiX)E9eFE$giP4(9MrPF7_Js{T6aT%O6Glper7a$G6e_LC6QKeFA#Kc1rUI$_cs+ zv>9~rbI>E`k>^of(6uk19YLqR2)StYeV}VWryqj;Kx;ww6Mh)-XeaMaC@1K_myj=L z$6vq)O6Sh+C;Vm93wA>1yazy!fHs2Ch2I6_l{PeAq~V~#f6B?o+<+fMrUJ$PBt&3o zJl+G{im~}MV<(@Jm%Ti5mH6UEKKJR;si#vy;;F`G#Xvkhj)2Os`NQcox&BHB!Y#$O z;Y0Cga*nSuYZ(_3y-dc@aU;aTrp=c`@qPhT_!vTC4cT*Q9|J_o`79Rg&2 z;ICfqS%<%r_|h-5a4Y^7z*devli)wc!rzp_KLPdM4E~!;`BwfY@z<-;C_Pn!e=_>w zQj;I$2~&AcoC;!}lRXu2UEo`E96qYwzk+WY_!8wkcK!B%KNEfa>ZJTvd(x{Z@2cz? zB9*Gd)E;kuf8WLN_$N&MujIBGpzZNUK&+Fb-oeusmI}?cAzV5sIgx5yo~SprWcBT(*2M0LOLFS zoNiF>SK*+vt*g4KY`I;DKY~voe7oc~j?cda{EIYy)$#eM-)+(SXB?mZ1@Mn({_NxP zQ@<<3SR~8;DjfDP>RSfc)bAF7{}wOw^QeWt<~yD%yz71Etn;tV@a*+a>#+Nf_V@<) z4`QsUg$y$fv?JY;9w+b^b{he@4Atb1=C1R>AI&F$a})lk8vL6v#_e|Dm;IqZ@t+Nz zcTw(gjDZ`e+{2b~*Q#=_^VhDg)7N1vk)^%rcezlu)lz0ECsx2m?M zUZ$^B*~|2oAbst+c>FYssa_fwbsg(;{>XlSlSh)0%k=kB|GO$4{}j5Kx7yOKPU(00 zNKlxwm+9X{`pMtJbernG(URV={x8Y`u)0HmwzOaDu0e|4Nc_4|I5d*5yBe`{&HoS*BjMIjMK_IDcD zC*tX;81JA(zQqRbrb?mjQ$MID{@dg6KY-QSY~`o+Y+CP={owm!I0;gyars@8W7Ylf zIG&eE=m7m-0YpXA^UQis`Y$8C0`e!A@fb(Ao)mux z$Ghc!?QzoI%ki}&U$>#9A3ufo9_0TM=+TTf+qe$Cp)iefLbgSE&p}rh{TY4*u=3Zd zaojUivg&Rm`OgM_V0S!z$eKU<=5H&(ONo&2PX$jG$p`<(Z%-d!=Hz({L&V~>wML4h%c#Hrr$zTd0MLPmyxa! zbLK2-xv0KRCf9cj_{x8Uxh(9_EKgGTA2J1#-P{3wdEgVmCcmZKA47aC=HNY)ue3|p z?HoBj@Qjre3um{JMD!ohH@N^hb8ok`oT?o?EzI9X{AftxF9ZMd10Q_8+6Mm3;J*%O z&GJ@L-wdz!LE+@>+ekk2E!!XbnZJ+6H(B{-U*VafC&Y3y319&rC(yn?-HbIev;GO`@z!5`eRMD{VDVt zWUK57e!Cg~#Or@Y@tNEc~#&y4BwFHMw&Y{TH(b9h3yY#py_zZZq)kHj$+X~enPOx5WQ6ZZ z5518oUP#6l;7w zgxC3ez&H7j{`)@PZ!*PGzR%zd2L2!hrl0$7N6I@%_CuNYpViwGTA!t|`bOF`F%8>@hr=aT^AWHQAwG=ZIfsUnsmvU7x zzRAV7e5{C#pcqf2PgpZnyqw+~&lL}NijWBkfbcsWAMne(NVP#0<6$bs+ujnC|8^f{ z>s$Px8*;^AD#qH3(0e)J`Ha_4jK{J=8*;@RIpt6aWqBQa-9}%s7;jVP-^St#+P|F3 zf_;nF-%*w$>7jqm6F>1le` zmHAK)O0!(q!lo>7(PxFYF)cKjDV|UJ8!~;)GvVzlan#fNw=D69x9B%n;$5!~VORw4 zE65hE@%iq}5|5EBto8?2XNi0Kw;<&U8KIlA#7&tKkQW)lm1GPz($}3?$aR!$qfcf1 zYOXdzG{b9YZ$iKkPY5P(o$o5tU}wez*vD@&n&A^}$}GA&S3I8SLm0*k{4mM?YbF`b zkFrpVr?P@DldH!34k<6qEfV7QqLezCAs3Fk9U1 zxfJEz<)qY#I(k>c;!(ERn(J8q}12k7fyj(&t+LN4o?*KWexoS-(!jpeq~I--ihM!Y#+i`W)shkvS;j>2y-90 z6W=*S2yeRC$63^qgGj5zH){hDO@5_n{RR+TJPgu#KX{o$nBamA3~3(sf-uMmYsyrqrT;5S>iv_)}$ePXZq0X zS>g`Q7ZCodXXu73@v4`?Kk^O1HQeI=9KtX9hc3?&&t=pgd~4=szL}*4ly6XXK6#zg zz)209)WAs%oYcTc4V=`#Ne!ITz)209)WAs%xN2Z~gNj-;Pth$*_cQI`cvk`c&myqu zl~>lOit77`w);=p?q}KV=h*Jg=X-4Z%4;RxV~by2&DDxx%UNDuen?Sf6T99ilmOn* zCa*%KA7MJe@w9JE7wwVL^|$xqF`}bf5xq(dOe9nY{G=+cMcBip3tQUqdXY0$yW#l# zhjIFeOkGnX!A_C9HgH9-+a@pUhRbUb(|y==piARxaU=>|x||hUF#3ssE}h@|aaI1! zI2wd5{E95=qsu+Y_Y(su{_lLRs)-YYjw4Lc7(_yBYm~LgdgXvzT2bdmWdX%ZZhVy4SjcJH!4bz28+nEkB z9cH?T=~kvYnC@kIfaxKoN16KPaQ;lEF%2=TVY-lMJJUg?!%R0Z-O6+a)4fa&Fg?Wd zC{uqe=g)K+(-6}drVE+2GaY0)%ybjetxR_?-OKa<(?d*;GWFMS{!FJa4Kb}@x{zr* z(?O=gOgAyz%5(?Qy-W`3K;)IXQ=XF82(h-nSeg-qL-4l*5Px{2vlraPGKWqN?=A*M%}`s+D=rqh^)nAR{| z$h4j5Ak$%{o0x88x`XLnrU#fFVybdY{a)l%<4kIdLiBj5)g2{_c#)h~+W z6C1_y(a_>{+#oJSPpydJXou0>i|2HVjy9y#cM#gzYD8DG(ql9zXjfFpFj{(hTUH7w zLx(SFMM4rrIYX{2Wy`Y8RtSk9Z+sQYLZ}QE_w|Y5*4VOTc!a{P$Pal>^O_8N^n79; z&sQ{^YLn}=-52BjD8_!BUe9+l?cxYMf626^FUNg0K03Xg4{5qz{@EJ8^D~c5ujeTh zz)7}Fujf~q>iHB{BAYulY1xfb=w1()W74r0FQHKwiUH@*Rv8LDaJx%rekkXIA$DV!#FsdSzjV?VO)>O}P zRjkTOhl%##V@*$IyVIqq{7=1t3_tx~=4k!jq>Dd?SWzT;LBCY8IPbh9p zr`jB?Za*#a7F+trVHKn4Eb82ri}JEw_u_`K(DtR*JG#gBTq^Fz$8epo^f69gvFI}3Fd)Il( z2>yDF^B<=f8Moa^Ikqk)IoHw~K5*mrezP<+A5* ziAo82P&z%1S|dI1HhO$a#yvuhd&#(0=2UrfgHh4y#J_&9U_CK(?u zw4X}GPZ8SxB;(j!(SF4e;SmKw`wI&Udzy&;UucD7*du6HW{Lwo8SU3q?lUKYJxAIY#_O;S6!zw&i#mHyR5d3GxcQO7Q6)k8yCjQ1o1!#N=<0FjUq@u+x z#y6a&fTfH-%ea`IjMFJnB)^AoE&p`jX(;WM{ffVhmX zoALR;Nk5CYU3mLYT+94=|9Twr|3van7OU8vD;VF&{Cb~T>+=BcW7+M7dz1iew=c1r zz)po<$MP@qse0{aT>hsVaoVm{J+2trnE&U@AF|nlwyRY;j$&T}m10-GFd zSB0Ff-L3@7(R$E&9(ha&)_R`d=X$Yx&EE{%NpG#d(?qHt>tQ*ffeX&$GR6Zod^6+r z-ywc1J_bpAT;Oyo^1#qoHu976Q z4jm8viXSReK68ZNdWl;(RrqEX{27+h!vh^XTS(WLm`FP1Tjzp*#Rb321>XsLyvi!+ z`w4NtFr*eurRerUKhyjW7jfLP@49TC*_F2ktKX8%1$A$lC z#(P*l+7BFMeEaoEu-4n8Jm-4N0Z#V6=mEw52`V+m;;{eS zihB+Bqw~>-PVz66c(&Lzr1V!9pyPIg;iv)iX!L~{%Qf^J&fyiX$S69 z{_ncrBT`Os8R_n*3;&c;RC)HZ{lHVmD*)Un--zUACJSkI;ok||Y5aQBMb2S~!=GQE zgx|vU;77pRvwE zj$kctr}8gy!Jl@)GqGRlRL}Y9Q|&aD!6?2 z0)iPIb1r9*3ts1fe?{WZ{}v@*`|U2^WG8Rg)`=H0|CSpR{~<-h6^s}DhXUj~91y%! z;>=_rk4X6zfP?S2@aLo9ob2th5{I+?XC*+-d#iyv>HlIEe5VWks0%)}&{_U@F8D^^ z)E`G|{c(p2{{i4m^?lm~pEyPJqtOLIUWOu~7`T%j=DOf3fji~9UgGeFJU^#r|LJM>)>sS5KOFi+9*zo+h4JCu+B>{VUU3Yt|uAwPt%vjjcH4qJl z!w^^>EH{$g+fA=WZw#Fu>&5%fDZV6-9IxJrY~`>^pmHR|&q|gc-^uRG&?H|RoyuUA zQ8C!csI(FcB;E)dEU~@=nKcp&S;1=jTS#gnq>_c30tQqPoMjk|^TUzI1xC$+hN?*2 zxebP)6>rU=x+FYU+|$zAUmPq!d};yQBnS5q~Fy_>sJG-*pF!}}-8+9g+^{fT`;_VdY z7Ho?4L$KYo*-O|Yk6J*tZD=Ynl6@PzAY5HZps_awr`W$zi;`Y&Q2IWLGY!r;vHXrH z-R@&k`mV)y1e|=!hwO(5cjT;jtF~Kv`|&#J_V!|oD#kfg^NsqtrU*P;ThwgS{$)mM zSFAhQhj&tQJ0~E+Xp0$3x?+o4x{NlwQygzAA6S8-LzeY)Mf;;|#i3aMz**36j*-9j_+!^5PPhwpz$0e%?;Z^3S1HI5Z+S?oJ6*0W8yqCie zhB4AGif7J{r7`bj!DX9qp}bw!l=HWp>kebm6H{bl@X4iAXugbxd>iA--S25mr(yo zJt8FBdF=PG%lFh{%l-Zky?5>4VkD!CPL}T_3#y(RcSpa zM!8QKx@pSeHk+Yg&N7>6mRX&c`svTFc}Lou@BaQ8A~!Zg!PXQe09zLn_Js zvVRx7q>SsO4bkN%qz;);dv7$V`+ZV-@mw+(XfzKMs*|RYq7Bp!j&x>2th)+F6wn{B z6GM!6_OSwskcQa{D$n z8>Pi%BD$ipKe@#XgSa7tj(o61T^L!IGBjXLZuH>%p#FBFwPR@_0ZCVVnN7I7Cf3^; zMK>n%3)SM-l&&a7z=S%QN)6lwXKKY&_G7SIJkTFS7V`i1Nu6(IQs<)yMMCwuCnOD_ zaws;tp0qXTt@(HjyRDVcX-dJ8c`Zw$T1>c+WawUnYM|ZCdLYd6avI!AX>bo1<+>y= zjLt?APO^X$aY7ndhI3hBt%(Mt?hlPCJ(Sg8 z_0g5^Ajz7b$ptE_?UwB${NB#~C^@%qV{2z)XD1uRtftN-I38r6H!58P^kZ0* zYtgL{Ozq>OP%IQgTW7RH40LyOc3X^(%budzs>BF0lSUJqbd{R5EM96->YS)oN(4KR zGBPHzkAz8BEJD}V)ZmOT4gR*SknkeJFIUdg-Xyg=yaLlpoR1Z5#9R=XqBZr*nwC~f zWmeWjjBt5x6q@Wd`ooccA(YQL#=B{4JP;76ZT|~1^Xxog!@`s zdT6jyE~yE}^F%SCB=ss`)J5i@D0+U3Ng7RDAf$McDDmWj%+5%O(hVPXqajyHN~QJOkqOAJ%gGiVN1Mw^o`Au=<^`I}nQ zrHtZ1>bY`$+JMI?k2xAbhe2!CO?7S7_6e47^XO(!>t47%c~~f_pE8aI%NAhXOQ%-- zgRREwC&2(YcQqW#1w_I>SZ9yqDyg=q+Cu&N%-J7wok*|yvFgQ0&HcY5(9{)Mjtbe_ zp_(8piT10F2V+?jOWh^OgBGhS+O1WV5E~4k-E1P=$^-8qH#(9{oUB$KTt`Q04fMI# zEi#?So-i~=Zr`XL2i)vadbCRP!tzK=EvmsR2WGjfl;v=&tCK-Usn&9mZMc_GJO6Ul zc=CW$gEL2M3QHOiQMeEj{bx;Y$im*t4FwsGVWCC2KB!bz$`4N&T3ER!fY8^fL~f31=SV*D6ok zRY&n9ReNS62IZ9|X78z;BXu6H2R^s07|YVr>Uo;Vur<)oR4E->Vu?a4IPRGkc4yI8 z)q9L_*J5=vVQlT}X~AmRG6grN=XJ+0A4K)BDU;kiP|9UYptrq~tyI-d2%<}e+=Z04#u5?QVOk%zUzJvmsO)M4eB#LD;R z`5Q0PE#0%O&+MM$IphX|-Im(g zToBTIY9yP2jFg&BoVw~%2p9{Lm+EbTAw3T3c@iuGZPVS_gVwQ6&*&6PoK|`qLohBZ z#b!q1T=}y(a@7M$>IBSmq1b0~>e0tq)&v8!(Uu;zQrpr-RW`{t@H&tz$Z>@klFQDh z%j$y*N5)sKtPVR7_}v%_P#o9ow%&3omEI$#4KNx@)ov2z9EoMx+*aC!3XkzGLj^VLk$T0P&QAewGxdf9SQUps?DQLpn8|$KJjnjHeFWb-zTxfGA zmiGb3?rfDzof6Pl>S`Nt0d@}!{H_;v>KAZoK_Q1iIkt4u8PmOkovr#eIrOd6U)l5! P%l;=Z#GwXJZiK~9=Me(vhjN{eyJC#w&!8p zTuG^}qg?}BgQmJy)+VK<4oFE{ol<)=N9xwiHPDqn+Mbv9Oz6`kA@%H(9&0lby5zXe zopV&r{rTATj-%APL=Q4eX`M1_U%gwdHTvwRu<+ujS=PPi%3cro`y#~M6 z;rDv{-iY6u@XMc@@p}t?Z^iE&_`MUqP5AvQe(%9Af9};6*L}FI!tebCegM~p%;!gN zebjvBWi@^u!|&txeGjk&JH^*Q{m!|%c8ZrPK0U)^UXZSvf7$LkrB zZt;$7$v$T8irc=vcIm#u-+JPK0T)iWzW<80w+?#Z9N(QKE0zyG;NzYD_~wAWFSu>^ zd0(#W+q3&gr@l7(vVXh!5Bu}7e{A*MKIxf%HXJ{9MR@*236-zBx#!u?w+Fm3_n|&1 zeLkPp`onF*XWh7R_YI4mS=m-GKPzYR!5=rCwPnwbzD2uQcJ=*uVgDgRavr&q za!%G>_dV&ot8N>9$Ii8V8^&~R+jzp<6}OzS^|;4g$GE3YT6)sn+lDuGJMyVzecyWG z$;T5*-uk@c&TP*=zj|x>mOXcLfBC}KXMA?=+Rv`Nr0}(mj%(A zto-S+eYXww{i*LWFCOyN6Cbwpo$;@WW*&CTZ6%ILjix$Yy21lzj*rD(d4S91tOdIz z1I~SrjWC~|KDcxISU7iQmdYIF5by#*y=9=&dumyp3en8GcTjal)`8RMg?;9u9$=o#~-V9RFl}+8O-=apqeRN6$yZ zi6^JW(evmy{=Y7c9+Kk3&((3}^=X_qd~FlB;6K9-5YsuAJD0yG&ieW*{Gqct;T;Iy8GaY^(3yT#K%Ymudbt{>YZskqJT)xy?d7U`K_mR| z8~!AL{vgoTZq)Gm`r`Tm>x<*eepw@qG5BSOKg7GHX~cMgFE-GL*d{6HgTmFOS%b2R<|$jzUR%=nE)&ese+!;F(+#u={3 zT_ePQdbyhZsu5orJau`HYk$}IuNs8841-@$o|GnyfP2f2!oSo*$`lP_S;@~bqlaBa z500MCmG$1s)oeD7>&?9OA>VO)*9E%2*NjtO_|_I{#5ab)56JJN-?BpE+su5=bnI*R zI{NfTJ>Sc<{Si&y!|;6=bsfj4yjJ6n(HGY|(ND*H*%avcK-VFz?TJSTCCKFGEa>?t zoIEs{bC^_v_sM$i<=WNG?#Fc1^saXFFDQvjUNt}KQ9=0nv8xNKddwJN^KG{ zmt(J!jQ(9_d`EfQT))v$!2MF zxrQSCQ~z78(}?%s2mEO@{#?0A!{x?L#>CNc1<1s&CTn^pNB9ii_Hp%2*q3(9Y`5;_ znfbQY=iE5)(^XI~cR@vYLAAfI%3o06Dkv!}FLf2TsR#jN)ug=LIR^ah?#t-u>B;)_%GI+b1w81 z`G=+EmsKp9==0~4Lu*jOgi>Ewu?PA*ck-Da%kV7L`1G?2%W8a)?rCY>!t&xWUw%eAM<2L_lV^Nu}u)Jf}YG2htUlm07wN{ZVVi!HB8IUAx*bHCc z{OrQAvN?rC^F33~)b_WL;|u+TIrjAPQ(rKQ5ZvumoV;9QZ$-|fK8DD9jV+#_MZS*}q;994}^75>F#d9u8t z^cpW-V=t`iG+9g$5sbT>!o@n*S0%HhpF{{E>sBl3lxY=pc0X+f-%v*q+nqxxkf}y&niJcXdeJE^vHaFRcZO$v^1DtLRH0r z>Hd<8Sn2c5ESe0jPovnHc-oRmpN=&cV3cQZk*|{RGTl>ERZ)d#Suj$E6fB$qGrqAr zW0Rg^#n1nUV5pX>Y~C*24gFt#ZmmQPKig#2)<>Sc$CHc zc#!~=M^AIOKu4*TqVd`2(}R}b1<-wJL57pcp#D;LoIywQNk)<`oY{=>7FK5$*36w} zR-Be%!~{gavWT7G9=04@_h97=;l!&5!UUk<#ic&D5?s|+RaIV5P*#Bi0u;xrk!aoL;EkPFQgHaZ{JKuRdnVZpV2A)`bz zV8m!}&yHNG036m%3V671R;JRgP0|G?lz#EB&K08*NjQ4ODl*-iWujt28 zWrnE;v&u^6mivnHDqvq<6+?QA{5oz&RW&MRZ6K?lF8ZU&ijEe$(pY2t&&SG$k&LBJ z`Tu+{N3eXU7yl839F_*jVkFUvT|y^TT3Wk-rDlq(QYVu~wq70i>S;ySY}&~73_Yd4zSuj4 zicYwgQaoO6vyzk@TJlF=V>3BFiG z(eSc8pIo@0eN>Ar6QQE01RZA>tD}ybq}s_(cWT9s1Ziogvtsiu?b~sFJUQ@J_)+h6 zm|%v3>7-zd&W5><3LU|XB;>-!G!BZQ$G;@YkJ@`q4Ne%0h9mXbDNxmKYALcHe?7gJ zb(b-rqN>P;ac!eRoJhV!br@f|5v;0Wm!4H{Qv41{@As}+7PG zr~rikcf2u7B6L)82ddKYi)u=%d@(&8iKXWp2s&~EilZWE(q$l2WP~7Sc~RvOVP}qC zI6XOPfhPPo_h7-T&m~YI7i1Sqo>nkD-!rvfa@Hh|^eZef0#x~m3otdk%fx&vxuX=W z$SB?^`P0T_<$J~#V7Rk$vOA6zqlF?2@0wpVC%r(_;3!Hkm4#I>hVWZ3AICWhDo2jc zv_(a*6%Gs*`XVs9>tvx(bA5j9IZ$~mz#(AaTyB@4m*SdA-Oe+sb_Bu{Ll^r%Sh2*S zqw5rvRu-07I7d`!wy=o1;TR*8 zi^@5(=&;(HW1fx;W+8NFNE0?+ zVAM{v?^JLds3o;VZ0jV%SliMibUCXJ?^x|d@>C}!5VzGFS2od+V#t%XP?Fzp#E(-Z z6mlQ5BxhQIC!@-TDx@0pew$=4m~EM%=LtgGtkUpZdF2_&t^!{$yI|PKBO;%MTc3xWobJk= zIWucqPC*)^6yljP(QyPrwj*xAu!2cB({vylE+6$RC07@Dnp^{k_{>{{`ZjAfJcHkz zk8lZ2Kao#5ebbixy5o00)5;d7jTGkAu6!b${X-s6oGn3=u8T|GB-FP|yJ7_PqHO$6 z_l}MsP134w*^zq>^yucotwH%=FPAIf|B?T+Oq6Dn+?#W`+(6|Ww*+?zd%7+Mjz0;I zd4_4v1l*^z6nFTNTvr>M|BzBV$+Dm876aD|Al%(`Z=`=0*AUajd-nf$bUvQ2=;3fgh(qr2^S)5IQT&p{wZtxd2#TYwFRD_&Z5?Q_eOtMz92r2pAt z;s0#mU2SfGNYC$~I6p}i9=F~jKPeVIIf8Y$`dj!LExg;pn@1<4b&!R>$)ZoS@NNsA zVc{RJ@R=6=Nel0_@cf>M^OI-cA9Ikn&b08yTlm=)-aJwvt@AAW9Tt71g|D;li!HqK ztPh)OE&Np${Yndeg@tdl@aY!*W(#i~g^<=J3*ThXud?uWS@_i!{#gsZ#=@_*@XZ$f zdJDhV!Urt;77K44<&f5`7CvOrZ@2J^EWEPti!J=kCeARP)LQsv3twsB`{U^j{zP-K zZggAtTQo}k9c1C7nbqY=weUL2>P{IJ9*H9IlWF0jdEJHQqN4KXysNw9S$HR=vt_1* zN1}@S%(n1OzGmY*3y(w+`Kh$~skjvI{@KESZk4MuYKdUXg^Gp>R*I4+z5o(vK*}~(|tH{r03y(*6B0pO!eE$g6 z<=SfDO-h#5?G}E3MXxOUp%#9Zg}>9n@3HWQS$J1MRR4!t_#_Lz&cdfy_#-TQe+z%4 zg?C$c%}F;7vhYV+^r;s97z>|a;RjmyObdUkh4)(c<1Bohg&$<$XIl8d7JjycA7bI> zS@;tye5Hjy(ZVmb@F!XLS_^-&gAPaxGg-^BcnHE07!e?3dObb8G!h0=z zwuR5L@Z&A~Obc(H!Y{V)UJGAq;d3nfN(+C6g>SU*XIl81 zE&S~kzRAMpTKH8K-fU5%b+v_`Y|*c=@KY>&vxU#I@S83CSr&eag`aBSw_5mo3%}jM zKWyQZg>SU*yDa=P3%|$0Pq*-{u2KI#+rlSV_!$;H#lp|D@ck|PITqe+;m@`3gDm`c z7CzO&KV#uDEd2QvKGVX_vhZFDe}RS1v+ye{{7eh~Hw!=8!WUThc@}=Qg|D>mg%*CX zg`Z>LYc2eh7Jj9LFS78B7QWcR-)!N17QV^Cmst2!7JjaUUv1&%S@<;;zSP1uTlfnt z{ALS3-@O_!NEgpY0Me}2yGYCEwTvd@$kF0)I-FTZeFy!0!|0mLc3I@Y{s{M7UPqR|#{A5Uv#X zCBobqgl7x9mN2&j;XHvKCp>^~roaynK9q2(z;_d7i63?gd@JF@38x5rEn$}KVVA&H z5N639-t`OT|7XH(!rKMDm@tz>c#FVQgjuqOn+3j*@G*o}3p|JLK*CJ|pG%mfdAL#F zsf3RsTr2PygpVg&DeySLg9y(Scr@X`g!2R*Mwq2|I8)#ugij!xD)7;SPbBOXcmUy( z2&V{q5Mh?uVVA%?2@fT_>u0e);Z(xg1>XBC;55Qp1pbaNOYCs7z&i;KC%jtVPYJW6 z4mSz>K4F&9;YNYqCOndGt-!AmW+@!56!;~=8H8sGyp}La-*BG5j}snEI8)#U2#+D0 zD)8NeS+a)R0^drQrD`}u;A;u96b-uszJf4I(D1IG#Quac32ztpV!~O3w+LKCn5Aa8 zS>Ou^XA@p6@EpS92{#FRE@76A;YNX{5}rV~R^T%TPb6F^@HoO=!m|Y)O*n^ep1{Kh zpFucN;30%r3Wie!KALbYVYk2o2u~uMBJe?kS=xnN0{0}$k}kY!uh^e3OS$lNf%mQf z%n~lVMd0rUvvdnL3%rwXKH=2@e@d98SGY;w_X)G)3O5S;Her@p;aY)TCCm~lTq*EN zgl7_-E$~{x=Mc^l_;JGL63!I(0mA1IP8IlW!Yq-(Zh>zl%+e^FBJj0@SrUa^0$)Lx zrA>I(f5rZUXA|Bo@Wq4+32za&iZDxR|-6iFcVOCw!otamlDnsco^Xe31N5gtrTPG2!Kew+LKC_|Jr!1-_7Q z9pTji&mmk-xJlr12{#aK1U%gv>b(lB-cb4>VCoHxy$`aj?T>bE;0qOkNF@0J3_$WD zI1*7q@z1;-u)5Y*ll)-bMF;rB68v=it*c}&wU*YuwPwCNv+ zr4M!6OuEq6wYW_84&FoBx;+Oh>N0Bs3b+yMjRNkwS#8@XuQ$}~8clzNMZbPeS8w1Y z@A{pmdlR;J-`Z0no%{Ba&Tpf$H?XPgQ}(YNdk*@!YL55TjZH=~SO&iE?~i%C{gm6K zPQsE<^WX-vHg!t{VZ!$tO865|3c95}jBftpAl#JITDSq!;sBsAR@;_Y;Taep`N&!q ze!^$sbF_QobZ_uiLIMWM4Sb^x!vws67BvvDjbu52P2S+dw%Wy@8k6=TN&X81 z8hxZ;T3;e59z) zk`6WZosAI18|>;0Rs&kx9~K*h<>_ts(VIMemwNC&ZEZP$mxHdlJ#GH9tU&$1Cxw1# zlDDA^b@~`A5^rFe8qO=~bx16d%?cj{Od~t2Mu(iBCn;-F{lF%CPRIdr6+X1Cfqp~X zUPW}E+M-H}iUpapAR^)7{%Q;q^=tAx_@kERue`>{a}6-ROPtQ5J=pf-YKSccS*Y$Q!iL>a%-=MgBZ{R2Hp>l(d(wDLHINMwT{;q|F{U4-{BvD zFSx8BNI^<4JE@_$W{zXp(aBFw>{YitxlVOGHDS?-s*+2h;RA0=b_x{f@*hlp32gHQ zGn2^qJcP(b{b2)A$T)<1q>v{#m(bW_7a@fp9k|qx?=VWJ_c6NpdfoiPLNu>nb1yVU zS2)%a<pBe0Q8?SV~ge~XT< zM@&(F!x(khNeR)}jL_nKfoWhiS5e&aDDL^++Txb9lUK$|u3rgCBju@G{1=FtFU_b^ z2@TDG>?D6L!$$H;uQUW1NH-s%n_oh0w3hXpYDBZFKZ*4!i`0P)Il=mYH>24b$absO zW#uDi1X|LX5jFhqn_;R2O2Dc^-jMn0T%i&=^zW}io%X*xwtv(f-D>WKE`HtKd%vfe zbTI0zUgI)oXYVBVZRhsx*7vu@AFOVT8NaOE`0)SpW`#$7gS34Y=GM;s-JV+Y8}biU zqhrS3zti#G{TkzEIpdpL9GbNS3pZ7bqQheu1~#e5P^2e#kEAqp6!7B%UosmngnYa{ zLYE?`XS2GNoPwUs@TycXUQS>m+SJ9s=LUADIp}WN)9dhig&j4&k742nzsG<#{JI-{ zr&;`tj>E5~;rAV`o$@<}9W}pln_m|2hTo0Q59jv==I_k!anWnX`O%)7-=E|03$vr< zw-57(%@jZ8LSv{Ll38*_B5$=`Bz&R zVnRav4Sn@)>M(d{?Q>0Na3$BjjS@09_*dp;RRXeS(YY<{?Og4_eaIaae(fu{!dKNb z5FX{__~3I)@oE?-#s~J1=yFY@UKENJ)sLM+>BnFfX+|a0dKfP^uotrA26n3=f$psY zQ?-MiL-(fQv$XC|FJnZt1!yqL4K1!z8}WHkLtAqFPhD7@EUe^+FA84_w?mDW;dX#r z1t3Lk$k&(~cxo|5Wb3A#7&%zSyxb9ss~E@QT-4m!BZS6H`KsMJ_|B1eQm1f?)>g_TDyl>?Rka3kaTc>Ne0_6reE^nIPe`Lgn>83N%ojhQKF308 zyRI3msEMmd15FsER$^$i6gcqqhBBc-t%`X-dF$43Qt*o_Fi=i#ktp~AN0=SzGio&e z1-Ga{BG0-!(5n;CcT&TT$@Nc2w~?H}AoKz$hM!529MMIL@_)o&M)@ZQix%~S=uRvD zJ+a_ZmFR6$@f4=0n%OH>`Mtr_DF1QV7-{lHwOEnPQ9i}Am47b8;Vh~!nt0T+)K*ZG zUoK;a^1qi!?p9;4G^za0&{W^-Pf?>OoL(fSV<@)m2idWd=w6c=KKCDy6FhYwYxUmh zVf4;vNgRk4l+8QTGK$vlfxm|?<=XPN-%*R`c*{3(#Y!=qbwO5v*_WmL7`_z8){%N0 zaBm#r+VEsdFbcPY_qL;dEQY=*u(a5S}k zhEJ^@;~&oDKv=HzEjTEf`>;7|T6RNMtP<8ST`0E>f!nGC zFnba9bg8*JBKsJGkxx)+c?0iDQ(CjS5RI+x+4TjZUrykc7YCs)!k@Ys6e!{lvy$t1 zFq9L#gL|6Xz^B3Cs9ciNA_&V5TqDoXBH;c6u32@bwfPU96u6i5mskRGz!o`tBO0~* zIl&3ohc+~UAOT9qYH46FgazPJ4H8Q)1a0d}j(jLyPlWuc7%aopv{dA1A)*gQ{ydCC z`L})T7<$WWK~zCgbj8GOwU9;xE5F zpIbrR`l2%l!-6lXq?k0K`+Grht6>K3PT^%tR}S*_>~kP!=8B|}weCt)ND zXvsLk|}A#rWG364}rGs)2`mSy$SwF!nIz; z6Rx*lLds7#l>RX0VsSk}s9My!UudqA0UNH_;M%$p<7c)dKb_gDZqH?x{monVO_J&f z%OWt`k`qiEh-r37zIu;j1n!@)PivX2=3$zQ+cZC^f_W)O99LZ=WQ&v3RtO}~@MZPz zXKihv#R+n}<1K1a>liy5nz61B_CfDSYfgJ*Eyh8IkGWD`gIF)5z)AGV32AybMRI)> z=#5Yb$yf1(Us@u_{3l36?e4=ovjW{ol@quiNsE8KP=c7-%;woBepbGi1P*F7qhkv` zVcfvWDh*(6XqnC~ZE74Wr4A7zq!&s3MkmEYg-G*8QP&1I~ zNRA)uz3O&1wA1$!TyjE-k~m)G2KFMh+ct#m|xBkl_1r$sR@SaG>vLq2j6OC zfTx3ulA(5}qoP9`XHW+KWe40$eSX;?KJ^QZO9^@R)%`bNVTpu`=@`J6@$6?Y>vodF1}TaAb$hxb*B4-g*6rzk<-G&Cn) zbwpP#(uv?)fTGa!G(*NHmu)&s+24FgUs4bV1DQ=dD}XAN~?Zq=zLA^rZbe zOQHgUZ*u({jBQ1VA}#|aNkoeKOplzv5t9PtN#n;XPD#G#$A*FHF~Ls5KoDId47|<0(J=5CbgW)rqZ0;}Lusb=ds?*Zgn`XQ z_ij+rd-~(5!@$=ZQ-^^fx>Ts!iCCAvCkzy$&UL~-e~usQeb>!y@bCLRE>0M@0OPAe zgvmB0xP99I_WwZM* zob@|!KImDQJ9ybjd3Zwb=ORFDQ}19j?5rFLuBQTry(?-GQ%gA-otd?E6T@BK0h($h0-sH<#Vq@!WK2l z@cAcT!{^lx!RImDx|en14R(pdwReH!-1dmQH>f5K66|}{O>S2jJ{-jJvIC5VT#tca zc_x~FLETKpKOoLg!B`&1kJ;kx%-G0}^e2+MEhK#gB0Pli!L6hb@p2lFcD!5x9Yo+r zitQ>wVSl+vZT%oNsVll3m)^_C^`&4NP3pOUuUT=*OH$RhocI|s@k|7OZ7Rjga}9Ki zd6wST$vhu|Rm?oU#gsXT8Z%D>W7I>*SG`3S2zoKoFiNE!-oP7mU!qjnmyq0W21vcZ z98@?tz3TpZS@PARfT-JxnnvHWK|fQ|TyK=vUk2A28jX}{=a;8A8hv0t3am@M!#;)& z?3T5cuI9w}+FisV&YgpK)7RbtYQ~bNW7h9NTUNengVAZBXN2hnHI!5V><4lG@n2-xrXC_mynHto5nJ-zCVXHj zJI={>>2zDOWxL$uy8|%~5?unA>ol710>I=3XZOpgy9Dn&Pp*G2k%m6lllEiX#Y}aJ zVpH8>n$@hg^Ff*$aOVap;V)ffNua|;z+wrHhj?5e_em^}!V1CDDSsd1)SSGxQ4Ir_ z8>-Re?{1ZiMXrt@3AFJgIP#3)0Kjq>5Gj9e$3&e20h~VQ@;5iIPhBTn5(ldH@qsph zEvV2|=vr-JW3Uen6;S?iA7G-|3(z|FneumwvB4mYfO8`^t~&4ih)g}QBo zcV}%{(F9jU`MVJ1@85L!`-m=oSFAw;=yF-W2Uau#Qf_h!_P+lbH~9Dc6qlUPLMeYs zFupoU*n-a{)g6?I_JiZ*hUU#y-S8RpY;yhcP;E}oKTy}dTPc=IvmScEbV09PfhJ)a zoTNzk`-tQ{%so!tgDlaFiX3L}zD{m%4vtoKs1Gq1^WHm{fOz^+&4^MqQp)-CyiodA zvtm5GFR?J->+kWpL3sogPapj*g2#csn0(~$@f$wOd&1{n^uUD3XAt>x zW3iEs&+z$3VBz!jKf&jI#HJ2;?+roLV@CAl9cmB8r{bE}8TqfVle}=fFla$MRsVw4 znHT=OkK|o-`r~`EBf0At3`mN<3&p|AejeeO=|cXS1Z*VVVZU%GbP<7By-Eu0iZR6H zURGP*X_x=#f~NH3S*D%;@@<5FRl0o6gq1!^QV<3f0Rj>{CE_`f$*1|1L0}^a0yz~ zY^pred%^{f9``>nGteY~uTFw*U|d)TsdE~X4j&Acf{A3+Nid(Jxi)pPxWYD7D+0-e zuEC%dL{U`+b#4^(qB!j~HPJ!sR;Pj^Q|1VuWO;2+qtKDzE={gG)FFoCK;26pT4GZs zjQ2NO{(~#^E%#sJ5~>L!t3gGwfq z&X0+2i@fSel60CMk%k_Hlho}=Os+owzRJ|cx3bHAurJ-)tKi(Q&#CL@f9S7m({ShVpr)nD&MTq?ufy%O6y*w4#Ecj*7-6L z{~!$G?1z|wj(?b_6aTRORaZ_tlztfe%hK4xVqwHTsE0oLk-$3sZGjWM0wB`t`CLdog$^Hkf1xYH=zil35HTLD z#C#ZUQ#lCEfv)Hz9u1TUNjxfrSd2$spt}{dVMIJPbFKvc$8iX>R)f76+Uv7z~YM&-hhvc1w-yX&Yy-5c|8;#&0F%I zohJ?V2iaG0DpqkamfZ{eu^{x>?6;VMQ-<=-q~rz`r?e|Y(dh!TKyILRLxf|N)I|CP|6#W34)Q!Rxd^V}2pj6C%SOHRsUX0HuMg6`= z8M>H*=_&rA!!%dRIIf6j8F~b!DkXSlWoV|ckxAw=#P@0;DC(uw`AzER7yCD`CMxdOlfl1KwIeR4d ze4P>KL^BO4Gm7#U)JYBs_ve9Pv>PB}ZBqy7rq)(j`5V+hXm5SjaOr0H|68t78B7(6 zY*X($sNL$#SG6oHK$&v}yIwHQ6q@^6UCjNh0eWcq-q6=E^`3-7=?`MER8Cum=y0?*8=y7m?%c(P)2x z<+YBoK`v%fwp5^r65(81?{auw&A7j{vENF|JJIxIbq+v8J-xASQx{^Uit&s>^_J@f zm5yudf%XPWq0qG0%|UZiMZ-$ zdbpO00sdM#YpB}^h_AorK>IUP$IgNFM2;Wqy=A!@+UeWl&y1$}zE%jFlo$VCNz%Pe z0;S3TjKC%LwNAumIncfi7H|%=a0cN}x)?gCB;{ z_ruq;5C_-bqT}GD7)O0YK8&TGK~OMaG@Op%7~IC9&7khakVFlMqJ|o(eo@q629?M` z^%m&AFN;*_TQuphcw_E+ScksVD%Wq+KMd91L4}TH7Zr1!7#sf*o%kmm#9M}L#&miT z4yAv9Nm|N$5^N;?Va8PE=fYNQo&9U0mamW`9pfKDN+WU2?-HKy^zF#lgT(e4;m++ms;6G+Sf$d z>yH!6whS@ujo%;%E zz$6lVj*LesLJ%Ep#c(s{rP#8nN_U4ZC)bytd$g>=7M*3)a!ep5TQp1NF^a8*%Ve#b zkYu<@eLh17B85||iR;fntB|b{GE9|2;du}xOG|`Yw?0Cn$ZXX%PJh0Is0?IaFe<&IJ%!&080&PKBg9)0 zg}S|sg!Ow8+XJXtoWxcRZ6UGkzSs@z^i5qFO>9qsld8Z!Cb3Ner78gIB({8fmc+JK zR+4^TV=~7JNMiekc-l64T7O0pE3t8BALmXj>bHm=gr`VJO`|DYj8Bk-QLER5SwHtl zGBd`-BPIM2H0%DL6FY7JfsP$l<5Nz{1eW}+@TX3{D8CG#Z2mk)j+FFw$^oPy#`7Cz z>;A}}2fzg*`4agv6H-QC`)=V?6EQ}(3;v0oKOnuG=s`X#hK|AkkzLO(G`0`%xx^2n zAfd5ci5NpfH<1)6@LBNEIZ8baH(;jA3>bKni5utB{QMZIfKF8~#t8{_nE?+1FKk8!divD(#MjD^5@+k}{W zcn`5~_VXb>1M54&Q3C5L>+~$oB1y-5I8*im|AA*l_5(M`VB1*FJk$)9mlF=94~k`( zCR8md{DNj#2-qaUv%xaDAGjG}b3c&D4#B?PF6v}IFhcY$`++53`5XIzvoYeY?FWt{ z$9DUHE|}qO?FZbh_s|)C`-a;HtxBZ!H(Y=AU6! zgv}rV>F)`f-%HJSc{5^%I)&p0dpFle*!(Xp&VFDSIH?T$V?6qBP^v+Iov?WrK6ls; z^b>g{Y~C)uw2fi&6S}$;Hviw*56sX)a{ZKXf)fdc(rZ!ISS9SY@N@dW{m*gw8`V*u zGVAA0$lHO2olcSVwmSZ;(ej-|lDP2?c8bP7 z8BAC{1mmd735U|3KP`r3nouGBVP<4m2-t~#U}?oah%NDt9T5MjI*Wgh8}g${Q%k_o zj(<|7;lMvlif~EmC>gEiZv0cF0{=vOLZtqYc7ID2aC+6a7^#;ERf`&Kq<&D$E{bY; z20q3|mZUz2+&;MME~!HAZdZlAZNz*DcvIB!Ooo3bokfAV8|_XEeuGF@=Tc~bG5Ag) zvd&~42O>8(4^Lz)V+`i~B95s~T{a76Q%ARIMe+Q%`RUl=cMJ7wqJAHYAQd`JkI{q5 z{a9_o1g%FHn>0O!O0MUrkpz>#$*EPj#_KK~cv$C2$- zxaDUGE%kDW99|CRVG1<9>Wt_(x&Be+l*Re(=snJ&gKz6r_s4BG-PxaU112jB?SVAy;Z_ zJi1G-40Vo?>n*@Wu1!xsu04Cr^KYY&Px_!S`~d`Vo_`CC-AMe;P!(6M^~&!!fD640ZPTSz!2)MhRl!Nc!I+=1^csUB2!BFDg2bP%lc z_aLqVsq@8YerfC=n3{LWf>_j|X?zhq*!LvJE<67n>Szq(d_6s}7GF=-?`X)w`oLGV z_wMnhdV^E37s%^xz7T`=sf2oebt;XYen$o`V<(;h9~cSYRG-H=T3$-)8z5@YM2j`i zVEEBm5W3Vik43D$5g$3j=OJEH!{+<0czy!km2AXv(64q_{uN)C=MAh|43z4DE|?j; z{|Kt$zqD}Z-qr9j;Kar|)H{?1E_5Y``7}J!4U5F{SF`gs>Phg&yJn7^??%fuwmc3~ z;1r8T`q2G1Y8>?wN`DScViLzr4md{0aQ||La%;Ejs$E;qDpHRcC2BXl;=M*yAn3LnRj+s3C;=s*LHfmK)O z@$eQsYgm{ve{8gRBO0Aqqr*yem;-6N!FBTaX=nkn-&X3Tn>iG##Uq5mQG_~`Yb6+x zljqi}bD3pHth!{O>6&;I{GG5qv`b8#!hrIE9cuo|Kb1|sZ7vvFIw=1fr??I{F0NT>i zH=L@`(-YD|zVZz@jX!bz9D4%BZm*|<9**j%M0A#3FgM1ZW=l+n)zeorO?!Wu0e3Ze z`cPb4{As-?NA%QP++l~>_mI|8cL)nTtr#Aor`4ik(bEt3XzS^pG7-_!xtu8UG!-Oj z9eIS-rD*RU`tP7rf0OQ!b=ShF8a)N2$HS?TARIk${?rrWQF}e@d@!n~(?nS8DrzfdL?N7Ieazsxb14}vH1yB0Z$Fx8wy=qvDo>mg8*WK&* zXzS@=nTY6V7$*va3;~I{0slZxsZl-s6_n~y=^oM3oiLB1ry}X`a9)g_IDg9bBO2T5 z>7@tI*{r)iaiCy&fiFf+DV(#Wh{UJc#q-+fX+OBD(bJXGqt??!5*$TOPm4S3P>+Bo z_4G6?fQRzaV)Qgyd{O-AUVOCm)F2ZPJ@w>7p{Fh&Q48=7^pqFX(^62Xv!#1PPmAah z#-GMWkB2K`^u+m7Pj8^Hy`FBpKcWTowdgE;VsVU~l;|YZpZwx^?ew$_CN_F1W*@Dm z9C0Gi(^bGyjuqfZJzYf$gwiLb#^@=7SnW^C@X^-OESZSt=~EfDO})%l;Pfq8Dct>NX|JT3Rp@D)=@n5}`qZKrC2bIe#42fu zxLrFXt%ZG!l1^tIt)zkCL87EmU@1o-cv4BFbh%La2)q;3%J>HptCchpA8jRNz#UAo zTPMS|si&ZL(Rea)D7wxvJIv8JSj$)LSlnbbEdt5!W)xPlOR5;>b`7SzL90A^>uNn zJ$I`;qJeE{JBV6a1=*%P1G4oK)JJ4E5<0{?3_dq)Eo^()v<--DdysASo3?#WLbM<6 z7pNfH1E&3BwtvyOU5_j6^U)qIL3A-B&ynQQ){itvqdJrA6Qb?6#SGD?PGI|S(e|b7 z+Iz9Rd$j#L(+*>U1;z&){t_;XEi6tYxgT=g52dcA({a}$FJUUgNVuQXZG8dvSDkLC z^!^~y|4sCW_P^*}-GBM-?tdp1NA!IWZ$a_;nV(ZIQe+>T{@4)i9wP6H7>&ku?~90h z|Mx#~nnd|zAiUmbW?=g5fk`*FcvfRu;ZkFv4LOqXG$z+i!d62z3op77(RP$>gBK^) z>u(Qw8goP4K0&a}3H%G@dzNHtxj%Vk zryKf2j$X^r17CWJwlI(-yo-_5R~RN(b8}>Pz17;L20Fw056AF)tz67|6|CoRBD~uW zFu|K!JI&tao!ANQO7ixs#s;}z0Hkfb5j)c4!O-M=AP(Qnuo)V=Zx9eS67dia`gs$1 zU*Phu_CS;M&ECLM8R+c|+>j}kkXL5jkSCYWOkDiOB@b?xjStC#LzQxwUYk64R%7yD zUsLkn1*?+>*EA;&Ube*>@}%U3Lj6IK6WD{(keGS=gfEfmH{^Ij4XL1Mk+;(%L5h}! zM8MEJ9IYV*AH6|o1H{2NEDqjUu{2oQ|YiZzs5q~IQE*WDoHt*MRvN{9j5LX54p z5GKo9{#PV}6mZk-z6yFoKmVb*f!Rqd?8ewe?MQ6nn`5}yfAV+{Zx7U{Jd#rz__-A? zV$5Xw^=MZoqM`NA(H*^#JwGxhh^2 z<;4Nrb_9q2oaY9wGn2fbn(bb^d=xJtRo-BV>f`uZ%}LhG-uRoISx$?K%LZPkUzHY> zFE|NSOAjLQV+K>;fq|FQARc!$G;2-xS4Vo8c|LR;i1`M#OolJ4oz}ae<5}@-khku1 z7rrnYTDD!1wQ8a?bxV_6{@&gYUc7<^wLfverTz6G&ZV?qOSaYq-oC1_^EB2?U09R* z7J-On>l2yWpz~;}TGC-QiCWIB>So$E=-JvCo!DnaPM}S{Bo?9Td++kER&j*jWo~ba zrwJcnArDc!t~S>-a+Q}7ZN7`CcA{Hj@G_#>F*w8G>YWsvf@7sAn5w4vX*J3O zu8i>m>FyYD{J=r{kQ*o-2!7-71x$hVdIRGJ!c)c%Odb09nf!uQPJO!e{ z<2l9Lz%DDH^ZD2sNc``H=B(uFU&cENqdFUdWGV0 zUCFex+>w_xeTOMPe~oNbKR^(PzR3-I9t8Sn2B${W86;{Z5%xG(=8Lf!)kt`NkOy8$ zuK$K@b;~xp{Dn;%>rTY2F9q|01smWH%R}#fgQ9J6bL$dhbb*I_Vg1W z%IN=E>I%Px6|McerWyU!hfN&bv&vfp2?L&{@L(Z;cPv|@lA%CoHYYIAP1@}M<*9VU z3(HS)sC0A3{2Iva37j0hN=6y)a%mf;YIz=oDY5=m?Xe}|6PdV+(d-RfjCa4v+*J3! zm?0e5Tz%C~^qdz>JGcYRJl-R|kP8WHp7Z^}o16_qbloPG7TaSh& zD&bh+3#iY~*cKuRfFSFf;AQ<=?~c?jSj%C9>K#$}@~>uMooTH%G<|~?&Ecom z8%#VFGjKto&3L_OOT#MDf{&}6j}1_N!x{tOm1;fjunqEW8ezoJa<;cYx zXA}9Y#myiW0*U@V-Cd;S4;v%MFYeNS#i*Ror1V+?#Z< z9&w)-dYw#?u}_?0oZ|)vB$&yh&Bfl~`-{5Z56KPdiCw;tYPFoBF&LsWaE*1$Cirp) zlDu{ezAriI8jX>>^AzV!5%1!}@DeljFA`mtDTeReM_;G~N2-)!s*NDFT;>KCB|Hi) zW5tmKxKWJ1oPu_Ubl8#bmnWgr*0A~o{i4Y@_Wq0GJ%2|TlIP_!gkay2Wx{k8CN8ik zMY7xmrbCe~)m$@p&0Kj=CU9Pj^K3EKt-PwOunh#o!?)UnlIy<)nkL8E=Js4YO^SeL zi#OQq(0n)aT7yF7TUqJ8tt@9eFqQ;-|7pQVsPfap10h6c>`AZ!BIJtiE#1r7z7iZz zsN_Z0HcNp_=(iegP|tQVj3JnGlAy2`&U%*0ki!ZZZr)9in5?@N9ztLA9D?MWRkyv1y8RZXcRjyUsFl0( z7%&cv-2xp$xr4v6lpFqw_$u-gt#F*S!hM?11wtq%vIr>Msn7-u(olhZl1=r#SNFeG zGn%XWH-Bq0N=F9>G5Iif(3hBF_#GhZ_YrrfC-b<#+SQZK-zK;eU1O$5jk!wW`fD8A z0d?m+y02T~U{v55i3=_rq^r*F-~~uj+Wmt|Q#JNOjn#`GxHLm!H)*Ua4UFK`iDxyi zmLFtMj9;l&ryVNh->Q_z@oV*}E>?2_|1rtnX1Y`GvWyP(X{RZ;zb$RuQa)gEZx?1> zd3!9}tr-rL!o#PXJhFQBX5%vcIYHU}!4a-Iimn24UBWtHHzHWX3(`J7GHyl!8H_Qb zS@^Fvnk;-VoQrO4668hJlwF4B8W=+Xpr%ndX~&1P>Pdr)ow#bb-gW7G&{4;r^A zF%_#vUe5IzM#B=o6!`vKAUPX(KAKM$ws>m6#-;vtz1&A`xRktu)q@~bBPxtqwctA4 z&>Iae9!rsezFNq@u1x@4>Na$h)r(V!Hxto)&4ip>&*-841z9Z~_e}g`ZSoAn2?bv8 zzov5N{Hi(WMMZ#;ylV=|D~f&deN})`yldw8sw%1rX3hlEA4##B`W7=plw5fTM#b#L zK@`Z;Bo)SP^}UE((+@fT3ikzft0p~*`Wx8+w}^JDOQF=Lhw&Mf4`D1P*z5;7o)hjt zKL#BJgB}9Fp@lCOx#6Ypfjy`ckJ^IAuNtO8 zMfG@LI#>C-7|~OYw+G9EOu?F34uN;DE^Aa{;9S^L@K1s)L$&mydY|6LmgU!C!~Ow- z!}S}qi`0Mgi*qi96wvI&fjC4|H$$%QOK3v=LSlc8!7^-~+eY_Dx!4GNboS~KGBR;? zEPU@pRB@3%iMW{vqcj&X-2!Af zSx@Q~C<|d-*NP#;(O`amL~A4wNk{#`1Nqh2IPtp^WdoDEk$n@65j}{#NMSIYTRn&Q znDC!TkH>mp6Ls&N`ba$vT;bq|y(Wv9FrLV_mexomLRxiX z2^!%reIR-s7EwfG=Nm$4ZnS}N(4<}zf;%E>^ghf{R|~Tv5$Yr45yYnt50{)az150P z;d6e9)L)vOp)9>SNW+7riFO>ju`k@`d^lD3aS^^&42AU)iHvt*$r@XHx))jx`VhM= z8JM6-8fgp(Ua45T3|`ksJj+f+@N&DtIl^YV=q_+W8NL3`=o6HW;TyyV!cYAK9>EN? zk!~CsyM(g}Y=Zju{$Rvhd94c?`cc?Nxo}J#?M}pBh~VQ#p!lH=5FsLzFt6uyL`7`y zv%!Z3UE(Z*6Mv^(yvot*6um!6)=FK33kn6-PFtxzpfh8`6_^L22ZCr5e9((1;@Alr zDlF&lGr~m&hY++9buM)Tmx{QgKgB7N;96n6%>`2!MoC{qmsb2OA}zml-jt-?gp#7? z*$E)j2Yhoe52xP7`;QN%4kPE;7ostGo*ml%DXL}q+OwxmpB_N=`66rD?w#xZdt{bQ zwu4_q^_)`oQa5kWUUeC|LfqtfzD6Re?&mJv!20B?mTR@%4JDN{CO>^}R^3;49o+gv zZ{3Ej%{#l)eR_KG(|!7_JnQG=r}KXqpZs+8zV)9bW;LtCx=&L*$xkl?$cA-)9eFH8%Cu7x>ws}D?JULU%C{`;n#;ikO<#DtvnD|Fbup` zw<8r@5-vRz{S%sZCid8?Mf=mrvl55`M{vW4Ky>kj&Pv>r)pac1G={pBf9y!t*BAs8 zr=iQ*v6y%3JC2?MuiB(AUd=&NyGN-&h+gJV;aB09&iSaWWT0C8XR*}vP;DqNGqkuX z^qaG1eOs5hmIS`Rw-y%hvm z$xn|sFtc_aG8QXvZ}JQI2}0Hz(D>vR68mMh_NH_Y;a%pmK}e9#?y6 zKM;JR36^%PYa>A$IK3(a?`7AXdLRg%2jmI7wEoL3Fn40s`n`#{p>q<(_josRWm;Ap z3V)7#an}0ni5NXMbXJ!an3WeD;4S(tEBS>HY3uiO8Q)_QwpR(78f?x7r8jg@*Q_w zbztoBx$rQHSUW?JPo@Az18xo)11`hp(a;?|ANm7-Z|fnN6XEemE~U=@-WL7k_x-)C z3WOf}?`;(j?&R-n;ruEm@T0us+-!>LzQTFg01A*B!m)GY?}G86!#1^_cr4lizGi4( zbL20AWuaB>Dyz@0)bsd?q@n4}dehj3zi_hAd47;JF3wXI^;0cZL#{_eUx1HS&j5xJ zTGyNN9!R%O|Me{_3;B~}M`+QkKUp?e|1q*M@}=0$A0!K!KUQ`cVzJy@Q#nSovqUuR zw0DbKT*S^_EJGauxrS1%$lohFQXOgJvQ%itTW_%24ddMKlVAONMgz3+Rn0CKLZq?WTo^b zRi&Si=!2<8ANBU1Z+-vKX3F=WysSOpXspUGZ;Igo)b9N-X?*{sH!ovX9pF5vTz)yE zIht0*JLouv@G0zo=T=$#hKB$^O+itv$7n1c4}-YTCGPmA<(%>K|5ps~`}L0PBd9HakNL1FYiMfYQkd;JxERR4Fwj*k9U zp!kCR7ws?l9|SY#_Yr*E0BP=)1@RmD?*snS|LqXz59$91WHj-A3_$(M-I5sp=l2ZY z`|yA4cVrE`&07cO;vU=w{weAK7%tWZGl8+!z?*T`K&Fcesuva%4pBa+c>?#3LRb$o zFo0PPr>=koCUQVyk1_ZhV~^3GF!p#6b1>^65!(H|>j4X(8!AN@;K!a~fcttm23SxJ z_D4addd++d+lT+d9OyKk{_+`wE}Y%}pZY zp@#E)g%7A$#$frr!m=@L`+x0=8u10;dvHqq4a<6CyKwRI}|V9S14Z2(aiT1 zZqh`XHPMnJ5XtuyP6v_62Yv8S{2%kM^{wl7+}Ga1O2w_pAim6dlUmMspAQ({yXeh% z=r@StPqz+Z-kSu zy8kG`crZW~nTXMk#$i2x7U!Wwe!=g~OWAX`+I<wlccB=*| zHq-9#)5b(n0@mtTXW$Uv5cdoYjYz=U@yqLP&6ai7Vf( zf{Dq?Djr%!G4XvLOqu7K`;#u1K31lV?~98QIbT|7QzB3BsU(gb>ia0BAGs%Db~QLZ z!ee06$PQINS)k8}n7DeJ77e9)VnsinSo3$i8u1yT=S4;T3;kz_khG|y+KK+{C0g_x zXp*9zMY>@6&QoYLocFd9{cVheyO~Dx|9lU~IRfiM^m`}^M8A@YY&Q*vLwS@Nme%hQ zvudsX6Q3b^WmNRfpiuRKkhG{0jAmNi9W zQx=H+7M=f8jvPw=3>n%I{Y%k}7JUH8qwfVjfpTN(3#;JoLE>u5ed$sT-KO4!{FM7+ zjuT9OFI}trP0ATrC3rsx#)_(Z`FDVRMdfJ}1acojx$E&yZt&Rjk$miSQ}nUh{h^wU zkKOK8iJ*5LyUl=E|k6&+0dH%PAWGjp(66w?YlCsZ`5DdwtOR_iP?E@Qz^j< z@7ocpY*VEemT&2kzav%#Bp4Zr5oqY1pveG$2adSyzJh`aI<$Ttb0s-$n6)dPIt|{|X4=pb&=Wl^lX8{E~ zc^*io`Yx&|t@2f4^3{-`w8-bK_E(jb&vn;Sm7a*(Ab#ImUzNM0tZ*)9%8Nl)1WnE< zESm2wsVOg_KFQG<$5P^n?utrM6qdP*=AoOfd~RfX4%TrfE#FC}<$!S&`b{YHl@(`K z)X-(zw66KFn7B);-Q^W9rM^SshtSpj!tx^DugT?~=fe%2>Y6g%2Exr9!ZC)P>Z`7- zD6a;#1d_zIX#-o6tAXy^<%J7C-RZ32=_f9^tfGv8G)=&V@h2tJ=|ZvPLwe{uiF^FD-IU8{(c^SU!666p5A$Hls&t zFCDZnWAx};M82|9`AHL;HrRdMqEi1n_cZrdw-e~Hb>N$25ARx7QCi$_XflX1a7=HP z%g7gJ7=-R@6HNw*Te~SEBf5hgkDIfW;3u}1<+S4lx8oQKE-bC`*C70KF2MA1qzxpG z_&>kif9h}acDbDX9jtR{)Kn1Q*y=&YRu6U|VVyjr+BLVjx}bDHWkr?0fXi6J$PES6 zzM=vrKM7H}MDG|}acOmBS>cjs&l;VMNYAh@qZJmJj#XF%F(WyM!lEKyWh}=9^O3t3 zR3Z@T1j_U(o%zrMWT;$HP*hY{G>?IoW74j-rgiSzlXq^yJGb7QJM_+d zcfT=FwZEduSHRJWAZfMaPo(8iWOj|#YqtQBRMy} z-}H~m-?TgY+kXGgX&^m)MEb~6GDeLabLv>r(Us7pYht(V`z7`0*=zsa2PCH)c+kOp z`u?e3|3fsvfI|;E{D>pnM;(34z+;a)e$e0{C!BcF$wO1qh7FhYtZ~`nJrgE+bIv$3 zchcl3d1p<{pEmvM88gp0w{T8Tv9DzAywVHjmn|r-sJy7E+F!G9(c&c+v$K}tgrSi# z$wUv-VLETRoFwG(BkuY9;>adl`HHh)JesAjtUB9x46V`er}K6DhvU!xT73Nfo7V*l()~mEy zM7?d%Yw>|vXpy3}mR6-$AB``dwrZ>vt*^QN+I#IYXU?1h;_bcn`|ij2zL~Ypzt>)S z@3q%n`!RFQE+2}=H-jDl-3Qu?Rn#cxKG4a?uNkYvTF|#ZH`6^h$f1C;C&wgYMgjc+j^%CzIapLp?z=A4Iw69&`k>7F1y2-2qw%x)!to^dRUWx_=ly zxPiX)E9eFE$giP4(9MrPF7_Js{T6aT%O6Glper7a$G6e_LC6QKeFA#Kc1rUI$_cs+ zv>9~rbI>E`k>^of(6uk19YLqR2)StYeV}VWryqj;Kx;ww6Mh)-XeaMaC@1K_myj=L z$6vq)O6Sh+C;Vm93wA>1yazy!fHs2Ch2I6_l{PeAq~V~#f6B?o+<+fMrUJ$PBt&3o zJl+G{im~}MV<(@Jm%Ti5mH6UEKKJR;si#vy;;F`G#Xvkhj)2Os`NQcox&BHB!Y#$O z;Y0Cga*nSuYZ(_3y-dc@aU;aTrp=c`@qPhT_!vTC4cT*Q9|J_o`79Rg&2 z;ICfqS%<%r_|h-5a4Y^7z*devli)wc!rzp_KLPdM4E~!;`BwfY@z<-;C_Pn!e=_>w zQj;I$2~&AcoC;!}lRXu2UEo`E96qYwzk+WY_!8wkcK!B%KNEfa>ZJTvd(x{Z@2cz? zB9*Gd)E;kuf8WLN_$N&MujIBGpzZNUK&+Fb-oeusmI}?cAzV5sIgx5yo~SprWcBT(*2M0LOLFS zoNiF>SK*+vt*g4KY`I;DKY~voe7oc~j?cda{EIYy)$#eM-)+(SXB?mZ1@Mn({_NxP zQ@<<3SR~8;DjfDP>RSfc)bAF7{}wOw^QeWt<~yD%yz71Etn;tV@a*+a>#+Nf_V@<) z4`QsUg$y$fv?JY;9w+b^b{he@4Atb1=C1R>AI&F$a})lk8vL6v#_e|Dm;IqZ@t+Nz zcTw(gjDZ`e+{2b~*Q#=_^VhDg)7N1vk)^%rcezlu)lz0ECsx2m?M zUZ$^B*~|2oAbst+c>FYssa_fwbsg(;{>XlSlSh)0%k=kB|GO$4{}j5Kx7yOKPU(00 zNKlxwm+9X{`pMtJbernG(URV={x8Y`u)0HmwzOaDu0e|4Nc_4|I5d*5yBe`{&HoS*BjMIjMK_IDcD zC*tX;81JA(zQqRbrb?mjQ$MID{@dg6KY-QSY~`o+Y+CP={owm!I0;gyars@8W7Ylf zIG&eE=m7m-0YpXA^UQis`Y$8C0`e!A@fb(Ao)mux z$Ghc!?QzoI%ki}&U$>#9A3ufo9_0TM=+TTf+qe$Cp)iefLbgSE&p}rh{TY4*u=3Zd zaojUivg&Rm`OgM_V0S!z$eKU<=5H&(ONo&2PX$jG$p`<(Z%-d!=Hz({L&V~>wML4h%c#Hrr$zTd0MLPmyxa! zbLK2-xv0KRCf9cj_{x8Uxh(9_EKgGTA2J1#-P{3wdEgVmCcmZKA47aC=HNY)ue3|p z?HoBj@Qjre3um{JMD!ohH@N^hb8ok`oT?o?EzI9X{AftxF9ZMd10Q_8+6Mm3;J*%O z&GJ@L-wdz!LE+@>+ekk2E!!XbnZJ+6H(B{-U*VafC&Y3y319&rC(yn?-HbIev;GO`@z!5`eRMD{VDVt zWUK57e!Cg~#Or@Y@tNEc~#&y4BwFHMw&Y{TH(b9h3yY#py_zZZq)kHj$+X~enPOx5WQ6ZZ z5518oUP#6l;7w zgxC3ez&H7j{`)@PZ!*PGzR%zd2L2!hrl0$7N6I@%_CuNYpViwGTA!t|`bOF`F%8>@hr=aT^AWHQAwG=ZIfsUnsmvU7x zzRAV7e5{C#pcqf2PgpZnyqw+~&lL}NijWBkfbcsWAMne(NVP#0<6$bs+ujnC|8^f{ z>s$Px8*;^AD#qH3(0e)J`Ha_4jK{J=8*;@RIpt6aWqBQa-9}%s7;jVP-^St#+P|F3 zf_;nF-%*w$>7jqm6F>1le` zmHAK)O0!(q!lo>7(PxFYF)cKjDV|UJ8!~;)GvVzlan#fNw=D69x9B%n;$5!~VORw4 zE65hE@%iq}5|5EBto8?2XNi0Kw;<&U8KIlA#7&tKkQW)lm1GPz($}3?$aR!$qfcf1 zYOXdzG{b9YZ$iKkPY5P(o$o5tU}wez*vD@&n&A^}$}GA&S3I8SLm0*k{4mM?YbF`b zkFrpVr?P@DldH!34k<6qEfV7QqLezCAs3Fk9U1 zxfJEz<)qY#I(k>c;!(ERn(J8q}12k7fyj(&t+LN4o?*KWexoS-(!jpeq~I--ihM!Y#+i`W)shkvS;j>2y-90 z6W=*S2yeRC$63^qgGj5zH){hDO@5_n{RR+TJPgu#KX{o$nBamA3~3(sf-uMmYsyrqrT;5S>iv_)}$ePXZq0X zS>g`Q7ZCodXXu73@v4`?Kk^O1HQeI=9KtX9hc3?&&t=pgd~4=szL}*4ly6XXK6#zg zz)209)WAs%oYcTc4V=`#Ne!ITz)209)WAs%xN2Z~gNj-;Pth$*_cQI`cvk`c&myqu zl~>lOit77`w);=p?q}KV=h*Jg=X-4Z%4;RxV~by2&DDxx%UNDuen?Sf6T99ilmOn* zCa*%KA7MJe@w9JE7wwVL^|$xqF`}bf5xq(dOe9nY{G=+cMcBip3tQUqdXY0$yW#l# zhjIFeOkGnX!A_C9HgH9-+a@pUhRbUb(|y==piARxaU=>|x||hUF#3ssE}h@|aaI1! zI2wd5{E95=qsu+Y_Y(su{_lLRs)-YYjw4Lc7(_yBYm~LgdgXvzT2bdmWdX%ZZhVy4SjcJH!4bz28+nEkB z9cH?T=~kvYnC@kIfaxKoN16KPaQ;lEF%2=TVY-lMJJUg?!%R0Z-O6+a)4fa&Fg?Wd zC{uqe=g)K+(-6}drVE+2GaY0)%ybjetxR_?-OKa<(?d*;GWFMS{!FJa4Kb}@x{zr* z(?O=gOgAyz%5(?Qy-W`3K;)IXQ=XF82(h-nSeg-qL-4l*5Px{2vlraPGKWqN?=A*M%}`s+D=rqh^)nAR{| z$h4j5Ak$%{o0x88x`XLnrU#fFVybdY{a)l%<4kIdLiBj5)g2{_c#)h~+W z6C1_y(a_>{+#oJSPpydJXou0>i|2HVjy9y#cM#gzYD8DG(ql9zXjfFpFj{(hTUH7w zLx(SFMM4rrIYX{2Wy`Y8RtSk9Z+sQYLZ}QE_w|Y5*4VOTc!a{P$Pal>^O_8N^n79; z&sQ{^YLn}=-52BjD8_!BUe9+l?cxYMf626^FUNg0K03Xg4{5qz{@EJ8^D~c5ujeTh zz)7}Fujf~q>iHB{BAYulY1xfb=w1()W74r0FQHKwiUH@*Rv8LDaJx%rekkXIA$DV!#FsdSzjV?VO)>O}P zRjkTOhl%##V@*$IyVIqq{7=1t3_tx~=4k!jq>Dd?SWzT;LBCY8IPbh9p zr`jB?Za*#a7F+trVHKn4Eb82ri}JEw_u_`K(DtR*JG#gBTq^Fz$8epo^f69gvFI}3Fd)Il( z2>yDF^B<=f8Moa^Ikqk)IoHw~K5*mrezP<+A5* ziAo82P&z%1S|dI1HhO$a#yvuhd&#(0=2UrfgHh4y#J_&9U_CK(?u zw4X}GPZ8SxB;(j!(SF4e;SmKw`wI&Udzy&;UucD7*du6HW{Lwo8SU3q?lUKYJxAIY#_O;S6!zw&i#mHyR5d3GxcQO7Q6)k8yCjQ1o1!#N=<0FjUq@u+x z#y6a&fTfH-%ea`IjMFJnB)^AoE&p`jX(;WM{ffVhmX zoALR;Nk5CYU3mLYT+94=|9Twr|3van7OU8vD;VF&{Cb~T>+=BcW7+M7dz1iew=c1r zz)po<$MP@qse0{aT>hsVaoVm{J+2trnE&U@AF|nlwyRY;j$&T}m10-GFd zSB0Ff-L3@7(R$E&9(ha&)_R`d=X$Yx&EE{%NpG#d(?qHt>tQ*ffeX&$GR6Zod^6+r z-ywc1J_bpAT;Oyo^1#qoHu976Q z4jm8viXSReK68ZNdWl;(RrqEX{27+h!vh^XTS(WLm`FP1Tjzp*#Rb321>XsLyvi!+ z`w4NtFr*eurRerUKhyjW7jfLP@49TC*_F2ktKX8%1$A$lC z#(P*l+7BFMeEaoEu-4n8Jm-4N0Z#V6=mEw52`V+m;;{eS zihB+Bqw~>-PVz66c(&Lzr1V!9pyPIg;iv)iX!L~{%Qf^J&fyiX$S69 z{_ncrBT`Os8R_n*3;&c;RC)HZ{lHVmD*)Un--zUACJSkI;ok||Y5aQBMb2S~!=GQE zgx|vU;77pRvwE zj$kctr}8gy!Jl@)GqGRlRL}Y9Q|&aD!6?2 z0)iPIb1r9*3ts1fe?{WZ{}v@*`|U2^WG8Rg)`=H0|CSpR{~<-h6^s}DhXUj~91y%! z;>=_rk4X6zfP?S2@aLo9ob2th5{I+?XC*+-d#iyv>HlIEe5VWks0%)}&{_U@F8D^^ z)E`G|{c(p2{{i4m^?lm~pEyPJqtOLIUWOu~7`T%j=DOf3fji~9UgGeFJU^#r|LJM>)>sS5KOFi+9*zo+h4JCu+B>{VUU3Yt|uAwPt%vjjcH4qJl z!w^^>EH{$g+fA=WZw#Fu>&5%fDZV6-9IxJrY~`>^pmHR|&q|gc-^uRG&?H|RoyuUA zQ8C!csI(FcB;E)dEU~@=nKcp&S;1=jTS#gnq>_c30tQqPoMjk|^TUzI1xC$+hN?*2 zxebP)6>rU=x+FYU+|$zAUmPq!d};yQBnS5q~Fy_>sJG-*pF!}}-8+9g+^{fT`;_VdY z7Ho?4L$KYo*-O|Yk6J*tZD=Ynl6@PzAY5HZps_awr`W$zi;`Y&Q2IWLGY!r;vHXrH z-R@&k`mV)y1e|=!hwO(5cjT;jtF~Kv`|&#J_V!|oD#kfg^NsqtrU*P;ThwgS{$)mM zSFAhQhj&tQJ0~E+Xp0$3x?+o4x{NlwQygzAA6S8-LzeY)Mf;;|#i3aMz**36j*-9j_+!^5PPhwpz$0e%?;Z^3S1HI5Z+S?oJ6*0W8yqCie zhB4AGif7J{r7`bj!DX9qp}bw!l=HWp>kebm6H{bl@X4iAXugbxd>iA--S25mr(yo zJt8FBdF=PG%lFh{%l-Zky?5>4VkD!CPL}T_3#y(RcSpa zM!8QKx@pSeHk+Yg&N7>6mRX&c`svTFc}Lou@BaQ8A~!Zg!PXQe09zLn_Js zvVRx7q>SsO4bkN%qz;);dv7$V`+ZV-@mw+(XfzKMs*|RYq7Bp!j&x>2th)+F6wn{B z6GM!6_OSwskcQa{D$n z8>Pi%BD$ipKe@#XgSa7tj(o61T^L!IGBjXLZuH>%p#FBFwPR@_0ZCVVnN7I7Cf3^; zMK>n%3)SM-l&&a7z=S%QN)6lwXKKY&_G7SIJkTFS7V`i1Nu6(IQs<)yMMCwuCnOD_ zaws;tp0qXTt@(HjyRDVcX-dJ8c`Zw$T1>c+WawUnYM|ZCdLYd6avI!AX>bo1<+>y= zjLt?APO^X$aY7ndhI3hBt%(Mt?hlPCJ(Sg8 z_0g5^Ajz7b$ptE_?UwB${NB#~C^@%qV{2z)XD1uRtftN-I38r6H!58P^kZ0* zYtgL{Ozq>OP%IQgTW7RH40LyOc3X^(%budzs>BF0lSUJqbd{R5EM96->YS)oN(4KR zGBPHzkAz8BEJD}V)ZmOT4gR*SknkeJFIUdg-Xyg=yaLlpoR1Z5#9R=XqBZr*nwC~f zWmeWjjBt5x6q@Wd`ooccA(YQL#=B{4JP;76ZT|~1^Xxog!@`s zdT6jyE~yE}^F%SCB=ss`)J5i@D0+U3Ng7RDAf$McDDmWj%+5%O(hVPXqajyHN~QJOkqOAJ%gGiVN1Mw^o`Au=<^`I}nQ zrHtZ1>bY`$+JMI?k2xAbhe2!CO?7S7_6e47^XO(!>t47%c~~f_pE8aI%NAhXOQ%-- zgRREwC&2(YcQqW#1w_I>SZ9yqDyg=q+Cu&N%-J7wok*|yvFgQ0&HcY5(9{)Mjtbe_ zp_(8piT10F2V+?jOWh^OgBGhS+O1WV5E~4k-E1P=$^-8qH#(9{oUB$KTt`Q04fMI# zEi#?So-i~=Zr`XL2i)vadbCRP!tzK=EvmsR2WGjfl;v=&tCK-Usn&9mZMc_GJO6Ul zc=CW$gEL2M3QHOiQMeEj{bx;Y$im*t4FwsGVWCC2KB!bz$`4N&T3ER!fY8^fL~f31=SV*D6ok zRY&n9ReNS62IZ9|X78z;BXu6H2R^s07|YVr>Uo;Vur<)oR4E->Vu?a4IPRGkc4yI8 z)q9L_*J5=vVQlT}X~AmRG6grN=XJ+0A4K)BDU;kiP|9UYptrq~tyI-d2%<}e+=Z04#u5?QVOk%zUzJvmsO)M4eB#LD;R z`5Q0PE#0%O&+MM$IphX|-Im(g zToBTIY9yP2jFg&BoVw~%2p9{Lm+EbTAw3T3c@iuGZPVS_gVwQ6&*&6PoK|`qLohBZ z#b!q1T=}y(a@7M$>IBSmq1b0~>e0tq)&v8!(Uu;zQrpr-RW`{t@H&tz$Z>@klFQDh z%j$y*N5)sKtPVR7_}v%_P#o9ow%&3omEI$#4KNx@)ov2z9EoMx+*aC!3XkzGLj^VLk$T0P&QAewGxdf9SQUps?DQLpn8|$KJjnjHeFWb-zTxfGA zmiGb3?rfDzof6Pl>S`Nt0d@}!{H_;v>KAZoK_Q1iIkt4u8PmOkovr#eIrOd6U)l5! P%l;=Z#GuazH0^uT%U1ZAQC?N;)rgRTgJ*1435^qaOQ_Bv=idZ4pul7ZvryPOa z-bgSI4@JU`u0W_)?VJh(tzAj}(yAo?R%Ll~fI;>AED1%$K$Mc16pGigwMOzGu_Mc1t5=<-^U7rIFSr z_0mY)WM)j1(|1H|tja5mr0WZ=D#2Si=Lv8ok(14g*?^O$ja8dDlfcPBR-Awyl|4V~ z9s2p)87R)yo2$EUxD-$*n7pn1Rs|u#xoU_P()YxI34Lk{hnoe2pdwU*i~!h_RI_+p zw%1&@5k>pF{QQ>LC<}uB5X6ZeRTfdEora>KyBi@ z^p+bG=pw5tOC#=5Phv7F4OXB-8f_IQtq81oX;dti6OX_-iOIle(%P8KV{-(_jk?aEBr>I<%WhK~z68_FC7rjj~tmoKN0THuBG zmO_R+D1U`U&#q5il?%(Z!#>d{CHYYA$It_4@wEN&CBM7-C4f@pAj}k&mi+2&+F)OY zgM33=j;?8OmK%5$0+DGDoX@|MUBKJz-m>+DZQFP3tgc~EM6lV#S$VVb3kv7VEh?5u zO6SclTd=Tv(PEwOOvRF=&sI8?J@@?b6)RV*UbA-H`VG#FRjy5&sb8+GtM@iEDtq?s z^X)&-bg;RlwXOZoi!U8M66gqas$H*jhmQ61_Jt$;$D^_MiPujKoH~uc`aITcB&4yf zZii!ad&h}z{Di~p+~#y|*mQzgu5&K8v&y|jNA*RQv9$}QTZk}FB2>(soqq`q)gr)` zFrR{>TwL;|t*$6f*6i!S+{S$Uz$FU$_7>$ezHP79M0>GN2wA*yx^R%^kSd^bGkym7 zJXfvG4={dA57U{>*r~pFpo2JL@u)s_b1kk8#EG*r5DyS%M=VC1(FhvIbU9sMs=Wax zlAN6(b(7KV2*lK_Zoe81MmkjsN2kghdcsh+QyuVcb>}KTd?-eNV5F~44Z}3Tk+|w? zJkY)&77qk_SWdOu-xUq?scg~zW2k^wY?_Jz zaOA`FU*qwtV9rf&8O6g4`lK2hygnb1hq`(F{Vax_O{U{eV$f0D372TX&>Sw-!2#x* z2jeWbaIGkK{!tFXWmP|oP7r$jb(P-D_4fg4Ri8+Dkg@)3fXwwnfLYbAvgz^kdD2yS zH`nh3)T;gftAB~b;`$5VGS@!~7}jUyKx4v^Cb-Q;hsnMOwpDzB#mgqXIsQEsUuEKD zSo~TOj|A586YfK6{?;nRRgJM-GpKX-Fh}eJJ5+2Xb zUnyYbXAeV$@vws2(1+ZeubTsCo9B+cgL8Do`^-5XOq_$cKAs7y`VZ)b3nB05X>xaS z{hY(3AWtL@%|E}CWzX&2^dP(CN^pKwGeq2~^N6$NO-~OvK7rGv5KMv0&4F@G!#voX z>4JR}2x~6r34_~izzs0unaV#MXD=xu2)doWJPf%0TmAHUmr;&rS=mn5CK~dr1bv>N zKm2^I1Kj*>!7%KH72Yxfes~7_)fw;}z~>qEg}-l4&A?Ak{?xwk_anZCtmaAdPXcEU z75%q;>Q~=aS4Et@Iv1he5&lMBQ?2atH#Ic0dfWVMa;?wnCw{*gjfNwB{wI(0gB^(y zbs!W6XMZ#lj(7Qk-94-l|M=*m{|hBC{B$UpkK^`QU& literal 0 HcmV?d00001 diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o new file mode 100644 index 0000000000000000000000000000000000000000..bd32e748e877f91bad7aebd4e0e4efff1e686b1b GIT binary patch literal 86232 zcmeHw34B!5_5VvI2?-Dq5ftk-AX*f~On?ZeNK66~4HyY1)#@aK2}D9BCKEPA(FA2W z1W{|%{@RLF>sI%=i$-LTE*7m?+(8zJQNg9wJ^yp=^5#2t-U|Uy+kd^EyuACq@7#0F zJ@?%8y?5v0qLQ)6NlBItN!Dm9cBN6vnlV2XA0wh;tYubR{s>_m8}$u!p3FC&iGh5be@6b~{7J=; zugd&Q?`8X=hx(%zcuQJldi~KeI~LCG@kIFaCt2T;$d2ut(jQqX&qP)nS>un6>sUCK zsE+r2s!2*B!S((~(FT9Zg7x_wFZ-KTWuKk@^Zax2&pqdvtV0WlM|94if=T;*`g(tP zy~>(XUr~3===xw)L%@6DiQXIq%&4fHRuc>iDQ=h$tf(&xR)l8^I?}2O);Cl)goCx= zK}Q<5`WyF(X4Qq~QIh_lspkbN!$fT(2IZN-ikUHg>q%h*Mt9)GlfuIBdhx1fL?)FPdvB0|Ht{eEbD%Ba4vPA`yg);sD{ z1&#n6LFG1(j>}i9bLry$620N70=$6r&_y2fAwky`hNVC zYF90_ErD5~X^l0(hGT0hYWWDrCMv+Sd&ms3)5PHUjn(zR25L|mr~+442E7g8`s&*0 z-p2asqrKJCzDy6+d#h?HrV~x=G@`4d)@f=*JR|tEq~pAB z7+P=8In)uRmiF|sD2ZEA|&1GX!F49 zgh~anyYxqCP!U<{Yo$>|nEWnRP*ShV4zcp~|ESN8_WA$Af6n9; zi;|YRvO79D@+XPr=#uv~kk6~iu|wB2fAqkGk1yxSkk$MGEn$>IZ@NvBJxYl?d@qzZ z)xfn>*90$G-YASd&Qln1Ss3}otggkn+RCn2an)2MkuOM>lE}Z6X1COlP#JHzC5PhT zuB^;jU`fl|IuRegs3WWS%VeH?&92iNApx}lq@UszTvif!a4vDwZG%7Bw3zhvM;4`P znZ(0ZSF0UaWa--_Ef1Dzm88Ogw?Ep#9Q@IJs6)wWzJnB^P9>(#THmLN?m=c%(z1v% z`6!W*@RcPInO`kfWa{tlI?F9LnZ`MG_BxFkzf3R7!^n7xEgq^61{?LBjV#1eVWz$fJm07vp`lS_ER*; z9vPp_2HqlM8OF~fsk<;ftJ$gXA7yJryJq~b9E(9E(e6c6X)!Sxzi3PNkmBeG19>e% zcE81IQwGu}B6HoWt2+@1E-)HhE*g!<;9lG`$@UnU*7Bi&k+v_HjPOY*&)Ze5k!kK&Ic z=Y5iHeUMy#NrtuAb2!DXPC1zHds9wan{IuaGK}I6rsgfpu-a4W|1ZPZnAV@-&D~BU zd{sBS{KqYh{&trmakPLYX7G&KK&Ep2WoAL zBVRu?h_0!*6%;h+r8Y9F`9i{qqrY87r;^Cq(V;ZANtXl^(RETw&u<#t5k7c)Xi6h7EW$ zH@)rgH+_*59>4dbwl60BV>+@P8q=fcvx_hOgTHBqbf)Ik@b$&fl!27Z`XXPe zZ{1_WhZ^EHb<6N1)nY4FbA;=!$!g9gdZkoS*3x#-GP6cXXKmg5NE%ZWN6t-`>fbIX zNqwHyx0cgjfALf4Bte$cT8a^0rE5vcf@Pvhkg7@&yX%&%RB?0xb%R9~#?T)5>W zUtX|KPgjd0MM?~L3h~v&Ecg~jCtIS2pOVnY_@k2->t5b&CZ$SGJxijrUb>T4YpD5a zE?>@yjE`KLK0b2KViA3q+lu0dcs!-(=&F@K$t5aRCgeQ3xMfbdHlz|lvm@|qGE_-R zUAed?`sFBdk2aE7WycM0-ywPgxe)_3Bl{j#lzIv(o37LYe#e{~P`S8?sv-IPG{mrFV#Uu{)@3#Z?a-Ihj} zpFF*-h`nA+4ND@M1-%|}Y5&!wEU6TU>YKT1Q`JBfEY*ef75tAIc%4-De-04$bN#7? z`10OMx6Y%5s9TfrI?}BVlXj3Bz3b`oPP+AtXA1RrFQ*LtRl3!jno98{si}njDwR5~ z8&gyNo^HLKdaPwd(|k{)TPxG;o;eQ)#RvlrJgj`-pEAL z`I?`Pm5PU}S&L2*z?A*{O&9bde~hHacBRPoe!ggRxN*;Fo=Uu3TB2K3isHy2<0G}{ zg~!j$&RTMZsKq4dKed^;gp3wHmi;ekX8uIh-Mwa}l*&&uv5CzL&ts^Vil2Um)_aQ< zmmIlZaa*ZqR0uzd8o;+irKLV@(O;^%=}J3zE7g>#II$+j{f*WiP`+)VeEo_x~ab#rod@;qK7?GRX^qq|ZQV9@@%C zTGcXYk0)XK>+5K{jBH@H&r-Qq7p{kY4ub~jOR}1)No;J;P!jooN3>6oXUpEK?G%ym zG1LIaGTeiFHmZD5V^8C)tfkMh3q<|YEw#~5EW;mpu4x+$#lA_(T67AL`lH1(f-3IO z^!deESBxZ}=?fY&$%pKe&KNWG6U?QBMt#YtZJM?RncLp;fxEuw=vWrl-}y559|K!6dsddr+AsjD|LW(N;k5{C(pD!K$4_4Ij*($*QMjon{^GM zQZzeP0ZFOto8!1_Zr>Jn?b`D?P*LZ4Y0?qYyXNIRlxc-FkheXb+~=}PYish9>octt zp22^}wAwwX6#v+hO8D0v>P!}=q^`@fo=KrD^`jKu>zUT=sUgd{E-mllp4MAwl>LR> z@;3Ig{?Y9|YLl9KSS$UX2ssXz5c_bu{$+BBcL-Z?H^FV+8_6KP4rTN0@w z|MiF}N(s&gvsWEpP?#t!Il9om}+{fiNWeq*H7K<&$a9=LC(9)V5 z?w3Tq5$<0cNf{_2TqaZ&+Mx1gv=1%X(1IS%dyG~#Hr&@qs96)KjN!fKCa$9#5#<|5AT^QG99Cy7;{q8omLOblJDZMy?R3SpUH)G1aCvHL&h@=78D z50_;$?C^BKNH;i(t`S`~OjWNJUF#SW))poqd(oH95&b#z+nu>hgRdiS6 z*ZJLp{*)ncn@UJ^<>Z5H)g(krbH`KhK_3g_DcwZv0VLZrolrD3au}+cJMAu-gfx(g z!t~fSVdhMo_2sIwj`XrZ8_7XlN$%6!%X&X~N=K%(+B2BCV(O+T{-r0C@I@)q@hlUa z^%|^<%QCG$^&CNyW$u`N z$N%o*f167#k|XHY^>aj|9exkm|E-i9+Q*YcIXJeD zj|)m@AMYSQw2udiMC233G$kTZi1zVu?jG#+@muKo+jxCnr80M!RyCOVPSyIZ5Q*%m zi!mKL-b{CtNaxAA;wq6YF`pSCg~;dYqQCM(`}&Z$soK{~bV2I|d(lTuB!O}BvsgbW zUhFUOsrEa{eLU6TEUI=-(iFj58>eA$5#1_@%*{52#+2w>xa64d&A;GD66i+Vjf4p;Nnc-dkd-L>G^E?tvo)aaT|N2 zT0YTF$~t@ILi3rd=4**X%*|-tqNmkuH;ECkezj4J4C2Q>C6N;jr>QaNCdWZ3S&MF= zR7%x;V#)rGf(`3$SJJja$kFZbm0U>4Zp-KKg`o(* zFT1DyD%*Of2aRvG_88KXZC&4UHMIfPWzoGm`QMZL?-l;{4gb3`o0}9JaQvd)*;mgy zlfS3uol{`_wXt;Xt%tQo#rvdtzAkt^`DASUb0*nT`LBLvn$^s&N-&9fB6_Hzk;8EH zc;YJtVYu}-K?IK{t-G!lx|KItcez4kFMM3SoE`T2e9n0_$=kgL5dA2-E)O7L z<0+V&w!I`8Q&oU!J%nen@;zwfZEMThT0|Qw*AHku-$+h}^Z8pTiG98I>Q9^B9Iv!3 zWQ8Md!Ah{7k8RXCwOZK~ZP)iBbER$O0Ir8D^uQIIj zMp@R)NqIZdt<6dQqQZRJ)8~r}>r>B^e`Q$Dr40UihV@lSD#hs$E8$D|;p+9NsZV5B zFY?3HrZituhV@t)KNsB6E${XW>(=x>)aLTj)hqew>dpM`;S6ehcdCc2 zjijrlc?Wv379C45u1`&0(5xUpjGzJv&*aBg-H9mH(%&xT4q_T$xAcoviRM7RA@ii3 zUZ{aJJ=BT4uyf&Ftb>K3IVfbcWwzTk3Iwgy_Mw29NkgU+PrbQpJ4bOhI4|B;$*?`Db)j zkliN8D67m$y`MxqtbX^z;ZY)0_^jr4DcNIWiVmS^f|BQEtEUTBJR;nT_;)&O`T;xE zwL-!F(vI~DQImG(1tMPQaOqg-eKy+<+D;Qw3^9+AlasNcVl0&PLe-yJMQ5rCcYAi* z7)m7G572GL^+X`sjw>iuyml;4fvmQ-b-I|m5d@)pUgx)`I5&s|Vns~v6P+Q`Q~%wI zT+r^XXGINX#G@^l{=xVGXH5~IyUZWrxvU5RsX|lgf*&PW4qdQAPb#1t zYM}U*I@?RKU3vuTAjkotF1SHSF_XI1!H;HIFQunaoL&WkDkU}-Tehhc}XU1`S4F( zyA@Aczvh?A{;%OgbDM_=G3!#Tf^`(kI44_T!_AZxo~M-#d)DdGfT9aF{yu5L)V~ zgIWW7jzL%hyFn1a8rb~=ltgFH8$t`X58&s8v99M?AsOZkVz4h?jd2_7_aP2qoKH^= z#GqflqVMvGFR#+E#PN|Ku`db!{+~V(c<#S>BEY+R?cNI8??ej6F9~AL8-$-^xBXm? z*X`+K+gdR`hvzKE!u(+Gy@$Ds2kbF@V)KPIAwPDVLn_jIpqnut;CD)6>Gz&qpNaQL za9Z%1%lzSEF@JE{!J zQ|J}Dd(#H*>}kE3mP+w$X{m(oOrxROmuabQ^t2x8#?NND`TpF~`c3*m^5NfP9W$Xx92^XQXZd)>c?-}Xo^rae&T6NzjqYY`9r^pk&n zMdUWR=4aIO4eqP4;^%!<=%ujOcTsw075-?oH@&*1pWF(g(?%Zl-X5B_-rgf+A#Lv= z_rNNp`fAaKZ=Z#8{LzWjH<$KPAIP2KvMWm-DJPU-=WBn?c{%zxP2}KARN}q%B|9II zdS$Y8;yYA8v7qON^zHUCs;<1}S(*Qm_hxXH6j?EsAR(G^8uu=4Ny{zwQY|1%_@G?q z)|G|7X5sEoFIeekvi_*tZ6@{^6|E}rBOWRXH4~TL8LE!$UCmIulPP70GE%Slt4Cjg zgYJE$pNX@!=%*2`Rzm9@^gtaYv_ z!D5}jA6)@)k$aJW1PW~kRn9HqNksG-POM&gCYxwULStz#Qi4=bMPxs2=+p>r>0(=2|g;(yGUmhHBY_}iHODI-M>=Mf|gB%F6{ z;e7+L@Bt)!M-&^&snMJB7%eKsoW6B55GSLmfsK02{*qNZEQReP#Mm?b9sKro0m|V^ z`z9J6>1jZFTl*Hgx4M&iw>#eB=j=kG_6XkJ+P+cpwePo8QR{*vZ@0f8NtTK9ZDWo5 zHVbwCh+W)IOS~@!#wz_ba$y?vuSy<3lc?OEtmtc>!GAGDcX`eeC__$>g4&4 z(SOfiiht_qd;9*@l_{wdzdq$4qIoc7_^ta}@2AZFHT_Q=O!42P^^NRrJ(`wE@u$<6 z=8d%Bm+x;~({272`&rkd52pB<^uBHTS)0;RDc+XOG>bBZzq6mUB4hrm^uPOHiht0( z@0$IrNRL#CU)h6c?&>jo)qeDD-~5N^f6u`b|5aw+KkUb!B~bj)Os07$bNJ2sSuMTh zUrYb922=dWtiHe4k6-(v_@*qT`8q3i@qX6*+4H~bYu&%kV2W?vr|$=St#9^8rTAsN zndbMsbKmQ0{j>M{x9I=AgDJkaPu~~%S~vAcrTCqF#uCjZeU4q<*ZMF!$kNWrp9CbZ*i zxVq9i=_v1nirP`5P7^zk^N!u4M#+T_0|wZHS!}m|RO+veU-w?xFMa6L*o?vUK`{(zz&BRGli|uG;r< zr`O(+GOnOtly}hNskEbWqj%Vl5krO@liMh+d>8qK4apgHq(qfGdXr3qr1=xAB>DpI zz@FXGm(kL|L4@+bVITgN-z)pFQ)=>AiqaCa{7pQE80{&UX*O+H z9PLIyNt>JSS?GwgL8dL~LAM6d(NnF^@Sd)=zD2A9sW65~$Ms;kVO^jT`B!u?Jt_aT zp7D8FtZ1)^lilP=E@Zg{J;w4WzlX(ZZM=sChr{@v$kREQTn1h`)~kC{C~oH=pZJWI z44CEbWG%-_$L+nz;t^8#NRWSFo zwK9vI5|Or$^2%~cRN8~O8EK2PToT);l1{RdinNPW+9T7ukoNIZW>UoM7|UIy(spzy zzgvZ1GOI{y(eq6X$)?VZwt6y!1)r?ao}kk1iQKs=?Ny!HS(njT;ZwyVm+R{)(E+Kp z%Fq4O#LP55DMt5>rsGA$o4?JBD?{+DM>!)@XW6e)1Q9)yA^!37TyAA8slu;s?5>gs z9sFc34u|qT?O){AlZh?sI78i!^`+DgslL=p_ZO@CM^M}nc{tt914Gu3hIzBX6;tUP zu9xQ-IwpRiW(aSRZw;B+&|nQ=U`XJs2_y87^SILbP-U>8p{R6Z4L3Kg^H z;b&CTGzN)3@eXlr*%ZDZzIah3z7c`AADZAF!zs->lkyy_H%N1H;z{L5-i6rY%X+(! zj*RCkexhfWv}NK~5jv%{vnFYctbtKR#OHK^EaKQu*q4ige`R}L9)dh05O&X#$%@Ky zsBn>QV{J|K%wWwtb~RG~`@oR8iu&*nUoNI`A>9SZP?`Y5`&4JL^JF;|`-W@(S5vN{ zqS8qL_Ojt(qDHwJ9?-cfDpKkW+l4N}#bhR4o4{Emxw(N^6?MAYW%=-rHMtafJbCPg zqnycOHQA+Z`Ep`qTbN@i2gwue8H!6y;(dF1Wn~~Zw=!544p7Te6QuI)LMp8Pj^y#) z+f^a)sp5qUO)LVVIyp+&b+ULd!%&PgnAvhT%IQM7ctLTBNkO}vAID_zVjMg--pY=- z*<~se67#^}`TTo7@g0!^|IQO2>!H)CgQcfd#@E_}UZ9hz7;D&fRcm8P`HsssfAWnR zQEmm@dN6KwVm(-=S^n1C(LSz9a~XekO7A{*7o|tWSz1=Ky{Y!M=kKC;yo+#?x;NGS zw%lEm9ua44(c0`yt-m#U7qzuDVl{YgYW;1wyC|)VA(j5lY`w?qUDS@Z#_reit~Gs9 z>)q$>taL%*l*FDK4V@62vlqQ(_t`nC?91UktGc45dOl6PsQ1Y8({G>E1ZmWo1EW@J zNayzKDi>5@ST#wG7a1opMoW(!Xx+bVNT5DAoqx@>K0vc9`J1S60?3>K74`KM^RR=q zlZ`7m?d1HDK%k*cac^pTq*f6uY8G90Q8g!Nhm@+dr$e6?ywATWLI z+yMWgF#n)tb$DK2c8)cqGBj%z{iv@sgnj}uIAq*}$;XiMR?bxEgEInE_4K=xR151v zjdfzB=3D(+P76e0jmY3KMqTro7Kf#DTt$aksHVCD0;a!*uDhCEuVZ6+ey-Ei z^kUuKkk1?VcQt)E(Q-if57Tv5)6Wp8_Q!{X&QI59~(z z#SZEDH&?o9zhw^TdF|aye;{GJ+^&{nRVvyx$d1KF)Y7~S_NN$QYRT5dyPE!|l!D7> zPt)^yv6KGG3Flze&1?zV|H~*Q(yKLieWO)HOuLxrxlTCAU$4@OXQ?XACo}zhgy}K? zGHat^p#6~B56+AB=YEQqf2fM(=c;Rcs$`JDo$4&FBrV4^+@B&GPspb#5b-QjC#JKh z|3Q@4N&hL&%S5O@Kf5;d=Y4mbCp1ompCld^5v!de~prV zn2pGYp{B)~k~_(NL_LHqSLsUg*|0d zyhmcAiSn;@k-z+(GLc`UW%jaZ-|is)SO@u^YWar!E%DW)djCb` zflsFWd9!J!^3T~I6P3%8m_PU^Zsxx?C3dQRm)z@6{$4JAMPOkbS+yWiHrP&N`9+K&;G~X4x0AA zK*=|Yf2oqsV;&4<{eQ?s|9iWr|9vj{k9k!}ZB@cqf7;eALH~^|`X7=d6Yfg?1F4@D z{-@;V(-@V$Rs-s6+J8SvPbwsa*Cf=c?y&y+%CBkvu}Z#a|GT@W|D`VaukWJ%3taSX zbM*DnevZrXo88Ygl2oA!UM zi~3Jg>D6#cNu&4vx~TtnO6cT2W8RRgS`|n3pRsh9`d_HzoBE&2lPwCnvj4*>J)Pph zLY1E1wZovYWkdH?{S z@3&LRh^c=jrFYUleXFF$_Pc~2Q~#g3$ls~t-?t0-16<@URPtL@dbZyLI!yT!UF6@p zzfAbFO0Q35{>Qt>AG1xSP~E8Lze@=+BqfnW|MeCg*=5 z9j5%hEBU7X_dZyr-ffy7 zoBD?a%Ji4Zll|ZH|94#U7n2Q2#qWY*F!g`iMgKvc$yBKS6oO3skI!&!KM&%CEecEI z$^LKZzg(p^%xvAO()0VM7)<@?x2_%SKbL=Yhr&j%|Jih{*(vw5K626jm0=>e@Ov4P z|4scT6Mx1`{p)zJM}gl>#bD~s_BBWZ`4nClqcBJ*%>HvO9j5-bDftQh!-FLX7s!+S z-_*Y+&9j{J->K5`d$|}){ku_mC;b=pm6FDQ{uRW?)c;&1-_-x3d?|Gf3a7Z_8Uvqp z(ZB9wNwX{aKjET(EC0d>1+@P(x;FLi)6?1iL*qp9UD|)HN^knlPL-bDPsU){zk$*_ z*?;@tQvd6~|ECipQ-9jaMcCA||E1j7P`Fl}?Ej|ykD+-IV}_cR_cWR0FgvA;nEDT* z^iKLO%#o6GJ!Sttj}BA+Vi)j7b*zmp`Y%)I`JHeKrv9(F=wF^IC0(b+A*_Fh4paZ1^l~o$^L{R+78?p1msU`v zH_N~E9GPCcpDv@~zo~yYrFSa-&-_wSj!Mh=*VAF@f2E83jY_^6#wsp}>jz6*l6}sO={uBrKvmN9=OX=BCrv0RPs&#AEV??Qt9={t0U@sHqBF6e>44ZmEK&}Hq+nbl76E~ z&uumaFJ4gm05XV^{BpJMWZKV6KglKia+Q9dA7DA|c8Bs`NW9GQ|HwstdASt4EBWuc$oHQj>%U?n#$lH_$nQ-RoGCq0oc(`! zxr~mn5gG9s*O`>wDgU=A`F=&u{@+Z8ng2nQo-tGY#&QBFXnJ{-*#4ZM^*74TExpO_ zbQk@1D*bgmW&JM)eKbB-$v4Ysd%4v3D0#B~%TkdxXYdl0-X>6y-W4VyuXTET_g5;t zk$tP5N`G57O)1Z2{;zb&fBLCX(t27S;=uWj(xKDq{8RFTvLnc9ox%U@VG8;3h%OPnczh zr$0o)_L--*$yN-H*WYW?VZ*ab@g&f` zB_fXt`UN(K{k}&$xwCJH$Ol61F*Z2bj=@SJmHB4^MqV}@*_j7j?md-jfAUM)FYm>#I8AZmf)in1?W1S&k6Cw>dGUYc*Nhj zNbot)2IKjhWaAj|SYz-~#BUOOVt72ClN0C}@K^;2_&UKShR5?MN}!i~#wOq&2tF}9 zo{v9)Uh*k+!B2I;OI+{?2{=DjO%^N0^45Jo;jwoKh=I9+zSIVuwqtBJUU^Ln9t&$# z?7l~=bjGfA%wwIYqj6`C++`sS;|q^9NWaL4jAe z;FT^owwf^#k5v`BfSAXc4p*_L$EuE9K+GdnJ^)Zrk64k2$0t%bCc&x`&YwJSwKkT{ zBUT1t*E;60&ezenvq#Lt;~;V2v3Q0YAATeJDu(Of)ICDaW}A479piH0nQmh6h#6=+ z{j*9PO;?O6M76Hvqh_KC-1{a`#E>lfnjSU(ky$NIr|d?8-iagTMW9mj}A%s3E{ zagTLbB1niwjPMh0d8}U~f`Xn$#PQ)}vZv)R?s`q&-gsiV+NkJz8+W!UoVxS4@UFs# z#G#h8L*ZtN_=&>J8u_`x&76Is@CJjwN6Z8EwSH;f{A)X$-|G!r{xr4 zUMqO(Ckn4akm6p2Z#3{D6#j^TAFc3o!*IC@UuNJV6y9p!qZM9C;}i^q3g2$vrzm_7 z^SA3Qk^ivi7h=I>geAMd(Hn&=Ze`F&v5?1(^20mZm z>amG^ccH=$HSBYl!iO685``BT_*Dv@V&K;){5%8yox&Fw_{{=0K+^Urfg8plyiXcu zMf~GPT<}&I0cX6$_TeJLfM2Q9#=iPCD1b9v1h~aw>?%y zJfN;TR(BV?M*@C0nXEU=Pj$aDmhb^EKh>7~oeTac;j~1R5PDLUobX&1{8ShG8W;S2 z7yMxt{ACyXV;6iMT8MDc|5z8igzy0{f4oLnO%j93;r(`e4i|5J&$t1$GPAWT<}^KJnDj9>4M+qf`8(IA44r&_CgVzvO}^QO8ZU62eI?_#DD}!+L^#|7o?rW9tU`y`p_+;?f(| z2lV?Q=L)>SmaE@`xr1;geO9^PZwo%tY(AR*v9z?^8`c5zdma}E{5+ffFcn)ucz>8D z<|zEvF7$T_yvF9E--FmrxRd?|^sA&b-pK_1BbZH!uWot zyWhnTz}6(FLrllmE+B9}aYKl`y{UrBE_L>Xc21j8bh7b*6M3f_EI7#D!#ywTP3@d? z*h8K!+dDW(*u@SM>~9YHh{bKzl|Uo?wktHIXU5BN@&C9@*IXPlch_6FvD$I0oHk-h z$eW|TC)8Op?`C~5?kColJ=@mAVUriifW7rbpp(s9N(yKzjgkV|tFxqFDF35PAxjEq ztHqLn;ruU;|IwzEB?ZUvzmfdUCzFUYyon?sBB@WL@QK7ek~bs|n2+ z7YrBI(l$f1LCe_cV9m6mYNk4s$VL>+mAKkuPneT%pHFU^R8|?P3;J>k>VveEt%Qn7 zCzJ(7R4abI9DlH)PVIF{cVheeSiGMs?EzC=Nl63K8yW(YHPv(-pbd}etg8B8(3PUG zb`I_P=6bu+o0T=eirU1a4Pu*EQlYcELNmLxVta$`aYv~NBlnCEzM+NH4RxW0;JBL5 z)QXy-(l{&X?NqHmprV0P4F{?!s%sowo44e0*#JnEJP8}gyQ0 zU1S~1qPwYBE=P>7m>KLuZt3jOv9oE%$FhLquDN=%;@P}iF$qlAidO6rrhW9d;)W3K zuynk$G`z6Ve zi>q`6K2gzZ^^}p1(uPj_&T|3?9qdnoq)`wnfiyr{lDR8N~`2Vxty1r&ef72IygJdT(YQZ0}6300AXmIcEG4|^BUvZ1<- z%*`oksH~{t&3U1H=K%vG}2PYMzkxQ;|_Tf$WCI@yb*e9aWa23 zd7Of6d$J(WmFV1z^j9<#R5VVXp=zVlV%S*P8N0?VXG0He6LJE!K}78*J#9cWPI}kc zKpiiyGGirJV`t) z)7QBAG&Glb`FJNSt~FfL7>IRscUV=OhRM39f660q%%$2fpFx=GBhBJ8k(FIEomA6I zdNFXaYpL$e?YUW^T$!y{o%Q9J0*k6Uuk49Ug@Y6|R(IQ*ow_T%H9IyfWy9zfFD8`b z^Y9@svWyy$ig06nkcSW2UJ1XF;>*+7*T$ALf{m3(%mrUiLo=lbw23H+<~*yePIjD> zKBhrp4&!Zv+McESc7#=kH^ zdQsHJOljm3o|hk{0r=EL`n4IQsXb^rj!d;nE7=vY^X^6UVMMi9*RZ_p3^YV^ z*KQZPBvZ{x==8c;Yk9P*cC@t@-Dos8tsxYcAvS@gi^{nb0h%-NIFW*W{**%TTj=y@juX^@iGP}nDqM1O2%)cL({h~F$ELXZ;tRIj#@f2y^o10F#T54zx4gB|3xf~7ox)=ECH`dut*yh?k`bje5{FGJW zGbql1@j5y*uAc;QIo=2OJc@HL`7acx#F4*#1BmI*r$h6Gc{B z7)So}c-zKVXHBo4Uz+^06nzGr9{~DXg){x103QQ5+If<~S)T*w&~oW9tq3NcK?-O3 zARU_iSimt~d4M+n{TPLt`QmF1%%96z^Y4n?xIxwQZgwjm8V+o?d+5;gr!q)^y3c7Xll8KBqS?=ij#aP03^13s1F9GD() z{iYA&Yv|B+`%!;6p8V1N(hfiRkF>*oOZ|20M~j71rkx92@N)sj{8j^w z`3(b(`CSM&>iJ8+k^fDAqrW`_IP!TKaP+rzfTO>?1UT|}2XM68dw?T7?s037XK4LJH+J>V#J0pRFwivZ^~O8emrfaARN9>8&& zyc%#EA5LJ$q`)WC{|vy9{#?LuJXsAm^5OlzIq(VfUko_XUjsPO{~mCp&lKDx|5qrk z?QxWg9>vGZ*OR~>^Tl42%KNE1I4*`z- z<^sUq13rrYM?Y_I!LJ1z?fiSd-v|D;E1XYb0Dm6vBLIIx;cVv*0N7LH-aZF6Xq}S_*T#gseq3OpnF$Jc_c7C!zC64X< zIe?=+GXUR2am~LDaI_CUd*#4#aovD@l>_4+(xLfeKzq0i@B+ZG9he9>>RACe+N}z3 zq^|`W+uPZIBmH8)vAw+!aBOey037)|3OMTdB;ZK@GT>O>asG?#EzWJ6u^l)T z=+^BA7U(fwIA6wm z-3s)`|9-$RUoQfV?U?=@L^EHT6+Qdy$8_lO{S5eE{q-;d3Viy64o!aq;F|%*dG{8; z!$7|k@MgfVUA+@<949{kIOca1;ApqMDBR5NMxe+1wgZm&^{0~36!-UD%OjIM zHH{chVEZ8b!GQmZ?&*9TrEunRDBwQ8D*zt>cnI*50AB!jvBFuO`v9K=_-ep^4)_|t zrvr}kA;6J-KHx}yDd0%o0yvKMt^pkBmjjOc?{dLcxZtY+UjzAF4>;3^?{9 z?SLcwkK;-CTrVYwj81|5a~mDHUZ`!n1>OeuSwN5Vx*Bk7XK>tz^f+#O7x-TUe2`x6 zzsGvwc=C3j$MNL-fFqx$0Y^R80FLx;0*>u7jvH}2={9cU-z(<8`eS|3zkka(+Ib&t zkSH*Y#s=TlEQba{;dd>G&*zz4^ZWeVs122LZkk?9d-@q}Tg5viJ*t9>2~aMZIIaLiW(aHQA!Nt*e>aU@>9O?OYNI7u1AU%%vupRy`#(Ss_j`tA%81%&P{@L9`wnV;=Pd~ts{<|1Y zUPLPBavU$!N$~&wwDrjj&~ppu-#tm*U_aRk_)h@e2DtheGLc{G*M0`{Sg)r6z7qK0 zxD@I2^DnMh3(Acz#rS0D*#9SzXp60=yNaNm@gccBA>qkJ?0DF|3Uf*S`Tr{>jXk0+-_^I<$Wd104IW697j(`uUpKe@y{;?7wi`68o>GfFAoV z{d|h`M19=epZQqvG4)AT;|k`3`s@oh>VxAS)MqQuqaE;h&`Pl9zg+0QQaG!N{bLVS zkOH5ud~uwE<$EB|qdvHvhUGg{(X(6}58(4A>>p19{y5H=2{_hw{ylpRd}^aZ`_*c| zQO_3vN4vcOIMQzd{9WMR1~}4x2{_I-el_6R0RI!CXZj$C=ZC4~~0l0j~i4 z8v)00?}dQlxc4%JvpzWPy%O-%!2f!{*8qMq;7I>Rz>%K!cjv%zk^U*bk^awsBmE12 z<2dtGz>&|pfFqxOyWkywBcJZ+LVck>`eARtk^W%7QP0BxNBRMheM0+o4B#s%uKhe0 zaIAMD70!NmG0^*gejVVYfMfqP1#skF2{`s&GXY0CF9saPW7hzV{Feic`Mm{jr2nJB z&HQrP!h!t_^ZSfIC64*!F$@Q$NB;ayEClEI9Qm9A_)4HZ4REBN4mg%eBj7kr!1vA2|J~j< zy8`&2oqr8DjuUQFIG?gXfBoJ&C}$7n1z!T6 zb-)Lor(-*V^9a;uKQ;^nK5e2ym*ZgyXSp~I!S~j1TyY%m!Ewb{;8Owo#{-Vzhe?3r z_yONf!|_8U(Brsej>7qb_2Oc{u^;>e;8>3O_Ye3s(*G9dk^e1#BmKRABmEyy3N5~)NM~LJ62>E~L!hZnep99}U|M@oKgoVUQ``ZsSPPmSA;9%zKCJ751 z>*;NPqaE&1IMMx%27GxET~J{BOFFckuKyOVLw*ijtr)>co-%r~L_+!8y`Md`B zJ3#+A;Aqc6XrEE;X@H~L0N^NhA>b(YF2J!Le*$nU$G-r+67*jWIMU<$&p2Mf{tM|p z0zNoi!hQ$GOMSRtDVXJ}`yIwnPwaP4?ik>M{WX5)h2tfB{~6mu>|YR{0sPU<4S?f# zX}-eQEl#FG`=|b%i}8Vg-wk|lyriEeW)Llom-PE-jNb@+o&`QT0RJ1{Xtxc3<9O)} zz>yyN3&g(xdbEE=Dk(vMZ{v6g*V(Y29hxS{#d9!OHqd7c>8kzb0l?8eTU~H`&kE_g@}3pa<8wFEhkwV91KSzt zzX2TS2MFrK`u=Uk4;K?pZJ!@%{ID4E_2W9jkLwIL&cS{Y$2r)3{b!h(r(|yIztoK`NwqzY3Co;8KfQl8`l|{!Jq#Z#tDlczdR=Az~i)abm;NY zGYnE-9OvD=f7tHj_VJ&&V%!&=|GP-em{tIz7Xhf{h>+WY>qyl|DAx30{mg%gX<4ZDm;T| zas5H>tHbz>z~_13gX<431CDmv1URlgYy%wWaeWE#ZtSoW_=NWF4LGhp91J+l>stUv z{?`GH{($TMNPn}UXZv4Hhprb70H1Y$KMpvyC%FEP{GS8*O~B{yRJx$Rw~;;vaMXV| z;7EUh!dd?&I<)?$0zK+q1~}?}HsHv=3UJhaci&5oDn6_yuIDTR{3_fZvmgxK>rTlxPF4~H6i^MF7)`lB(5)I zrjalTtPk?<2RQQg0*>^90Y`ehj%V^8?Lx2Lt2gOS2YRfhKLdOX)%6dfR!+gJ{)e;XZIANBzbj9W=DT<=rCIQHXZOhEwb zss`i=X_y( z;kv-Vtm+EP5%7=M}P1Fj{b0%;GSsbA%L%>xX#y5z_DC#eu4d3 zDbVw`nVL^I;HiMm06YzFZlgGGIVJ%KwWt(&0a^Y_TH2=Q}RN|Q5=K)81avRQp^^DM=`S2K(1M^=;hsJpgmILEG zK<>W53>|K`@=>$ zv>h%4KIjkly)F8~EsEas2mG!9{o!%okN&U*aP)`g0OvZZ^?Vs{wA&jBXMNa*H9dZx zi{*~*eR0`odR%wS0=zdfroiQ%4LCku#`gbEphrD%{WTZT zt^_^Lb)laHIQoy$DDVmW2fvHKaydrPvp!4c(DnKR;Di1%4si6J zGXY2cnF=`i&v}5O|AYWXJud+q{pT{kkskM(MgO_cg&x1(LH~IY=+S>(037}2O~BEA zwkn+chx=%4=TCqh{U<$@h$!%F^dJ45j_E&xfFAv4DB$QnqX9?%84Ec2&ji5H&XX0+ z`n1rY^ED0V(SJgKqyJnCIQq{o07w713h>n+_gcVF&)We<|G67*q+bCz`p-JRk^W7< z(SNo9j{bx5S@fSYn8%_2==m)B&u5U|gMc3WM}H4)`cILfH~k0SCqe%?8~CIDQ~{3u zQwuoy&uqZaZVMF7`YeTf;dkHYKlt4@`p>PvAN>cv??(T54Cq&b+@}CXJ)Z|0{pV%C zk$x-S=szCfp#K~IIMNRW9Q|h~;OIZ&07w5R104P5EQPcG z@Y;p;pK72-|5*Sy`p;DgH~r_gK#%@&8{p_a4*-t-^Elw>KhFS;cKfr!S)XN)uUCK` z{bvi{=s%wTj{egDIQmaFHY5cuU-X}zfTNy=0FM517~n{s3po1EXuy%a6mayPDS)H@ z)BukDGZ%35pNkdFr?2VI{<9S5(SLpqIQq}S3OD^{CD5b){0(sQpACSc|7-*t{bxJi zXtx~-XMK3BN$2YupkD`gMt8cPz~zqqa{%DzKLY_r|2Z0P^dBGKsOJcUvs(MWIzTbd z-%Izj{uO}Z`syse(LRlUqudJ>&i07_|0vL-eQp4}H|TjQ;F#Z4F8E&oUjuSq0UY^k z104O~Uw|What~rkfy)u;_W>N~4*?wMeSjnVXuy&Fbik3m0&t{1A8@3<1aPFk5^$uy z5pblx4{)S^8gQh4-UZJT)|B?-HE`{R2Lj#)aJD-K_N!_-G(Ga^3-nCOfgtN_5tIK^ z^DOWH;A&bg)}OJyDD{Qh{eVBe%g2H1*G+V2eFiW{f%V-V=(7bX^?6Xm`P2_^{Y?!+ zUcetxaXt+KT(40xg#1@18a^TaR=~X~&i2_|{+#D4I3We(ufMTn9Q9=S-z$2)$AK@` zikST8RdFugR2Apb7!_w+4W$KA4!9ap353@)I554c%HsMF@n7OSRh&;-0Ph7jx4j&g zkG3sej{scz0ORF=>t|<-F9Cdi22^+i@B=hRXZ^h}%RLD2&w&15zz;?hXBg1y_d^)Z1AII1IS%j-0Urst{yvEL zi~?N0zrpwkfR9lPALAziUJST?_R6=zfS&~P%K#q(xc=^j`JW8E_X$VaMrC27@WZJ||Gug?c zO$$OG4LD8%WfephT-g zcjP&Ro~P3DG7HSJv%@2nBp^xU8Y0p*@uTU7IuVvvMah z+sRz*3y*E`Iho534sS2}YUChV zI_cnx&e%uxHXMAx8F`}o%7za$tZTSx-R_yQn?Ocp>ue?Dz`ybPDf;~hvP?geeU~>} z7D~U}&=E@i9_@S{?W}Mz@7H!-E$l=K4rYx5E5^Z!r?VC|K?FIsz;>R+%m*IV{zU8kpk4SDx$yJ?7q;Y_qte(x?7ZcmUU`|N z>*v_u-f;RIWta3I`j70&`cL~43g-a0u&V03zC?E{vN_Q`7>^B{*B9->E0S3M;aFEH zvNaj)uj&Cu==X)oLw%`OvM(BM?v2H}8xw-$2Y79Kft?j#;T_a$_u|qTR80Y-2PP>uyZO zy20MwXndeC+SL=wt9`nBu}n*yOr$*1SUNgBxE{){+!;NXS~~M9E6Yaq%^cZpFDu%5 zt}d|A?>T!K%TY?|1SexV=^r|o`ckM?rB|*yxNnz^>~_XxAc-@!SU<4IT94iYH!60w zHuk@0dTJ@OM} zPdApP%E*kFv+JSVoCL%m_XkR~lW7DejHg~2cFM{pv^EZ0n#I-in42t4=5K?qQSJPw62 zC(Z{#Co^m24jkH?43zJR3MfvW7<6_(3Z#v#8`oKahM9g!Mb#~oelk4P->>4UM&C{~ zhcbixtN|z?qs#}Snk6%3{;JWRgSym*LYWRw+G;Ab0&gF9GS~CJR*9CoRv;Y2l~k=I zvjW=aii+2kAVa1VURo<&I~!g?=_lBfaQan6eDGk=NtHXnuMZY2{86#>YS9wQdc9bc z?a?X^=Wpe4l*;3DqkX)Nl{T+^;A|4w2DA^TZmNwumvWrU+6pX_OH_@RxQ+am66w}P z>Md+=WzgU%LD=AzH|+XTw3o>=5YeXI`U5r*YA@%=_Hz0J?d4AJ;uA#+-z>J?DT0yc z;AGp&k(Up2X7674)cuu~kCRdTT8Fb|rJ7{zSy>9T8S3&YfZ+Vcf~QYC^)yF*>;TN) zJMby-^-6eeXm3+326}oYy<0^?nV=QUbe4v2ArYI~C{j(eY~=aMDb3fx$DN zCpsnT92n1?^oua0uiL$0=4?Hl2M!*%Kkzn>h#>61UiS>o;S6inq<3e<(!dU*XvIvZ zQ?oDJQ)F#{?0>3gD#X5Bqz6)Rft)OMg`23#DI#({vH?IUdgqoZ&J@enwG`|#!XwQ`S_y`7`S(W|`dPGmA z@-6VlYo6(?f4Qdj|HYaUNtkZXa%yeiPX6rH~>mn$AKTom*>UHhFu4q z6t4#!7Cpj&`=E#Hm_QpNaH7(CWA(qLps`t#?*nf_EXxp!M_Dn1k2Wwsg@7Y@ly|jmpxcM<3uwX z2|4dza|ej?0kn_OBSw00t5(QmT(rG4tZKlte?ZDpxgIQn7d792X9{FZ!Bo~G%6b&V zh02QK_-rb(knclC3*m72KB3vH9TVtFYx9e*5&E7z0zSDSjJrb--UP{{feD-Xk<$9R;0bCOtr6J(w(a- zy3VZw5w^E$TWM+6jHBbK2I{w1b&^LOJ|fgIzLv`z_!h) z=z4gjlKR=hG4<<1RX6n9R@M4}0jmmus>s@w8t4TB{?_b|B%zk-Ep>s~=E1(MRBxiM zJ+`?&4!=nRTiODV>Lo3SzQ#oVw&?nJEXUHGjP|AmLT%NNU@+KJ9o%A7C1deuo{E~@ z&Hdr(8Wzh#2@ZER(HY7r*dhun^_+Sj=d&&;9#ZvHlktrGFE>=UX zl2hB3O7`|`1VJreZ@y?S0yF7vO(wvm)HW8SjMy@f>XnD5dO}5JZWCB&SfYWdI>@|u z4Y>Fs;LnX=foeHwlaB+n62zfg`$e+_+x$?7Qtn`1ymwP9zAaZ*atg4ltNNqKR8_z) zd9u|ipY#wUH867L*PV%U*XpTID6rU=>jZiQPU%cVb(tJ_e)P=!ZTZh=A;?P+6IS0pyn z73)t$pwo!Qu%zER?Rh;#f!dltlh==;@4XM+D`O^hNnlY2{dWA`d*CSPK2(NR)34@# ziVPnW-4kcHv2X}2Y#1%Et=OaMX6`<0;>ed9HYe50YYtoN#92}DU_LN;<*t(luu9EK z>ViXhOGvO4#^aW@2u>@OG)KEqiR89Wdn8zwjHL#XeUVhK-5)Xf_yQjW{Gq;H+-1?b z9p*RSty)LzAb|l9I@9csF-hwuEiLCU_z;IL;r^<~%J3yC8p4stz~K5wD6)w*jYQz{ zTTRotx+p8XU~eRvOh&f>pl1S+wLFK*4JV6mT9rRK1Vn~{f%7Ag*44rG_A4UI9W9OR zp-WmK=q+!FM>yIZfubsh9_5dKRZmuqfUzkM+~UcGvt~8jgE|7m0V8qyWi&(2 zl`c=uOu~Ztt!DbJqj|Mot?VQRvEf8gJjbV6rUW-#4wLu|RguWXp`i#&hX)d{6RS71 zEwTlsdR>Xln_+{JRn?bB#i~}ebS#9b+_j1LV?B`#N!;61wK16(?8h&aKPudMtYsbV zBB7oz{FcLj-_on#Qr}YI>Ba8=4F<{I3Gb8TZ$)MZk{|aqPL^MN`y2cl4}-rGXfa6r zJ@7tR{YZ;J^7p~}Wcj&dC4c5H_=iwA1j*kG?~~O(jLZ-u|8?*_S^keI?tFgClgZC} zTh&?_@!(^Zh|4H_)@PwP5JQYU-Lv>)`Ed^|=J81Rah(J8m*6f_5m>*OuW~_y(OckB z{04qEy{k1sk!JFL4AR)Ag3Q`S%hFsAuszI#i_5cuh!4QiO@BRt5Y)P(j;gz<|EGYu z>0fh|W|I1`pE31s06lK{_mO_Jj;TedyQx14bZ+|hy68W_MgQ}pzgp$iUft zGSB*n2mj;5|E9sueEfWe_|5t=P8CwE%?cT2{(lMlZuxiA!lh-sNW577xSyQu=kmV< z>_l74dU_cNok#rqFsiwA5dd!beVv+v9%}q}A3&!55!P=A9wwn^w+v?ful3MB+^MYL z{cEC{qLTvI{}le;&M>_Adj)ZuWnoOtD*svj1zuZ`%I= z@gK_mhk?<}eqXQFFYU)M+O&V+GOVCw&-hyMMf|7of}s2}$Ln)*)zz^(irJPx&4 z)-3(V-i_*LZ6kiue|w1^f6J4>v_A#>ZvJ~9uDR|I_AdpT?qU;t$x#a zaer*N}cA`_{9x!Ql$29O7pA-{)b!Uv1~HtTPRM)BewU*k3xN z89Rv|?Oy?xY5$LaAFCP+LwR8h>1TRQG~d7Pp}&XpR}drWZ-R^Y8UH!u-}GN6={LVC zd?b$_7eYUeJ~jF8CjNFNq^Hk#zsG~$I$0BT8}ugsNzhNb=^rM3v;0i{RuBGh;-7yA z{b>(=^|1oHXB~q7N#eH+2iD`q4g_w0`pvR@9HHkp@Vm92VJiPlqQmkJ!)2ELFFf=Q zPg4JD9{TsW=x=e+fBdo9CbRxOK>FEU$_95U{A#TPek^~}e_s5iycNLj=D+%FS_QWg z^dFu_W`4$dNxxZ650m|8Ycbh7+KPdnN#fUN?*3!q&mlU-e2m{j{6_V$_7ndbhGW@& z=D)!s|7$4!`$;h7zXLAj=ltWEh@nD>ei1)bA>0A-Wiai>chh#He`C4k>c`Fz0`}u; z;WG6@_vNa;6Bm0STxWFHrhZLTct^S^)|&?lQ&1mNdY52ZMrMh|wrDbB@Yt&7H$Zr` z)k;@Bj@@aoz~#D{?Xm*CLD6IB=pfg@YztSC^1}=8S}gF}MY3&CXD%>|+T2MO;DwcU zIXJY)aQjzZ{`cM{>CG1Tl?1k^hxvG}-R0xCdYF&r+C@H|Yj^p0SiWZCwuK{pVX&>% zLJ$yJjj)ADwk2CtF5OlmQtlmNTfv`}OMi8Z!cQ*fDX%9Sxn#JJ@P!hDc!qG(qq_+2 zH0W<5JZ<2gCOm22|ETbj)P7Q#^f{uJ{XVAOL-@Ut7~)?f{80mci16J8{vU)tYv7L) z{v89~qj2a%jWAnHrc|Plg5}#*fFWRKXG8hPHna@4U;~F+uw7?zC?6J?T!LNr)vBm$ z3l=3@f}NdxDU9Oyy$3!Ivg$^^%mcp> z@VWf40+Medd;Z6R-Ufr+~0@u}1)Rv-3D8+F4?pWjoLE!0Q!$Mpizrr(XfMoBU3|=ZbNe*T099oZPs~ z>$)!kKBpMJEOg-cEmk!*`FIx44R7$kZ}7ms=z;&*1NTD}chl>5;KLsHEgtyi0G}o1 zA?%;o(1d1*`3A4YrWKwW?HT`-!WXkU_1=DXI~JzwbHsS$CyKd%&l2;E8p1!Q@Z5ZZ z*D;3yck{!I9{8gk`0thc+&tvFq_+Y-A>8CI1N?X~ZbC7s(BnbB%L9MF1AiLuxniC( zkK|8-PZu|P&H;RunE&uP-$oC5Tn~1WGwy-^)B~Rl--B*)?)1Q)@xZ6U`ly?nB_8+( zfY^;bhPcZxmGq#u+&1vhp7?j~97LYL_u%kDzCOJbmrqFWF^;?q>9FN6d)VSIPCU46 zXneOf1yWw*VTru63~n||uyN0ge8LTaF8Ysfhh_FWgPRRUDAQwmqML?8?4WdGIkL^E zli4C0ZiKCg;YK*y5pIODG2zAjF6zUb%`ztOy4qs10{g z>%3L_+v16>&{yRBE5BebQe6yW+5OzKPhA-ccp#v6Vz+g{NvuFM{69Q6f~KKhD{T9& z>xGTcN!XAY@H??+zgC7Rxoyt5Z0Fp3#N7zxs`|3JKuuFG{0qN<*vfcfeKa0y%`=BL zja!jObO26iq#_%ly>T~F)WIQ-?Y-KCpzQp{IQ%0+Jg?=cr*QK(_ET;e>3CJPHssvG zjX0Ofx>eClu?h6HZfR}af_-|#^*9-yE`mM!K@?iBGnsPll0e26a^MN6$lC6Bt83<( zbaJ7hkKo`Zt!kfS{f)2@NFhbY;K~ZKQE9nS@Q%*+d#W0|7Yw z(40(c?nrH@Q?;MDf~^;K;ZcPEp0dzGZTq(Vm~LJmz1klf=!*8^nJ&?s8Uy)4sMIIj zPi~oy&L;t-K`1L2cTo}9E`b#qk+AB-4Qst zGYGrTUAM5i)yntie3zT*qjRvzUDMGx(d4E{9b>{SuAniy_6blgRnsn@KI}6|k+pqW zH&eCd+EWdugY#=nsL!Z3x@W;k4BdR4?%&~L5S&VlLA&gN>MKW{Tr(&bcHDEIGH2Fv zx5ik&?sZxNoR0De&T0n&(3|j)Fzr+|*fOMglo0%9k0|EK)h;=Rp#P8L^p!R*JH)GE zL>J~f=U(2EJxE2_U!(^zKB!)(hC4Weuo}Oa@~VLDo7Ln5{c6y=dyRYfT2olC7qXf= zP{u=|9uQrNt+ zU`OUEMjx^C zU_Rh%RBBs83jVFY`a$|X3F!C05;j^EKz^@O*PKXp#UOu1zOtt_+iJitS2ZxIbq^#W zJ?g+BymSpkBQTK|>P_YLlfd$^wGOV|!GF}kP)F-Mh~v=%#(Blwr2mMZ$2Cr-AM?O@ zMb4DN>#ru>Ddb3dMg=bQ^13z3k+@&b%lvxf>q*P#O9O>i;&wHhwSFSk=u{!XGd<$qk@ zK_UMx5BZ-H^wR$O1TO9WlE7C$obCTA;pm_B0zcaI5SF)9K)svbVtaT83*uN7jK5p< zaQ}w>m+j&*c*kJsU7%rw{~g5Ho~s0oeG%jR0v{0gzX)8?KOk_dV=U((flK`x<`^ghU{k%coa(*=|aIBLUupP;9uuY*FAAvZ_m)|wA z{o))91ImfQ#q`%B2m$dOa4~)hf)LRDPPiEVG{i9=J<4Q!FM<$?;i`s<@$VoA0dd*B zexOi|uY@?$%kdHGHsik*^iuxs1TN*<)Q(WEY`-%^`;zi21TN=4K7q^jh;tYW=m+U% zIgh##(%60<#4(ukXK7gZ8NZ2`o_A;O)Z3N0+(2L&$u{}|z@SNeaqpqKsUw*vD^`YM6Ta>Tr2K>H;!=290StJ{L1o`{`|J0)^<7&XE`quj&cSB{<^?FA@Fwuew)A#3S8L_Z+)&JnnjQzLL$f9eD->FWh9>q)D?rQg;FT-K9LflK)t3CH?_Yf9|TgrJx8 z=Q@GQ`ZGp2`UkeWW#!y2=x-PJLjsrW_fdgMJ0BPFFA{S03VP}P?+aYY`Gvrx|9>TL zN&j1cOaGT)Mj@E>_5^`T|DP&wDId>qU_k$00~h=MY(X#mzf|DT{|@2!kpAxx^wR(R z0+;^B^CK8AU((KN2*(Gm;jo<?mCF%cpgrl9(|K|u?`rj{bY3C9lKMbP8tdg=e42weJqzrdxPuM>{-M9#-l1q2MsH!AF}KmYDS^xR1G&FoK3t}x=yJaU;_T;HgkyQ(8YAO#2}d=b5;(yYcK7G;3p~pyj`#+F z^Slx9K7sovj`&7_R|>pG;8H%WyK<27;|#*nNAbzZXI7-&&M)xvQ5@^lREp!Hp5lm? zP#hm@1LCCuzmwvKA0zOm1%8~s-x4_I9iehG5CY0MLB;eZslUD^)c&0 zE4pgcidBn4b29I-I#T_E=`EqozP`a^XSR26Ak@>@+n4IL=42Y@WST5cHGeE)U6;uu zdi#e4)7iv8XMal72YR!KOe&d34i02fH)J(<{cvwORfcu| z^Sjly^QJxeV(l>k@>Xsldyeh=hHDR#Ex8n&JwnZP;Zn|=Uvg7;f*X%NMIa^O7r7?# zsmR*MnwayaAJhRO{!9%a>zuWBIvsaRM)wdkceZmAwi6u>j&(rT4@ls{R!ylb<~$Z0 zYXfZOqvP?yH0l>~ei3(G*+*m#QimTTU#5OlCT-!Wl?C10~Ae|QQh?!2MtYh3Qm z^LFwu7{sc64$eHF{O}zv`)X)c#y)!ijl&+@zwX+|XCvz)pNk~cKibnAoIOSZqd|IP zL#P&iTC$^iaudPaxzP6b?RMc4#FLdO-t(7Jr^mn*4q5i2!KT~>6oO5KAJh&wOGofnvpJ+x0h<kvKgD`zv7L0CJ-MWo z+U-el7i3H7bskcA^r+66pOWT8kJ@=&4R&E!tz8&CY8SR0jytJicD{~DlsjKsVPvsM z4wCS~77R)HU%msgrk1!Gq4S6mmzz+Q$nJ4_iE&~9A5?Vk-{W_awknDE(rAxfWo6HT zmPf-++RihIespWCm7Qf5G8n?PqngLodOLS2J4@9j+mto(TSH}Nh$K`P+=k2wdlBad#|Yh`D~ z5w>)QxAWU}lU=7VVMp%u;MfX^w%hmb2IIJMLdL0aJ3kDKU&>8Hg10?pgE&_W;%NBw z$mrWu!*|CE!{f31!f5yq4eJo8TSxkp^wwI(oj*VU*lnDeSv0$AF!yI7FGMFGX&fAw zXo84r=MgNo8?YKnVblX8Id!C(tfZEZ?$x&cp!u(Du#+}y*-s$#-wenmm zw;6YF%~kv{R=4u=VMIo?DZ<%z+ev8XM0XXNm;m0fZ7+9)Wn<3LkfAO9R<%#{Q^*L8 z{S$PLI?csfnW`Pz@6q|Mx3=_LbWPm`D^O2 zv(N~%i4N3ME2}HJU;&GpCcp*ivH_xdQYNH3Q1#W5M3 zpe~s7gPgmI#hz>n5z>)+E?(&0m7N(GxuO9}<}P6HD7eBryRa61M_z@<9(P`4ZF3XD z*IF64WPQJ9VWCcjNh0o%DPWYj5sh6yUfFWRnVM4c-diW@wp zKVFpfjybQ<5$k7c^6f9K!#Yz|&+U2z8#_|Bov)eGNP|Rl4o}#Vx!t-2#XY8&JB8X_ zT`R@h5OL_py+o6-&BA0{Lh&p2Ty_9^G4VM-@*bj6JU^GG46+MQ$Z z!nY>Sj#YaHvOIss3fpR&9Ki?pyNbJF7mhpMB4%8*M<;5~iv|K7kN7&-VDup#B*i}0DKMVk7~&2_(s8ico_8jj3;qzy{gBY@ z`^l`rImYt^(&pV=W8B?$9-y%s6)`9pq@842=ph#G<<&m|iDXhzQyT>#OSsHs@P|rq z#Q4j?DgMH2h%G+}$ma@rgh{0{g9Dw}lzJLrGHdx@sB<{GG11+b?F?=1>>EyndIv)3 z)b+!uOg7Y$9_$Y#`+8FYSw*haKTi8G=WXMSkKC7U^tVJTAjm?T-QgNNJ!Tk zb>5=$MU=PRa(yfM+6s#v*7*_2c~FRU!Q5QslEJZ;0h0?MRv>`vQ4~(}ux$=V!#Ehd zib=rn=t$Y|D0^kT15XX*E1mnh%bcBL2PEL&v$7N`=xEW3`O4JWg|-ldMFgh`8=h0s z5ZOn@*oWzH9RW^<0Fj%92H}t37P1Sg>&*UX+(uJ>0My#AD*8ci>^x9Ju*H(Rsp=xG zArzFXvJB5j{YS`RI6eZd^T?yUYh-I{71XMY7nape*~K5!LyDe*%|0@Ew3;oav>oe0 z?{_tB@!#0@vF}x$1sKPj2%{ZMNNy1Qcz5p6@w#$ps8h&E*c(@#aNS&b#llr7La82Enm=@n91#+{*{CLjMFDsxEve?)=_7 zeX+}AyYl=vsh1;;d*a;TPGtCLZ0-}-kea}gj$I{V@JhWg0C@X;Qn|EP=^>l_B#z@k ztZ; zAcm(DM3ujo-oze{30YuD0OlwX+&PJpMR4aM?aoP@JU?`J3?^Cy6OBDdgzCvXI(8~J z_CIXU;SpjngRII*;vpq_Ce;uf7;sy{Pm>Sa_Na1^v0vjftKtI!+=N|t$UQ9=A3+nI z<8e^WLTJ6%6^I$lpoFLU-RAdco& z*CSeE6XETs9x|{Gn+GxHnYh!}P;0x-VK2~mmA5cVU5L5q?WUF79P5Q1^TuLt(do-Q z%)X3ugM+iWJ1Kq~jmpkG_M(U1h;x2Ju?v)H-&{ZL957EwrCwMEWrqG|bc9Ek=M!TQ z?Pk#8H%wl9%C!$ayXcD`xM{J77IDAk8p3^&E_CcN*1+*nZ@oBJzEHMCRfO757NK-} z(pMyIgerdeO&a6~8D7y-DB~kWv5A{#9>p`(cUXC*r}Z*5G6r+c{+Z6%Da5WXG?WFe z7A#&o^C_d{+gcF3LRK-xV%phu&dxq8OeV;4vAB~bf#oT9k?O8=vYi9Me3#R_OJ%3* zqwBpJ>oFESM#C>3X9^AKh_ek&{0A1Q?7AY4NqEOoSn)Mh?yrm zpkX-|zsFKa!J*__YLvW$vvuZ}1lKBlmAZ&Q9)FgV$5$phh%0=$giqo&K4a107^mM} zydh9qUQM*UoyOJ7KY^G&3f@C8; zlzJq6yb#z?GdeBMz@+UUwTSm^M2Pe}eHpn+b_Ci-YpU~#=_bme=+FR?{X~ZZ7c0?2 z&+4s2WzXDzZ{qtRwIf}G&8EcnD}hfcrJ?gIR-_GliT-@j6=^`~?2fU0bb9p4x^gt>ue^X=I-89S)JBXDxDroOQJ!ntn^fP%8HU6EoAu7CHqpH z15%D3AuplRV5pbkX;AW_F0;y_cT_~j5?-tC#9q_A`^aQ)GI}HuJ;MXZM51}&f`tp9 zj+!%pE|^ydop)I!^pg3N(3XW2&`U47q!PLi(vpMy{dA?!JTRC|H7{Mh_To&oGr0-m zg8gp)`w6cj6#J>t+FD@-u@S&trnlZwm-!m z;&}-^GPUZ;A0>#gk#BOMqwxPbK-Zw@~7JLlybkD}Nc#O7dIv#xtV%kbDYpUisujmE^bT3E_PRG$wiFZ$LvO z`4g9^9uq3#y=?}{Uin`DR!ROI&6M{x&4V(p{LcfcB!6VF>U2b9ET8rtul#=pR!ROY znk*#VD^-!dz4GZwzLNZPV zY0pGz#0R(0Q{=w}tdjf@nk*#V(^Zkbz4A{0tt5Z%m8#PsVva=e{|+DT_-CWNlKd0z zpNF(g@BM&`d=o!z@{!-F4aMi5caXouNB+?^)hUE_N{#rC zOt1W}`^aBOlTGv#bVTyb-#tF^t*GiWt_@4_&&9_p|3_NBHj^u9gEo*?p0|F~r~i=d ze}T(U6};in!D(6kL0H1)$ zaoQ8B1uoB90ZVU!q6@i2wZP^1C}7bEqdd`^S6Lr+LAf3Rmfj@XR#gb_PF)VpL$!)e z+X^q|ql2yJ5@Gs~i^w<-uxKYNPb*NZvPx9t{NGnjtZM;_cBJyO9@Q%AgDzOk$9TQl z%!L3)_Ht|!s#R90w<&F5+}ya7@23IxCZ?QMK=6?*0ikC(Ua~_u9+FkJ91!#3f+z&U zyqDt*vg(!t93k8)7rxBjQ~i90#=V^A4`^uRUBr3m>vk^IO!3gKY217M*`@I%oR_}t z)i}+MOyA^6jdhI#QU12Z>6|aqcezqysqvLs_Gx^)1aawM{+{ZGk7@e5J@k)jdL0Jc z*8kP?-*FLDcuM1kJov9Q{)`8wYQXx)6!iaqoGs#yttpNn_nsZ7=`TKb5COCj{ri1z zdeL2pzR?Gt>w{nEgVQ;+68~-=e3K8p75Lf03(fQ09X|AT`QZ2a;Eyu@Qe6E885!xf zKJ+Jj@EO=tD~Da<6+4Ec<{0bku!w28!gKq(TwtL#LEb~0{FFy3U znVz0BR5H&mkNMC)<%7TAgTLy7zu|+^JLQUY^TESD_+lS?l@H$KgKzf1Z}GwJ^1<)( z!N2W;@Attiyzl2X{kTGJPV%31sf%=ZdtSQCy%g80qJ}HjQf&dQX+;fJxuS;aUQxr9 zu&B|salEaCzHp@*Z^I34ybbsJ@iyEB$J;KYFWdmf+n5el-tjhE9)pCtgqbqTJ;U4~ ztQc^=@B)ip79^I&S1gId6DzL1dUbS7VohX8Jeq(K80^4c!u&$V!r!pbTZGgNc)ONJ z45fPqvOS69#!Xg|f5rnWGayiU?_hp{gDd9ju=Gfrr3QFD2Iz-5>CL@K{fBiVRQ_PdkB_>}XBD9jUN3roP-N8PpB?q2Q>k}; z8_071svjnG!59nXC%RKf{DFz3YpDUQVW0!ap)J0m#SfZv(Qmx&@13}SnW8&?n!E)4 z?rN$4`F3RK>eY$1#PT(XwX37663ZhU(bM<~M`aN4Q!1B>y<+v6C6U$9_5|2{D%LiY zo3A>hSu@i^FN%H1`6UzoB#Yd}{cRW{L!D_jA*$OIO%Hve)7Ex zZ3d_3OiDygSKkJw=SE7{miZm9!IvocNOthW=JT{|SMs z^SzQwSHyANFWl?Q(uGML?9C3QvdrHRsKxR zc83020{@V})pMqzpDys93VJy&($3Nj=WBY>XQ|-RB5-=vGy0J4Q6l;nJ_cVyAd(k1 z&(q%V<`p@wU#X}0+Yh3bdbVqNFaP@mPHWld^N7aDADRSyNZ=uXOS?&X(qEiYBDr!s zzQyR&@qS+TPaHHxAGt0%1pb7em;9d>xU@gr%TuCp(H*kk|F*zG0%W zEyu_3p+9(}L^$1@89XjJbpDplL1TO77UHF^yhdBb5{xDzQQctrVk^a&jlA7LYXSq*F zJ9lY4y>`392RG}N=%qhAE9l!$HujPGDa9^>f6`}Mj?n*NK`-~s4+{KW1--QM_XU4x z=VJnwc78+P(#|u^wQ3A1-=%2j2*JX9Etc#yWP&{RQzs@&p=Lh zrH0S<1ijn`4{DsmHwyYE1b%_Qe=cxoPw9v21ihR`x!${kJwGkzM+GkZ_InzqaeYS6 z)2{?5k$vR2>V!S7MVqn19F0@fEbxyDT#nb=Q&F=VFTIzfMA=+?4F9zPmwY}eaLLEK ze<%H=eQp)>bOtc|cM4qczf<6n|9=YnLcvGIbLofYgN736vlJgA*Y6zCPQ*xF{mBO? z5xyQD!>5lxBrkrWf*F@_b=(Ix=QQFY>Hph@{&9gzzdEjQGLy8=p9HF5G zx#G(jC;sxBV8%r_+1%J?r=XuMaQR##$tNqv?HT-eDU0O#;7A;6oZGePrBF{~sNtr;HEx3HnyS zXP?03`u(NADV7?2UKRKvfu9t3zrasvoa{4C;4{uZ1&MHJ=X!z5@m`>D?|7Sh=$n1$ z7yHm(3`omv*iuVMty(hZt4!rMoghJSh<$-IeQR|26Z=Aim6bp75ClM1D}037;kK69PX= i;2|B)iM~$YD+PYGz()iw-@boW;2#k5zY=)8!2ciIXxHEX literal 0 HcmV?d00001 diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o new file mode 100644 index 0000000000000000000000000000000000000000..bd3b5c200e2c35bd962ff105477e09423c49beb3 GIT binary patch literal 2720 zcmbtV%}*0i5PxM65CsczFk)gkiAFY*G{zWXT58KCHqZ#DK}jiPl>|yjyH(^MhbG3x z3rDa130^#tXrljxTue0a;>|=8oZs6w-IwJx5S?V-%>3r-eeUdJa@meZL@-6fEfHvp z3X$&!>ok8mjUPSVU~n2Adz|K% zhl}5(+fng)u4Bnl>GX}*==^eh!>h*<_H{ckHc^*a{6#!rk0&nss7f}Zcx3yoh-^h8 z!>7A@c4Y7`b^-X_$|1<7U@PHvf zQeoI@&>($h=<9?+#C(`!+}|#M8abM*i{ZOILPlVg?nLr&<1djf=J>Diaf&s~KTkM_ z@29T`5oJN~tHgOPbkpaPzIIN5*gw2f-cQEw5N4{+M=S5P$^jOxpC!yxe_z!fSFxzy zO<%aaOPHztu8KQq{Y&I$svqt36Yx4wA5#j~-yuw%zxKaFh#4tZ$RaRDV>} z*Vm8#X1M+v!cd?6NR+g%_!Y&O!575*ttLx@8hY752MxaO6&6~)h^qLlP(06{;ddmM z*8f1Q-%*bIemS1c1#dt6b`bJP)&Hd8nT3}HJv?{#=5g7GeyM=7B=^x5u8%ums_&@# zi~FHdxV~=FW%zZ9p9ea|vSpkx=3$x%aMKP0m%W$MwzwrdN_rAA0yg4W6B3T*pvtVwLxtk_&>Hl zxG8^8`l~}Hndh_F1{cp{7q&|!5$ef>soczDDp#1vW@j^Vg}KyZE>j?u1YA8;ss9C?`PYm9 literal 0 HcmV?d00001 diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile new file mode 100644 index 0000000..69e964f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile @@ -0,0 +1,6 @@ +# This file is generated by gyp; do not edit. + +export builddir_name ?= ./build/. +.PHONY: all +all: + $(MAKE) kerberos diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi new file mode 100644 index 0000000..e8ac042 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi @@ -0,0 +1,138 @@ +# Do not edit. File was generated by node-gyp's "configure" step +{ + "target_defaults": { + "cflags": [], + "default_configuration": "Release", + "defines": [], + "include_dirs": [], + "libraries": [] + }, + "variables": { + "clang": 0, + "gcc_version": 44, + "host_arch": "x64", + "icu_data_file": "icudt54l.dat", + "icu_data_in": "../../deps/icu/source/data/in/icudt54l.dat", + "icu_endianness": "l", + "icu_gyp_path": "tools/icu/icu-generic.gyp", + "icu_locales": "en,root", + "icu_path": "./deps/icu", + "icu_small": "true", + "icu_ver_major": "54", + "node_install_npm": "true", + "node_prefix": "/", + "node_shared_cares": "false", + "node_shared_http_parser": "false", + "node_shared_libuv": "false", + "node_shared_openssl": "false", + "node_shared_v8": "false", + "node_shared_zlib": "false", + "node_tag": "", + "node_use_dtrace": "false", + "node_use_etw": "false", + "node_use_mdb": "false", + "node_use_openssl": "true", + "node_use_perfctr": "false", + "openssl_no_asm": 0, + "python": "/data/opt/bin/python", + "target_arch": "x64", + "uv_library": "static_library", + "uv_parent_path": "/deps/uv/", + "uv_use_dtrace": "false", + "v8_enable_gdbjit": 0, + "v8_enable_i18n_support": 1, + "v8_no_strict_aliasing": 1, + "v8_optimized_debug": 0, + "v8_random_seed": 0, + "v8_use_snapshot": "false", + "want_separate_host_toolset": 0, + "nodedir": "/home/fmason/.node-gyp/0.12.7", + "copy_dev_lib": "true", + "standalone_static_library": 1, + "cache_lock_stale": "60000", + "sign_git_tag": "", + "user_agent": "npm/2.11.3 node/v0.12.7 linux x64", + "always_auth": "", + "bin_links": "true", + "key": "", + "description": "true", + "fetch_retries": "2", + "heading": "npm", + "if_present": "", + "init_version": "1.0.0", + "user": "", + "force": "", + "cache_min": "10", + "init_license": "ISC", + "editor": "vi", + "rollback": "true", + "tag_version_prefix": "v", + "cache_max": "Infinity", + "userconfig": "/home/fmason/.npmrc", + "engine_strict": "", + "init_author_name": "", + "init_author_url": "", + "tmp": "/tmp", + "depth": "Infinity", + "save_dev": "", + "usage": "", + "cafile": "", + "https_proxy": "", + "onload_script": "", + "rebuild_bundle": "true", + "save_bundle": "", + "shell": "/bin/bash", + "prefix": "/usr/local", + "browser": "", + "cache_lock_wait": "10000", + "registry": "https://registry.npmjs.org/", + "save_optional": "", + "scope": "", + "searchopts": "", + "versions": "", + "cache": "/home/fmason/.npm", + "ignore_scripts": "", + "searchsort": "name", + "version": "", + "local_address": "", + "viewer": "man", + "color": "true", + "fetch_retry_mintimeout": "10000", + "umask": "0002", + "fetch_retry_maxtimeout": "60000", + "message": "%s", + "ca": "", + "cert": "", + "global": "", + "link": "", + "access": "", + "save": "", + "unicode": "true", + "long": "", + "production": "", + "unsafe_perm": "true", + "node_version": "0.12.7", + "tag": "latest", + "git_tag_version": "true", + "shrinkwrap": "true", + "fetch_retry_factor": "10", + "npat": "", + "proprietary_attribs": "true", + "save_exact": "", + "strict_ssl": "true", + "dev": "", + "globalconfig": "/usr/local/etc/npmrc", + "init_module": "/home/fmason/.npm-init.js", + "parseable": "", + "globalignorefile": "/usr/local/etc/npmignore", + "cache_lock_retries": "10", + "save_prefix": "^", + "group": "1002", + "init_author_email": "", + "searchexclude": "", + "git": "git", + "optional": "true", + "json": "", + "spin": "true" + } +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk new file mode 100644 index 0000000..36824f0 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk @@ -0,0 +1,151 @@ +# This file is generated by gyp; do not edit. + +TOOLSET := target +TARGET := kerberos +DEFS_Debug := \ + '-DNODE_GYP_MODULE_NAME=kerberos' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-DBUILDING_NODE_EXTENSION' \ + '-DDEBUG' \ + '-D_DEBUG' + +# Flags passed to all source files. +CFLAGS_Debug := \ + -fPIC \ + -pthread \ + -Wall \ + -Wextra \ + -Wno-unused-parameter \ + -m64 \ + -g \ + -O0 + +# Flags passed to only C files. +CFLAGS_C_Debug := + +# Flags passed to only C++ files. +CFLAGS_CC_Debug := \ + -fno-rtti + +INCS_Debug := \ + -I/home/fmason/.node-gyp/0.12.7/src \ + -I/home/fmason/.node-gyp/0.12.7/deps/uv/include \ + -I/home/fmason/.node-gyp/0.12.7/deps/v8/include \ + -I$(srcdir)/node_modules/nan \ + -I/usr/include/mit-krb5 + +DEFS_Release := \ + '-DNODE_GYP_MODULE_NAME=kerberos' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-DBUILDING_NODE_EXTENSION' + +# Flags passed to all source files. +CFLAGS_Release := \ + -fPIC \ + -pthread \ + -Wall \ + -Wextra \ + -Wno-unused-parameter \ + -m64 \ + -O3 \ + -ffunction-sections \ + -fdata-sections \ + -fno-tree-vrp \ + -fno-tree-sink \ + -fno-omit-frame-pointer + +# Flags passed to only C files. +CFLAGS_C_Release := + +# Flags passed to only C++ files. +CFLAGS_CC_Release := \ + -fno-rtti + +INCS_Release := \ + -I/home/fmason/.node-gyp/0.12.7/src \ + -I/home/fmason/.node-gyp/0.12.7/deps/uv/include \ + -I/home/fmason/.node-gyp/0.12.7/deps/v8/include \ + -I$(srcdir)/node_modules/nan \ + -I/usr/include/mit-krb5 + +OBJS := \ + $(obj).target/$(TARGET)/lib/kerberos.o \ + $(obj).target/$(TARGET)/lib/worker.o \ + $(obj).target/$(TARGET)/lib/kerberosgss.o \ + $(obj).target/$(TARGET)/lib/base64.o \ + $(obj).target/$(TARGET)/lib/kerberos_context.o + +# Add to the list of files we specially track dependencies for. +all_deps += $(OBJS) + +# CFLAGS et al overrides must be target-local. +# See "Target-specific Variable Values" in the GNU Make manual. +$(OBJS): TOOLSET := $(TOOLSET) +$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) +$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) + +# Suffix rules, putting all outputs into $(obj). + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# Try building from generated source, too. + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) + +$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# End of this set of suffix rules +### Rules for final target. +LDFLAGS_Debug := \ + -pthread \ + -rdynamic \ + -m64 + +LDFLAGS_Release := \ + -pthread \ + -rdynamic \ + -m64 + +LIBS := \ + -lkrb5 \ + -lgssapi_krb5 + +$(obj).target/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) +$(obj).target/kerberos.node: LIBS := $(LIBS) +$(obj).target/kerberos.node: TOOLSET := $(TOOLSET) +$(obj).target/kerberos.node: $(OBJS) FORCE_DO_CMD + $(call do_cmd,solink_module) + +all_deps += $(obj).target/kerberos.node +# Add target alias +.PHONY: kerberos +kerberos: $(builddir)/kerberos.node + +# Copy this to the executable output path. +$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) +$(builddir)/kerberos.node: $(obj).target/kerberos.node FORCE_DO_CMD + $(call do_cmd,copy) + +all_deps += $(builddir)/kerberos.node +# Short alias for building this executable. +.PHONY: kerberos.node +kerberos.node: $(obj).target/kerberos.node $(builddir)/kerberos.node + +# Add executable to "all" target. +.PHONY: all +all: $(builddir)/kerberos.node + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log new file mode 100644 index 0000000..5679d63 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log @@ -0,0 +1,25 @@ +../lib/kerberos.cc:848:43: error: no viable conversion from 'Handle' to 'Local' + Local info[2] = { Nan::Null(), result}; + ^~~~~~ +/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:269:26: note: candidate constructor (the implicit copy constructor) not viable: cannot bind base class object of type 'Handle' to derived class reference 'const v8::Local &' for 1st argument +template class Local : public Handle { + ^ +/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:272:29: note: candidate template ignored: could not match 'Local' against 'Handle' + template inline Local(Local that) + ^ +/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:281:29: note: candidate template ignored: could not match 'S *' against 'Handle' + template inline Local(S* that) : Handle(that) { } + ^ +1 error generated. +make: *** [Release/obj.target/kerberos/lib/kerberos.o] Error 1 +gyp ERR! build error +gyp ERR! stack Error: `make` failed with exit code: 2 +gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23) +gyp ERR! stack at ChildProcess.emit (events.js:98:17) +gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:820:12) +gyp ERR! System Darwin 14.3.0 +gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" +gyp ERR! cwd /Users/christkv/coding/projects/kerberos +gyp ERR! node -v v0.10.35 +gyp ERR! node-gyp -v v1.0.1 +gyp ERR! not ok diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js new file mode 100644 index 0000000..b8c8532 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js @@ -0,0 +1,6 @@ +// Get the Kerberos library +module.exports = require('./lib/kerberos'); +// Set up the auth processes +module.exports['processes'] = { + MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js new file mode 100644 index 0000000..f1e9231 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js @@ -0,0 +1,281 @@ +var format = require('util').format; + +var MongoAuthProcess = function(host, port, service_name) { + // Check what system we are on + if(process.platform == 'win32') { + this._processor = new Win32MongoProcessor(host, port, service_name); + } else { + this._processor = new UnixMongoProcessor(host, port, service_name); + } +} + +MongoAuthProcess.prototype.init = function(username, password, callback) { + this._processor.init(username, password, callback); +} + +MongoAuthProcess.prototype.transition = function(payload, callback) { + this._processor.transition(payload, callback); +} + +/******************************************************************* + * + * Win32 SSIP Processor for MongoDB + * + *******************************************************************/ +var Win32MongoProcessor = function(host, port, service_name) { + this.host = host; + this.port = port + // SSIP classes + this.ssip = require("../kerberos").SSIP; + // Set up first transition + this._transition = Win32MongoProcessor.first_transition(this); + // Set up service name + service_name = service_name || "mongodb"; + // Set up target + this.target = format("%s/%s", service_name, host); + // Number of retries + this.retries = 10; +} + +Win32MongoProcessor.prototype.init = function(username, password, callback) { + var self = this; + // Save the values used later + this.username = username; + this.password = password; + // Aquire credentials + this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { + if(err) return callback(err); + // Save credentials + self.security_credentials = security_credentials; + // Callback with success + callback(null); + }); +} + +Win32MongoProcessor.prototype.transition = function(payload, callback) { + if(this._transition == null) return callback(new Error("Transition finished")); + this._transition(payload, callback); +} + +Win32MongoProcessor.first_transition = function(self) { + return function(payload, callback) { + self.ssip.SecurityContext.initialize( + self.security_credentials, + self.target, + payload, function(err, security_context) { + if(err) return callback(err); + + // If no context try again until we have no more retries + if(!security_context.hasContext) { + if(self.retries == 0) return callback(new Error("Failed to initialize security context")); + // Update the number of retries + self.retries = self.retries - 1; + // Set next transition + return self.transition(payload, callback); + } + + // Set next transition + self._transition = Win32MongoProcessor.second_transition(self); + self.security_context = security_context; + // Return the payload + callback(null, security_context.payload); + }); + } +} + +Win32MongoProcessor.second_transition = function(self) { + return function(payload, callback) { + // Perform a step + self.security_context.initialize(self.target, payload, function(err, security_context) { + if(err) return callback(err); + + // If no context try again until we have no more retries + if(!security_context.hasContext) { + if(self.retries == 0) return callback(new Error("Failed to initialize security context")); + // Update the number of retries + self.retries = self.retries - 1; + // Set next transition + self._transition = Win32MongoProcessor.first_transition(self); + // Retry + return self.transition(payload, callback); + } + + // Set next transition + self._transition = Win32MongoProcessor.third_transition(self); + // Return the payload + callback(null, security_context.payload); + }); + } +} + +Win32MongoProcessor.third_transition = function(self) { + return function(payload, callback) { + var messageLength = 0; + // Get the raw bytes + var encryptedBytes = new Buffer(payload, 'base64'); + var encryptedMessage = new Buffer(messageLength); + // Copy first byte + encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); + // Set up trailer + var securityTrailerLength = encryptedBytes.length - messageLength; + var securityTrailer = new Buffer(securityTrailerLength); + // Copy the bytes + encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); + + // Types used + var SecurityBuffer = self.ssip.SecurityBuffer; + var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; + + // Set up security buffers + var buffers = [ + new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) + , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) + ]; + + // Set up the descriptor + var descriptor = new SecurityBufferDescriptor(buffers); + + // Decrypt the data + self.security_context.decryptMessage(descriptor, function(err, security_context) { + if(err) return callback(err); + + var length = 4; + if(self.username != null) { + length += self.username.length; + } + + var bytesReceivedFromServer = new Buffer(length); + bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION + bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION + bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION + bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION + + if(self.username != null) { + var authorization_id_bytes = new Buffer(self.username, 'utf8'); + authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); + } + + self.security_context.queryContextAttributes(0x00, function(err, sizes) { + if(err) return callback(err); + + var buffers = [ + new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) + , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) + , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) + ] + + var descriptor = new SecurityBufferDescriptor(buffers); + + self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { + if(err) return callback(err); + callback(null, security_context.payload); + }); + }); + }); + } +} + +/******************************************************************* + * + * UNIX MIT Kerberos processor + * + *******************************************************************/ +var UnixMongoProcessor = function(host, port, service_name) { + this.host = host; + this.port = port + // SSIP classes + this.Kerberos = require("../kerberos").Kerberos; + this.kerberos = new this.Kerberos(); + service_name = service_name || "mongodb"; + // Set up first transition + this._transition = UnixMongoProcessor.first_transition(this); + // Set up target + this.target = format("%s@%s", service_name, host); + // Number of retries + this.retries = 10; +} + +UnixMongoProcessor.prototype.init = function(username, password, callback) { + var self = this; + this.username = username; + this.password = password; + // Call client initiate + this.kerberos.authGSSClientInit( + self.target + , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { + self.context = context; + // Return the context + callback(null, context); + }); +} + +UnixMongoProcessor.prototype.transition = function(payload, callback) { + if(this._transition == null) return callback(new Error("Transition finished")); + this._transition(payload, callback); +} + +UnixMongoProcessor.first_transition = function(self) { + return function(payload, callback) { + self.kerberos.authGSSClientStep(self.context, '', function(err, result) { + if(err) return callback(err); + // Set up the next step + self._transition = UnixMongoProcessor.second_transition(self); + // Return the payload + callback(null, self.context.response); + }) + } +} + +UnixMongoProcessor.second_transition = function(self) { + return function(payload, callback) { + self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { + if(err && self.retries == 0) return callback(err); + // Attempt to re-establish a context + if(err) { + // Adjust the number of retries + self.retries = self.retries - 1; + // Call same step again + return self.transition(payload, callback); + } + + // Set up the next step + self._transition = UnixMongoProcessor.third_transition(self); + // Return the payload + callback(null, self.context.response || ''); + }); + } +} + +UnixMongoProcessor.third_transition = function(self) { + return function(payload, callback) { + // GSS Client Unwrap + self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { + if(err) return callback(err, false); + + // Wrap the response + self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { + if(err) return callback(err, false); + // Set up the next step + self._transition = UnixMongoProcessor.fourth_transition(self); + // Return the payload + callback(null, self.context.response); + }); + }); + } +} + +UnixMongoProcessor.fourth_transition = function(self) { + return function(payload, callback) { + // Clean up context + self.kerberos.authGSSClientClean(self.context, function(err, result) { + if(err) return callback(err, false); + // Set the transition to null + self._transition = null; + // Callback with valid authentication + callback(null, true); + }); + } +} + +// Set the process +exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c new file mode 100644 index 0000000..aca0a61 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c @@ -0,0 +1,134 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * 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. + **/ + +#include "base64.h" + +#include +#include +#include +#include + +void die2(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +// base64 tables +static char basis_64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static signed char index_64[128] = +{ + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 +}; +#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) + +// base64_encode : base64 encode +// +// value : data to encode +// vlen : length of data +// (result) : new char[] - c-str of result +char *base64_encode(const unsigned char *value, int vlen) +{ + char *result = (char *)malloc((vlen * 4) / 3 + 5); + if(result == NULL) die2("Memory allocation failed"); + char *out = result; + while (vlen >= 3) + { + *out++ = basis_64[value[0] >> 2]; + *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; + *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; + *out++ = basis_64[value[2] & 0x3F]; + value += 3; + vlen -= 3; + } + if (vlen > 0) + { + *out++ = basis_64[value[0] >> 2]; + unsigned char oval = (value[0] << 4) & 0x30; + if (vlen > 1) oval |= value[1] >> 4; + *out++ = basis_64[oval]; + *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; + *out++ = '='; + } + *out = '\0'; + + return result; +} + +// base64_decode : base64 decode +// +// value : c-str to decode +// rlen : length of decoded result +// (result) : new unsigned char[] - decoded result +unsigned char *base64_decode(const char *value, int *rlen) +{ + *rlen = 0; + int c1, c2, c3, c4; + + int vlen = strlen(value); + unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); + if(result == NULL) die2("Memory allocation failed"); + unsigned char *out = result; + + while (1) + { + if (value[0]==0) + return result; + c1 = value[0]; + if (CHAR64(c1) == -1) + goto base64_decode_error;; + c2 = value[1]; + if (CHAR64(c2) == -1) + goto base64_decode_error;; + c3 = value[2]; + if ((c3 != '=') && (CHAR64(c3) == -1)) + goto base64_decode_error;; + c4 = value[3]; + if ((c4 != '=') && (CHAR64(c4) == -1)) + goto base64_decode_error;; + + value += 4; + *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); + *rlen += 1; + if (c3 != '=') + { + *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); + *rlen += 1; + if (c4 != '=') + { + *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); + *rlen += 1; + } + } + } + +base64_decode_error: + *result = 0; + *rlen = 0; + return result; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h new file mode 100644 index 0000000..9152e6a --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h @@ -0,0 +1,22 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * 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. + **/ +#ifndef BASE64_H +#define BASE64_H + +char *base64_encode(const unsigned char *value, int vlen); +unsigned char *base64_decode(const char *value, int *rlen); + +#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc new file mode 100644 index 0000000..5b25d74 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc @@ -0,0 +1,893 @@ +#include "kerberos.h" +#include +#include +#include "worker.h" +#include "kerberos_context.h" + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) +#endif + +void die(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +// Call structs +typedef struct AuthGSSClientCall { + uint32_t flags; + char *uri; +} AuthGSSClientCall; + +typedef struct AuthGSSClientStepCall { + KerberosContext *context; + char *challenge; +} AuthGSSClientStepCall; + +typedef struct AuthGSSClientUnwrapCall { + KerberosContext *context; + char *challenge; +} AuthGSSClientUnwrapCall; + +typedef struct AuthGSSClientWrapCall { + KerberosContext *context; + char *challenge; + char *user_name; +} AuthGSSClientWrapCall; + +typedef struct AuthGSSClientCleanCall { + KerberosContext *context; +} AuthGSSClientCleanCall; + +typedef struct AuthGSSServerInitCall { + char *service; + bool constrained_delegation; + char *username; +} AuthGSSServerInitCall; + +typedef struct AuthGSSServerCleanCall { + KerberosContext *context; +} AuthGSSServerCleanCall; + +typedef struct AuthGSSServerStepCall { + KerberosContext *context; + char *auth_data; +} AuthGSSServerStepCall; + +Kerberos::Kerberos() : Nan::ObjectWrap() { +} + +Nan::Persistent Kerberos::constructor_template; + +void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("Kerberos").ToLocalChecked()); + + // Set up method for the Kerberos instance + Nan::SetPrototypeMethod(t, "authGSSClientInit", AuthGSSClientInit); + Nan::SetPrototypeMethod(t, "authGSSClientStep", AuthGSSClientStep); + Nan::SetPrototypeMethod(t, "authGSSClientUnwrap", AuthGSSClientUnwrap); + Nan::SetPrototypeMethod(t, "authGSSClientWrap", AuthGSSClientWrap); + Nan::SetPrototypeMethod(t, "authGSSClientClean", AuthGSSClientClean); + Nan::SetPrototypeMethod(t, "authGSSServerInit", AuthGSSServerInit); + Nan::SetPrototypeMethod(t, "authGSSServerClean", AuthGSSServerClean); + Nan::SetPrototypeMethod(t, "authGSSServerStep", AuthGSSServerStep); + + constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("Kerberos").ToLocalChecked(), t->GetFunction()); +} + +NAN_METHOD(Kerberos::New) { + // Create a Kerberos instance + Kerberos *kerberos = new Kerberos(); + // Return the kerberos object + kerberos->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientInit +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientInit(Worker *worker) { + gss_client_state *state; + gss_client_response *response; + + // Allocate state + state = (gss_client_state *)malloc(sizeof(gss_client_state)); + if(state == NULL) die("Memory allocation failed"); + + // Unpack the parameter data struct + AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; + // Start the kerberos client + response = authenticate_gss_client_init(call->uri, call->flags, state); + + // Release the parameter struct memory + free(call->uri); + free(call); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + free(state); + } else { + worker->return_value = state; + } + + // Free structure + free(response); +} + +static Local _map_authGSSClientInit(Worker *worker) { + KerberosContext *context = KerberosContext::New(); + context->state = (gss_client_state *)worker->return_value; + return context->handle(); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientInit) { + // Ensure valid call + if(info.Length() != 3) return Nan::ThrowError("Requires a service string uri, integer flags and a callback function"); + if(info.Length() == 3 && (!info[0]->IsString() || !info[1]->IsInt32() || !info[2]->IsFunction())) + return Nan::ThrowError("Requires a service string uri, integer flags and a callback function"); + + Local service = info[0]->ToString(); + // Convert uri string to c-string + char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); + if(service_str == NULL) die("Memory allocation failed"); + + // Write v8 string to c-string + service->WriteUtf8(service_str); + + // Allocate a structure + AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); + if(call == NULL) die("Memory allocation failed"); + call->flags =info[1]->ToInt32()->Uint32Value(); + call->uri = service_str; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[2]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientInit; + worker->mapper = _map_authGSSClientInit; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientStep +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientStep(Worker *worker) { + gss_client_state *state; + gss_client_response *response; + char *challenge; + + // Unpack the parameter data struct + AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; + // Get the state + state = call->context->state; + challenge = call->challenge; + + // Check what kind of challenge we have + if(call->challenge == NULL) { + challenge = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_client_step(state, challenge); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->challenge != NULL) free(call->challenge); + free(call); + free(response); +} + +static Local _map_authGSSClientStep(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientStep) { + // Ensure valid call + if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + + // Challenge string + char *challenge_str = NULL; + // Let's unpack the parameters + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsClientInstance()) { + return Nan::ThrowError("GSS context is not a client instance"); + } + + int callbackArg = 1; + + // If we have a challenge string + if(info.Length() == 3) { + // Unpack the challenge string + Local challenge = info[1]->ToString(); + // Convert uri string to c-string + challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); + if(challenge_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + challenge->WriteUtf8(challenge_str); + + callbackArg = 2; + } + + // Allocate a structure + AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientStepCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->challenge = challenge_str; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[callbackArg]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientStep; + worker->mapper = _map_authGSSClientStep; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientUnwrap +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientUnwrap(Worker *worker) { + gss_client_response *response; + char *challenge; + + // Unpack the parameter data struct + AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; + challenge = call->challenge; + + // Check what kind of challenge we have + if(call->challenge == NULL) { + challenge = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_client_unwrap(call->context->state, challenge); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->challenge != NULL) free(call->challenge); + free(call); + free(response); +} + +static Local _map_authGSSClientUnwrap(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientUnwrap) { + // Ensure valid call + if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); + + // Challenge string + char *challenge_str = NULL; + // Let's unpack the parameters + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsClientInstance()) { + return Nan::ThrowError("GSS context is not a client instance"); + } + + // If we have a challenge string + if(info.Length() == 3) { + // Unpack the challenge string + Local challenge = info[1]->ToString(); + // Convert uri string to c-string + challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); + if(challenge_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + challenge->WriteUtf8(challenge_str); + } + + // Allocate a structure + AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->challenge = challenge_str; + + // Unpack the callback + Local callbackHandle = info.Length() == 3 ? Local::Cast(info[2]) : Local::Cast(info[1]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientUnwrap; + worker->mapper = _map_authGSSClientUnwrap; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientWrap +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientWrap(Worker *worker) { + gss_client_response *response; + char *user_name = NULL; + + // Unpack the parameter data struct + AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; + user_name = call->user_name; + + // Check what kind of challenge we have + if(call->user_name == NULL) { + user_name = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->challenge != NULL) free(call->challenge); + if(call->user_name != NULL) free(call->user_name); + free(call); + free(response); +} + +static Local _map_authGSSClientWrap(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientWrap) { + // Ensure valid call + if(info.Length() != 3 && info.Length() != 4) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); + if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); + if(info.Length() == 4 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsString() || !info[3]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); + + // Challenge string + char *challenge_str = NULL; + char *user_name_str = NULL; + + // Let's unpack the kerberos context + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsClientInstance()) { + return Nan::ThrowError("GSS context is not a client instance"); + } + + // Unpack the challenge string + Local challenge = info[1]->ToString(); + // Convert uri string to c-string + challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); + if(challenge_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + challenge->WriteUtf8(challenge_str); + + // If we have a user string + if(info.Length() == 4) { + // Unpack user name + Local user_name = info[2]->ToString(); + // Convert uri string to c-string + user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); + if(user_name_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + user_name->WriteUtf8(user_name_str); + } + + // Allocate a structure + AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->challenge = challenge_str; + call->user_name = user_name_str; + + // Unpack the callback + Local callbackHandle = info.Length() == 4 ? Local::Cast(info[3]) : Local::Cast(info[2]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientWrap; + worker->mapper = _map_authGSSClientWrap; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientClean +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSClientClean(Worker *worker) { + gss_client_response *response; + + // Unpack the parameter data struct + AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; + + // Perform authentication step + response = authenticate_gss_client_clean(call->context->state); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + free(call); + free(response); +} + +static Local _map_authGSSClientClean(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSClientClean) { + // Ensure valid call + if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function"); + if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function"); + + // Let's unpack the kerberos context + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsClientInstance()) { + return Nan::ThrowError("GSS context is not a client instance"); + } + + // Allocate a structure + AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[1]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSClientClean; + worker->mapper = _map_authGSSClientClean; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSServerInit +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSServerInit(Worker *worker) { + gss_server_state *state; + gss_client_response *response; + + // Allocate state + state = (gss_server_state *)malloc(sizeof(gss_server_state)); + if(state == NULL) die("Memory allocation failed"); + + // Unpack the parameter data struct + AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)worker->parameters; + // Start the kerberos service + response = authenticate_gss_server_init(call->service, call->constrained_delegation, call->username, state); + + // Release the parameter struct memory + free(call->service); + free(call->username); + free(call); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + free(state); + } else { + worker->return_value = state; + } + + // Free structure + free(response); +} + +static Local _map_authGSSServerInit(Worker *worker) { + KerberosContext *context = KerberosContext::New(); + context->server_state = (gss_server_state *)worker->return_value; + return context->handle(); +} + +// Server Initialize method +NAN_METHOD(Kerberos::AuthGSSServerInit) { + // Ensure valid call + if(info.Length() != 4) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function"); + + if(!info[0]->IsString() || + !info[1]->IsBoolean() || + !(info[2]->IsString() || info[2]->IsNull()) || + !info[3]->IsFunction() + ) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function"); + + if (!info[1]->BooleanValue() && !info[2]->IsNull()) return Nan::ThrowError("S4U2Self only possible when constrained delegation is enabled"); + + // Allocate a structure + AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)calloc(1, sizeof(AuthGSSServerInitCall)); + if(call == NULL) die("Memory allocation failed"); + + Local service = info[0]->ToString(); + // Convert service string to c-string + char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); + if(service_str == NULL) die("Memory allocation failed"); + + // Write v8 string to c-string + service->WriteUtf8(service_str); + + call->service = service_str; + + call->constrained_delegation = info[1]->BooleanValue(); + + if (info[2]->IsNull()) + { + call->username = NULL; + } + else + { + Local tmpString = info[2]->ToString(); + + char *tmpCstr = (char *)calloc(tmpString->Utf8Length() + 1, sizeof(char)); + if(tmpCstr == NULL) die("Memory allocation failed"); + + tmpString->WriteUtf8(tmpCstr); + + call->username = tmpCstr; + } + + // Unpack the callback + Local callbackHandle = Local::Cast(info[3]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSServerInit; + worker->mapper = _map_authGSSServerInit; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSServerClean +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSServerClean(Worker *worker) { + gss_client_response *response; + + // Unpack the parameter data struct + AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)worker->parameters; + + // Perform authentication step + response = authenticate_gss_server_clean(call->context->server_state); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + free(call); + free(response); +} + +static Local _map_authGSSServerClean(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSServerClean) { + // // Ensure valid call + if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function"); + if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function"); + + // Let's unpack the kerberos context + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsServerInstance()) { + return Nan::ThrowError("GSS context is not a server instance"); + } + + // Allocate a structure + AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)calloc(1, sizeof(AuthGSSServerCleanCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[1]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSServerClean; + worker->mapper = _map_authGSSServerClean; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSServerStep +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authGSSServerStep(Worker *worker) { + gss_server_state *state; + gss_client_response *response; + char *auth_data; + + // Unpack the parameter data struct + AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)worker->parameters; + // Get the state + state = call->context->server_state; + auth_data = call->auth_data; + + // Check if we got auth_data or not + if(call->auth_data == NULL) { + auth_data = (char *)""; + } + + // Perform authentication step + response = authenticate_gss_server_step(state, auth_data); + + // If we have an error mark worker as having had an error + if(response->return_code == AUTH_GSS_ERROR) { + worker->error = TRUE; + worker->error_code = response->return_code; + worker->error_message = response->message; + } else { + worker->return_code = response->return_code; + } + + // Free up structure + if(call->auth_data != NULL) free(call->auth_data); + free(call); + free(response); +} + +static Local _map_authGSSServerStep(Worker *worker) { + Nan::HandleScope scope; + // Return the return code + return Nan::New(worker->return_code); +} + +// Initialize method +NAN_METHOD(Kerberos::AuthGSSServerStep) { + // Ensure valid call + if(info.Length() != 3) return Nan::ThrowError("Requires a GSS context, auth-data string and callback function"); + if(!KerberosContext::HasInstance(info[0])) return Nan::ThrowError("1st arg must be a GSS context"); + if (!info[1]->IsString()) return Nan::ThrowError("2nd arg must be auth-data string"); + if (!info[2]->IsFunction()) return Nan::ThrowError("3rd arg must be a callback function"); + + // Auth-data string + char *auth_data_str = NULL; + // Let's unpack the parameters + Local object = info[0]->ToObject(); + KerberosContext *kerberos_context = KerberosContext::Unwrap(object); + + if (!kerberos_context->IsServerInstance()) { + return Nan::ThrowError("GSS context is not a server instance"); + } + + // Unpack the auth_data string + Local auth_data = info[1]->ToString(); + // Convert uri string to c-string + auth_data_str = (char *)calloc(auth_data->Utf8Length() + 1, sizeof(char)); + if(auth_data_str == NULL) die("Memory allocation failed"); + // Write v8 string to c-string + auth_data->WriteUtf8(auth_data_str); + + // Allocate a structure + AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)calloc(1, sizeof(AuthGSSServerStepCall)); + if(call == NULL) die("Memory allocation failed"); + call->context = kerberos_context; + call->auth_data = auth_data_str; + + // Unpack the callback + Local callbackHandle = Local::Cast(info[2]); + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authGSSServerStep; + worker->mapper = _map_authGSSServerStep; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// UV Lib callbacks +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +void Kerberos::Process(uv_work_t* work_req) { + // Grab the worker + Worker *worker = static_cast(work_req->data); + // Execute the worker code + worker->execute(worker); +} + +void Kerberos::After(uv_work_t* work_req) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Get the worker reference + Worker *worker = static_cast(work_req->data); + + // If we have an error + if(worker->error) { + Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); + Local obj = err->ToObject(); + obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); + Local info[2] = { err, Nan::Null() }; + // Execute the error + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } else { + // // Map the data + Local result = worker->mapper(worker); + // Set up the callback with a null first + #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + Local info[2] = { Nan::Null(), result}; + #else + Local info[2] = { Nan::Null(), Nan::New(result)}; + #endif + + // Wrap the callback function call in a TryCatch so that we can call + // node's FatalException afterwards. This makes it possible to catch + // the exception from JavaScript land using the + // process.on('uncaughtException') event. + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } + + // Clean up the memory + delete worker->callback; + delete worker; +} + +// Exporting function +NAN_MODULE_INIT(init) { + Kerberos::Initialize(target); + KerberosContext::Initialize(target); +} + +NODE_MODULE(kerberos, init); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h new file mode 100644 index 0000000..beafa4d --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h @@ -0,0 +1,50 @@ +#ifndef KERBEROS_H +#define KERBEROS_H + +#include +#include +#include +#include + +#include "nan.h" +#include +#include + +extern "C" { + #include "kerberosgss.h" +} + +using namespace v8; +using namespace node; + +class Kerberos : public Nan::ObjectWrap { + +public: + Kerberos(); + ~Kerberos() {}; + + // Constructor used for creating new Kerberos objects from C++ + static Nan::Persistent constructor_template; + + // Initialize function for the object + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + + // Method available + static NAN_METHOD(AuthGSSClientInit); + static NAN_METHOD(AuthGSSClientStep); + static NAN_METHOD(AuthGSSClientUnwrap); + static NAN_METHOD(AuthGSSClientWrap); + static NAN_METHOD(AuthGSSClientClean); + static NAN_METHOD(AuthGSSServerInit); + static NAN_METHOD(AuthGSSServerClean); + static NAN_METHOD(AuthGSSServerStep); + +private: + static NAN_METHOD(New); + // Handles the uv calls + static void Process(uv_work_t* work_req); + // Called after work is done + static void After(uv_work_t* work_req); +}; + +#endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js new file mode 100644 index 0000000..c7bae58 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js @@ -0,0 +1,164 @@ +var kerberos = require('../build/Release/kerberos') + , KerberosNative = kerberos.Kerberos; + +var Kerberos = function() { + this._native_kerberos = new KerberosNative(); +} + +// callback takes two arguments, an error string if defined and a new context +// uri should be given as service@host. Services are not always defined +// in a straightforward way. Use 'HTTP' for SPNEGO / Negotiate authentication. +Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { + return this._native_kerberos.authGSSClientInit(uri, flags, callback); +} + +// This will obtain credentials using a credentials cache. To override the default +// location (posible /tmp/krb5cc_nnnnnn, where nnnn is your numeric uid) use +// the environment variable KRB5CNAME. +// The credentials (suitable for using in an 'Authenticate: ' header, when prefixed +// with 'Negotiate ') will be available as context.response inside the callback +// if no error is indicated. +// callback takes one argument, an error string if defined +Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { + if(typeof challenge == 'function') { + callback = challenge; + challenge = ''; + } + + return this._native_kerberos.authGSSClientStep(context, challenge, callback); +} + +Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { + if(typeof challenge == 'function') { + callback = challenge; + challenge = ''; + } + + return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); +} + +Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { + if(typeof user_name == 'function') { + callback = user_name; + user_name = ''; + } + + return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); +} + +// free memory used by a context created using authGSSClientInit. +// callback takes one argument, an error string if defined. +Kerberos.prototype.authGSSClientClean = function(context, callback) { + return this._native_kerberos.authGSSClientClean(context, callback); +} + +// The server will obtain credentials using a keytab. To override the +// default location (probably /etc/krb5.keytab) set the KRB5_KTNAME +// environment variable. +// The service name should be in the form service, or service@host.name +// e.g. for HTTP, use "HTTP" or "HTTP@my.host.name". See gss_import_name +// for GSS_C_NT_HOSTBASED_SERVICE. +// +// a boolean turns on "constrained_delegation". this enables acquisition of S4U2Proxy +// credentials which will be stored in a credentials cache during the authGSSServerStep +// method. this parameter is optional. +// +// when "constrained_delegation" is enabled, a username can (optionally) be provided and +// S4U2Self protocol transition will be initiated. In this case, we will not +// require any "auth" data during the authGSSServerStep. This parameter is optional +// but constrained_delegation MUST be enabled for this to work. When S4U2Self is +// used, the username will be assumed to have been already authenticated, and no +// actual authentication will be performed. This is basically a way to "bootstrap" +// kerberos credentials (which can then be delegated with S4U2Proxy) for a user +// authenticated externally. +// +// callback takes two arguments, an error string if defined and a new context +// +Kerberos.prototype.authGSSServerInit = function(service, constrained_delegation, username, callback) { + if(typeof(constrained_delegation) === 'function') { + callback = constrained_delegation; + constrained_delegation = false; + username = null; + } + + if (typeof(constrained_delegation) === 'string') { + throw new Error("S4U2Self protocol transation is not possible without enabling constrained delegation"); + } + + if (typeof(username) === 'function') { + callback = username; + username = null; + } + + constrained_delegation = !!constrained_delegation; + + return this._native_kerberos.authGSSServerInit(service, constrained_delegation, username, callback); +}; + +//callback takes one argument, an error string if defined. +Kerberos.prototype.authGSSServerClean = function(context, callback) { + return this._native_kerberos.authGSSServerClean(context, callback); +}; + +// authData should be the base64 encoded authentication data obtained +// from client, e.g., in the Authorization header (without the leading +// "Negotiate " string) during SPNEGO authentication. The authenticated user +// is available in context.username after successful authentication. +// callback takes one argument, an error string if defined. +// +// Note: when S4U2Self protocol transition was requested in the authGSSServerInit +// no actual authentication will be performed and authData will be ignored. +// +Kerberos.prototype.authGSSServerStep = function(context, authData, callback) { + return this._native_kerberos.authGSSServerStep(context, authData, callback); +}; + +Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { + return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); +} + +Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { + return this._native_kerberos.prepareOutboundPackage(principal, inputdata); +} + +Kerberos.prototype.decryptMessage = function(challenge) { + return this._native_kerberos.decryptMessage(challenge); +} + +Kerberos.prototype.encryptMessage = function(challenge) { + return this._native_kerberos.encryptMessage(challenge); +} + +Kerberos.prototype.queryContextAttribute = function(attribute) { + if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); + return this._native_kerberos.queryContextAttribute(attribute); +} + +// Some useful result codes +Kerberos.AUTH_GSS_CONTINUE = 0; +Kerberos.AUTH_GSS_COMPLETE = 1; + +// Some useful gss flags +Kerberos.GSS_C_DELEG_FLAG = 1; +Kerberos.GSS_C_MUTUAL_FLAG = 2; +Kerberos.GSS_C_REPLAY_FLAG = 4; +Kerberos.GSS_C_SEQUENCE_FLAG = 8; +Kerberos.GSS_C_CONF_FLAG = 16; +Kerberos.GSS_C_INTEG_FLAG = 32; +Kerberos.GSS_C_ANON_FLAG = 64; +Kerberos.GSS_C_PROT_READY_FLAG = 128; +Kerberos.GSS_C_TRANS_FLAG = 256; + +// Export Kerberos class +exports.Kerberos = Kerberos; + +// If we have SSPI (windows) +if(kerberos.SecurityCredentials) { + // Put all SSPI classes in it's own namespace + exports.SSIP = { + SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials + , SecurityContext: require('./win32/wrappers/security_context').SecurityContext + , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer + , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor + } +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc new file mode 100644 index 0000000..bf24118 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc @@ -0,0 +1,134 @@ +#include "kerberos_context.h" + +Nan::Persistent KerberosContext::constructor_template; + +KerberosContext::KerberosContext() : Nan::ObjectWrap() { + state = NULL; + server_state = NULL; +} + +KerberosContext::~KerberosContext() { +} + +KerberosContext* KerberosContext::New() { + Nan::HandleScope scope; + Local obj = Nan::New(constructor_template)->GetFunction()->NewInstance(); + KerberosContext *kerberos_context = Nan::ObjectWrap::Unwrap(obj); + return kerberos_context; +} + +NAN_METHOD(KerberosContext::New) { + // Create code object + KerberosContext *kerberos_context = new KerberosContext(); + // Wrap it + kerberos_context->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +void KerberosContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(static_cast(New)); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("KerberosContext").ToLocalChecked()); + + // Get prototype + Local proto = t->PrototypeTemplate(); + + // Getter for the response + Nan::SetAccessor(proto, Nan::New("response").ToLocalChecked(), KerberosContext::ResponseGetter); + + // Getter for the username + Nan::SetAccessor(proto, Nan::New("username").ToLocalChecked(), KerberosContext::UsernameGetter); + + // Getter for the targetname - server side only + Nan::SetAccessor(proto, Nan::New("targetname").ToLocalChecked(), KerberosContext::TargetnameGetter); + + Nan::SetAccessor(proto, Nan::New("delegatedCredentialsCache").ToLocalChecked(), KerberosContext::DelegatedCredentialsCacheGetter); + + // Set persistent + constructor_template.Reset(t); + // NanAssignPersistent(constructor_template, t); + + // Set the symbol + target->ForceSet(Nan::New("KerberosContext").ToLocalChecked(), t->GetFunction()); +} + + +// Response Setter / Getter +NAN_GETTER(KerberosContext::ResponseGetter) { + gss_client_state *client_state; + gss_server_state *server_state; + + // Unpack the object + KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); + + // Response could come from client or server state... + client_state = context->state; + server_state = context->server_state; + + // If client state is in use, take response from there, otherwise from server + char *response = client_state != NULL ? client_state->response : + server_state != NULL ? server_state->response : NULL; + + if(response == NULL) { + info.GetReturnValue().Set(Nan::Null()); + } else { + // Return the response + info.GetReturnValue().Set(Nan::New(response).ToLocalChecked()); + } +} + +// username Getter +NAN_GETTER(KerberosContext::UsernameGetter) { + // Unpack the object + KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); + + gss_client_state *client_state = context->state; + gss_server_state *server_state = context->server_state; + + // If client state is in use, take response from there, otherwise from server + char *username = client_state != NULL ? client_state->username : + server_state != NULL ? server_state->username : NULL; + + if(username == NULL) { + info.GetReturnValue().Set(Nan::Null()); + } else { + info.GetReturnValue().Set(Nan::New(username).ToLocalChecked()); + } +} + +// targetname Getter - server side only +NAN_GETTER(KerberosContext::TargetnameGetter) { + // Unpack the object + KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); + + gss_server_state *server_state = context->server_state; + + char *targetname = server_state != NULL ? server_state->targetname : NULL; + + if(targetname == NULL) { + info.GetReturnValue().Set(Nan::Null()); + } else { + info.GetReturnValue().Set(Nan::New(targetname).ToLocalChecked()); + } +} + +// targetname Getter - server side only +NAN_GETTER(KerberosContext::DelegatedCredentialsCacheGetter) { + // Unpack the object + KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); + + gss_server_state *server_state = context->server_state; + + char *delegated_credentials_cache = server_state != NULL ? server_state->delegated_credentials_cache : NULL; + + if(delegated_credentials_cache == NULL) { + info.GetReturnValue().Set(Nan::Null()); + } else { + info.GetReturnValue().Set(Nan::New(delegated_credentials_cache).ToLocalChecked()); + } +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h new file mode 100644 index 0000000..23eb577 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h @@ -0,0 +1,64 @@ +#ifndef KERBEROS_CONTEXT_H +#define KERBEROS_CONTEXT_H + +#include +#include +#include +#include + +#include "nan.h" +#include +#include + +extern "C" { + #include "kerberosgss.h" +} + +using namespace v8; +using namespace node; + +class KerberosContext : public Nan::ObjectWrap { + +public: + KerberosContext(); + ~KerberosContext(); + + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + inline bool IsClientInstance() { + return state != NULL; + } + + inline bool IsServerInstance() { + return server_state != NULL; + } + + // Constructor used for creating new Kerberos objects from C++ + static Nan::Persistent constructor_template; + + // Initialize function for the object + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + + // Public constructor + static KerberosContext* New(); + + // Handle to the kerberos client context + gss_client_state *state; + + // Handle to the kerberos server context + gss_server_state *server_state; + +private: + static NAN_METHOD(New); + // In either client state or server state + static NAN_GETTER(ResponseGetter); + static NAN_GETTER(UsernameGetter); + // Only in the "server_state" + static NAN_GETTER(TargetnameGetter); + static NAN_GETTER(DelegatedCredentialsCacheGetter); +}; +#endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c new file mode 100644 index 0000000..2fbca00 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c @@ -0,0 +1,931 @@ +/** + * Copyright (c) 2006-2010 Apple Inc. All rights reserved. + * + * 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. + * + **/ +/* + * S4U2Proxy implementation + * Copyright (C) 2015 David Mansfield + * Code inspired by mod_auth_kerb. + */ + +#include "kerberosgss.h" + +#include "base64.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" + +void die1(const char *message) { + if(errno) { + perror(message); + } else { + printf("ERROR: %s\n", message); + } + + exit(1); +} + +static gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min); +static gss_client_response *other_error(const char *fmt, ...); +static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem); + +static gss_client_response *store_gss_creds(gss_server_state *state); +static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context context, krb5_principal princ, krb5_ccache *ccache); + +/* +char* server_principal_details(const char* service, const char* hostname) +{ + char match[1024]; + int match_len = 0; + char* result = NULL; + + int code; + krb5_context kcontext; + krb5_keytab kt = NULL; + krb5_kt_cursor cursor = NULL; + krb5_keytab_entry entry; + char* pname = NULL; + + // Generate the principal prefix we want to match + snprintf(match, 1024, "%s/%s@", service, hostname); + match_len = strlen(match); + + code = krb5_init_context(&kcontext); + if (code) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot initialize Kerberos5 context", code)); + return NULL; + } + + if ((code = krb5_kt_default(kcontext, &kt))) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot get default keytab", code)); + goto end; + } + + if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot get sequence cursor from keytab", code)); + goto end; + } + + while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) + { + if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Cannot parse principal name from keytab", code)); + goto end; + } + + if (strncmp(pname, match, match_len) == 0) + { + result = malloc(strlen(pname) + 1); + strcpy(result, pname); + krb5_free_unparsed_name(kcontext, pname); + krb5_free_keytab_entry_contents(kcontext, &entry); + break; + } + + krb5_free_unparsed_name(kcontext, pname); + krb5_free_keytab_entry_contents(kcontext, &entry); + } + + if (result == NULL) + { + PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", + "Principal not found in keytab", -1)); + } + +end: + if (cursor) + krb5_kt_end_seq_get(kcontext, kt, &cursor); + if (kt) + krb5_kt_close(kcontext, kt); + krb5_free_context(kcontext); + + return result; +} +*/ +gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; + gss_client_response *response = NULL; + int ret = AUTH_GSS_COMPLETE; + + state->server_name = GSS_C_NO_NAME; + state->context = GSS_C_NO_CONTEXT; + state->gss_flags = gss_flags; + state->username = NULL; + state->response = NULL; + + // Import server name first + name_token.length = strlen(service); + name_token.value = (char *)service; + + maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); + + if (GSS_ERROR(maj_stat)) { + response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + +end: + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + return response; +} + +gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { + OM_uint32 min_stat; + int ret = AUTH_GSS_COMPLETE; + gss_client_response *response = NULL; + + if(state->context != GSS_C_NO_CONTEXT) + gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); + + if(state->server_name != GSS_C_NO_NAME) + gss_release_name(&min_stat, &state->server_name); + + if(state->username != NULL) { + free(state->username); + state->username = NULL; + } + + if (state->response != NULL) { + free(state->response); + state->response = NULL; + } + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + return response; +} + +gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_CONTINUE; + gss_client_response *response = NULL; + + // Always clear out the old response + if (state->response != NULL) { + free(state->response); + state->response = NULL; + } + + // If there is a challenge (data from the server) we need to give it to GSS + if (challenge && *challenge) { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + + // Do GSSAPI step + maj_stat = gss_init_sec_context(&min_stat, + GSS_C_NO_CREDENTIAL, + &state->context, + state->server_name, + GSS_C_NO_OID, + (OM_uint32)state->gss_flags, + 0, + GSS_C_NO_CHANNEL_BINDINGS, + &input_token, + NULL, + &output_token, + NULL, + NULL); + + if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { + response = gss_error(__func__, "gss_init_sec_context", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; + // Grab the client response to send back to the server + if(output_token.length) { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); + maj_stat = gss_release_buffer(&min_stat, &output_token); + } + + // Try to get the user name if we have completed all GSS operations + if (ret == AUTH_GSS_COMPLETE) { + gss_name_t gssuser = GSS_C_NO_NAME; + maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); + + if(GSS_ERROR(maj_stat)) { + response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + gss_buffer_desc name_token; + name_token.length = 0; + maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); + + if(GSS_ERROR(maj_stat)) { + if(name_token.value) + gss_release_buffer(&min_stat, &name_token); + gss_release_name(&min_stat, &gssuser); + + response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } else { + state->username = (char *)malloc(name_token.length + 1); + if(state->username == NULL) die1("Memory allocation failed"); + strncpy(state->username, (char*) name_token.value, name_token.length); + state->username[name_token.length] = 0; + gss_release_buffer(&min_stat, &name_token); + gss_release_name(&min_stat, &gssuser); + } + } + +end: + if(output_token.value) + gss_release_buffer(&min_stat, &output_token); + if(input_token.value) + free(input_token.value); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + gss_client_response *response = NULL; + int ret = AUTH_GSS_CONTINUE; + + // Always clear out the old response + if(state->response != NULL) { + free(state->response); + state->response = NULL; + } + + // If there is a challenge (data from the server) we need to give it to GSS + if(challenge && *challenge) { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + + // Do GSSAPI step + maj_stat = gss_unwrap(&min_stat, + state->context, + &input_token, + &output_token, + NULL, + NULL); + + if(maj_stat != GSS_S_COMPLETE) { + response = gss_error(__func__, "gss_unwrap", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } else { + ret = AUTH_GSS_COMPLETE; + } + + // Grab the client response + if(output_token.length) { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); + gss_release_buffer(&min_stat, &output_token); + } +end: + if(output_token.value) + gss_release_buffer(&min_stat, &output_token); + if(input_token.value) + free(input_token.value); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_CONTINUE; + gss_client_response *response = NULL; + char buf[4096], server_conf_flags; + unsigned long buf_size; + + // Always clear out the old response + if(state->response != NULL) { + free(state->response); + state->response = NULL; + } + + if(challenge && *challenge) { + int len; + input_token.value = base64_decode(challenge, &len); + input_token.length = len; + } + + if(user) { + // get bufsize + server_conf_flags = ((char*) input_token.value)[0]; + ((char*) input_token.value)[0] = 0; + buf_size = ntohl(*((long *) input_token.value)); + free(input_token.value); +#ifdef PRINTFS + printf("User: %s, %c%c%c\n", user, + server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', + server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', + server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); + printf("Maximum GSS token size is %ld\n", buf_size); +#endif + + // agree to terms (hack!) + buf_size = htonl(buf_size); // not relevant without integrity/privacy + memcpy(buf, &buf_size, 4); + buf[0] = GSS_AUTH_P_NONE; + // server decides if principal can log in as user + strncpy(buf + 4, user, sizeof(buf) - 4); + input_token.value = buf; + input_token.length = 4 + strlen(user); + } + + // Do GSSAPI wrap + maj_stat = gss_wrap(&min_stat, + state->context, + 0, + GSS_C_QOP_DEFAULT, + &input_token, + NULL, + &output_token); + + if (maj_stat != GSS_S_COMPLETE) { + response = gss_error(__func__, "gss_wrap", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } else + ret = AUTH_GSS_COMPLETE; + // Grab the client response to send back to the server + if (output_token.length) { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; + gss_release_buffer(&min_stat, &output_token); + } +end: + if (output_token.value) + gss_release_buffer(&min_stat, &output_token); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_server_init(const char *service, bool constrained_delegation, const char *username, gss_server_state *state) +{ + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_COMPLETE; + gss_client_response *response = NULL; + gss_cred_usage_t usage = GSS_C_ACCEPT; + + state->context = GSS_C_NO_CONTEXT; + state->server_name = GSS_C_NO_NAME; + state->client_name = GSS_C_NO_NAME; + state->server_creds = GSS_C_NO_CREDENTIAL; + state->client_creds = GSS_C_NO_CREDENTIAL; + state->username = NULL; + state->targetname = NULL; + state->response = NULL; + state->constrained_delegation = constrained_delegation; + state->delegated_credentials_cache = NULL; + + // Server name may be empty which means we aren't going to create our own creds + size_t service_len = strlen(service); + if (service_len != 0) + { + // Import server name first + name_token.length = strlen(service); + name_token.value = (char *)service; + + maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); + + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + if (state->constrained_delegation) + { + usage = GSS_C_BOTH; + } + + // Get credentials + maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, + GSS_C_NO_OID_SET, usage, &state->server_creds, NULL, NULL); + + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_acquire_cred", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + } + + // If a username was passed, perform the S4U2Self protocol transition to acquire + // a credentials from that user as if we had done gss_accept_sec_context. + // In this scenario, the passed username is assumed to be already authenticated + // by some external mechanism, and we are here to "bootstrap" some gss credentials. + // In authenticate_gss_server_step we will bypass the actual authentication step. + if (username != NULL) + { + gss_name_t gss_username; + + name_token.length = strlen(username); + name_token.value = (char *)username; + + maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_USER_NAME, &gss_username); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + maj_stat = gss_acquire_cred_impersonate_name(&min_stat, + state->server_creds, + gss_username, + GSS_C_INDEFINITE, + GSS_C_NO_OID_SET, + GSS_C_INITIATE, + &state->client_creds, + NULL, + NULL); + + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_acquire_cred_impersonate_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + } + + gss_release_name(&min_stat, &gss_username); + + if (response != NULL) + { + goto end; + } + + // because the username MAY be a "local" username, + // we want get the canonical name from the acquired creds. + maj_stat = gss_inquire_cred(&min_stat, state->client_creds, &state->client_name, NULL, NULL, NULL); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_inquire_cred", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + } + +end: + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_server_clean(gss_server_state *state) +{ + OM_uint32 min_stat; + int ret = AUTH_GSS_COMPLETE; + gss_client_response *response = NULL; + + if (state->context != GSS_C_NO_CONTEXT) + gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); + if (state->server_name != GSS_C_NO_NAME) + gss_release_name(&min_stat, &state->server_name); + if (state->client_name != GSS_C_NO_NAME) + gss_release_name(&min_stat, &state->client_name); + if (state->server_creds != GSS_C_NO_CREDENTIAL) + gss_release_cred(&min_stat, &state->server_creds); + if (state->client_creds != GSS_C_NO_CREDENTIAL) + gss_release_cred(&min_stat, &state->client_creds); + if (state->username != NULL) + { + free(state->username); + state->username = NULL; + } + if (state->targetname != NULL) + { + free(state->targetname); + state->targetname = NULL; + } + if (state->response != NULL) + { + free(state->response); + state->response = NULL; + } + if (state->delegated_credentials_cache) + { + // TODO: what about actually destroying the cache? It can't be done now as + // the whole point is having it around for the lifetime of the "session" + free(state->delegated_credentials_cache); + } + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *auth_data) +{ + OM_uint32 maj_stat; + OM_uint32 min_stat; + gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; + gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; + int ret = AUTH_GSS_CONTINUE; + gss_client_response *response = NULL; + + // Always clear out the old response + if (state->response != NULL) + { + free(state->response); + state->response = NULL; + } + + // we don't need to check the authentication token if S4U2Self protocol + // transition was done, because we already have the client credentials. + if (state->client_creds == GSS_C_NO_CREDENTIAL) + { + if (auth_data && *auth_data) + { + int len; + input_token.value = base64_decode(auth_data, &len); + input_token.length = len; + } + else + { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->message = strdup("No auth_data value in request from client"); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + maj_stat = gss_accept_sec_context(&min_stat, + &state->context, + state->server_creds, + &input_token, + GSS_C_NO_CHANNEL_BINDINGS, + &state->client_name, + NULL, + &output_token, + NULL, + NULL, + &state->client_creds); + + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_accept_sec_context", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + // Grab the server response to send back to the client + if (output_token.length) + { + state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); + maj_stat = gss_release_buffer(&min_stat, &output_token); + } + } + + // Get the user name + maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + state->username = (char *)malloc(output_token.length + 1); + strncpy(state->username, (char*) output_token.value, output_token.length); + state->username[output_token.length] = 0; + + // Get the target name if no server creds were supplied + if (state->server_creds == GSS_C_NO_CREDENTIAL) + { + gss_name_t target_name = GSS_C_NO_NAME; + maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); + if (GSS_ERROR(maj_stat)) + { + response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + state->targetname = (char *)malloc(output_token.length + 1); + strncpy(state->targetname, (char*) output_token.value, output_token.length); + state->targetname[output_token.length] = 0; + } + + if (state->constrained_delegation && state->client_creds != GSS_C_NO_CREDENTIAL) + { + if ((response = store_gss_creds(state)) != NULL) + { + goto end; + } + } + + ret = AUTH_GSS_COMPLETE; + +end: + if (output_token.length) + gss_release_buffer(&min_stat, &output_token); + if (input_token.value) + free(input_token.value); + + if(response == NULL) { + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->return_code = ret; + } + + // Return the response + return response; +} + +static gss_client_response *store_gss_creds(gss_server_state *state) +{ + OM_uint32 maj_stat, min_stat; + krb5_principal princ = NULL; + krb5_ccache ccache = NULL; + krb5_error_code problem; + krb5_context context; + gss_client_response *response = NULL; + + problem = krb5_init_context(&context); + if (problem) { + response = other_error("No auth_data value in request from client"); + return response; + } + + problem = krb5_parse_name(context, state->username, &princ); + if (problem) { + response = krb5_ctx_error(context, problem); + goto end; + } + + if ((response = create_krb5_ccache(state, context, princ, &ccache))) + { + goto end; + } + + maj_stat = gss_krb5_copy_ccache(&min_stat, state->client_creds, ccache); + if (GSS_ERROR(maj_stat)) { + response = gss_error(__func__, "gss_krb5_copy_ccache", maj_stat, min_stat); + response->return_code = AUTH_GSS_ERROR; + goto end; + } + + krb5_cc_close(context, ccache); + ccache = NULL; + + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + // TODO: something other than AUTH_GSS_COMPLETE? + response->return_code = AUTH_GSS_COMPLETE; + + end: + if (princ) + krb5_free_principal(context, princ); + if (ccache) + krb5_cc_destroy(context, ccache); + krb5_free_context(context); + + return response; +} + +static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context kcontext, krb5_principal princ, krb5_ccache *ccache) +{ + char *ccname = NULL; + int fd; + krb5_error_code problem; + krb5_ccache tmp_ccache = NULL; + gss_client_response *error = NULL; + + // TODO: mod_auth_kerb used a temp file under /run/httpd/krbcache. what can we do? + ccname = strdup("FILE:/tmp/krb5cc_nodekerberos_XXXXXX"); + if (!ccname) die1("Memory allocation failed"); + + fd = mkstemp(ccname + strlen("FILE:")); + if (fd < 0) { + error = other_error("mkstemp() failed: %s", strerror(errno)); + goto end; + } + + close(fd); + + problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache); + if (problem) { + error = krb5_ctx_error(kcontext, problem); + goto end; + } + + problem = krb5_cc_initialize(kcontext, tmp_ccache, princ); + if (problem) { + error = krb5_ctx_error(kcontext, problem); + goto end; + } + + state->delegated_credentials_cache = strdup(ccname); + + // TODO: how/when to cleanup the creds cache file? + // TODO: how to expose the credentials expiration time? + + *ccache = tmp_ccache; + tmp_ccache = NULL; + + end: + if (tmp_ccache) + krb5_cc_destroy(kcontext, tmp_ccache); + + if (ccname && error) + unlink(ccname); + + if (ccname) + free(ccname); + + return error; +} + + +gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min) { + OM_uint32 maj_stat, min_stat; + OM_uint32 msg_ctx = 0; + gss_buffer_desc status_string; + + gss_client_response *response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + + char *message = NULL; + message = calloc(1024, 1); + if(message == NULL) die1("Memory allocation failed"); + + response->message = message; + + int nleft = 1024; + int n; + + n = snprintf(message, nleft, "%s(%s)", func, op); + message += n; + nleft -= n; + + do { + maj_stat = gss_display_status (&min_stat, + err_maj, + GSS_C_GSS_CODE, + GSS_C_NO_OID, + &msg_ctx, + &status_string); + if(GSS_ERROR(maj_stat)) + break; + + n = snprintf(message, nleft, ": %.*s", + (int)status_string.length, (char*)status_string.value); + message += n; + nleft -= n; + + gss_release_buffer(&min_stat, &status_string); + + maj_stat = gss_display_status (&min_stat, + err_min, + GSS_C_MECH_CODE, + GSS_C_NULL_OID, + &msg_ctx, + &status_string); + if(!GSS_ERROR(maj_stat)) { + n = snprintf(message, nleft, ": %.*s", + (int)status_string.length, (char*)status_string.value); + message += n; + nleft -= n; + + gss_release_buffer(&min_stat, &status_string); + } + } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); + + return response; +} + +static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem) +{ + gss_client_response *response = NULL; + const char *error_text = krb5_get_error_message(context, problem); + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->message = strdup(error_text); + // TODO: something other than AUTH_GSS_ERROR? AUTH_KRB5_ERROR ? + response->return_code = AUTH_GSS_ERROR; + krb5_free_error_message(context, error_text); + return response; +} + +static gss_client_response *other_error(const char *fmt, ...) +{ + size_t needed; + char *msg; + gss_client_response *response = NULL; + va_list ap, aps; + + va_start(ap, fmt); + + va_copy(aps, ap); + needed = snprintf(NULL, 0, fmt, aps); + va_end(aps); + + msg = malloc(needed); + if (!msg) die1("Memory allocation failed"); + + vsnprintf(msg, needed, fmt, ap); + va_end(ap); + + response = calloc(1, sizeof(gss_client_response)); + if(response == NULL) die1("Memory allocation failed"); + response->message = msg; + + // TODO: something other than AUTH_GSS_ERROR? + response->return_code = AUTH_GSS_ERROR; + + return response; +} + + +#pragma clang diagnostic pop + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h new file mode 100644 index 0000000..fa7e311 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h @@ -0,0 +1,73 @@ +/** + * Copyright (c) 2006-2009 Apple Inc. All rights reserved. + * + * 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. + **/ +#ifndef KERBEROS_GSS_H +#define KERBEROS_GSS_H + +#include + +#include +#include +#include + +#define krb5_get_err_text(context,code) error_message(code) + +#define AUTH_GSS_ERROR -1 +#define AUTH_GSS_COMPLETE 1 +#define AUTH_GSS_CONTINUE 0 + +#define GSS_AUTH_P_NONE 1 +#define GSS_AUTH_P_INTEGRITY 2 +#define GSS_AUTH_P_PRIVACY 4 + +typedef struct { + int return_code; + char *message; +} gss_client_response; + +typedef struct { + gss_ctx_id_t context; + gss_name_t server_name; + long int gss_flags; + char* username; + char* response; +} gss_client_state; + +typedef struct { + gss_ctx_id_t context; + gss_name_t server_name; + gss_name_t client_name; + gss_cred_id_t server_creds; + gss_cred_id_t client_creds; + char* username; + char* targetname; + char* response; + bool constrained_delegation; + char* delegated_credentials_cache; +} gss_server_state; + +// char* server_principal_details(const char* service, const char* hostname); + +gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); +gss_client_response *authenticate_gss_client_clean(gss_client_state *state); +gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); +gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); +gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); + +gss_client_response *authenticate_gss_server_init(const char* service, bool constrained_delegation, const char *username, gss_server_state* state); +gss_client_response *authenticate_gss_server_clean(gss_server_state *state); +gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *challenge); + +#endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js new file mode 100644 index 0000000..d9120fb --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js @@ -0,0 +1,15 @@ +// Load the native SSPI classes +var kerberos = require('../build/Release/kerberos') + , Kerberos = kerberos.Kerberos + , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer + , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor + , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials + , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; +var SSPI = function() { +} + +exports.SSPI = SSPI; +exports.SecurityBuffer = SecurityBuffer; +exports.SecurityBufferDescriptor = SecurityBufferDescriptor; +exports.SecurityCredentials = SecurityCredentials; +exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c new file mode 100644 index 0000000..502a021 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c @@ -0,0 +1,121 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * 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. + **/ + +#include "base64.h" + +#include +#include + +// base64 tables +static char basis_64[] = + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static signed char index_64[128] = +{ + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, + -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, + 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, + -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, + 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, + -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, + 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 +}; +#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) + +// base64_encode : base64 encode +// +// value : data to encode +// vlen : length of data +// (result) : new char[] - c-str of result +char *base64_encode(const unsigned char *value, int vlen) +{ + char *result = (char *)malloc((vlen * 4) / 3 + 5); + char *out = result; + unsigned char oval; + + while (vlen >= 3) + { + *out++ = basis_64[value[0] >> 2]; + *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; + *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; + *out++ = basis_64[value[2] & 0x3F]; + value += 3; + vlen -= 3; + } + if (vlen > 0) + { + *out++ = basis_64[value[0] >> 2]; + oval = (value[0] << 4) & 0x30; + if (vlen > 1) oval |= value[1] >> 4; + *out++ = basis_64[oval]; + *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; + *out++ = '='; + } + *out = '\0'; + + return result; +} + +// base64_decode : base64 decode +// +// value : c-str to decode +// rlen : length of decoded result +// (result) : new unsigned char[] - decoded result +unsigned char *base64_decode(const char *value, int *rlen) +{ + int c1, c2, c3, c4; + int vlen = (int)strlen(value); + unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); + unsigned char *out = result; + *rlen = 0; + + while (1) + { + if (value[0]==0) + return result; + c1 = value[0]; + if (CHAR64(c1) == -1) + goto base64_decode_error;; + c2 = value[1]; + if (CHAR64(c2) == -1) + goto base64_decode_error;; + c3 = value[2]; + if ((c3 != '=') && (CHAR64(c3) == -1)) + goto base64_decode_error;; + c4 = value[3]; + if ((c4 != '=') && (CHAR64(c4) == -1)) + goto base64_decode_error;; + + value += 4; + *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); + *rlen += 1; + if (c3 != '=') + { + *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); + *rlen += 1; + if (c4 != '=') + { + *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); + *rlen += 1; + } + } + } + +base64_decode_error: + *result = 0; + *rlen = 0; + return result; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h new file mode 100644 index 0000000..f0e1f06 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h @@ -0,0 +1,18 @@ +/** + * Copyright (c) 2006-2008 Apple Inc. All rights reserved. + * + * 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. + **/ + +char *base64_encode(const unsigned char *value, int vlen); +unsigned char *base64_decode(const char *value, int *rlen); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc new file mode 100644 index 0000000..c7b583f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc @@ -0,0 +1,51 @@ +#include "kerberos.h" +#include +#include +#include "base64.h" +#include "wrappers/security_buffer.h" +#include "wrappers/security_buffer_descriptor.h" +#include "wrappers/security_context.h" +#include "wrappers/security_credentials.h" + +Nan::Persistent Kerberos::constructor_template; + +Kerberos::Kerberos() : Nan::ObjectWrap() { +} + +void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("Kerberos").ToLocalChecked()); + + // Set persistent + constructor_template.Reset(t); + + // Set the symbol + Nan::Set(target, Nan::New("Kerberos").ToLocalChecked(), t->GetFunction()); +} + +NAN_METHOD(Kerberos::New) { + // Load the security.dll library + load_library(); + // Create a Kerberos instance + Kerberos *kerberos = new Kerberos(); + // Return the kerberos object + kerberos->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +// Exporting function +NAN_MODULE_INIT(init) { + Kerberos::Initialize(target); + SecurityContext::Initialize(target); + SecurityBuffer::Initialize(target); + SecurityBufferDescriptor::Initialize(target); + SecurityCredentials::Initialize(target); +} + +NODE_MODULE(kerberos, init); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h new file mode 100644 index 0000000..0fd2760 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h @@ -0,0 +1,60 @@ +#ifndef KERBEROS_H +#define KERBEROS_H + +#include +#include +#include +#include "nan.h" + +extern "C" { + #include "kerberos_sspi.h" + #include "base64.h" +} + +using namespace v8; +using namespace node; + +class Kerberos : public Nan::ObjectWrap { + +public: + Kerberos(); + ~Kerberos() {}; + + // Constructor used for creating new Kerberos objects from C++ + static Nan::Persistent constructor_template; + + // Initialize function for the object + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + + // Method available + static NAN_METHOD(AcquireAlternateCredentials); + static NAN_METHOD(PrepareOutboundPackage); + static NAN_METHOD(DecryptMessage); + static NAN_METHOD(EncryptMessage); + static NAN_METHOD(QueryContextAttributes); + +private: + static NAN_METHOD(New); + + // Pointer to context object + SEC_WINNT_AUTH_IDENTITY m_Identity; + // credentials + CredHandle m_Credentials; + // Expiry time for ticket + TimeStamp Expiration; + // package info + SecPkgInfo m_PkgInfo; + // context + CtxtHandle m_Context; + // Do we have a context + bool m_HaveContext; + // Attributes + DWORD CtxtAttr; + + // Handles the uv calls + static void Process(uv_work_t* work_req); + // Called after work is done + static void After(uv_work_t* work_req); +}; + +#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c new file mode 100644 index 0000000..d75c9ab --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c @@ -0,0 +1,244 @@ +#include "kerberos_sspi.h" +#include +#include + +static HINSTANCE _sspi_security_dll = NULL; +static HINSTANCE _sspi_secur32_dll = NULL; + +/** + * Encrypt A Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { + // Create function pointer instance + encryptMessage_fn pfn_encryptMessage = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + // Map function to library method + pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); + // Check if the we managed to map function pointer + if(!pfn_encryptMessage) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); +} + +/** + * Acquire Credentials + */ +SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( + LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, + void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, + PCredHandle phCredential, PTimeStamp ptsExpiry +) { + SECURITY_STATUS status; + // Create function pointer instance + acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + // Map function + #ifdef _UNICODE + pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); + #else + pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); + #endif + + // Check if the we managed to map function pointer + if(!pfn_acquireCredentialsHandle) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Status + status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, + pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry + ); + + // Call the function + return status; +} + +/** + * Delete Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { + // Create function pointer instance + deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + // Map function + pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); + + // Check if the we managed to map function pointer + if(!pfn_deleteSecurityContext) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_deleteSecurityContext)(phContext); +} + +/** + * Decrypt Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { + // Create function pointer instance + decryptMessage_fn pfn_decryptMessage = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + // Map function + pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); + + // Check if the we managed to map function pointer + if(!pfn_decryptMessage) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); +} + +/** + * Initialize Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( + PCredHandle phCredential, PCtxtHandle phContext, + LPSTR pszTargetName, unsigned long fContextReq, + unsigned long Reserved1, unsigned long TargetDataRep, + PSecBufferDesc pInput, unsigned long Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, + unsigned long * pfContextAttr, PTimeStamp ptsExpiry +) { + SECURITY_STATUS status; + // Create function pointer instance + initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + // Map function + #ifdef _UNICODE + pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); + #else + pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); + #endif + + // Check if the we managed to map function pointer + if(!pfn_initializeSecurityContext) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Execute intialize context + status = (*pfn_initializeSecurityContext)( + phCredential, phContext, pszTargetName, fContextReq, + Reserved1, TargetDataRep, pInput, Reserved2, + phNewContext, pOutput, pfContextAttr, ptsExpiry + ); + + // Call the function + return status; +} +/** + * Query Context Attributes + */ +SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( + PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer +) { + // Create function pointer instance + queryContextAttributes_fn pfn_queryContextAttributes = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return -1; + + #ifdef _UNICODE + pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); + #else + pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); + #endif + + // Check if the we managed to map function pointer + if(!pfn_queryContextAttributes) { + printf("GetProcAddress failed.\n"); + return -2; + } + + // Call the function + return (*pfn_queryContextAttributes)( + phContext, ulAttribute, pBuffer + ); +} + +/** + * InitSecurityInterface + */ +PSecurityFunctionTable _ssip_InitSecurityInterface() { + INIT_SECURITY_INTERFACE InitSecurityInterface; + PSecurityFunctionTable pSecurityInterface = NULL; + + // Return error if library not loaded + if(_sspi_security_dll == NULL) return NULL; + + #ifdef _UNICODE + // Get the address of the InitSecurityInterface function. + InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( + _sspi_secur32_dll, + TEXT("InitSecurityInterfaceW")); + #else + // Get the address of the InitSecurityInterface function. + InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( + _sspi_secur32_dll, + TEXT("InitSecurityInterfaceA")); + #endif + + if(!InitSecurityInterface) { + printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); + return NULL; + } + + // Use InitSecurityInterface to get the function table. + pSecurityInterface = (*InitSecurityInterface)(); + + if(!pSecurityInterface) { + printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); + return NULL; + } + + return pSecurityInterface; +} + +/** + * Load security.dll dynamically + */ +int load_library() { + DWORD err; + // Load the library + _sspi_security_dll = LoadLibrary("security.dll"); + + // Check if the library loaded + if(_sspi_security_dll == NULL) { + err = GetLastError(); + return err; + } + + // Load the library + _sspi_secur32_dll = LoadLibrary("secur32.dll"); + + // Check if the library loaded + if(_sspi_secur32_dll == NULL) { + err = GetLastError(); + return err; + } + + return 0; +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h new file mode 100644 index 0000000..a3008dc --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h @@ -0,0 +1,106 @@ +#ifndef SSPI_C_H +#define SSPI_C_H + +#define SECURITY_WIN32 1 + +#include +#include + +/** + * Encrypt A Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); + +typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); + +/** + * Acquire Credentials + */ +SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( + LPSTR pszPrincipal, // Name of principal + LPSTR pszPackage, // Name of package + unsigned long fCredentialUse, // Flags indicating use + void * pvLogonId, // Pointer to logon ID + void * pAuthData, // Package specific data + SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func + void * pvGetKeyArgument, // Value to pass to GetKey() + PCredHandle phCredential, // (out) Cred Handle + PTimeStamp ptsExpiry // (out) Lifetime (optional) +); + +typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( + LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, + void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, + PCredHandle phCredential, PTimeStamp ptsExpiry + ); + +/** + * Delete Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( + PCtxtHandle phContext // Context to delete +); + +typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); + +/** + * Decrypt Message + */ +SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( + PCtxtHandle phContext, + PSecBufferDesc pMessage, + unsigned long MessageSeqNo, + unsigned long pfQOP +); + +typedef DWORD (WINAPI *decryptMessage_fn)( + PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); + +/** + * Initialize Security Context + */ +SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( + PCredHandle phCredential, // Cred to base context + PCtxtHandle phContext, // Existing context (OPT) + LPSTR pszTargetName, // Name of target + unsigned long fContextReq, // Context Requirements + unsigned long Reserved1, // Reserved, MBZ + unsigned long TargetDataRep, // Data rep of target + PSecBufferDesc pInput, // Input Buffers + unsigned long Reserved2, // Reserved, MBZ + PCtxtHandle phNewContext, // (out) New Context handle + PSecBufferDesc pOutput, // (inout) Output Buffers + unsigned long * pfContextAttr, // (out) Context attrs + PTimeStamp ptsExpiry // (out) Life span (OPT) +); + +typedef DWORD (WINAPI *initializeSecurityContext_fn)( + PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, + unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, + PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); + +/** + * Query Context Attributes + */ +SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( + PCtxtHandle phContext, // Context to query + unsigned long ulAttribute, // Attribute to query + void * pBuffer // Buffer for attributes +); + +typedef DWORD (WINAPI *queryContextAttributes_fn)( + PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); + +/** + * InitSecurityInterface + */ +PSecurityFunctionTable _ssip_InitSecurityInterface(); + +typedef DWORD (WINAPI *initSecurityInterface_fn) (); + +/** + * Load security.dll dynamically + */ +int load_library(); + +#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc new file mode 100644 index 0000000..e7a472f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc @@ -0,0 +1,7 @@ +#include "worker.h" + +Worker::Worker() { +} + +Worker::~Worker() { +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h new file mode 100644 index 0000000..c2ccb6b --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h @@ -0,0 +1,38 @@ +#ifndef WORKER_H_ +#define WORKER_H_ + +#include +#include +#include +#include + +using namespace node; +using namespace v8; + +class Worker { + public: + Worker(); + virtual ~Worker(); + + // libuv's request struct. + uv_work_t request; + // Callback + Nan::Callback *callback; + // Parameters + void *parameters; + // Results + void *return_value; + // Did we raise an error + bool error; + // The error message + char *error_message; + // Error code if not message + int error_code; + // Any return code + int return_code; + // Method we are going to fire + void (*execute)(Worker *worker); + Local (*mapper)(Worker *worker); +}; + +#endif // WORKER_H_ diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc new file mode 100644 index 0000000..fdf8e49 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc @@ -0,0 +1,101 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "security_buffer.h" + +using namespace node; + +Nan::Persistent SecurityBuffer::constructor_template; + +SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : Nan::ObjectWrap() { + this->size = size; + this->data = calloc(size, sizeof(char)); + this->security_type = security_type; + // Set up the data in the sec_buffer + this->sec_buffer.BufferType = security_type; + this->sec_buffer.cbBuffer = (unsigned long)size; + this->sec_buffer.pvBuffer = this->data; +} + +SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : Nan::ObjectWrap() { + this->size = size; + this->data = data; + this->security_type = security_type; + // Set up the data in the sec_buffer + this->sec_buffer.BufferType = security_type; + this->sec_buffer.cbBuffer = (unsigned long)size; + this->sec_buffer.pvBuffer = this->data; +} + +SecurityBuffer::~SecurityBuffer() { + free(this->data); +} + +NAN_METHOD(SecurityBuffer::New) { + SecurityBuffer *security_obj; + + if(info.Length() != 2) + return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); + + if(!info[0]->IsInt32()) + return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); + + if(!info[1]->IsInt32() && !Buffer::HasInstance(info[1])) + return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); + + // Unpack buffer type + uint32_t buffer_type = info[0]->ToUint32()->Value(); + + // If we have an integer + if(info[1]->IsInt32()) { + security_obj = new SecurityBuffer(buffer_type, info[1]->ToUint32()->Value()); + } else { + // Get the length of the Buffer + size_t length = Buffer::Length(info[1]->ToObject()); + // Allocate space for the internal void data pointer + void *data = calloc(length, sizeof(char)); + // Write the data to out of V8 heap space + memcpy(data, Buffer::Data(info[1]->ToObject()), length); + // Create new SecurityBuffer + security_obj = new SecurityBuffer(buffer_type, length, data); + } + + // Wrap it + security_obj->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +NAN_METHOD(SecurityBuffer::ToBuffer) { + // Unpack the Security Buffer object + SecurityBuffer *security_obj = Nan::ObjectWrap::Unwrap(info.This()); + // Create a Buffer + Local buffer = Nan::CopyBuffer((char *)security_obj->data, (uint32_t)security_obj->size).ToLocalChecked(); + // Return the buffer + info.GetReturnValue().Set(buffer); +} + +void SecurityBuffer::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("SecurityBuffer").ToLocalChecked()); + + // Class methods + Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer); + + // Set persistent + constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("SecurityBuffer").ToLocalChecked(), t->GetFunction()); +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h new file mode 100644 index 0000000..0c97d56 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h @@ -0,0 +1,48 @@ +#ifndef SECURITY_BUFFER_H +#define SECURITY_BUFFER_H + +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include +#include +#include +#include + +using namespace v8; +using namespace node; + +class SecurityBuffer : public Nan::ObjectWrap { + public: + SecurityBuffer(uint32_t security_type, size_t size); + SecurityBuffer(uint32_t security_type, size_t size, void *data); + ~SecurityBuffer(); + + // Internal values + void *data; + size_t size; + uint32_t security_type; + SecBuffer sec_buffer; + + // Has instance check + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + // Functions available from V8 + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + static NAN_METHOD(ToBuffer); + + // Constructor used for creating new Long objects from C++ + static Nan::Persistent constructor_template; + + private: + static NAN_METHOD(New); +}; + +#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js new file mode 100644 index 0000000..4996163 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js @@ -0,0 +1,12 @@ +var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; + +// Add some attributes +SecurityBufferNative.VERSION = 0; +SecurityBufferNative.EMPTY = 0; +SecurityBufferNative.DATA = 1; +SecurityBufferNative.TOKEN = 2; +SecurityBufferNative.PADDING = 9; +SecurityBufferNative.STREAM = 10; + +// Export the modified class +exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc new file mode 100644 index 0000000..fce0d81 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc @@ -0,0 +1,182 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include "security_buffer_descriptor.h" +#include "security_buffer.h" + +Nan::Persistent SecurityBufferDescriptor::constructor_template; + +SecurityBufferDescriptor::SecurityBufferDescriptor() : Nan::ObjectWrap() { +} + +SecurityBufferDescriptor::SecurityBufferDescriptor(const Nan::Persistent& arrayObjectPersistent) : Nan::ObjectWrap() { + SecurityBuffer *security_obj = NULL; + // Get the Local value + Local arrayObject = Nan::New(arrayObjectPersistent); + + // Safe reference to array + this->arrayObject = arrayObject; + + // Unpack the array and ensure we have a valid descriptor + this->secBufferDesc.cBuffers = arrayObject->Length(); + this->secBufferDesc.ulVersion = SECBUFFER_VERSION; + + if(arrayObject->Length() == 1) { + // Unwrap the buffer + security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); + // Assign the buffer + this->secBufferDesc.pBuffers = &security_obj->sec_buffer; + } else { + this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; + this->secBufferDesc.cBuffers = arrayObject->Length(); + + // Assign the buffers + for(uint32_t i = 0; i < arrayObject->Length(); i++) { + security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); + this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; + this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; + this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; + } + } +} + +SecurityBufferDescriptor::~SecurityBufferDescriptor() { +} + +size_t SecurityBufferDescriptor::bufferSize() { + SecurityBuffer *security_obj = NULL; + + if(this->secBufferDesc.cBuffers == 1) { + security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); + return security_obj->size; + } else { + int bytesToAllocate = 0; + + for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { + bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; + } + + // Return total size + return bytesToAllocate; + } +} + +char *SecurityBufferDescriptor::toBuffer() { + SecurityBuffer *security_obj = NULL; + char *data = NULL; + + if(this->secBufferDesc.cBuffers == 1) { + security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); + data = (char *)malloc(security_obj->size * sizeof(char)); + memcpy(data, security_obj->data, security_obj->size); + } else { + size_t bytesToAllocate = this->bufferSize(); + char *data = (char *)calloc(bytesToAllocate, sizeof(char)); + int offset = 0; + + for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { + memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); + offset +=this->secBufferDesc.pBuffers[i].cbBuffer; + } + + // Return the data + return data; + } + + return data; +} + +NAN_METHOD(SecurityBufferDescriptor::New) { + SecurityBufferDescriptor *security_obj; + Nan::Persistent arrayObject; + + if(info.Length() != 1) + return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); + + if(!info[0]->IsInt32() && !info[0]->IsArray()) + return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); + + if(info[0]->IsArray()) { + Local array = Local::Cast(info[0]); + // Iterate over all items and ensure we the right type + for(uint32_t i = 0; i < array->Length(); i++) { + if(!SecurityBuffer::HasInstance(array->Get(i))) { + return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); + } + } + } + + // We have a single integer + if(info[0]->IsInt32()) { + // Create new SecurityBuffer instance + Local argv[] = {Nan::New(0x02), info[0]}; + Local security_buffer = Nan::New(SecurityBuffer::constructor_template)->GetFunction()->NewInstance(2, argv); + // Create a new array + Local array = Nan::New(1); + // Set the first value + array->Set(0, security_buffer); + + // Create persistent handle + Nan::Persistent persistenHandler; + persistenHandler.Reset(array); + + // Create descriptor + security_obj = new SecurityBufferDescriptor(persistenHandler); + } else { + // Create a persistent handler + Nan::Persistent persistenHandler; + persistenHandler.Reset(Local::Cast(info[0])); + // Create a descriptor + security_obj = new SecurityBufferDescriptor(persistenHandler); + } + + // Wrap it + security_obj->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +NAN_METHOD(SecurityBufferDescriptor::ToBuffer) { + // Unpack the Security Buffer object + SecurityBufferDescriptor *security_obj = Nan::ObjectWrap::Unwrap(info.This()); + + // Get the buffer + char *buffer_data = security_obj->toBuffer(); + size_t buffer_size = security_obj->bufferSize(); + + // Create a Buffer + Local buffer = Nan::CopyBuffer(buffer_data, (uint32_t)buffer_size).ToLocalChecked(); + + // Return the buffer + info.GetReturnValue().Set(buffer); +} + +void SecurityBufferDescriptor::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("SecurityBufferDescriptor").ToLocalChecked()); + + // Class methods + Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer); + + // Set persistent + constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("SecurityBufferDescriptor").ToLocalChecked(), t->GetFunction()); +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h new file mode 100644 index 0000000..dc28f7e --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h @@ -0,0 +1,46 @@ +#ifndef SECURITY_BUFFER_DESCRIPTOR_H +#define SECURITY_BUFFER_DESCRIPTOR_H + +#include +#include +#include + +#include +#include +#include +#include + +using namespace v8; +using namespace node; + +class SecurityBufferDescriptor : public Nan::ObjectWrap { + public: + Local arrayObject; + SecBufferDesc secBufferDesc; + + SecurityBufferDescriptor(); + SecurityBufferDescriptor(const Nan::Persistent& arrayObjectPersistent); + ~SecurityBufferDescriptor(); + + // Has instance check + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + char *toBuffer(); + size_t bufferSize(); + + // Functions available from V8 + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + static NAN_METHOD(ToBuffer); + + // Constructor used for creating new Long objects from C++ + static Nan::Persistent constructor_template; + + private: + static NAN_METHOD(New); +}; + +#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js new file mode 100644 index 0000000..9421392 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js @@ -0,0 +1,3 @@ +var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; +// Export the modified class +exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc new file mode 100644 index 0000000..5d7ad54 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc @@ -0,0 +1,856 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "security_context.h" +#include "security_buffer_descriptor.h" + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) +#endif + +static LPSTR DisplaySECError(DWORD ErrCode); + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// UV Lib callbacks +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void Process(uv_work_t* work_req) { + // Grab the worker + Worker *worker = static_cast(work_req->data); + // Execute the worker code + worker->execute(worker); +} + +static void After(uv_work_t* work_req) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Get the worker reference + Worker *worker = static_cast(work_req->data); + + // If we have an error + if(worker->error) { + Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); + Local obj = err->ToObject(); + obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); + Local info[2] = { err, Nan::Null() }; + // Execute the error + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } else { + // // Map the data + Local result = worker->mapper(worker); + // Set up the callback with a null first + Local info[2] = { Nan::Null(), result}; + // Wrap the callback function call in a TryCatch so that we can call + // node's FatalException afterwards. This makes it possible to catch + // the exception from JavaScript land using the + // process.on('uncaughtException') event. + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } + + // Clean up the memory + delete worker->callback; + delete worker; +} + +Nan::Persistent SecurityContext::constructor_template; + +SecurityContext::SecurityContext() : Nan::ObjectWrap() { +} + +SecurityContext::~SecurityContext() { + if(this->hasContext) { + _sspi_DeleteSecurityContext(&this->m_Context); + } +} + +NAN_METHOD(SecurityContext::New) { + PSecurityFunctionTable pSecurityInterface = NULL; + DWORD dwNumOfPkgs; + SECURITY_STATUS status; + + // Create code object + SecurityContext *security_obj = new SecurityContext(); + // Get security table interface + pSecurityInterface = _ssip_InitSecurityInterface(); + // Call the security interface + status = (*pSecurityInterface->EnumerateSecurityPackages)( + &dwNumOfPkgs, + &security_obj->m_PkgInfo); + if(status != SEC_E_OK) { + printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); + return Nan::ThrowError("Failed in retrieving security packages"); + } + + // Wrap it + security_obj->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +// +// Async InitializeContext +// +typedef struct SecurityContextStaticInitializeCall { + char *service_principal_name_str; + char *decoded_input_str; + int decoded_input_str_length; + SecurityContext *context; +} SecurityContextStaticInitializeCall; + +static void _initializeContext(Worker *worker) { + // Status of operation + SECURITY_STATUS status; + BYTE *out_bound_data_str = NULL; + SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; + + // Structures used for c calls + SecBufferDesc ibd, obd; + SecBuffer ib, ob; + + // + // Prepare data structure for returned data from SSPI + ob.BufferType = SECBUFFER_TOKEN; + ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; + // Allocate space for return data + out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; + ob.pvBuffer = out_bound_data_str; + // prepare buffer description + obd.cBuffers = 1; + obd.ulVersion = SECBUFFER_VERSION; + obd.pBuffers = &ob; + + // + // Prepare the data we are passing to the SSPI method + if(call->decoded_input_str_length > 0) { + ib.BufferType = SECBUFFER_TOKEN; + ib.cbBuffer = call->decoded_input_str_length; + ib.pvBuffer = call->decoded_input_str; + // prepare buffer description + ibd.cBuffers = 1; + ibd.ulVersion = SECBUFFER_VERSION; + ibd.pBuffers = &ib; + } + + // Perform initialization step + status = _sspi_initializeSecurityContext( + &call->context->security_credentials->m_Credentials + , NULL + , const_cast(call->service_principal_name_str) + , 0x02 // MUTUAL + , 0 + , 0 // Network + , call->decoded_input_str_length > 0 ? &ibd : NULL + , 0 + , &call->context->m_Context + , &obd + , &call->context->CtxtAttr + , &call->context->Expiration + ); + + // If we have a ok or continue let's prepare the result + if(status == SEC_E_OK + || status == SEC_I_COMPLETE_NEEDED + || status == SEC_I_CONTINUE_NEEDED + || status == SEC_I_COMPLETE_AND_CONTINUE + ) { + call->context->hasContext = true; + call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); + + // Set the context + worker->return_code = status; + worker->return_value = call->context; + } else if(status == SEC_E_INSUFFICIENT_MEMORY) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INSUFFICIENT_MEMORY There is not enough memory available to complete the requested action."; + } else if(status == SEC_E_INTERNAL_ERROR) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INTERNAL_ERROR An error occurred that did not map to an SSPI error code."; + } else if(status == SEC_E_INVALID_HANDLE) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INVALID_HANDLE The handle passed to the function is not valid."; + } else if(status == SEC_E_INVALID_TOKEN) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_INVALID_TOKEN The error is due to a malformed input token, such as a token corrupted in transit, a token of incorrect size, or a token passed into the wrong security package. Passing a token to the wrong package can happen if the client and server did not negotiate the proper security package."; + } else if(status == SEC_E_LOGON_DENIED) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_LOGON_DENIED The logon failed."; + } else if(status == SEC_E_NO_AUTHENTICATING_AUTHORITY) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_NO_AUTHENTICATING_AUTHORITY No authority could be contacted for authentication. The domain name of the authenticating party could be wrong, the domain could be unreachable, or there might have been a trust relationship failure."; + } else if(status == SEC_E_NO_CREDENTIALS) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_NO_CREDENTIALS No credentials are available in the security package."; + } else if(status == SEC_E_TARGET_UNKNOWN) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_TARGET_UNKNOWN The target was not recognized."; + } else if(status == SEC_E_UNSUPPORTED_FUNCTION) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_UNSUPPORTED_FUNCTION A context attribute flag that is not valid (ISC_REQ_DELEGATE or ISC_REQ_PROMPT_FOR_CREDS) was specified in the fContextReq parameter."; + } else if(status == SEC_E_WRONG_PRINCIPAL) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = "SEC_E_WRONG_PRINCIPAL The principal that received the authentication request is not the same as the one passed into the pszTargetName parameter. This indicates a failure in mutual authentication."; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } + + // Clean up data + if(call->decoded_input_str != NULL) free(call->decoded_input_str); + if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); +} + +static Local _map_initializeContext(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return context->handle(); +} + +NAN_METHOD(SecurityContext::InitializeContext) { + char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; + int decoded_input_str_length = NULL; + // Store reference to security credentials + SecurityCredentials *security_credentials = NULL; + + // We need 3 parameters + if(info.Length() != 4) + return Nan::ThrowError("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); + + // First parameter must be an instance of SecurityCredentials + if(!SecurityCredentials::HasInstance(info[0])) + return Nan::ThrowError("First parameter for Initialize must be an instance of SecurityCredentials"); + + // Second parameter must be a string + if(!info[1]->IsString()) + return Nan::ThrowError("Second parameter for Initialize must be a string"); + + // Third parameter must be a base64 encoded string + if(!info[2]->IsString()) + return Nan::ThrowError("Second parameter for Initialize must be a string"); + + // Third parameter must be a callback + if(!info[3]->IsFunction()) + return Nan::ThrowError("Third parameter for Initialize must be a callback function"); + + // Let's unpack the values + Local service_principal_name = info[1]->ToString(); + service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); + service_principal_name->WriteUtf8(service_principal_name_str); + + // Unpack the user name + Local input = info[2]->ToString(); + + if(input->Utf8Length() > 0) { + input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); + input->WriteUtf8(input_str); + + // Now let's get the base64 decoded string + decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); + // Free original allocation + free(input_str); + } + + // Unpack the Security credentials + security_credentials = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); + // Create Security context instance + Local security_context_value = Nan::New(constructor_template)->GetFunction()->NewInstance(); + // Unwrap the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(security_context_value); + // Add a reference to the security_credentials + security_context->security_credentials = security_credentials; + + // Build the call function + SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); + call->context = security_context; + call->decoded_input_str = decoded_input_str; + call->decoded_input_str_length = decoded_input_str_length; + call->service_principal_name_str = service_principal_name_str; + + // Callback + Local callback = Local::Cast(info[3]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _initializeContext; + worker->mapper = _map_initializeContext; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +NAN_GETTER(SecurityContext::PayloadGetter) { + // Unpack the context object + SecurityContext *context = Nan::ObjectWrap::Unwrap(info.This()); + // Return the low bits + info.GetReturnValue().Set(Nan::New(context->payload).ToLocalChecked()); +} + +NAN_GETTER(SecurityContext::HasContextGetter) { + // Unpack the context object + SecurityContext *context = Nan::ObjectWrap::Unwrap(info.This()); + // Return the low bits + info.GetReturnValue().Set(Nan::New(context->hasContext)); +} + +// +// Async InitializeContextStep +// +typedef struct SecurityContextStepStaticInitializeCall { + char *service_principal_name_str; + char *decoded_input_str; + int decoded_input_str_length; + SecurityContext *context; +} SecurityContextStepStaticInitializeCall; + +static void _initializeContextStep(Worker *worker) { + // Outbound data array + BYTE *out_bound_data_str = NULL; + // Status of operation + SECURITY_STATUS status; + // Unpack data + SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; + SecurityContext *context = call->context; + // Structures used for c calls + SecBufferDesc ibd, obd; + SecBuffer ib, ob; + + // + // Prepare data structure for returned data from SSPI + ob.BufferType = SECBUFFER_TOKEN; + ob.cbBuffer = context->m_PkgInfo->cbMaxToken; + // Allocate space for return data + out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; + ob.pvBuffer = out_bound_data_str; + // prepare buffer description + obd.cBuffers = 1; + obd.ulVersion = SECBUFFER_VERSION; + obd.pBuffers = &ob; + + // + // Prepare the data we are passing to the SSPI method + if(call->decoded_input_str_length > 0) { + ib.BufferType = SECBUFFER_TOKEN; + ib.cbBuffer = call->decoded_input_str_length; + ib.pvBuffer = call->decoded_input_str; + // prepare buffer description + ibd.cBuffers = 1; + ibd.ulVersion = SECBUFFER_VERSION; + ibd.pBuffers = &ib; + } + + // Perform initialization step + status = _sspi_initializeSecurityContext( + &context->security_credentials->m_Credentials + , context->hasContext == true ? &context->m_Context : NULL + , const_cast(call->service_principal_name_str) + , 0x02 // MUTUAL + , 0 + , 0 // Network + , call->decoded_input_str_length ? &ibd : NULL + , 0 + , &context->m_Context + , &obd + , &context->CtxtAttr + , &context->Expiration + ); + + // If we have a ok or continue let's prepare the result + if(status == SEC_E_OK + || status == SEC_I_COMPLETE_NEEDED + || status == SEC_I_CONTINUE_NEEDED + || status == SEC_I_COMPLETE_AND_CONTINUE + ) { + // Set the new payload + if(context->payload != NULL) free(context->payload); + context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); + worker->return_code = status; + worker->return_value = context; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } + + // Clean up data + if(call->decoded_input_str != NULL) free(call->decoded_input_str); + if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); +} + +static Local _map_initializeContextStep(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return context->handle(); +} + +NAN_METHOD(SecurityContext::InitalizeStep) { + char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; + int decoded_input_str_length = NULL; + + // We need 3 parameters + if(info.Length() != 3) + return Nan::ThrowError("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); + + // Second parameter must be a string + if(!info[0]->IsString()) + return Nan::ThrowError("First parameter for Initialize must be a string"); + + // Third parameter must be a base64 encoded string + if(!info[1]->IsString()) + return Nan::ThrowError("Second parameter for Initialize must be a string"); + + // Third parameter must be a base64 encoded string + if(!info[2]->IsFunction()) + return Nan::ThrowError("Third parameter for Initialize must be a callback function"); + + // Let's unpack the values + Local service_principal_name = info[0]->ToString(); + service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); + service_principal_name->WriteUtf8(service_principal_name_str); + + // Unpack the user name + Local input = info[1]->ToString(); + + if(input->Utf8Length() > 0) { + input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); + input->WriteUtf8(input_str); + // Now let's get the base64 decoded string + decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); + // Free input string + free(input_str); + } + + // Unwrap the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); + + // Create call structure + SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); + call->context = security_context; + call->decoded_input_str = decoded_input_str; + call->decoded_input_str_length = decoded_input_str_length; + call->service_principal_name_str = service_principal_name_str; + + // Callback + Local callback = Local::Cast(info[2]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _initializeContextStep; + worker->mapper = _map_initializeContextStep; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +// Async EncryptMessage +// +typedef struct SecurityContextEncryptMessageCall { + SecurityContext *context; + SecurityBufferDescriptor *descriptor; + unsigned long flags; +} SecurityContextEncryptMessageCall; + +static void _encryptMessage(Worker *worker) { + SECURITY_STATUS status; + // Unpack call + SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; + // Unpack the security context + SecurityContext *context = call->context; + SecurityBufferDescriptor *descriptor = call->descriptor; + + // Let's execute encryption + status = _sspi_EncryptMessage( + &context->m_Context + , call->flags + , &descriptor->secBufferDesc + , 0 + ); + + // We've got ok + if(status == SEC_E_OK) { + int bytesToAllocate = (int)descriptor->bufferSize(); + // Free up existing payload + if(context->payload != NULL) free(context->payload); + // Save the payload + context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); + // Set result + worker->return_code = status; + worker->return_value = context; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } +} + +static Local _map_encryptMessage(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return context->handle(); +} + +NAN_METHOD(SecurityContext::EncryptMessage) { + if(info.Length() != 3) + return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + if(!SecurityBufferDescriptor::HasInstance(info[0])) + return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + if(!info[1]->IsUint32()) + return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + if(!info[2]->IsFunction()) + return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); + + // Unpack the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); + + // Unpack the descriptor + SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); + + // Create call structure + SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); + call->context = security_context; + call->descriptor = descriptor; + call->flags = (unsigned long)info[1]->ToInteger()->Value(); + + // Callback + Local callback = Local::Cast(info[2]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _encryptMessage; + worker->mapper = _map_encryptMessage; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +// Async DecryptMessage +// +typedef struct SecurityContextDecryptMessageCall { + SecurityContext *context; + SecurityBufferDescriptor *descriptor; +} SecurityContextDecryptMessageCall; + +static void _decryptMessage(Worker *worker) { + unsigned long quality = 0; + SECURITY_STATUS status; + + // Unpack parameters + SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; + SecurityContext *context = call->context; + SecurityBufferDescriptor *descriptor = call->descriptor; + + // Let's execute encryption + status = _sspi_DecryptMessage( + &context->m_Context + , &descriptor->secBufferDesc + , 0 + , (unsigned long)&quality + ); + + // We've got ok + if(status == SEC_E_OK) { + int bytesToAllocate = (int)descriptor->bufferSize(); + // Free up existing payload + if(context->payload != NULL) free(context->payload); + // Save the payload + context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); + // Set return values + worker->return_code = status; + worker->return_value = context; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } +} + +static Local _map_decryptMessage(Worker *worker) { + // Unwrap the security context + SecurityContext *context = (SecurityContext *)worker->return_value; + // Return the value + return context->handle(); +} + +NAN_METHOD(SecurityContext::DecryptMessage) { + if(info.Length() != 2) + return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); + if(!SecurityBufferDescriptor::HasInstance(info[0])) + return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); + if(!info[1]->IsFunction()) + return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); + + // Unpack the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); + // Unpack the descriptor + SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); + // Create call structure + SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); + call->context = security_context; + call->descriptor = descriptor; + + // Callback + Local callback = Local::Cast(info[1]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _decryptMessage; + worker->mapper = _map_decryptMessage; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +// +// Async QueryContextAttributes +// +typedef struct SecurityContextQueryContextAttributesCall { + SecurityContext *context; + uint32_t attribute; +} SecurityContextQueryContextAttributesCall; + +static void _queryContextAttributes(Worker *worker) { + SECURITY_STATUS status; + + // Cast to data structure + SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; + + // Allocate some space + SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); + // Let's grab the query context attribute + status = _sspi_QueryContextAttributes( + &call->context->m_Context, + call->attribute, + sizes + ); + + if(status == SEC_E_OK) { + worker->return_code = status; + worker->return_value = sizes; + } else { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } +} + +static Local _map_queryContextAttributes(Worker *worker) { + // Cast to data structure + SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; + // Unpack the attribute + uint32_t attribute = call->attribute; + + // Convert data + if(attribute == SECPKG_ATTR_SIZES) { + SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; + // Create object + Local value = Nan::New(); + value->Set(Nan::New("maxToken").ToLocalChecked(), Nan::New(uint32_t(sizes->cbMaxToken))); + value->Set(Nan::New("maxSignature").ToLocalChecked(), Nan::New(uint32_t(sizes->cbMaxSignature))); + value->Set(Nan::New("blockSize").ToLocalChecked(), Nan::New(uint32_t(sizes->cbBlockSize))); + value->Set(Nan::New("securityTrailer").ToLocalChecked(), Nan::New(uint32_t(sizes->cbSecurityTrailer))); + return value; + } + + // Return the value + return Nan::Null(); +} + +NAN_METHOD(SecurityContext::QueryContextAttributes) { + if(info.Length() != 2) + return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); + if(!info[0]->IsInt32()) + return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); + if(!info[1]->IsFunction()) + return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); + + // Unpack the security context + SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); + + // Unpack the int value + uint32_t attribute = info[0]->ToInt32()->Value(); + + // Check that we have a supported attribute + if(attribute != SECPKG_ATTR_SIZES) + return Nan::ThrowError("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); + + // Create call structure + SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); + call->attribute = attribute; + call->context = security_context; + + // Callback + Local callback = Local::Cast(info[1]); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = new Nan::Callback(callback); + worker->parameters = call; + worker->execute = _queryContextAttributes; + worker->mapper = _map_queryContextAttributes; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +void SecurityContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(static_cast(SecurityContext::New)); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("SecurityContext").ToLocalChecked()); + + // Class methods + Nan::SetMethod(t, "initialize", SecurityContext::InitializeContext); + + // Set up method for the instance + Nan::SetPrototypeMethod(t, "initialize", SecurityContext::InitalizeStep); + Nan::SetPrototypeMethod(t, "decryptMessage", SecurityContext::DecryptMessage); + Nan::SetPrototypeMethod(t, "queryContextAttributes", SecurityContext::QueryContextAttributes); + Nan::SetPrototypeMethod(t, "encryptMessage", SecurityContext::EncryptMessage); + + // Get prototype + Local proto = t->PrototypeTemplate(); + + // Getter for the response + Nan::SetAccessor(proto, Nan::New("payload").ToLocalChecked(), SecurityContext::PayloadGetter); + Nan::SetAccessor(proto, Nan::New("hasContext").ToLocalChecked(), SecurityContext::HasContextGetter); + + // Set persistent + SecurityContext::constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("SecurityContext").ToLocalChecked(), t->GetFunction()); +} + +static LPSTR DisplaySECError(DWORD ErrCode) { + LPSTR pszName = NULL; // WinError.h + + switch(ErrCode) { + case SEC_E_BUFFER_TOO_SMALL: + pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; + break; + + case SEC_E_CRYPTO_SYSTEM_INVALID: + pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; + break; + case SEC_E_INCOMPLETE_MESSAGE: + pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; + break; + + case SEC_E_INVALID_HANDLE: + pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_INVALID_TOKEN: + pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; + break; + + case SEC_E_MESSAGE_ALTERED: + pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_OUT_OF_SEQUENCE: + pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; + break; + + case SEC_E_QOP_NOT_SUPPORTED: + pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; + break; + + case SEC_I_CONTEXT_EXPIRED: + pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; + break; + + case SEC_I_RENEGOTIATE: + pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; + break; + + case SEC_E_ENCRYPT_FAILURE: + pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; + break; + + case SEC_E_DECRYPT_FAILURE: + pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; + break; + case -1: + pszName = "Failed to load security.dll library"; + break; + } + + return pszName; +} + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h new file mode 100644 index 0000000..1d9387d --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h @@ -0,0 +1,74 @@ +#ifndef SECURITY_CONTEXT_H +#define SECURITY_CONTEXT_H + +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include +#include +#include +#include +#include "security_credentials.h" +#include "../worker.h" +#include + +extern "C" { + #include "../kerberos_sspi.h" + #include "../base64.h" +} + +using namespace v8; +using namespace node; + +class SecurityContext : public Nan::ObjectWrap { + public: + SecurityContext(); + ~SecurityContext(); + + // Security info package + PSecPkgInfo m_PkgInfo; + // Do we have a context + bool hasContext; + // Reference to security credentials + SecurityCredentials *security_credentials; + // Security context + CtxtHandle m_Context; + // Attributes + DWORD CtxtAttr; + // Expiry time for ticket + TimeStamp Expiration; + // Payload + char *payload; + + // Has instance check + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + // Functions available from V8 + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + static NAN_METHOD(InitializeContext); + static NAN_METHOD(InitalizeStep); + static NAN_METHOD(DecryptMessage); + static NAN_METHOD(QueryContextAttributes); + static NAN_METHOD(EncryptMessage); + + // Payload getter + static NAN_GETTER(PayloadGetter); + // hasContext getter + static NAN_GETTER(HasContextGetter); + + // Constructor used for creating new Long objects from C++ + static Nan::Persistent constructor_template; + + // private: + // Create a new instance + static NAN_METHOD(New); +}; + +#endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js new file mode 100644 index 0000000..ef04e92 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js @@ -0,0 +1,3 @@ +var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; +// Export the modified class +exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc new file mode 100644 index 0000000..732af3f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc @@ -0,0 +1,348 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "security_credentials.h" + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) +#endif + +static LPSTR DisplaySECError(DWORD ErrCode); + +Nan::Persistent SecurityCredentials::constructor_template; + +SecurityCredentials::SecurityCredentials() : Nan::ObjectWrap() { +} + +SecurityCredentials::~SecurityCredentials() { +} + +NAN_METHOD(SecurityCredentials::New) { + // Create security credentials instance + SecurityCredentials *security_credentials = new SecurityCredentials(); + // Wrap it + security_credentials->Wrap(info.This()); + // Return the object + info.GetReturnValue().Set(info.This()); +} + +// Call structs +typedef struct SecurityCredentialCall { + char *package_str; + char *username_str; + char *password_str; + char *domain_str; + SecurityCredentials *credentials; +} SecurityCredentialCall; + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// authGSSClientInit +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +static void _authSSPIAquire(Worker *worker) { + // Status of operation + SECURITY_STATUS status; + + // Unpack data + SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; + + // // Unwrap the credentials + // SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; + SecurityCredentials *security_credentials = new SecurityCredentials(); + + // If we have domain string + if(call->domain_str != NULL) { + security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); + security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); + } else { + security_credentials->m_Identity.Domain = NULL; + security_credentials->m_Identity.DomainLength = 0; + } + + // Set up the user + security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); + security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); + + // If we have a password string + if(call->password_str != NULL) { + // Set up the password + security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); + security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); + } + + #ifdef _UNICODE + security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; + #else + security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; + #endif + + // Attempt to acquire credentials + status = _sspi_AcquireCredentialsHandle( + NULL, + call->package_str, + SECPKG_CRED_OUTBOUND, + NULL, + call->password_str != NULL ? &security_credentials->m_Identity : NULL, + NULL, NULL, + &security_credentials->m_Credentials, + &security_credentials->Expiration + ); + + // We have an error + if(status != SEC_E_OK) { + worker->error = TRUE; + worker->error_code = status; + worker->error_message = DisplaySECError(status); + } else { + worker->return_code = status; + worker->return_value = security_credentials; + } + + // Free up parameter structure + if(call->package_str != NULL) free(call->package_str); + if(call->domain_str != NULL) free(call->domain_str); + if(call->password_str != NULL) free(call->password_str); + if(call->username_str != NULL) free(call->username_str); + free(call); +} + +static Local _map_authSSPIAquire(Worker *worker) { + return Nan::Null(); +} + +NAN_METHOD(SecurityCredentials::Aquire) { + char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; + // Unpack the variables + if(info.Length() != 2 && info.Length() != 3 && info.Length() != 4 && info.Length() != 5) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(!info[0]->IsString()) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(!info[1]->IsString()) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(info.Length() == 3 && (!info[2]->IsString() && !info[2]->IsFunction())) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(info.Length() == 4 && (!info[3]->IsString() && !info[3]->IsUndefined() && !info[3]->IsNull()) && !info[3]->IsFunction()) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + if(info.Length() == 5 && !info[4]->IsFunction()) + return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); + + Local callbackHandle; + + // Figure out which parameter is the callback + if(info.Length() == 5) { + callbackHandle = Local::Cast(info[4]); + } else if(info.Length() == 4) { + callbackHandle = Local::Cast(info[3]); + } else if(info.Length() == 3) { + callbackHandle = Local::Cast(info[2]); + } + + // Unpack the package + Local package = info[0]->ToString(); + package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); + package->WriteUtf8(package_str); + + // Unpack the user name + Local username = info[1]->ToString(); + username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); + username->WriteUtf8(username_str); + + // If we have a password + if(info.Length() == 3 || info.Length() == 4 || info.Length() == 5) { + Local password = info[2]->ToString(); + password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); + password->WriteUtf8(password_str); + } + + // If we have a domain + if((info.Length() == 4 || info.Length() == 5) && info[3]->IsString()) { + Local domain = info[3]->ToString(); + domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); + domain->WriteUtf8(domain_str); + } + + // Allocate call structure + SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); + call->domain_str = domain_str; + call->package_str = package_str; + call->password_str = password_str; + call->username_str = username_str; + + // Unpack the callback + Nan::Callback *callback = new Nan::Callback(callbackHandle); + + // Let's allocate some space + Worker *worker = new Worker(); + worker->error = false; + worker->request.data = worker; + worker->callback = callback; + worker->parameters = call; + worker->execute = _authSSPIAquire; + worker->mapper = _map_authSSPIAquire; + + // Schedule the worker with lib_uv + uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); + + // Return no value as it's callback based + info.GetReturnValue().Set(Nan::Undefined()); +} + +void SecurityCredentials::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Define a new function template + Local t = Nan::New(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + t->SetClassName(Nan::New("SecurityCredentials").ToLocalChecked()); + + // Class methods + Nan::SetMethod(t, "aquire", Aquire); + + // Set persistent + constructor_template.Reset(t); + + // Set the symbol + target->ForceSet(Nan::New("SecurityCredentials").ToLocalChecked(), t->GetFunction()); + + // Attempt to load the security.dll library + load_library(); +} + +static LPSTR DisplaySECError(DWORD ErrCode) { + LPSTR pszName = NULL; // WinError.h + + switch(ErrCode) { + case SEC_E_BUFFER_TOO_SMALL: + pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; + break; + + case SEC_E_CRYPTO_SYSTEM_INVALID: + pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; + break; + case SEC_E_INCOMPLETE_MESSAGE: + pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; + break; + + case SEC_E_INVALID_HANDLE: + pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_INVALID_TOKEN: + pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; + break; + + case SEC_E_MESSAGE_ALTERED: + pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; + break; + + case SEC_E_OUT_OF_SEQUENCE: + pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; + break; + + case SEC_E_QOP_NOT_SUPPORTED: + pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; + break; + + case SEC_I_CONTEXT_EXPIRED: + pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; + break; + + case SEC_I_RENEGOTIATE: + pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; + break; + + case SEC_E_ENCRYPT_FAILURE: + pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; + break; + + case SEC_E_DECRYPT_FAILURE: + pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; + break; + case -1: + pszName = "Failed to load security.dll library"; + break; + + } + + return pszName; +} + +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// UV Lib callbacks +// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +void SecurityCredentials::Process(uv_work_t* work_req) { + // Grab the worker + Worker *worker = static_cast(work_req->data); + // Execute the worker code + worker->execute(worker); +} + +void SecurityCredentials::After(uv_work_t* work_req) { + // Grab the scope of the call from Node + Nan::HandleScope scope; + + // Get the worker reference + Worker *worker = static_cast(work_req->data); + + // If we have an error + if(worker->error) { + Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); + Local obj = err->ToObject(); + obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); + Local info[2] = { err, Nan::Null() }; + // Execute the error + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } else { + SecurityCredentials *return_value = (SecurityCredentials *)worker->return_value; + // Create a new instance + Local result = Nan::New(constructor_template)->GetFunction()->NewInstance(); + // Unwrap the credentials + SecurityCredentials *security_credentials = Nan::ObjectWrap::Unwrap(result); + // Set the values + security_credentials->m_Identity = return_value->m_Identity; + security_credentials->m_Credentials = return_value->m_Credentials; + security_credentials->Expiration = return_value->Expiration; + // Set up the callback with a null first + Local info[2] = { Nan::Null(), result}; + // Wrap the callback function call in a TryCatch so that we can call + // node's FatalException afterwards. This makes it possible to catch + // the exception from JavaScript land using the + // process.on('uncaughtException') event. + Nan::TryCatch try_catch; + + // Call the callback + worker->callback->Call(ARRAY_SIZE(info), info); + + // If we have an exception handle it as a fatalexception + if (try_catch.HasCaught()) { + Nan::FatalException(try_catch); + } + } + + // Clean up the memory + delete worker->callback; + delete worker; +} + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h new file mode 100644 index 0000000..71751a0 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h @@ -0,0 +1,68 @@ +#ifndef SECURITY_CREDENTIALS_H +#define SECURITY_CREDENTIALS_H + +#include +#include +#include + +#define SECURITY_WIN32 1 + +#include +#include +#include +#include +#include +#include "../worker.h" +#include + +extern "C" { + #include "../kerberos_sspi.h" +} + +// SEC_WINNT_AUTH_IDENTITY makes it unusually hard +// to compile for both Unicode and ansi, so I use this macro: +#ifdef _UNICODE +#define USTR(str) (str) +#else +#define USTR(str) ((unsigned char*)(str)) +#endif + +using namespace v8; +using namespace node; + +class SecurityCredentials : public Nan::ObjectWrap { + public: + SecurityCredentials(); + ~SecurityCredentials(); + + // Pointer to context object + SEC_WINNT_AUTH_IDENTITY m_Identity; + // credentials + CredHandle m_Credentials; + // Expiry time for ticket + TimeStamp Expiration; + + // Has instance check + static inline bool HasInstance(Local val) { + if (!val->IsObject()) return false; + Local obj = val->ToObject(); + return Nan::New(constructor_template)->HasInstance(obj); + }; + + // Functions available from V8 + static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); + static NAN_METHOD(Aquire); + + // Constructor used for creating new Long objects from C++ + static Nan::Persistent constructor_template; + + private: + // Create a new instance + static NAN_METHOD(New); + // Handles the uv calls + static void Process(uv_work_t* work_req); + // Called after work is done + static void After(uv_work_t* work_req); +}; + +#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js new file mode 100644 index 0000000..4215c92 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js @@ -0,0 +1,22 @@ +var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; + +// Add simple kebros helper +SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { + if(typeof password == 'function') { + callback = password; + password = null; + } else if(typeof domain == 'function') { + callback = domain; + domain = null; + } + + // We are going to use the async version + if(typeof callback == 'function') { + return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); + } else { + return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); + } +} + +// Export the modified class +exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc new file mode 100644 index 0000000..e7a472f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc @@ -0,0 +1,7 @@ +#include "worker.h" + +Worker::Worker() { +} + +Worker::~Worker() { +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h new file mode 100644 index 0000000..1b0dced --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h @@ -0,0 +1,38 @@ +#ifndef WORKER_H_ +#define WORKER_H_ + +#include +#include +#include +#include + +using namespace node; +using namespace v8; + +class Worker { + public: + Worker(); + virtual ~Worker(); + + // libuv's request struct. + uv_work_t request; + // Callback + Nan::Callback *callback; + // Parameters + void *parameters; + // Results + void *return_value; + // Did we raise an error + bool error; + // The error message + char *error_message; + // Error code if not message + int error_code; + // Any return code + int return_code; + // Method we are going to fire + void (*execute)(Worker *worker); + Local (*mapper)(Worker *worker); +}; + +#endif // WORKER_H_ diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc new file mode 100644 index 0000000..47971da --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc @@ -0,0 +1,30 @@ +## DNT config file +## see https://github.com/rvagg/dnt + +NODE_VERSIONS="\ + master \ + v0.11.13 \ + v0.10.30 \ + v0.10.29 \ + v0.10.28 \ + v0.10.26 \ + v0.10.25 \ + v0.10.24 \ + v0.10.23 \ + v0.10.22 \ + v0.10.21 \ + v0.10.20 \ + v0.10.19 \ + v0.8.28 \ + v0.8.27 \ + v0.8.26 \ + v0.8.24 \ +" +OUTPUT_PREFIX="nan-" +TEST_CMD=" \ + cd /dnt/ && \ + npm install && \ + node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ + node_modules/.bin/tap --gc test/js/*-test.js \ +" + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md new file mode 100644 index 0000000..457e7c4 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md @@ -0,0 +1,374 @@ +# NAN ChangeLog + +**Version 2.0.9: current Node 4.0.0, Node 12: 0.12.7, Node 10: 0.10.40, iojs: 3.2.0** + +### 2.0.9 Sep 8 2015 + + - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7 + +### 2.0.8 Aug 28 2015 + + - Work around duplicate linking bug in clang 11902da + +### 2.0.7 Aug 26 2015 + + - Build: Repackage + +### 2.0.6 Aug 26 2015 + + - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1 + - Bugfix: Remove unused static std::map instances 525bddc + - Bugfix: Make better use of maybe versions of APIs bfba85b + - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d + +### 2.0.5 Aug 10 2015 + + - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1 + - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d + +### 2.0.4 Aug 6 2015 + + - Build: Repackage + +### 2.0.3 Aug 6 2015 + + - Bugfix: Don't use clang++ / g++ syntax extension. 231450e + +### 2.0.2 Aug 6 2015 + + - Build: Repackage + +### 2.0.1 Aug 6 2015 + + - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687 + - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601 + - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f + - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed + +### 2.0.0 Jul 31 2015 + + - Change: Renamed identifiers with leading underscores b5932b4 + - Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1 + - Change: Replace NanScope and NanEscpableScope macros with classes 47751c4 + - Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99 + - Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5 + - Change: Rename NanNewBuffer to NanCopyBuffer d6af78d + - Change: Remove Nan prefix from all names 72d1f67 + - Change: Update Buffer API for new upstream changes d5d3291 + - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a + - Change: Get rid of Handles e6c0daf + - Feature: Support io.js 3 with V8 4.4 + - Feature: Introduce NanPersistent 7fed696 + - Feature: Introduce NanGlobal 4408da1 + - Feature: Added NanTryCatch 10f1ca4 + - Feature: Update for V8 v4.3 4b6404a + - Feature: Introduce NanNewOneByteString c543d32 + - Feature: Introduce namespace Nan 67ed1b1 + - Removal: Remove NanLocker and NanUnlocker dd6e401 + - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9 + - Removal: Remove NanReturn* macros d90a25c + - Removal: Remove HasInstance e8f84fe + + +### 1.9.0 Jul 31 2015 + + - Feature: Added `NanFatalException` 81d4a2c + - Feature: Added more error types 4265f06 + - Feature: Added dereference and function call operators to NanCallback c4b2ed0 + - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c + - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6 + - Feature: Added NanErrnoException dd87d9e + - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130 + - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c + - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b + +### 1.8.4 Apr 26 2015 + + - Build: Repackage + +### 1.8.3 Apr 26 2015 + + - Bugfix: Include missing header 1af8648 + +### 1.8.2 Apr 23 2015 + + - Build: Repackage + +### 1.8.1 Apr 23 2015 + + - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 + +### 1.8.0 Apr 23 2015 + + - Feature: Allow primitives with NanReturnValue 2e4475e + - Feature: Added comparison operators to NanCallback 55b075e + - Feature: Backport thread local storage 15bb7fa + - Removal: Remove support for signatures with arguments 8a2069d + - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 + +### 1.7.0 Feb 28 2015 + + - Feature: Made NanCallback::Call accept optional target 8d54da7 + - Feature: Support atom-shell 0.21 0b7f1bb + +### 1.6.2 Feb 6 2015 + + - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 + +### 1.6.1 Jan 23 2015 + + - Build: version bump + +### 1.5.3 Jan 23 2015 + + - Build: repackage + +### 1.6.0 Jan 23 2015 + + - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af + - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 + - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 + +### 1.5.2 Jan 23 2015 + + - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 + - Bugfix: Readded missing String constructors 18d828f + - Bugfix: Add overload handling NanNew(..) 5ef813b + - Bugfix: Fix uv_work_cb versioning 997e4ae + - Bugfix: Add function factory and test 4eca89c + - Bugfix: Add object template factory and test cdcb951 + - Correctness: Lifted an io.js related typedef c9490be + - Correctness: Make explicit downcasts of String lengths 00074e6 + - Windows: Limit the scope of disabled warning C4530 83d7deb + +### 1.5.1 Jan 15 2015 + + - Build: version bump + +### 1.4.3 Jan 15 2015 + + - Build: version bump + +### 1.4.2 Jan 15 2015 + + - Feature: Support io.js 0dbc5e8 + +### 1.5.0 Jan 14 2015 + + - Feature: Support io.js b003843 + - Correctness: Improved NanNew internals 9cd4f6a + - Feature: Implement progress to NanAsyncWorker 8d6a160 + +### 1.4.1 Nov 8 2014 + + - Bugfix: Handle DEBUG definition correctly + - Bugfix: Accept int as Boolean + +### 1.4.0 Nov 1 2014 + + - Feature: Added NAN_GC_CALLBACK 6a5c245 + - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 + - Correctness: Added constness to references in NanHasInstance 02c61cd + - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 + - Windoze: Shut Visual Studio up when compiling 8d558c1 + - License: Switch to plain MIT from custom hacked MIT license 11de983 + - Build: Added test target to Makefile e232e46 + - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 + - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 + - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 + +### 1.3.0 Aug 2 2014 + + - Added NanNew(std::string) + - Added NanNew(std::string&) + - Added NanAsciiString helper class + - Added NanUtf8String helper class + - Added NanUcs2String helper class + - Deprecated NanRawString() + - Deprecated NanCString() + - Added NanGetIsolateData(v8::Isolate *isolate) + - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) + - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) + - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) + - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) + +### 1.2.0 Jun 5 2014 + + - Add NanSetPrototypeTemplate + - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, + introduced _NanWeakCallbackDispatcher + - Removed -Wno-unused-local-typedefs from test builds + - Made test builds Windows compatible ('Sleep()') + +### 1.1.2 May 28 2014 + + - Release to fix more stuff-ups in 1.1.1 + +### 1.1.1 May 28 2014 + + - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 + +### 1.1.0 May 25 2014 + + - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead + - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), + (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, + v8::String::ExternalAsciiStringResource* + - Deprecate NanSymbol() + - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker + +### 1.0.0 May 4 2014 + + - Heavy API changes for V8 3.25 / Node 0.11.13 + - Use cpplint.py + - Removed NanInitPersistent + - Removed NanPersistentToLocal + - Removed NanFromV8String + - Removed NanMakeWeak + - Removed NanNewLocal + - Removed NAN_WEAK_CALLBACK_OBJECT + - Removed NAN_WEAK_CALLBACK_DATA + - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions + - Introduce NanUndefined, NanNull, NanTrue and NanFalse + - Introduce NanEscapableScope and NanEscapeScope + - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) + - Introduce NanMakeCallback for node::MakeCallback + - Introduce NanSetTemplate + - Introduce NanGetCurrentContext + - Introduce NanCompileScript and NanRunScript + - Introduce NanAdjustExternalMemory + - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback + - Introduce NanGetHeapStatistics + - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() + +### 0.8.0 Jan 9 2014 + + - NanDispose -> NanDisposePersistent, deprecate NanDispose + - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() + +### 0.7.1 Jan 9 2014 + + - Fixes to work against debug builds of Node + - Safer NanPersistentToLocal (avoid reinterpret_cast) + - Speed up common NanRawString case by only extracting flattened string when necessary + +### 0.7.0 Dec 17 2013 + + - New no-arg form of NanCallback() constructor. + - NanCallback#Call takes Handle rather than Local + - Removed deprecated NanCallback#Run method, use NanCallback#Call instead + - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS + - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() + - Introduce NanRawString() for char* (or appropriate void*) from v8::String + (replacement for NanFromV8String) + - Introduce NanCString() for null-terminated char* from v8::String + +### 0.6.0 Nov 21 2013 + + - Introduce NanNewLocal(v8::Handle value) for use in place of + v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 + +### 0.5.2 Nov 16 2013 + + - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public + +### 0.5.1 Nov 12 2013 + + - Use node::MakeCallback() instead of direct v8::Function::Call() + +### 0.5.0 Nov 11 2013 + + - Added @TooTallNate as collaborator + - New, much simpler, "include_dirs" for binding.gyp + - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros + +### 0.4.4 Nov 2 2013 + + - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ + +### 0.4.3 Nov 2 2013 + + - Include node_object_wrap.h, removed from node.h for Node 0.11.8. + +### 0.4.2 Nov 2 2013 + + - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for + Node 0.11.8 release. + +### 0.4.1 Sep 16 2013 + + - Added explicit `#include ` as it was removed from node.h for v0.11.8 + +### 0.4.0 Sep 2 2013 + + - Added NAN_INLINE and NAN_DEPRECATED and made use of them + - Added NanError, NanTypeError and NanRangeError + - Cleaned up code + +### 0.3.2 Aug 30 2013 + + - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent + in NanAsyncWorker + +### 0.3.1 Aug 20 2013 + + - fix "not all control paths return a value" compile warning on some platforms + +### 0.3.0 Aug 19 2013 + + - Made NAN work with NPM + - Lots of fixes to NanFromV8String, pulling in features from new Node core + - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API + - Added optional error number argument for NanThrowError() + - Added NanInitPersistent() + - Added NanReturnNull() and NanReturnEmptyString() + - Added NanLocker and NanUnlocker + - Added missing scopes + - Made sure to clear disposed Persistent handles + - Changed NanAsyncWorker to allocate error messages on the heap + - Changed NanThrowError(Local) to NanThrowError(Handle) + - Fixed leak in NanAsyncWorker when errmsg is used + +### 0.2.2 Aug 5 2013 + + - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() + +### 0.2.1 Aug 5 2013 + + - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for + NanFromV8String() + +### 0.2.0 Aug 5 2013 + + - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, + NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY + - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, + _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, + _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, + _NAN_PROPERTY_QUERY_ARGS + - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer + - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, + NAN_WEAK_CALLBACK_DATA, NanMakeWeak + - Renamed THROW_ERROR to _NAN_THROW_ERROR + - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) + - Added NanBufferUse(char*, uint32_t) + - Added NanNewContextHandle(v8::ExtensionConfiguration*, + v8::Handle, v8::Handle) + - Fixed broken NanCallback#GetFunction() + - Added optional encoding and size arguments to NanFromV8String() + - Added NanGetPointerSafe() and NanSetPointerSafe() + - Added initial test suite (to be expanded) + - Allow NanUInt32OptionValue to convert any Number object + +### 0.1.0 Jul 21 2013 + + - Added `NAN_GETTER`, `NAN_SETTER` + - Added `NanThrowError` with single Local argument + - Added `NanNewBufferHandle` with single uint32_t argument + - Added `NanHasInstance(Persistent&, Handle)` + - Added `Local NanCallback#GetFunction()` + - Added `NanCallback#Call(int, Local[])` + - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md new file mode 100644 index 0000000..77666cd --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md @@ -0,0 +1,13 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2015 NAN contributors +----------------------------------- + +*NAN contributors listed at * + +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/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md new file mode 100644 index 0000000..db3daec --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md @@ -0,0 +1,367 @@ +Native Abstractions for Node.js +=============================== + +**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.12 as well as io.js.** + +***Current version: 2.0.9*** + +*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* + +[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) + +[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](http://travis-ci.org/nodejs/nan) +[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) + +Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. + +This project also contains some helper utilities that make addon development a bit more pleasant. + + * **[News & Updates](#news)** + * **[Usage](#usage)** + * **[Example](#example)** + * **[API](#api)** + * **[Tests](#tests)** + * **[Governance & Contributing](#governance)** + + +## News & Updates + + +## Usage + +Simply add **NAN** as a dependency in the *package.json* of your Node addon: + +``` bash +$ npm install --save nan +``` + +Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: + +``` python +"include_dirs" : [ + "` when compiling your addon. + + +## Example + +Just getting started with Nan? Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. + +For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. + +For another example, see **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. + + +## API + +Additional to the NAN documentation below, please consult: + +* [The V8 Getting Started Guide](https://developers.google.com/v8/get_started) +* [The V8 Embedders Guide](https://developers.google.com/v8/embed) +* [V8 API Documentation](http://v8docs.nodesource.com/) + + + +### JavaScript-accessible methods + +A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://developers.google.com/v8/embed#templates) for further information. + +In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. + +* **Method argument types** + - Nan::FunctionCallbackInfo + - Nan::PropertyCallbackInfo + - Nan::ReturnValue +* **Method declarations** + - Method declaration + - Getter declaration + - Setter declaration + - Property getter declaration + - Property setter declaration + - Property enumerator declaration + - Property deleter declaration + - Property query declaration + - Index getter declaration + - Index setter declaration + - Index enumerator declaration + - Index deleter declaration + - Index query declaration +* Method and template helpers + - Nan::SetMethod() + - Nan::SetNamedPropertyHandler() + - Nan::SetIndexedPropertyHandler() + - Nan::SetPrototypeMethod() + - Nan::SetTemplate() + - Nan::SetPrototypeTemplate() + - Nan::SetInstanceTemplate() + +### Scopes + +A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. + +A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. + +The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. + + - Nan::HandleScope + - Nan::EscapableHandleScope + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). + +### Persistent references + +An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. + +Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. + + - Nan::PersistentBase & v8::PersistentBase + - Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits + - Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits + - Nan::Persistent + - Nan::Global + - Nan::WeakCallbackInfo + - Nan::WeakCallbackType + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). + +### New + +NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. + + - Nan::New() + - Nan::Undefined() + - Nan::Null() + - Nan::True() + - Nan::False() + - Nan::EmptyString() + + +### Converters + +NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. + + - Nan::To() + +### Maybe Types + +The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. + +* **Maybe Types** + - Nan::MaybeLocal + - Nan::Maybe + - Nan::Nothing + - Nan::Just +* **Maybe Helpers** + - Nan::ToDetailString() + - Nan::ToArrayIndex() + - Nan::Equals() + - Nan::NewInstance() + - Nan::GetFunction() + - Nan::Set() + - Nan::ForceSet() + - Nan::Get() + - Nan::GetPropertyAttributes() + - Nan::Has() + - Nan::Delete() + - Nan::GetPropertyNames() + - Nan::GetOwnPropertyNames() + - Nan::SetPrototype() + - Nan::ObjectProtoToString() + - Nan::HasOwnProperty() + - Nan::HasRealNamedProperty() + - Nan::HasRealIndexedProperty() + - Nan::HasRealNamedCallbackProperty() + - Nan::GetRealNamedPropertyInPrototypeChain() + - Nan::GetRealNamedProperty() + - Nan::CallAsFunction() + - Nan::CallAsConstructor() + - Nan::GetSourceLine() + - Nan::GetLineNumber() + - Nan::GetStartColumn() + - Nan::GetEndColumn() + - Nan::CloneElementAt() + +### Script + +NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. + + - Nan::CompileScript() + - Nan::RunScript() + + +### Errors + +NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. + +Note that an Error object is simply a specialized form of `v8::Value`. + +Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. + + - Nan::Error() + - Nan::RangeError() + - Nan::ReferenceError() + - Nan::SyntaxError() + - Nan::TypeError() + - Nan::ThrowError() + - Nan::ThrowRangeError() + - Nan::ThrowReferenceError() + - Nan::ThrowSyntaxError() + - Nan::ThrowTypeError() + - Nan::FatalException() + - Nan::ErrnoException() + - Nan::TryCatch + + +### Buffers + +NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. + + - Nan::NewBuffer() + - Nan::CopyBuffer() + - Nan::FreeCallback() + +### Nan::Callback + +`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. + + - Nan::Callback + +### Asynchronous work helpers + +`Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier. + + - Nan::AsyncWorker + - Nan::AsyncProgressWorker + - Nan::AsyncQueueWorker + +### Strings & Bytes + +Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. + + - Nan::Encoding + - Nan::Encode() + - Nan::DecodeBytes() + - Nan::DecodeWrite() + + +### V8 internals + +The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. + + - NAN_GC_CALLBACK() + - Nan::AddGCEpilogueCallback() + - Nan::RemoveGCEpilogueCallback() + - Nan::AddGCPrologueCallback() + - Nan::RemoveGCPrologueCallback() + - Nan::GetHeapStatistics() + - Nan::SetCounterFunction() + - Nan::SetCreateHistogramFunction() + - Nan::SetAddHistogramSampleFunction() + - Nan::IdleNotification() + - Nan::LowMemoryNotification() + - Nan::ContextDisposedNotification() + - Nan::GetInternalFieldPointer() + - Nan::SetInternalFieldPointer() + - Nan::AdjustExternalMemory() + + +### Miscellaneous V8 Helpers + + - Nan::Utf8String + - Nan::GetCurrentContext() + - Nan::SetIsolateData() + - Nan::GetIsolateData() + + +### Miscellaneous Node Helpers + + - Nan::MakeCallback() + - Nan::ObjectWrap + - NAN_MODULE_INIT() + - Nan::Export() + + + + + +### Tests + +To run the NAN tests do: + +``` sh +npm install +npm run-script rebuild-tests +npm test +``` + +Or just: + +``` sh +npm install +make test +``` + + +## Governance & Contributing + +NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group + +### Addon API Working Group (WG) + +The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. + +Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project [README.md](./README.md#collaborators). + +Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. + +_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. + +For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). + +### Consensus Seeking Process + +The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. + +Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. + +If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. + +### Developer's Certificate of Origin 1.0 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or +* (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or +* (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. + + +### WG Members / Collaborators + + + + + + + + + +
      Rod VaggGitHub/rvaggTwitter/@rvagg
      Benjamin ByholmGitHub/kkoopa-
      Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
      Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
      Brett LawsonGitHub/brett19Twitter/@brett19x
      Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
      David SiegelGitHub/agnat-
      + +## Licence & copyright + +Copyright (c) 2015 NAN WG Members / Collaborators (listed above). + +Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml new file mode 100644 index 0000000..1378d31 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml @@ -0,0 +1,38 @@ +# http://www.appveyor.com/docs/appveyor-yml + +# Test against these versions of Io.js and Node.js. +environment: + matrix: + # node.js + - nodejs_version: "0.8" + - nodejs_version: "0.10" + - nodejs_version: "0.12" + # io.js + - nodejs_version: "1" + - nodejs_version: "2" + - nodejs_version: "3" + +# Install scripts. (runs after repo cloning) +install: + # Get the latest stable version of Node 0.STABLE.latest + - ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version} + - ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)} + - IF %nodejs_version% LSS 1 npm -g install npm + - IF %nodejs_version% LSS 1 set PATH=%APPDATA%\npm;%PATH% + # Typical npm stuff. + - npm install + - IF %nodejs_version% EQU 0.8 (node node_modules\node-gyp\bin\node-gyp.js rebuild --msvs_version=2013 --directory test) ELSE (npm run rebuild-tests) + +# Post-install test scripts. +test_script: + # Output useful info for debugging. + - node --version + - npm --version + # run tests + - IF %nodejs_version% LSS 1 (npm test) ELSE (iojs node_modules\tap\bin\tap.js --gc test/js/*-test.js) + +# Don't actually build. +build: off + +# Set build version format here instead of in the admin panel. +version: "{build}" diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh new file mode 100755 index 0000000..75a975a --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash + +files=" \ + methods.md \ + scopes.md \ + persistent.md \ + new.md \ + converters.md \ + maybe_types.md \ + script.md \ + errors.md \ + buffers.md \ + callback.md \ + asyncworker.md \ + string_bytes.md \ + v8_internals.md \ + v8_misc.md \ + node_misc.md \ +" + +__dirname=$(dirname "${BASH_SOURCE[0]}") +head=$(perl -e 'while (<>) { if (!$en){print;} if ($_=~/ NanNew("foo").ToLocalChecked() */ + if (arguments[groups[3][0]] === 'NanNew') { + return [arguments[0], '.ToLocalChecked()'].join(''); + } + + /* insert warning for removed functions as comment on new line above */ + switch (arguments[groups[4][0]]) { + case 'GetIndexedPropertiesExternalArrayData': + case 'GetIndexedPropertiesExternalArrayDataLength': + case 'GetIndexedPropertiesExternalArrayDataType': + case 'GetIndexedPropertiesPixelData': + case 'GetIndexedPropertiesPixelDataLength': + case 'HasIndexedPropertiesInExternalArrayData': + case 'HasIndexedPropertiesInPixelData': + case 'SetIndexedPropertiesToExternalArrayData': + case 'SetIndexedPropertiesToPixelData': + return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join(''); + default: + } + + /* remove unnecessary NanScope() */ + switch (arguments[groups[5][0]]) { + case 'NAN_GETTER': + case 'NAN_METHOD': + case 'NAN_SETTER': + case 'NAN_INDEX_DELETER': + case 'NAN_INDEX_ENUMERATOR': + case 'NAN_INDEX_GETTER': + case 'NAN_INDEX_QUERY': + case 'NAN_INDEX_SETTER': + case 'NAN_PROPERTY_DELETER': + case 'NAN_PROPERTY_ENUMERATOR': + case 'NAN_PROPERTY_GETTER': + case 'NAN_PROPERTY_QUERY': + case 'NAN_PROPERTY_SETTER': + return arguments[groups[5][0] - 1]; + default: + } + + /* Value converstion */ + switch (arguments[groups[6][0]]) { + case 'Boolean': + case 'Int32': + case 'Integer': + case 'Number': + case 'Object': + case 'String': + case 'Uint32': + return [arguments[groups[6][0] - 2], 'NanTo(', arguments[groups[6][0] - 1]].join(''); + default: + } + + /* other value conversion */ + switch (arguments[groups[7][0]]) { + case 'BooleanValue': + return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); + case 'Int32Value': + return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); + case 'IntegerValue': + return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); + case 'Uint32Value': + return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); + default: + } + + /* NAN_WEAK_CALLBACK */ + if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') { + return ['template\nvoid ', + arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo &data)'].join(''); + } + + /* use methods on NAN classes instead */ + switch (arguments[groups[9][0]]) { + case 'NanDisposePersistent': + return [arguments[groups[9][0] + 1], '.Reset('].join(''); + case 'NanObjectWrapHandle': + return [arguments[groups[9][0] + 1], '->handle('].join(''); + default: + } + + /* use method on NanPersistent instead */ + if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') { + return arguments[groups[10][0] + 1] + '.SetWeak('; + } + + /* These return Maybes, the upper ones take no arguments */ + switch (arguments[groups[11][0]]) { + case 'GetEndColumn': + case 'GetFunction': + case 'GetLineNumber': + case 'GetOwnPropertyNames': + case 'GetPropertyNames': + case 'GetSourceLine': + case 'GetStartColumn': + case 'NewInstance': + case 'ObjectProtoToString': + case 'ToArrayIndex': + case 'ToDetailString': + return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join(''); + case 'CallAsConstructor': + case 'CallAsFunction': + case 'CloneElementAt': + case 'Delete': + case 'ForceSet': + case 'Get': + case 'GetPropertyAttributes': + case 'GetRealNamedProperty': + case 'GetRealNamedPropertyInPrototypeChain': + case 'Has': + case 'HasOwnProperty': + case 'HasRealIndexedProperty': + case 'HasRealNamedCallbackProperty': + case 'HasRealNamedProperty': + case 'Set': + case 'SetAccessor': + case 'SetIndexedPropertyHandler': + case 'SetNamedPropertyHandler': + case 'SetPrototype': + return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join(''); + default: + } + + /* Automatic ToLocalChecked(), take it or leave it */ + switch (arguments[groups[12][0]]) { + case 'Date': + case 'String': + case 'RegExp': + return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join(''); + default: + } + + /* NanEquals is now required for uniformity */ + if (arguments[groups[13][0]] === 'Equals') { + return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join(''); + } + + /* use method on replacement class instead */ + if (arguments[groups[14][0]] === 'NanAssignPersistent') { + return [arguments[groups[14][0] + 1], '.Reset('].join(''); + } + + /* args --> info */ + if (arguments[groups[15][0]] === 'args') { + return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join(''); + } + + /* ObjectWrap --> NanObjectWrap */ + if (arguments[groups[16][0]] === 'ObjectWrap') { + return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join(''); + } + + /* Persistent --> NanPersistent */ + if (arguments[groups[17][0]] === 'Persistent') { + return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join(''); + } + + /* This should not happen. A switch is probably missing a case if it does. */ + throw 'Unhandled match: ' + arguments[0]; +} + +/* reads a file, runs replacement and writes it back */ +function processFile(file) { + fs.readFile(file, {encoding: 'utf8'}, function (err, data) { + if (err) { + throw err; + } + + /* run replacement twice, might need more runs */ + fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) { + if (err) { + throw err; + } + }); + }); +} + +/* process file names from command line and process the identified files */ +for (i = 2, length = process.argv.length; i < length; i++) { + glob(process.argv[i], function (err, matches) { + if (err) { + throw err; + } + matches.forEach(processFile); + }); +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md new file mode 100644 index 0000000..7f07e4b --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md @@ -0,0 +1,14 @@ +1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, +false positives and missed opportunities. The input files are rewritten in place. Make sure that +you have backups. You will have to manually review the changes afterwards and do some touchups. + +```sh +$ tools/1to2.js + + Usage: 1to2 [options] + + Options: + + -h, --help output usage information + -V, --version output the version number +``` diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json new file mode 100644 index 0000000..2dcdd78 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json @@ -0,0 +1,19 @@ +{ + "name": "1to2", + "version": "1.0.0", + "description": "NAN 1 -> 2 Migration Script", + "main": "1to2.js", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/nan.git" + }, + "contributors": [ + "Benjamin Byholm (https://github.com/kkoopa/)", + "Mathias Küsel (https://github.com/mathiask88/)" + ], + "dependencies": { + "glob": "~5.0.10", + "commander": "~2.8.1" + }, + "license": "MIT" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json new file mode 100644 index 0000000..9955d1f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json @@ -0,0 +1,55 @@ +{ + "name": "kerberos", + "version": "0.0.15", + "description": "Kerberos library for Node.js", + "main": "index.js", + "repository": { + "type": "git", + "url": "https://github.com/christkv/kerberos.git" + }, + "keywords": [ + "kerberos", + "security", + "authentication" + ], + "dependencies": { + "nan": "~2.0" + }, + "devDependencies": { + "nodeunit": "latest" + }, + "scripts": { + "install": "(node-gyp rebuild) || (exit 0)", + "test": "nodeunit ./test" + }, + "author": { + "name": "Christian Amor Kvalheim" + }, + "license": "Apache 2.0", + "gitHead": "035be2e4619d7f3d7ea5103da1f60a6045ef8d7c", + "bugs": { + "url": "https://github.com/christkv/kerberos/issues" + }, + "homepage": "https://github.com/christkv/kerberos", + "_id": "kerberos@0.0.15", + "_shasum": "c7dd5a2d311ce79c308c2670a9187d9bf745ed52", + "_from": "kerberos@>=0.0.0 <0.1.0", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "c7dd5a2d311ce79c308c2670a9187d9bf745ed52", + "tarball": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.15.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-0.0.15.tgz" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js new file mode 100644 index 0000000..a06c5fd --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js @@ -0,0 +1,34 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Simple initialize of Kerberos object'] = function(test) { + var Kerberos = require('../lib/kerberos.js').Kerberos; + var kerberos = new Kerberos(); + // console.dir(kerberos) + + // Initiate kerberos client + kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { + console.log("===================================== authGSSClientInit") + test.equal(null, err); + test.ok(context != null && typeof context == 'object'); + // console.log("===================================== authGSSClientInit") + console.dir(err) + console.dir(context) + // console.dir(typeof result) + + // Perform the first step + kerberos.authGSSClientStep(context, function(err, result) { + console.log("===================================== authGSSClientStep") + console.dir(err) + console.dir(result) + console.dir(context) + + test.done(); + }); + }); +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js new file mode 100644 index 0000000..c8509db --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js @@ -0,0 +1,15 @@ +if (/^win/.test(process.platform)) { + +exports['Simple initialize of Kerberos win32 object'] = function(test) { + var KerberosNative = require('../build/Release/kerberos').Kerberos; + // console.dir(KerberosNative) + var kerberos = new KerberosNative(); + console.log("=========================================== 0") + console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); + console.log("=========================================== 1") + console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); + console.log("=========================================== 2") + test.done(); +} + +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js new file mode 100644 index 0000000..3531b6b --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js @@ -0,0 +1,41 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Initialize a security Buffer Descriptor'] = function(test) { + var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor + SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; + + // Create descriptor with single Buffer + var securityDescriptor = new SecurityBufferDescriptor(100); + try { + // Fail to work due to no valid Security Buffer + securityDescriptor = new SecurityBufferDescriptor(["hello"]); + test.ok(false); + } catch(err){} + + // Should Correctly construct SecurityBuffer + var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); + securityDescriptor = new SecurityBufferDescriptor([buffer]); + // Should correctly return a buffer + var result = securityDescriptor.toBuffer(); + test.equal(100, result.length); + + // Should Correctly construct SecurityBuffer + var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + securityDescriptor = new SecurityBufferDescriptor([buffer]); + var result = securityDescriptor.toBuffer(); + test.equal("hello world", result.toString()); + + // Test passing in more than one Buffer + var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); + securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); + var result = securityDescriptor.toBuffer(); + test.equal("hello worldadam and eve", result.toString()); + test.done(); +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js new file mode 100644 index 0000000..b52b959 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js @@ -0,0 +1,22 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Initialize a security Buffer'] = function(test) { + var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; + // Create empty buffer + var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); + var buffer = securityBuffer.toBuffer(); + test.equal(100, buffer.length); + + // Access data passed in + var allocated_buffer = new Buffer(256); + securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); + buffer = securityBuffer.toBuffer(); + test.deepEqual(allocated_buffer, buffer); + test.done(); +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js new file mode 100644 index 0000000..7758180 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js @@ -0,0 +1,55 @@ +exports.setUp = function(callback) { + callback(); +} + +exports.tearDown = function(callback) { + callback(); +} + +exports['Initialize a set of security credentials'] = function(test) { + var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; + + // Aquire some credentials + try { + var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); + } catch(err) { + console.dir(err) + test.ok(false); + } + + + + // console.dir(SecurityCredentials); + + // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor + // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; + + // // Create descriptor with single Buffer + // var securityDescriptor = new SecurityBufferDescriptor(100); + // try { + // // Fail to work due to no valid Security Buffer + // securityDescriptor = new SecurityBufferDescriptor(["hello"]); + // test.ok(false); + // } catch(err){} + + // // Should Correctly construct SecurityBuffer + // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); + // securityDescriptor = new SecurityBufferDescriptor([buffer]); + // // Should correctly return a buffer + // var result = securityDescriptor.toBuffer(); + // test.equal(100, result.length); + + // // Should Correctly construct SecurityBuffer + // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + // securityDescriptor = new SecurityBufferDescriptor([buffer]); + // var result = securityDescriptor.toBuffer(); + // test.equal("hello world", result.toString()); + + // // Test passing in more than one Buffer + // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); + // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); + // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); + // var result = securityDescriptor.toBuffer(); + // test.equal("hello worldadam and eve", result.toString()); + test.done(); +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/package.json new file mode 100644 index 0000000..f690f67 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/package.json @@ -0,0 +1,66 @@ +{ + "name": "mongodb-core", + "version": "1.2.14", + "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", + "main": "index.js", + "scripts": { + "test": "node test/runner.js -t functional" + }, + "repository": { + "type": "git", + "url": "git://github.com/christkv/mongodb-core.git" + }, + "keywords": [ + "mongodb", + "core" + ], + "dependencies": { + "bson": "~0.4", + "kerberos": "~0.0" + }, + "devDependencies": { + "integra": "0.1.8", + "optimist": "latest", + "jsdoc": "3.3.0-alpha8", + "semver": "4.1.0", + "gleak": "0.5.0", + "mongodb-tools": "~1.0", + "mkdirp": "0.5.0", + "rimraf": "2.2.6", + "mongodb-version-manager": "^0.7.1", + "co": "4.5.4" + }, + "optionalDependencies": { + "kerberos": "~0.0" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache 2.0", + "bugs": { + "url": "https://github.com/christkv/mongodb-core/issues" + }, + "homepage": "https://github.com/christkv/mongodb-core", + "gitHead": "ea4e6c9fe93e4ace4cbffb816d47ee282c1cd844", + "_id": "mongodb-core@1.2.14", + "_shasum": "0f1393778b71f1e2b86228fd160ec9ad5a8cd9a3", + "_from": "mongodb-core@1.2.14", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "0f1393778b71f1e2b86228fd160ec9ad5a8cd9a3", + "tarball": "http://registry.npmjs.org/mongodb-core/-/mongodb-core-1.2.14.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-1.2.14.tgz" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat new file mode 100644 index 0000000..25ccf0b --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat @@ -0,0 +1,11000 @@ +1 2 +2 1 +3 0 +4 0 +5 1 +6 0 +7 0 +8 0 +9 0 +10 1 +11 0 +12 0 +13 0 +14 1 +15 0 +16 0 +17 0 +18 1 +19 0 +20 0 +21 0 +22 1 +23 0 +24 0 +25 0 +26 0 +27 1 +28 0 +29 0 +30 0 +31 1 +32 0 +33 0 +34 0 +35 0 +36 0 +37 1 +38 0 +39 0 +40 0 +41 0 +42 0 +43 1 +44 0 +45 0 +46 0 +47 0 +48 0 +49 0 +50 0 +51 0 +52 0 +53 0 +54 0 +55 0 +56 0 +57 0 +58 0 +59 1 +60 0 +61 2 +62 0 +63 0 +64 1 +65 0 +66 0 +67 0 +68 1 +69 0 +70 0 +71 0 +72 0 +73 1 +74 0 +75 0 +76 0 +77 0 +78 0 +79 1 +80 0 +81 0 +82 0 +83 0 +84 0 +85 0 +86 1 +87 0 +88 0 +89 0 +90 0 +91 0 +92 0 +93 1 +94 0 +95 0 +96 0 +97 0 +98 0 +99 0 +100 0 +101 1 +102 0 +103 0 +104 0 +105 0 +106 0 +107 0 +108 1 +109 0 +110 0 +111 0 +112 0 +113 0 +114 0 +115 1 +116 0 +117 0 +118 0 +119 1 +120 0 +121 0 +122 0 +123 0 +124 0 +125 0 +126 1 +127 0 +128 1 +129 0 +130 0 +131 0 +132 1 +133 1 +134 0 +135 0 +136 0 +137 1 +138 0 +139 0 +140 0 +141 0 +142 0 +143 0 +144 1 +145 0 +146 0 +147 0 +148 0 +149 0 +150 0 +151 0 +152 0 +153 1 +154 0 +155 0 +156 0 +157 0 +158 0 +159 0 +160 0 +161 0 +162 0 +163 0 +164 0 +165 0 +166 0 +167 0 +168 0 +169 0 +170 1 +171 0 +172 0 +173 0 +174 0 +175 0 +176 0 +177 0 +178 1 +179 0 +180 0 +181 0 +182 0 +183 0 +184 0 +185 0 +186 1 +187 0 +188 0 +189 0 +190 0 +191 0 +192 1 +193 0 +194 0 +195 0 +196 1 +197 0 +198 0 +199 0 +200 1 +201 0 +202 0 +203 0 +204 0 +205 0 +206 0 +207 1 +208 0 +209 0 +210 0 +211 0 +212 0 +213 0 +214 0 +215 1 +216 0 +217 0 +218 0 +219 0 +220 0 +221 0 +222 0 +223 1 +224 0 +225 0 +226 0 +227 0 +228 0 +229 0 +230 1 +231 0 +232 0 +233 0 +234 0 +235 0 +236 0 +237 1 +238 0 +239 0 +240 0 +241 0 +242 0 +243 0 +244 0 +245 1 +246 0 +247 0 +248 0 +249 0 +250 0 +251 0 +252 0 +253 0 +254 1 +255 0 +256 0 +257 0 +258 0 +259 1 +260 0 +261 0 +262 0 +263 0 +264 0 +265 1 +266 0 +267 0 +268 0 +269 0 +270 0 +271 0 +272 1 +273 0 +274 0 +275 0 +276 0 +277 0 +278 0 +279 0 +280 0 +281 1 +282 0 +283 1 +284 0 +285 0 +286 1 +287 0 +288 0 +289 0 +290 0 +291 1 +292 0 +293 0 +294 0 +295 0 +296 1 +297 0 +298 0 +299 0 +300 0 +301 0 +302 0 +303 1 +304 0 +305 0 +306 0 +307 0 +308 0 +309 1 +310 0 +311 0 +312 0 +313 0 +314 0 +315 0 +316 1 +317 0 +318 0 +319 0 +320 0 +321 0 +322 0 +323 0 +324 0 +325 1 +326 0 +327 0 +328 0 +329 0 +330 0 +331 0 +332 0 +333 0 +334 1 +335 0 +336 0 +337 0 +338 0 +339 0 +340 0 +341 0 +342 0 +343 1 +344 0 +345 0 +346 0 +347 0 +348 0 +349 0 +350 0 +351 0 +352 1 +353 0 +354 0 +355 0 +356 0 +357 0 +358 0 +359 0 +360 0 +361 1 +362 0 +363 0 +364 0 +365 0 +366 0 +367 0 +368 0 +369 1 +370 0 +371 0 +372 0 +373 0 +374 0 +375 0 +376 0 +377 1 +378 0 +379 0 +380 0 +381 0 +382 0 +383 0 +384 0 +385 1 +386 0 +387 0 +388 0 +389 0 +390 1 +391 0 +392 0 +393 0 +394 0 +395 0 +396 0 +397 0 +398 0 +399 0 +400 0 +401 0 +402 1 +403 0 +404 0 +405 0 +406 0 +407 0 +408 0 +409 0 +410 1 +411 0 +412 0 +413 0 +414 0 +415 0 +416 0 +417 0 +418 0 +419 1 +420 0 +421 0 +422 0 +423 0 +424 0 +425 0 +426 0 +427 1 +428 0 +429 0 +430 0 +431 0 +432 0 +433 0 +434 0 +435 1 +436 0 +437 0 +438 0 +439 0 +440 0 +441 0 +442 0 +443 1 +444 0 +445 0 +446 0 +447 0 +448 0 +449 0 +450 1 +451 0 +452 0 +453 0 +454 0 +455 0 +456 1 +457 0 +458 0 +459 0 +460 0 +461 0 +462 0 +463 0 +464 1 +465 0 +466 0 +467 0 +468 0 +469 0 +470 0 +471 0 +472 0 +473 1 +474 0 +475 0 +476 0 +477 0 +478 0 +479 0 +480 0 +481 1 +482 0 +483 0 +484 0 +485 0 +486 0 +487 0 +488 0 +489 0 +490 1 +491 0 +492 0 +493 0 +494 0 +495 0 +496 0 +497 0 +498 0 +499 0 +500 0 +501 0 +502 0 +503 0 +504 1 +505 0 +506 0 +507 0 +508 0 +509 0 +510 0 +511 0 +512 1 +513 0 +514 0 +515 0 +516 0 +517 0 +518 0 +519 4 +520 0 +521 1 +522 0 +523 0 +524 0 +525 1 +526 0 +527 0 +528 0 +529 0 +530 1 +531 0 +532 0 +533 0 +534 1 +535 0 +536 0 +537 0 +538 0 +539 1 +540 0 +541 0 +542 0 +543 0 +544 0 +545 1 +546 0 +547 0 +548 0 +549 0 +550 0 +551 1 +552 0 +553 0 +554 0 +555 0 +556 0 +557 0 +558 0 +559 1 +560 0 +561 0 +562 0 +563 0 +564 0 +565 0 +566 0 +567 1 +568 0 +569 0 +570 0 +571 0 +572 0 +573 0 +574 0 +575 0 +576 1 +577 0 +578 0 +579 0 +580 0 +581 0 +582 0 +583 0 +584 0 +585 0 +586 0 +587 0 +588 0 +589 0 +590 0 +591 0 +592 0 +593 1 +594 0 +595 0 +596 0 +597 0 +598 0 +599 0 +600 0 +601 0 +602 1 +603 0 +604 0 +605 0 +606 0 +607 0 +608 0 +609 0 +610 0 +611 1 +612 0 +613 0 +614 0 +615 0 +616 0 +617 0 +618 0 +619 0 +620 1 +621 0 +622 0 +623 0 +624 0 +625 0 +626 0 +627 0 +628 0 +629 1 +630 0 +631 0 +632 0 +633 0 +634 0 +635 0 +636 0 +637 0 +638 0 +639 1 +640 0 +641 0 +642 0 +643 0 +644 0 +645 0 +646 1 +647 0 +648 0 +649 0 +650 0 +651 0 +652 1 +653 1 +654 0 +655 0 +656 1 +657 0 +658 1 +659 0 +660 0 +661 0 +662 0 +663 0 +664 1 +665 0 +666 0 +667 0 +668 0 +669 0 +670 0 +671 0 +672 0 +673 0 +674 0 +675 0 +676 0 +677 1 +678 0 +679 0 +680 0 +681 0 +682 0 +683 0 +684 0 +685 0 +686 1 +687 0 +688 0 +689 0 +690 0 +691 0 +692 0 +693 0 +694 0 +695 1 +696 0 +697 0 +698 0 +699 0 +700 0 +701 0 +702 0 +703 1 +704 0 +705 0 +706 0 +707 0 +708 0 +709 0 +710 0 +711 0 +712 1 +713 0 +714 0 +715 0 +716 0 +717 0 +718 0 +719 0 +720 1 +721 0 +722 0 +723 0 +724 0 +725 0 +726 0 +727 0 +728 1 +729 0 +730 0 +731 0 +732 0 +733 0 +734 0 +735 0 +736 0 +737 1 +738 0 +739 0 +740 0 +741 0 +742 0 +743 0 +744 0 +745 1 +746 0 +747 0 +748 0 +749 0 +750 0 +751 0 +752 0 +753 1 +754 0 +755 0 +756 0 +757 0 +758 0 +759 0 +760 0 +761 1 +762 0 +763 0 +764 0 +765 0 +766 0 +767 0 +768 1 +769 0 +770 0 +771 0 +772 0 +773 0 +774 0 +775 0 +776 0 +777 1 +778 0 +779 0 +780 0 +781 0 +782 0 +783 0 +784 0 +785 0 +786 1 +787 0 +788 0 +789 0 +790 0 +791 0 +792 1 +793 0 +794 0 +795 0 +796 0 +797 0 +798 0 +799 0 +800 0 +801 1 +802 0 +803 0 +804 0 +805 0 +806 0 +807 0 +808 0 +809 0 +810 0 +811 0 +812 0 +813 0 +814 0 +815 0 +816 0 +817 0 +818 0 +819 0 +820 1 +821 0 +822 0 +823 0 +824 0 +825 0 +826 0 +827 0 +828 0 +829 1 +830 0 +831 0 +832 0 +833 0 +834 0 +835 0 +836 0 +837 1 +838 0 +839 0 +840 0 +841 0 +842 0 +843 0 +844 0 +845 0 +846 1 +847 0 +848 0 +849 0 +850 0 +851 0 +852 0 +853 0 +854 0 +855 2 +856 0 +857 0 +858 0 +859 0 +860 0 +861 0 +862 1 +863 0 +864 0 +865 0 +866 0 +867 0 +868 0 +869 0 +870 0 +871 1 +872 0 +873 0 +874 0 +875 0 +876 0 +877 0 +878 1 +879 0 +880 0 +881 0 +882 0 +883 0 +884 0 +885 0 +886 0 +887 0 +888 0 +889 0 +890 0 +891 0 +892 0 +893 0 +894 0 +895 0 +896 1 +897 0 +898 0 +899 0 +900 0 +901 0 +902 0 +903 0 +904 0 +905 0 +906 1 +907 0 +908 0 +909 0 +910 0 +911 0 +912 0 +913 0 +914 0 +915 1 +916 0 +917 0 +918 0 +919 0 +920 0 +921 0 +922 1 +923 0 +924 0 +925 0 +926 0 +927 0 +928 0 +929 0 +930 1 +931 0 +932 0 +933 0 +934 0 +935 0 +936 0 +937 0 +938 0 +939 1 +940 0 +941 0 +942 0 +943 0 +944 0 +945 0 +946 0 +947 0 +948 0 +949 1 +950 0 +951 0 +952 0 +953 0 +954 0 +955 0 +956 0 +957 0 +958 1 +959 0 +960 0 +961 0 +962 0 +963 0 +964 0 +965 0 +966 0 +967 0 +968 1 +969 0 +970 0 +971 0 +972 0 +973 0 +974 0 +975 0 +976 0 +977 0 +978 1 +979 0 +980 0 +981 0 +982 0 +983 0 +984 0 +985 0 +986 0 +987 0 +988 1 +989 0 +990 0 +991 0 +992 0 +993 0 +994 0 +995 0 +996 0 +997 1 +998 0 +999 0 +1000 0 +1001 0 +1002 0 +1003 0 +1004 0 +1005 1 +1006 0 +1007 0 +1008 0 +1009 0 +1010 0 +1011 0 +1012 1 +1013 0 +1014 0 +1015 0 +1016 0 +1017 0 +1018 0 +1019 0 +1020 0 +1021 0 +1022 0 +1023 0 +1024 0 +1025 0 +1026 0 +1027 0 +1028 0 +1029 0 +1030 0 +1031 1 +1032 0 +1033 0 +1034 0 +1035 0 +1036 0 +1037 0 +1038 0 +1039 0 +1040 0 +1041 0 +1042 1 +1043 0 +1044 0 +1045 0 +1046 0 +1047 0 +1048 0 +1049 0 +1050 1 +1051 0 +1052 0 +1053 0 +1054 0 +1055 0 +1056 0 +1057 1 +1058 0 +1059 0 +1060 0 +1061 0 +1062 0 +1063 0 +1064 0 +1065 0 +1066 0 +1067 1 +1068 0 +1069 0 +1070 0 +1071 0 +1072 0 +1073 0 +1074 0 +1075 0 +1076 0 +1077 1 +1078 0 +1079 0 +1080 0 +1081 0 +1082 0 +1083 0 +1084 0 +1085 0 +1086 0 +1087 1 +1088 0 +1089 0 +1090 0 +1091 0 +1092 0 +1093 0 +1094 1 +1095 0 +1096 0 +1097 0 +1098 0 +1099 0 +1100 0 +1101 0 +1102 1 +1103 0 +1104 0 +1105 0 +1106 0 +1107 0 +1108 0 +1109 0 +1110 0 +1111 1 +1112 0 +1113 0 +1114 0 +1115 0 +1116 0 +1117 0 +1118 0 +1119 0 +1120 1 +1121 0 +1122 0 +1123 0 +1124 0 +1125 0 +1126 0 +1127 0 +1128 0 +1129 0 +1130 1 +1131 0 +1132 0 +1133 0 +1134 0 +1135 0 +1136 0 +1137 0 +1138 0 +1139 0 +1140 1 +1141 0 +1142 0 +1143 0 +1144 0 +1145 0 +1146 0 +1147 0 +1148 0 +1149 0 +1150 0 +1151 1 +1152 0 +1153 0 +1154 0 +1155 0 +1156 0 +1157 0 +1158 0 +1159 0 +1160 1 +1161 0 +1162 0 +1163 0 +1164 0 +1165 0 +1166 0 +1167 1 +1168 0 +1169 0 +1170 0 +1171 0 +1172 0 +1173 0 +1174 0 +1175 0 +1176 1 +1177 0 +1178 0 +1179 0 +1180 0 +1181 0 +1182 1 +1183 0 +1184 0 +1185 0 +1186 0 +1187 0 +1188 0 +1189 0 +1190 1 +1191 0 +1192 0 +1193 0 +1194 0 +1195 0 +1196 0 +1197 0 +1198 1 +1199 0 +1200 0 +1201 0 +1202 0 +1203 0 +1204 0 +1205 0 +1206 1 +1207 0 +1208 0 +1209 0 +1210 0 +1211 0 +1212 0 +1213 0 +1214 0 +1215 0 +1216 1 +1217 0 +1218 0 +1219 0 +1220 0 +1221 0 +1222 0 +1223 0 +1224 0 +1225 0 +1226 1 +1227 0 +1228 0 +1229 0 +1230 0 +1231 0 +1232 0 +1233 0 +1234 0 +1235 0 +1236 0 +1237 0 +1238 0 +1239 1 +1240 0 +1241 0 +1242 0 +1243 0 +1244 0 +1245 0 +1246 0 +1247 0 +1248 1 +1249 0 +1250 0 +1251 0 +1252 0 +1253 0 +1254 0 +1255 0 +1256 0 +1257 1 +1258 0 +1259 0 +1260 0 +1261 0 +1262 0 +1263 0 +1264 0 +1265 0 +1266 1 +1267 0 +1268 0 +1269 0 +1270 0 +1271 0 +1272 0 +1273 0 +1274 0 +1275 1 +1276 0 +1277 0 +1278 0 +1279 0 +1280 0 +1281 0 +1282 0 +1283 0 +1284 0 +1285 0 +1286 0 +1287 0 +1288 0 +1289 0 +1290 0 +1291 0 +1292 0 +1293 1 +1294 0 +1295 0 +1296 0 +1297 0 +1298 0 +1299 0 +1300 0 +1301 0 +1302 0 +1303 0 +1304 0 +1305 0 +1306 0 +1307 0 +1308 0 +1309 0 +1310 1 +1311 0 +1312 0 +1313 0 +1314 0 +1315 0 +1316 0 +1317 0 +1318 1 +1319 0 +1320 0 +1321 0 +1322 0 +1323 0 +1324 0 +1325 0 +1326 0 +1327 1 +1328 0 +1329 0 +1330 0 +1331 0 +1332 0 +1333 0 +1334 0 +1335 0 +1336 1 +1337 0 +1338 0 +1339 0 +1340 0 +1341 0 +1342 0 +1343 0 +1344 0 +1345 0 +1346 1 +1347 0 +1348 0 +1349 0 +1350 0 +1351 0 +1352 0 +1353 0 +1354 0 +1355 0 +1356 1 +1357 0 +1358 0 +1359 0 +1360 0 +1361 0 +1362 0 +1363 0 +1364 0 +1365 1 +1366 0 +1367 0 +1368 0 +1369 0 +1370 0 +1371 0 +1372 0 +1373 1 +1374 0 +1375 0 +1376 0 +1377 0 +1378 0 +1379 0 +1380 0 +1381 0 +1382 0 +1383 1 +1384 0 +1385 0 +1386 0 +1387 0 +1388 0 +1389 0 +1390 0 +1391 0 +1392 1 +1393 0 +1394 0 +1395 0 +1396 0 +1397 0 +1398 0 +1399 0 +1400 1 +1401 0 +1402 0 +1403 0 +1404 0 +1405 0 +1406 0 +1407 0 +1408 0 +1409 0 +1410 1 +1411 0 +1412 0 +1413 0 +1414 0 +1415 0 +1416 0 +1417 0 +1418 0 +1419 0 +1420 1 +1421 0 +1422 0 +1423 0 +1424 0 +1425 0 +1426 0 +1427 0 +1428 0 +1429 0 +1430 0 +1431 1 +1432 0 +1433 0 +1434 0 +1435 0 +1436 0 +1437 0 +1438 0 +1439 0 +1440 0 +1441 1 +1442 0 +1443 0 +1444 0 +1445 0 +1446 0 +1447 2 +1448 0 +1449 0 +1450 0 +1451 0 +1452 0 +1453 0 +1454 0 +1455 1 +1456 0 +1457 0 +1458 0 +1459 0 +1460 0 +1461 0 +1462 0 +1463 0 +1464 0 +1465 1 +1466 0 +1467 0 +1468 0 +1469 0 +1470 0 +1471 0 +1472 0 +1473 0 +1474 0 +1475 1 +1476 0 +1477 0 +1478 0 +1479 0 +1480 0 +1481 0 +1482 0 +1483 0 +1484 0 +1485 1 +1486 0 +1487 0 +1488 0 +1489 0 +1490 0 +1491 0 +1492 0 +1493 0 +1494 1 +1495 0 +1496 0 +1497 0 +1498 0 +1499 0 +1500 0 +1501 0 +1502 0 +1503 1 +1504 0 +1505 0 +1506 0 +1507 0 +1508 0 +1509 0 +1510 0 +1511 0 +1512 0 +1513 0 +1514 0 +1515 0 +1516 0 +1517 0 +1518 0 +1519 0 +1520 1 +1521 0 +1522 0 +1523 0 +1524 0 +1525 0 +1526 0 +1527 0 +1528 0 +1529 1 +1530 0 +1531 0 +1532 0 +1533 0 +1534 0 +1535 0 +1536 0 +1537 0 +1538 0 +1539 1 +1540 0 +1541 0 +1542 0 +1543 0 +1544 0 +1545 0 +1546 0 +1547 0 +1548 1 +1549 0 +1550 0 +1551 0 +1552 0 +1553 0 +1554 0 +1555 0 +1556 0 +1557 1 +1558 0 +1559 0 +1560 0 +1561 0 +1562 0 +1563 0 +1564 0 +1565 0 +1566 0 +1567 1 +1568 0 +1569 0 +1570 0 +1571 0 +1572 0 +1573 0 +1574 0 +1575 1 +1576 0 +1577 0 +1578 0 +1579 0 +1580 0 +1581 0 +1582 0 +1583 0 +1584 1 +1585 0 +1586 0 +1587 0 +1588 0 +1589 0 +1590 0 +1591 0 +1592 0 +1593 1 +1594 0 +1595 0 +1596 0 +1597 0 +1598 0 +1599 0 +1600 0 +1601 0 +1602 1 +1603 0 +1604 0 +1605 0 +1606 0 +1607 0 +1608 0 +1609 0 +1610 0 +1611 1 +1612 0 +1613 0 +1614 0 +1615 0 +1616 0 +1617 0 +1618 0 +1619 0 +1620 0 +1621 1 +1622 0 +1623 0 +1624 0 +1625 0 +1626 0 +1627 0 +1628 0 +1629 0 +1630 0 +1631 1 +1632 0 +1633 0 +1634 0 +1635 0 +1636 0 +1637 0 +1638 0 +1639 0 +1640 1 +1641 0 +1642 0 +1643 0 +1644 0 +1645 0 +1646 0 +1647 0 +1648 0 +1649 0 +1650 1 +1651 0 +1652 0 +1653 0 +1654 0 +1655 0 +1656 0 +1657 0 +1658 0 +1659 0 +1660 1 +1661 0 +1662 0 +1663 0 +1664 0 +1665 0 +1666 0 +1667 0 +1668 0 +1669 0 +1670 1 +1671 0 +1672 0 +1673 0 +1674 0 +1675 0 +1676 0 +1677 0 +1678 0 +1679 0 +1680 1 +1681 0 +1682 0 +1683 0 +1684 0 +1685 0 +1686 0 +1687 0 +1688 0 +1689 0 +1690 1 +1691 0 +1692 0 +1693 0 +1694 0 +1695 0 +1696 0 +1697 0 +1698 0 +1699 0 +1700 0 +1701 1 +1702 0 +1703 0 +1704 0 +1705 0 +1706 0 +1707 0 +1708 1 +1709 0 +1710 0 +1711 0 +1712 0 +1713 0 +1714 0 +1715 0 +1716 1 +1717 0 +1718 0 +1719 0 +1720 0 +1721 0 +1722 0 +1723 0 +1724 0 +1725 0 +1726 0 +1727 0 +1728 0 +1729 0 +1730 0 +1731 0 +1732 0 +1733 0 +1734 1 +1735 0 +1736 0 +1737 0 +1738 0 +1739 0 +1740 0 +1741 0 +1742 0 +1743 1 +1744 0 +1745 0 +1746 0 +1747 0 +1748 0 +1749 0 +1750 0 +1751 0 +1752 0 +1753 1 +1754 0 +1755 0 +1756 0 +1757 0 +1758 0 +1759 0 +1760 0 +1761 0 +1762 0 +1763 1 +1764 0 +1765 0 +1766 0 +1767 0 +1768 0 +1769 0 +1770 0 +1771 0 +1772 0 +1773 1 +1774 0 +1775 0 +1776 0 +1777 0 +1778 0 +1779 0 +1780 0 +1781 0 +1782 0 +1783 1 +1784 0 +1785 0 +1786 0 +1787 0 +1788 0 +1789 0 +1790 0 +1791 0 +1792 0 +1793 1 +1794 0 +1795 0 +1796 0 +1797 0 +1798 0 +1799 0 +1800 0 +1801 0 +1802 0 +1803 1 +1804 0 +1805 0 +1806 0 +1807 0 +1808 0 +1809 0 +1810 0 +1811 0 +1812 0 +1813 1 +1814 0 +1815 0 +1816 0 +1817 0 +1818 0 +1819 0 +1820 0 +1821 0 +1822 1 +1823 0 +1824 0 +1825 0 +1826 0 +1827 0 +1828 0 +1829 1 +1830 0 +1831 0 +1832 0 +1833 0 +1834 0 +1835 0 +1836 0 +1837 0 +1838 0 +1839 1 +1840 0 +1841 0 +1842 0 +1843 0 +1844 0 +1845 0 +1846 0 +1847 0 +1848 0 +1849 1 +1850 0 +1851 0 +1852 0 +1853 0 +1854 0 +1855 0 +1856 0 +1857 0 +1858 0 +1859 1 +1860 0 +1861 0 +1862 0 +1863 0 +1864 0 +1865 0 +1866 0 +1867 0 +1868 0 +1869 1 +1870 0 +1871 0 +1872 0 +1873 0 +1874 0 +1875 0 +1876 0 +1877 0 +1878 0 +1879 1 +1880 0 +1881 0 +1882 0 +1883 0 +1884 0 +1885 0 +1886 0 +1887 0 +1888 0 +1889 1 +1890 0 +1891 0 +1892 0 +1893 0 +1894 0 +1895 0 +1896 0 +1897 0 +1898 0 +1899 0 +1900 0 +1901 0 +1902 0 +1903 0 +1904 0 +1905 0 +1906 0 +1907 0 +1908 0 +1909 0 +1910 1 +1911 0 +1912 0 +1913 0 +1914 0 +1915 0 +1916 0 +1917 0 +1918 0 +1919 0 +1920 0 +1921 0 +1922 0 +1923 0 +1924 0 +1925 0 +1926 0 +1927 0 +1928 0 +1929 0 +1930 1 +1931 0 +1932 0 +1933 0 +1934 0 +1935 0 +1936 0 +1937 0 +1938 0 +1939 1 +1940 0 +1941 0 +1942 0 +1943 0 +1944 0 +1945 0 +1946 0 +1947 0 +1948 0 +1949 1 +1950 0 +1951 0 +1952 0 +1953 0 +1954 0 +1955 0 +1956 0 +1957 0 +1958 1 +1959 0 +1960 0 +1961 0 +1962 0 +1963 0 +1964 0 +1965 0 +1966 0 +1967 0 +1968 1 +1969 0 +1970 0 +1971 0 +1972 0 +1973 0 +1974 0 +1975 0 +1976 0 +1977 0 +1978 1 +1979 0 +1980 0 +1981 0 +1982 0 +1983 0 +1984 0 +1985 0 +1986 0 +1987 0 +1988 1 +1989 0 +1990 0 +1991 0 +1992 0 +1993 0 +1994 0 +1995 0 +1996 1 +1997 0 +1998 0 +1999 0 +2000 0 +2001 0 +2002 0 +2003 0 +2004 1 +2005 0 +2006 0 +2007 0 +2008 0 +2009 0 +2010 0 +2011 0 +2012 0 +2013 0 +2014 1 +2015 0 +2016 0 +2017 0 +2018 0 +2019 0 +2020 0 +2021 0 +2022 0 +2023 0 +2024 1 +2025 0 +2026 0 +2027 0 +2028 0 +2029 0 +2030 0 +2031 0 +2032 0 +2033 1 +2034 0 +2035 0 +2036 0 +2037 0 +2038 0 +2039 0 +2040 0 +2041 2 +2042 0 +2043 0 +2044 0 +2045 0 +2046 0 +2047 0 +2048 0 +2049 1 +2050 0 +2051 0 +2052 0 +2053 0 +2054 0 +2055 0 +2056 0 +2057 0 +2058 0 +2059 0 +2060 0 +2061 0 +2062 0 +2063 0 +2064 0 +2065 0 +2066 0 +2067 1 +2068 0 +2069 0 +2070 0 +2071 0 +2072 0 +2073 0 +2074 0 +2075 0 +2076 1 +2077 0 +2078 0 +2079 0 +2080 0 +2081 0 +2082 0 +2083 0 +2084 0 +2085 0 +2086 1 +2087 0 +2088 0 +2089 0 +2090 0 +2091 0 +2092 0 +2093 0 +2094 0 +2095 0 +2096 1 +2097 0 +2098 0 +2099 0 +2100 0 +2101 0 +2102 0 +2103 0 +2104 0 +2105 1 +2106 0 +2107 0 +2108 0 +2109 0 +2110 0 +2111 0 +2112 0 +2113 0 +2114 0 +2115 0 +2116 1 +2117 0 +2118 0 +2119 0 +2120 0 +2121 0 +2122 0 +2123 0 +2124 0 +2125 1 +2126 0 +2127 0 +2128 0 +2129 0 +2130 0 +2131 0 +2132 0 +2133 1 +2134 0 +2135 0 +2136 0 +2137 0 +2138 0 +2139 0 +2140 0 +2141 1 +2142 0 +2143 0 +2144 0 +2145 0 +2146 0 +2147 0 +2148 0 +2149 0 +2150 1 +2151 0 +2152 0 +2153 0 +2154 0 +2155 0 +2156 0 +2157 0 +2158 0 +2159 1 +2160 0 +2161 0 +2162 0 +2163 0 +2164 0 +2165 0 +2166 0 +2167 0 +2168 0 +2169 1 +2170 0 +2171 0 +2172 0 +2173 0 +2174 0 +2175 0 +2176 0 +2177 1 +2178 0 +2179 0 +2180 0 +2181 0 +2182 0 +2183 0 +2184 0 +2185 0 +2186 0 +2187 1 +2188 0 +2189 0 +2190 0 +2191 0 +2192 0 +2193 0 +2194 0 +2195 0 +2196 1 +2197 0 +2198 0 +2199 0 +2200 0 +2201 0 +2202 0 +2203 0 +2204 1 +2205 0 +2206 0 +2207 0 +2208 0 +2209 0 +2210 0 +2211 0 +2212 0 +2213 0 +2214 1 +2215 0 +2216 0 +2217 0 +2218 0 +2219 0 +2220 0 +2221 0 +2222 0 +2223 0 +2224 1 +2225 0 +2226 0 +2227 0 +2228 0 +2229 0 +2230 0 +2231 0 +2232 0 +2233 1 +2234 0 +2235 0 +2236 0 +2237 0 +2238 0 +2239 0 +2240 0 +2241 0 +2242 1 +2243 0 +2244 0 +2245 0 +2246 0 +2247 0 +2248 0 +2249 0 +2250 1 +2251 0 +2252 0 +2253 0 +2254 0 +2255 0 +2256 0 +2257 0 +2258 0 +2259 0 +2260 1 +2261 0 +2262 0 +2263 0 +2264 0 +2265 0 +2266 0 +2267 0 +2268 0 +2269 0 +2270 1 +2271 0 +2272 0 +2273 0 +2274 0 +2275 0 +2276 0 +2277 0 +2278 0 +2279 0 +2280 1 +2281 0 +2282 0 +2283 0 +2284 0 +2285 0 +2286 0 +2287 0 +2288 0 +2289 0 +2290 1 +2291 0 +2292 0 +2293 0 +2294 0 +2295 0 +2296 0 +2297 0 +2298 1 +2299 0 +2300 0 +2301 0 +2302 0 +2303 0 +2304 0 +2305 0 +2306 1 +2307 0 +2308 0 +2309 0 +2310 0 +2311 0 +2312 0 +2313 0 +2314 0 +2315 1 +2316 0 +2317 0 +2318 0 +2319 0 +2320 0 +2321 0 +2322 0 +2323 0 +2324 0 +2325 1 +2326 0 +2327 0 +2328 0 +2329 0 +2330 0 +2331 0 +2332 0 +2333 0 +2334 0 +2335 1 +2336 0 +2337 0 +2338 0 +2339 0 +2340 0 +2341 0 +2342 0 +2343 0 +2344 0 +2345 1 +2346 0 +2347 0 +2348 0 +2349 0 +2350 0 +2351 0 +2352 0 +2353 1 +2354 0 +2355 0 +2356 0 +2357 0 +2358 0 +2359 0 +2360 0 +2361 1 +2362 0 +2363 0 +2364 0 +2365 0 +2366 0 +2367 0 +2368 0 +2369 0 +2370 0 +2371 1 +2372 0 +2373 0 +2374 0 +2375 0 +2376 0 +2377 0 +2378 0 +2379 0 +2380 0 +2381 1 +2382 0 +2383 0 +2384 0 +2385 0 +2386 0 +2387 0 +2388 0 +2389 0 +2390 1 +2391 0 +2392 0 +2393 0 +2394 0 +2395 0 +2396 0 +2397 0 +2398 0 +2399 0 +2400 0 +2401 0 +2402 0 +2403 0 +2404 0 +2405 0 +2406 0 +2407 0 +2408 0 +2409 0 +2410 0 +2411 1 +2412 0 +2413 0 +2414 0 +2415 0 +2416 0 +2417 0 +2418 0 +2419 0 +2420 0 +2421 1 +2422 0 +2423 0 +2424 0 +2425 0 +2426 0 +2427 0 +2428 0 +2429 0 +2430 0 +2431 0 +2432 0 +2433 0 +2434 0 +2435 0 +2436 0 +2437 0 +2438 0 +2439 0 +2440 1 +2441 0 +2442 0 +2443 0 +2444 0 +2445 0 +2446 0 +2447 0 +2448 0 +2449 0 +2450 0 +2451 1 +2452 0 +2453 0 +2454 0 +2455 0 +2456 0 +2457 0 +2458 0 +2459 0 +2460 0 +2461 1 +2462 0 +2463 0 +2464 0 +2465 0 +2466 0 +2467 0 +2468 0 +2469 1 +2470 0 +2471 0 +2472 0 +2473 0 +2474 0 +2475 0 +2476 0 +2477 1 +2478 0 +2479 0 +2480 0 +2481 0 +2482 0 +2483 0 +2484 0 +2485 0 +2486 1 +2487 0 +2488 0 +2489 0 +2490 0 +2491 0 +2492 0 +2493 0 +2494 0 +2495 0 +2496 1 +2497 0 +2498 0 +2499 0 +2500 0 +2501 0 +2502 0 +2503 0 +2504 0 +2505 0 +2506 1 +2507 0 +2508 0 +2509 0 +2510 0 +2511 0 +2512 0 +2513 0 +2514 0 +2515 0 +2516 1 +2517 0 +2518 0 +2519 0 +2520 0 +2521 0 +2522 0 +2523 0 +2524 0 +2525 0 +2526 0 +2527 1 +2528 0 +2529 0 +2530 0 +2531 0 +2532 0 +2533 0 +2534 0 +2535 0 +2536 0 +2537 1 +2538 0 +2539 0 +2540 0 +2541 0 +2542 0 +2543 0 +2544 0 +2545 0 +2546 0 +2547 0 +2548 0 +2549 0 +2550 0 +2551 0 +2552 0 +2553 0 +2554 0 +2555 0 +2556 0 +2557 1 +2558 0 +2559 0 +2560 0 +2561 0 +2562 0 +2563 0 +2564 0 +2565 0 +2566 1 +2567 0 +2568 0 +2569 0 +2570 0 +2571 0 +2572 0 +2573 0 +2574 0 +2575 1 +2576 0 +2577 0 +2578 0 +2579 0 +2580 0 +2581 0 +2582 0 +2583 0 +2584 1 +2585 0 +2586 0 +2587 0 +2588 0 +2589 0 +2590 0 +2591 0 +2592 0 +2593 0 +2594 0 +2595 1 +2596 0 +2597 0 +2598 0 +2599 0 +2600 0 +2601 0 +2602 0 +2603 0 +2604 0 +2605 1 +2606 0 +2607 0 +2608 0 +2609 0 +2610 0 +2611 0 +2612 0 +2613 0 +2614 0 +2615 0 +2616 0 +2617 0 +2618 0 +2619 0 +2620 0 +2621 0 +2622 0 +2623 0 +2624 0 +2625 1 +2626 0 +2627 0 +2628 0 +2629 0 +2630 0 +2631 0 +2632 0 +2633 0 +2634 0 +2635 1 +2636 0 +2637 0 +2638 0 +2639 1 +2640 0 +2641 0 +2642 0 +2643 1 +2644 0 +2645 0 +2646 0 +2647 0 +2648 0 +2649 0 +2650 0 +2651 0 +2652 0 +2653 1 +2654 0 +2655 0 +2656 0 +2657 0 +2658 0 +2659 0 +2660 0 +2661 0 +2662 0 +2663 1 +2664 0 +2665 0 +2666 0 +2667 0 +2668 0 +2669 0 +2670 0 +2671 1 +2672 0 +2673 0 +2674 0 +2675 0 +2676 0 +2677 0 +2678 0 +2679 1 +2680 0 +2681 0 +2682 0 +2683 0 +2684 0 +2685 0 +2686 0 +2687 0 +2688 0 +2689 1 +2690 0 +2691 0 +2692 0 +2693 0 +2694 0 +2695 0 +2696 0 +2697 0 +2698 0 +2699 1 +2700 0 +2701 0 +2702 0 +2703 0 +2704 0 +2705 0 +2706 0 +2707 0 +2708 0 +2709 1 +2710 0 +2711 0 +2712 0 +2713 0 +2714 0 +2715 0 +2716 1 +2717 0 +2718 0 +2719 0 +2720 0 +2721 0 +2722 0 +2723 0 +2724 1 +2725 0 +2726 0 +2727 0 +2728 0 +2729 0 +2730 0 +2731 0 +2732 0 +2733 0 +2734 1 +2735 0 +2736 0 +2737 0 +2738 0 +2739 0 +2740 0 +2741 0 +2742 0 +2743 0 +2744 1 +2745 0 +2746 0 +2747 0 +2748 0 +2749 0 +2750 0 +2751 0 +2752 0 +2753 1 +2754 0 +2755 0 +2756 0 +2757 0 +2758 0 +2759 0 +2760 0 +2761 0 +2762 0 +2763 1 +2764 0 +2765 0 +2766 0 +2767 0 +2768 0 +2769 0 +2770 0 +2771 0 +2772 0 +2773 1 +2774 0 +2775 0 +2776 0 +2777 0 +2778 0 +2779 0 +2780 0 +2781 0 +2782 0 +2783 1 +2784 0 +2785 0 +2786 0 +2787 0 +2788 0 +2789 0 +2790 0 +2791 0 +2792 1 +2793 0 +2794 0 +2795 0 +2796 0 +2797 0 +2798 0 +2799 0 +2800 0 +2801 0 +2802 0 +2803 0 +2804 0 +2805 0 +2806 0 +2807 0 +2808 0 +2809 0 +2810 0 +2811 0 +2812 0 +2813 0 +2814 0 +2815 0 +2816 0 +2817 0 +2818 0 +2819 0 +2820 0 +2821 1 +2822 0 +2823 0 +2824 0 +2825 0 +2826 0 +2827 0 +2828 0 +2829 0 +2830 0 +2831 1 +2832 0 +2833 0 +2834 0 +2835 0 +2836 0 +2837 0 +2838 0 +2839 0 +2840 0 +2841 1 +2842 0 +2843 0 +2844 0 +2845 0 +2846 0 +2847 0 +2848 0 +2849 0 +2850 0 +2851 1 +2852 0 +2853 0 +2854 0 +2855 0 +2856 0 +2857 0 +2858 0 +2859 0 +2860 0 +2861 1 +2862 0 +2863 0 +2864 0 +2865 0 +2866 0 +2867 0 +2868 0 +2869 0 +2870 0 +2871 1 +2872 0 +2873 0 +2874 0 +2875 0 +2876 0 +2877 0 +2878 0 +2879 0 +2880 1 +2881 0 +2882 0 +2883 0 +2884 0 +2885 0 +2886 0 +2887 0 +2888 1 +2889 0 +2890 0 +2891 0 +2892 0 +2893 0 +2894 0 +2895 0 +2896 0 +2897 1 +2898 0 +2899 0 +2900 0 +2901 0 +2902 0 +2903 0 +2904 0 +2905 0 +2906 1 +2907 0 +2908 0 +2909 0 +2910 0 +2911 0 +2912 0 +2913 0 +2914 1 +2915 0 +2916 0 +2917 0 +2918 0 +2919 0 +2920 0 +2921 0 +2922 1 +2923 0 +2924 0 +2925 0 +2926 0 +2927 0 +2928 0 +2929 0 +2930 0 +2931 0 +2932 0 +2933 0 +2934 0 +2935 0 +2936 0 +2937 0 +2938 1 +2939 0 +2940 0 +2941 0 +2942 0 +2943 0 +2944 0 +2945 0 +2946 0 +2947 0 +2948 0 +2949 1 +2950 0 +2951 0 +2952 0 +2953 0 +2954 0 +2955 0 +2956 0 +2957 0 +2958 0 +2959 1 +2960 0 +2961 0 +2962 0 +2963 0 +2964 0 +2965 0 +2966 0 +2967 0 +2968 1 +2969 0 +2970 0 +2971 0 +2972 0 +2973 0 +2974 0 +2975 0 +2976 0 +2977 1 +2978 0 +2979 0 +2980 0 +2981 0 +2982 0 +2983 0 +2984 0 +2985 0 +2986 0 +2987 1 +2988 0 +2989 0 +2990 0 +2991 0 +2992 0 +2993 0 +2994 0 +2995 0 +2996 0 +2997 1 +2998 0 +2999 0 +3000 0 +3001 0 +3002 0 +3003 0 +3004 0 +3005 0 +3006 0 +3007 0 +3008 0 +3009 0 +3010 0 +3011 0 +3012 0 +3013 0 +3014 0 +3015 1 +3016 0 +3017 0 +3018 0 +3019 0 +3020 0 +3021 0 +3022 0 +3023 0 +3024 0 +3025 1 +3026 0 +3027 0 +3028 0 +3029 0 +3030 0 +3031 0 +3032 0 +3033 0 +3034 1 +3035 0 +3036 0 +3037 0 +3038 0 +3039 0 +3040 0 +3041 0 +3042 1 +3043 0 +3044 0 +3045 0 +3046 0 +3047 0 +3048 0 +3049 0 +3050 0 +3051 0 +3052 1 +3053 0 +3054 0 +3055 0 +3056 0 +3057 0 +3058 0 +3059 0 +3060 0 +3061 0 +3062 1 +3063 0 +3064 0 +3065 0 +3066 0 +3067 0 +3068 0 +3069 0 +3070 0 +3071 0 +3072 1 +3073 0 +3074 0 +3075 0 +3076 0 +3077 0 +3078 0 +3079 0 +3080 0 +3081 0 +3082 1 +3083 0 +3084 0 +3085 0 +3086 0 +3087 0 +3088 0 +3089 0 +3090 0 +3091 0 +3092 1 +3093 0 +3094 0 +3095 0 +3096 0 +3097 0 +3098 0 +3099 0 +3100 0 +3101 0 +3102 1 +3103 0 +3104 0 +3105 0 +3106 0 +3107 0 +3108 0 +3109 0 +3110 0 +3111 0 +3112 1 +3113 0 +3114 0 +3115 0 +3116 0 +3117 0 +3118 0 +3119 0 +3120 1 +3121 0 +3122 0 +3123 0 +3124 0 +3125 0 +3126 0 +3127 0 +3128 0 +3129 1 +3130 0 +3131 0 +3132 0 +3133 0 +3134 0 +3135 0 +3136 0 +3137 0 +3138 0 +3139 1 +3140 0 +3141 0 +3142 0 +3143 0 +3144 0 +3145 0 +3146 0 +3147 0 +3148 0 +3149 1 +3150 0 +3151 0 +3152 0 +3153 0 +3154 0 +3155 0 +3156 0 +3157 1 +3158 0 +3159 0 +3160 0 +3161 0 +3162 0 +3163 0 +3164 0 +3165 1 +3166 0 +3167 0 +3168 0 +3169 0 +3170 0 +3171 0 +3172 0 +3173 0 +3174 0 +3175 1 +3176 0 +3177 0 +3178 0 +3179 0 +3180 0 +3181 0 +3182 0 +3183 0 +3184 0 +3185 1 +3186 0 +3187 0 +3188 0 +3189 0 +3190 0 +3191 0 +3192 0 +3193 0 +3194 0 +3195 0 +3196 1 +3197 0 +3198 0 +3199 0 +3200 0 +3201 0 +3202 0 +3203 0 +3204 0 +3205 0 +3206 0 +3207 1 +3208 0 +3209 0 +3210 0 +3211 0 +3212 0 +3213 0 +3214 0 +3215 1 +3216 0 +3217 0 +3218 0 +3219 0 +3220 0 +3221 0 +3222 0 +3223 1 +3224 0 +3225 0 +3226 0 +3227 0 +3228 0 +3229 0 +3230 0 +3231 0 +3232 1 +3233 0 +3234 1 +3235 0 +3236 0 +3237 0 +3238 0 +3239 1 +3240 0 +3241 0 +3242 0 +3243 0 +3244 0 +3245 0 +3246 0 +3247 0 +3248 1 +3249 0 +3250 0 +3251 0 +3252 0 +3253 0 +3254 0 +3255 0 +3256 0 +3257 0 +3258 1 +3259 0 +3260 0 +3261 0 +3262 0 +3263 0 +3264 0 +3265 0 +3266 0 +3267 0 +3268 0 +3269 1 +3270 0 +3271 0 +3272 0 +3273 0 +3274 0 +3275 0 +3276 0 +3277 0 +3278 1 +3279 0 +3280 0 +3281 0 +3282 0 +3283 0 +3284 0 +3285 0 +3286 0 +3287 1 +3288 0 +3289 0 +3290 0 +3291 0 +3292 0 +3293 0 +3294 0 +3295 0 +3296 0 +3297 1 +3298 0 +3299 0 +3300 0 +3301 0 +3302 0 +3303 0 +3304 0 +3305 0 +3306 0 +3307 1 +3308 0 +3309 0 +3310 0 +3311 0 +3312 0 +3313 0 +3314 0 +3315 0 +3316 0 +3317 1 +3318 0 +3319 0 +3320 0 +3321 0 +3322 0 +3323 0 +3324 0 +3325 1 +3326 0 +3327 0 +3328 0 +3329 0 +3330 0 +3331 0 +3332 0 +3333 0 +3334 0 +3335 1 +3336 0 +3337 0 +3338 0 +3339 0 +3340 0 +3341 0 +3342 0 +3343 0 +3344 1 +3345 0 +3346 0 +3347 0 +3348 0 +3349 0 +3350 0 +3351 0 +3352 0 +3353 0 +3354 1 +3355 0 +3356 0 +3357 0 +3358 0 +3359 0 +3360 0 +3361 0 +3362 0 +3363 0 +3364 0 +3365 1 +3366 0 +3367 0 +3368 0 +3369 0 +3370 0 +3371 0 +3372 0 +3373 0 +3374 0 +3375 1 +3376 0 +3377 0 +3378 0 +3379 0 +3380 0 +3381 0 +3382 0 +3383 0 +3384 0 +3385 0 +3386 1 +3387 0 +3388 0 +3389 0 +3390 0 +3391 0 +3392 0 +3393 0 +3394 0 +3395 0 +3396 0 +3397 1 +3398 0 +3399 0 +3400 0 +3401 0 +3402 0 +3403 0 +3404 0 +3405 0 +3406 0 +3407 1 +3408 0 +3409 0 +3410 0 +3411 0 +3412 0 +3413 0 +3414 0 +3415 0 +3416 0 +3417 1 +3418 0 +3419 0 +3420 0 +3421 0 +3422 0 +3423 0 +3424 0 +3425 0 +3426 0 +3427 0 +3428 1 +3429 0 +3430 0 +3431 0 +3432 0 +3433 0 +3434 0 +3435 0 +3436 0 +3437 1 +3438 0 +3439 0 +3440 0 +3441 0 +3442 0 +3443 0 +3444 0 +3445 1 +3446 0 +3447 0 +3448 0 +3449 0 +3450 0 +3451 0 +3452 0 +3453 0 +3454 1 +3455 0 +3456 0 +3457 0 +3458 0 +3459 0 +3460 0 +3461 0 +3462 0 +3463 0 +3464 1 +3465 0 +3466 0 +3467 0 +3468 0 +3469 0 +3470 0 +3471 0 +3472 0 +3473 0 +3474 1 +3475 0 +3476 0 +3477 0 +3478 0 +3479 0 +3480 0 +3481 0 +3482 0 +3483 0 +3484 1 +3485 0 +3486 0 +3487 0 +3488 0 +3489 0 +3490 0 +3491 0 +3492 0 +3493 0 +3494 1 +3495 0 +3496 0 +3497 0 +3498 0 +3499 0 +3500 0 +3501 0 +3502 0 +3503 0 +3504 1 +3505 0 +3506 0 +3507 0 +3508 0 +3509 0 +3510 0 +3511 0 +3512 0 +3513 0 +3514 1 +3515 0 +3516 0 +3517 0 +3518 0 +3519 0 +3520 0 +3521 0 +3522 0 +3523 0 +3524 1 +3525 0 +3526 0 +3527 0 +3528 0 +3529 0 +3530 0 +3531 0 +3532 0 +3533 1 +3534 0 +3535 0 +3536 0 +3537 0 +3538 0 +3539 0 +3540 0 +3541 0 +3542 0 +3543 0 +3544 0 +3545 0 +3546 0 +3547 0 +3548 0 +3549 0 +3550 0 +3551 1 +3552 0 +3553 0 +3554 0 +3555 0 +3556 0 +3557 0 +3558 0 +3559 0 +3560 0 +3561 1 +3562 0 +3563 0 +3564 0 +3565 0 +3566 0 +3567 0 +3568 0 +3569 0 +3570 1 +3571 0 +3572 0 +3573 0 +3574 0 +3575 0 +3576 0 +3577 0 +3578 0 +3579 0 +3580 1 +3581 0 +3582 0 +3583 0 +3584 0 +3585 0 +3586 0 +3587 0 +3588 0 +3589 0 +3590 1 +3591 0 +3592 0 +3593 0 +3594 0 +3595 0 +3596 0 +3597 0 +3598 0 +3599 1 +3600 0 +3601 0 +3602 0 +3603 0 +3604 0 +3605 0 +3606 0 +3607 0 +3608 0 +3609 1 +3610 0 +3611 0 +3612 0 +3613 0 +3614 0 +3615 0 +3616 0 +3617 0 +3618 0 +3619 0 +3620 1 +3621 0 +3622 0 +3623 0 +3624 0 +3625 0 +3626 0 +3627 0 +3628 0 +3629 0 +3630 1 +3631 0 +3632 0 +3633 0 +3634 0 +3635 0 +3636 0 +3637 0 +3638 0 +3639 1 +3640 0 +3641 0 +3642 0 +3643 0 +3644 0 +3645 1 +3646 0 +3647 0 +3648 0 +3649 0 +3650 0 +3651 1 +3652 0 +3653 0 +3654 0 +3655 0 +3656 0 +3657 0 +3658 1 +3659 0 +3660 0 +3661 0 +3662 0 +3663 0 +3664 0 +3665 0 +3666 1 +3667 0 +3668 0 +3669 0 +3670 0 +3671 0 +3672 0 +3673 0 +3674 0 +3675 0 +3676 1 +3677 0 +3678 0 +3679 0 +3680 0 +3681 0 +3682 0 +3683 0 +3684 0 +3685 1 +3686 0 +3687 0 +3688 0 +3689 0 +3690 0 +3691 0 +3692 0 +3693 0 +3694 0 +3695 1 +3696 0 +3697 0 +3698 0 +3699 0 +3700 0 +3701 0 +3702 0 +3703 0 +3704 0 +3705 0 +3706 1 +3707 0 +3708 0 +3709 0 +3710 0 +3711 0 +3712 0 +3713 0 +3714 0 +3715 0 +3716 1 +3717 0 +3718 0 +3719 0 +3720 0 +3721 0 +3722 0 +3723 0 +3724 0 +3725 0 +3726 0 +3727 0 +3728 0 +3729 0 +3730 0 +3731 0 +3732 0 +3733 0 +3734 0 +3735 0 +3736 1 +3737 0 +3738 0 +3739 0 +3740 0 +3741 0 +3742 0 +3743 0 +3744 0 +3745 0 +3746 1 +3747 0 +3748 0 +3749 0 +3750 0 +3751 0 +3752 0 +3753 0 +3754 0 +3755 0 +3756 1 +3757 0 +3758 0 +3759 0 +3760 0 +3761 0 +3762 0 +3763 1 +3764 0 +3765 0 +3766 0 +3767 0 +3768 0 +3769 0 +3770 0 +3771 1 +3772 0 +3773 0 +3774 0 +3775 0 +3776 0 +3777 0 +3778 1 +3779 0 +3780 0 +3781 0 +3782 0 +3783 0 +3784 0 +3785 0 +3786 0 +3787 0 +3788 0 +3789 0 +3790 0 +3791 0 +3792 0 +3793 0 +3794 0 +3795 0 +3796 0 +3797 1 +3798 0 +3799 0 +3800 0 +3801 0 +3802 0 +3803 0 +3804 0 +3805 0 +3806 1 +3807 0 +3808 0 +3809 0 +3810 0 +3811 0 +3812 0 +3813 0 +3814 0 +3815 0 +3816 0 +3817 1 +3818 0 +3819 0 +3820 0 +3821 0 +3822 0 +3823 0 +3824 0 +3825 0 +3826 0 +3827 1 +3828 0 +3829 1 +3830 0 +3831 0 +3832 0 +3833 0 +3834 1 +3835 0 +3836 0 +3837 0 +3838 0 +3839 0 +3840 0 +3841 0 +3842 0 +3843 0 +3844 0 +3845 1 +3846 0 +3847 0 +3848 0 +3849 0 +3850 0 +3851 0 +3852 0 +3853 0 +3854 0 +3855 1 +3856 0 +3857 0 +3858 0 +3859 0 +3860 0 +3861 0 +3862 0 +3863 1 +3864 0 +3865 0 +3866 0 +3867 0 +3868 0 +3869 0 +3870 0 +3871 0 +3872 0 +3873 1 +3874 0 +3875 0 +3876 0 +3877 0 +3878 0 +3879 0 +3880 0 +3881 0 +3882 0 +3883 1 +3884 0 +3885 0 +3886 0 +3887 0 +3888 0 +3889 0 +3890 0 +3891 0 +3892 0 +3893 0 +3894 1 +3895 0 +3896 0 +3897 0 +3898 0 +3899 0 +3900 0 +3901 0 +3902 0 +3903 0 +3904 0 +3905 1 +3906 0 +3907 0 +3908 0 +3909 0 +3910 0 +3911 0 +3912 0 +3913 0 +3914 1 +3915 0 +3916 0 +3917 0 +3918 0 +3919 0 +3920 0 +3921 0 +3922 0 +3923 0 +3924 0 +3925 1 +3926 0 +3927 0 +3928 0 +3929 0 +3930 0 +3931 0 +3932 0 +3933 0 +3934 1 +3935 0 +3936 0 +3937 0 +3938 0 +3939 0 +3940 0 +3941 0 +3942 0 +3943 0 +3944 0 +3945 1 +3946 0 +3947 0 +3948 0 +3949 0 +3950 0 +3951 0 +3952 0 +3953 0 +3954 0 +3955 1 +3956 0 +3957 0 +3958 0 +3959 0 +3960 0 +3961 0 +3962 0 +3963 0 +3964 0 +3965 0 +3966 1 +3967 0 +3968 0 +3969 0 +3970 0 +3971 0 +3972 0 +3973 0 +3974 0 +3975 1 +3976 0 +3977 0 +3978 0 +3979 0 +3980 0 +3981 0 +3982 0 +3983 0 +3984 1 +3985 0 +3986 0 +3987 0 +3988 0 +3989 0 +3990 0 +3991 0 +3992 0 +3993 0 +3994 1 +3995 0 +3996 0 +3997 0 +3998 0 +3999 0 +4000 0 +4001 0 +4002 0 +4003 0 +4004 0 +4005 0 +4006 0 +4007 0 +4008 0 +4009 0 +4010 0 +4011 0 +4012 0 +4013 0 +4014 1 +4015 0 +4016 0 +4017 0 +4018 0 +4019 0 +4020 0 +4021 0 +4022 0 +4023 0 +4024 1 +4025 0 +4026 0 +4027 0 +4028 0 +4029 0 +4030 0 +4031 0 +4032 0 +4033 0 +4034 0 +4035 1 +4036 0 +4037 0 +4038 0 +4039 0 +4040 0 +4041 0 +4042 0 +4043 0 +4044 0 +4045 1 +4046 0 +4047 0 +4048 0 +4049 0 +4050 0 +4051 0 +4052 0 +4053 0 +4054 0 +4055 0 +4056 1 +4057 0 +4058 0 +4059 0 +4060 0 +4061 0 +4062 0 +4063 0 +4064 0 +4065 0 +4066 1 +4067 0 +4068 0 +4069 0 +4070 0 +4071 0 +4072 0 +4073 0 +4074 1 +4075 0 +4076 0 +4077 0 +4078 0 +4079 0 +4080 0 +4081 0 +4082 0 +4083 0 +4084 1 +4085 0 +4086 0 +4087 0 +4088 0 +4089 0 +4090 0 +4091 0 +4092 0 +4093 1 +4094 0 +4095 0 +4096 0 +4097 0 +4098 0 +4099 0 +4100 0 +4101 0 +4102 1 +4103 0 +4104 0 +4105 0 +4106 0 +4107 0 +4108 0 +4109 0 +4110 0 +4111 0 +4112 1 +4113 0 +4114 0 +4115 0 +4116 0 +4117 0 +4118 0 +4119 0 +4120 0 +4121 0 +4122 1 +4123 0 +4124 0 +4125 0 +4126 0 +4127 0 +4128 0 +4129 0 +4130 0 +4131 0 +4132 0 +4133 1 +4134 0 +4135 0 +4136 0 +4137 0 +4138 0 +4139 0 +4140 0 +4141 0 +4142 0 +4143 0 +4144 1 +4145 0 +4146 0 +4147 0 +4148 0 +4149 0 +4150 0 +4151 0 +4152 0 +4153 0 +4154 1 +4155 0 +4156 0 +4157 0 +4158 0 +4159 0 +4160 0 +4161 0 +4162 0 +4163 0 +4164 0 +4165 1 +4166 0 +4167 0 +4168 0 +4169 0 +4170 0 +4171 0 +4172 0 +4173 0 +4174 0 +4175 0 +4176 1 +4177 0 +4178 0 +4179 0 +4180 0 +4181 0 +4182 0 +4183 0 +4184 0 +4185 1 +4186 0 +4187 0 +4188 0 +4189 0 +4190 0 +4191 0 +4192 0 +4193 0 +4194 0 +4195 1 +4196 0 +4197 0 +4198 0 +4199 0 +4200 0 +4201 0 +4202 0 +4203 0 +4204 0 +4205 0 +4206 0 +4207 0 +4208 0 +4209 0 +4210 0 +4211 0 +4212 1 +4213 0 +4214 0 +4215 0 +4216 0 +4217 0 +4218 0 +4219 0 +4220 0 +4221 1 +4222 0 +4223 0 +4224 0 +4225 0 +4226 0 +4227 0 +4228 0 +4229 0 +4230 1 +4231 0 +4232 0 +4233 0 +4234 0 +4235 0 +4236 0 +4237 0 +4238 0 +4239 1 +4240 0 +4241 0 +4242 0 +4243 0 +4244 0 +4245 0 +4246 0 +4247 0 +4248 0 +4249 1 +4250 0 +4251 0 +4252 0 +4253 0 +4254 0 +4255 0 +4256 0 +4257 0 +4258 1 +4259 0 +4260 0 +4261 0 +4262 0 +4263 0 +4264 0 +4265 0 +4266 0 +4267 0 +4268 1 +4269 0 +4270 0 +4271 0 +4272 0 +4273 0 +4274 0 +4275 0 +4276 0 +4277 0 +4278 1 +4279 0 +4280 0 +4281 0 +4282 0 +4283 0 +4284 0 +4285 0 +4286 0 +4287 0 +4288 0 +4289 1 +4290 0 +4291 0 +4292 0 +4293 0 +4294 0 +4295 0 +4296 0 +4297 0 +4298 0 +4299 1 +4300 0 +4301 0 +4302 0 +4303 0 +4304 0 +4305 0 +4306 0 +4307 0 +4308 0 +4309 1 +4310 0 +4311 0 +4312 0 +4313 0 +4314 0 +4315 0 +4316 0 +4317 0 +4318 1 +4319 0 +4320 0 +4321 0 +4322 0 +4323 0 +4324 0 +4325 0 +4326 0 +4327 1 +4328 0 +4329 0 +4330 0 +4331 0 +4332 0 +4333 0 +4334 0 +4335 0 +4336 0 +4337 1 +4338 0 +4339 0 +4340 0 +4341 0 +4342 0 +4343 0 +4344 0 +4345 0 +4346 0 +4347 1 +4348 0 +4349 0 +4350 0 +4351 0 +4352 0 +4353 0 +4354 0 +4355 1 +4356 0 +4357 0 +4358 0 +4359 0 +4360 0 +4361 0 +4362 0 +4363 0 +4364 0 +4365 0 +4366 0 +4367 0 +4368 0 +4369 0 +4370 0 +4371 0 +4372 0 +4373 0 +4374 1 +4375 0 +4376 0 +4377 0 +4378 0 +4379 0 +4380 0 +4381 0 +4382 0 +4383 0 +4384 1 +4385 0 +4386 0 +4387 0 +4388 0 +4389 0 +4390 0 +4391 0 +4392 0 +4393 1 +4394 0 +4395 0 +4396 0 +4397 0 +4398 0 +4399 0 +4400 0 +4401 0 +4402 0 +4403 1 +4404 0 +4405 0 +4406 0 +4407 0 +4408 0 +4409 0 +4410 0 +4411 0 +4412 1 +4413 0 +4414 0 +4415 0 +4416 0 +4417 0 +4418 0 +4419 0 +4420 0 +4421 0 +4422 0 +4423 1 +4424 0 +4425 0 +4426 0 +4427 0 +4428 0 +4429 0 +4430 2 +4431 0 +4432 0 +4433 0 +4434 0 +4435 0 +4436 0 +4437 1 +4438 0 +4439 0 +4440 0 +4441 0 +4442 0 +4443 0 +4444 0 +4445 1 +4446 0 +4447 0 +4448 0 +4449 0 +4450 0 +4451 0 +4452 0 +4453 0 +4454 1 +4455 0 +4456 0 +4457 0 +4458 0 +4459 0 +4460 0 +4461 0 +4462 1 +4463 0 +4464 0 +4465 0 +4466 0 +4467 0 +4468 0 +4469 0 +4470 0 +4471 1 +4472 0 +4473 0 +4474 0 +4475 0 +4476 0 +4477 0 +4478 0 +4479 0 +4480 1 +4481 0 +4482 0 +4483 0 +4484 0 +4485 0 +4486 0 +4487 0 +4488 1 +4489 0 +4490 0 +4491 0 +4492 0 +4493 0 +4494 0 +4495 0 +4496 0 +4497 1 +4498 0 +4499 0 +4500 0 +4501 0 +4502 0 +4503 0 +4504 0 +4505 1 +4506 0 +4507 0 +4508 0 +4509 0 +4510 0 +4511 0 +4512 0 +4513 1 +4514 0 +4515 0 +4516 0 +4517 0 +4518 0 +4519 0 +4520 1 +4521 0 +4522 0 +4523 0 +4524 0 +4525 0 +4526 0 +4527 0 +4528 0 +4529 1 +4530 0 +4531 0 +4532 0 +4533 0 +4534 0 +4535 0 +4536 0 +4537 0 +4538 1 +4539 0 +4540 0 +4541 0 +4542 0 +4543 0 +4544 0 +4545 0 +4546 1 +4547 0 +4548 0 +4549 0 +4550 0 +4551 0 +4552 1 +4553 0 +4554 0 +4555 0 +4556 0 +4557 0 +4558 0 +4559 1 +4560 0 +4561 0 +4562 0 +4563 0 +4564 0 +4565 0 +4566 0 +4567 1 +4568 0 +4569 0 +4570 0 +4571 0 +4572 0 +4573 0 +4574 0 +4575 1 +4576 0 +4577 0 +4578 0 +4579 0 +4580 0 +4581 0 +4582 0 +4583 1 +4584 0 +4585 0 +4586 0 +4587 0 +4588 0 +4589 0 +4590 0 +4591 1 +4592 0 +4593 0 +4594 0 +4595 0 +4596 0 +4597 0 +4598 0 +4599 0 +4600 1 +4601 0 +4602 0 +4603 0 +4604 0 +4605 0 +4606 0 +4607 1 +4608 0 +4609 0 +4610 0 +4611 0 +4612 0 +4613 0 +4614 0 +4615 0 +4616 1 +4617 0 +4618 0 +4619 0 +4620 0 +4621 0 +4622 0 +4623 0 +4624 0 +4625 1 +4626 0 +4627 0 +4628 0 +4629 0 +4630 0 +4631 0 +4632 0 +4633 0 +4634 1 +4635 0 +4636 0 +4637 0 +4638 0 +4639 0 +4640 0 +4641 0 +4642 0 +4643 0 +4644 0 +4645 0 +4646 0 +4647 0 +4648 0 +4649 0 +4650 0 +4651 0 +4652 1 +4653 0 +4654 0 +4655 0 +4656 0 +4657 0 +4658 0 +4659 0 +4660 0 +4661 1 +4662 0 +4663 0 +4664 0 +4665 1 +4666 0 +4667 0 +4668 0 +4669 0 +4670 0 +4671 0 +4672 1 +4673 0 +4674 0 +4675 0 +4676 0 +4677 0 +4678 1 +4679 0 +4680 0 +4681 0 +4682 0 +4683 0 +4684 0 +4685 0 +4686 1 +4687 0 +4688 0 +4689 0 +4690 0 +4691 0 +4692 0 +4693 0 +4694 1 +4695 0 +4696 0 +4697 0 +4698 0 +4699 0 +4700 0 +4701 0 +4702 1 +4703 0 +4704 0 +4705 0 +4706 0 +4707 0 +4708 0 +4709 1 +4710 0 +4711 0 +4712 0 +4713 0 +4714 0 +4715 0 +4716 0 +4717 1 +4718 0 +4719 0 +4720 0 +4721 0 +4722 0 +4723 0 +4724 0 +4725 1 +4726 0 +4727 0 +4728 0 +4729 0 +4730 0 +4731 0 +4732 0 +4733 0 +4734 1 +4735 0 +4736 0 +4737 0 +4738 0 +4739 0 +4740 0 +4741 0 +4742 0 +4743 0 +4744 1 +4745 0 +4746 0 +4747 0 +4748 0 +4749 0 +4750 0 +4751 0 +4752 1 +4753 0 +4754 0 +4755 0 +4756 0 +4757 0 +4758 0 +4759 0 +4760 1 +4761 0 +4762 0 +4763 0 +4764 0 +4765 0 +4766 0 +4767 0 +4768 0 +4769 1 +4770 0 +4771 0 +4772 0 +4773 0 +4774 0 +4775 0 +4776 0 +4777 0 +4778 1 +4779 0 +4780 0 +4781 0 +4782 0 +4783 0 +4784 0 +4785 0 +4786 1 +4787 0 +4788 0 +4789 0 +4790 0 +4791 0 +4792 0 +4793 0 +4794 0 +4795 0 +4796 1 +4797 0 +4798 0 +4799 0 +4800 0 +4801 0 +4802 0 +4803 0 +4804 1 +4805 0 +4806 0 +4807 0 +4808 0 +4809 0 +4810 0 +4811 0 +4812 0 +4813 1 +4814 0 +4815 0 +4816 0 +4817 0 +4818 0 +4819 0 +4820 0 +4821 0 +4822 1 +4823 0 +4824 0 +4825 0 +4826 0 +4827 0 +4828 0 +4829 0 +4830 0 +4831 1 +4832 0 +4833 0 +4834 0 +4835 0 +4836 0 +4837 0 +4838 0 +4839 0 +4840 0 +4841 0 +4842 0 +4843 0 +4844 0 +4845 0 +4846 0 +4847 0 +4848 0 +4849 0 +4850 0 +4851 0 +4852 0 +4853 0 +4854 0 +4855 0 +4856 0 +4857 0 +4858 0 +4859 0 +4860 0 +4861 0 +4862 0 +4863 0 +4864 0 +4865 1 +4866 0 +4867 0 +4868 0 +4869 0 +4870 0 +4871 0 +4872 1 +4873 0 +4874 0 +4875 0 +4876 0 +4877 0 +4878 0 +4879 0 +4880 1 +4881 0 +4882 0 +4883 0 +4884 0 +4885 0 +4886 0 +4887 0 +4888 0 +4889 0 +4890 1 +4891 0 +4892 0 +4893 0 +4894 0 +4895 0 +4896 0 +4897 0 +4898 1 +4899 0 +4900 0 +4901 0 +4902 0 +4903 0 +4904 0 +4905 1 +4906 0 +4907 0 +4908 0 +4909 0 +4910 0 +4911 0 +4912 0 +4913 1 +4914 0 +4915 0 +4916 0 +4917 0 +4918 0 +4919 0 +4920 0 +4921 0 +4922 0 +4923 1 +4924 0 +4925 0 +4926 0 +4927 0 +4928 0 +4929 0 +4930 0 +4931 0 +4932 0 +4933 1 +4934 0 +4935 0 +4936 0 +4937 0 +4938 0 +4939 0 +4940 0 +4941 0 +4942 0 +4943 0 +4944 0 +4945 0 +4946 0 +4947 0 +4948 1 +4949 0 +4950 0 +4951 0 +4952 0 +4953 0 +4954 0 +4955 0 +4956 1 +4957 0 +4958 0 +4959 0 +4960 0 +4961 0 +4962 0 +4963 0 +4964 1 +4965 0 +4966 0 +4967 0 +4968 0 +4969 0 +4970 0 +4971 0 +4972 1 +4973 0 +4974 0 +4975 0 +4976 0 +4977 0 +4978 0 +4979 1 +4980 0 +4981 0 +4982 0 +4983 0 +4984 0 +4985 0 +4986 0 +4987 1 +4988 0 +4989 0 +4990 0 +4991 0 +4992 0 +4993 0 +4994 1 +4995 0 +4996 0 +4997 0 +4998 0 +4999 0 +5000 0 +5001 0 +5002 0 +5003 1 +5004 0 +5005 0 +5006 0 +5007 0 +5008 0 +5009 0 +5010 0 +5011 0 +5012 1 +5013 0 +5014 0 +5015 0 +5016 0 +5017 0 +5018 0 +5019 0 +5020 1 +5021 0 +5022 0 +5023 0 +5024 0 +5025 0 +5026 0 +5027 0 +5028 0 +5029 1 +5030 0 +5031 0 +5032 0 +5033 0 +5034 0 +5035 0 +5036 0 +5037 1 +5038 0 +5039 0 +5040 0 +5041 0 +5042 0 +5043 0 +5044 0 +5045 1 +5046 0 +5047 0 +5048 0 +5049 0 +5050 0 +5051 0 +5052 0 +5053 1 +5054 0 +5055 0 +5056 0 +5057 0 +5058 0 +5059 0 +5060 0 +5061 0 +5062 1 +5063 0 +5064 0 +5065 0 +5066 0 +5067 0 +5068 0 +5069 0 +5070 0 +5071 0 +5072 0 +5073 0 +5074 0 +5075 0 +5076 0 +5077 0 +5078 0 +5079 1 +5080 0 +5081 0 +5082 0 +5083 0 +5084 0 +5085 0 +5086 1 +5087 0 +5088 0 +5089 0 +5090 0 +5091 0 +5092 0 +5093 0 +5094 1 +5095 0 +5096 0 +5097 0 +5098 0 +5099 0 +5100 0 +5101 0 +5102 0 +5103 1 +5104 0 +5105 0 +5106 0 +5107 0 +5108 0 +5109 0 +5110 1 +5111 0 +5112 0 +5113 0 +5114 0 +5115 0 +5116 0 +5117 0 +5118 1 +5119 0 +5120 0 +5121 0 +5122 0 +5123 0 +5124 0 +5125 0 +5126 0 +5127 1 +5128 0 +5129 0 +5130 0 +5131 0 +5132 0 +5133 0 +5134 1 +5135 0 +5136 0 +5137 0 +5138 0 +5139 0 +5140 0 +5141 1 +5142 0 +5143 0 +5144 0 +5145 0 +5146 0 +5147 0 +5148 0 +5149 1 +5150 0 +5151 0 +5152 0 +5153 0 +5154 0 +5155 0 +5156 0 +5157 0 +5158 1 +5159 0 +5160 0 +5161 0 +5162 0 +5163 0 +5164 0 +5165 0 +5166 0 +5167 1 +5168 0 +5169 0 +5170 0 +5171 0 +5172 0 +5173 0 +5174 0 +5175 1 +5176 0 +5177 0 +5178 0 +5179 0 +5180 0 +5181 0 +5182 1 +5183 0 +5184 0 +5185 0 +5186 0 +5187 0 +5188 0 +5189 0 +5190 1 +5191 0 +5192 0 +5193 0 +5194 0 +5195 0 +5196 0 +5197 0 +5198 0 +5199 1 +5200 0 +5201 0 +5202 0 +5203 0 +5204 0 +5205 0 +5206 0 +5207 0 +5208 1 +5209 0 +5210 0 +5211 0 +5212 0 +5213 0 +5214 0 +5215 0 +5216 0 +5217 0 +5218 1 +5219 0 +5220 0 +5221 0 +5222 0 +5223 0 +5224 0 +5225 0 +5226 1 +5227 0 +5228 0 +5229 0 +5230 0 +5231 0 +5232 0 +5233 0 +5234 1 +5235 0 +5236 0 +5237 0 +5238 0 +5239 0 +5240 0 +5241 0 +5242 1 +5243 0 +5244 0 +5245 0 +5246 0 +5247 0 +5248 0 +5249 0 +5250 0 +5251 1 +5252 0 +5253 0 +5254 0 +5255 0 +5256 0 +5257 0 +5258 0 +5259 0 +5260 0 +5261 0 +5262 0 +5263 0 +5264 0 +5265 0 +5266 0 +5267 0 +5268 1 +5269 0 +5270 0 +5271 0 +5272 0 +5273 0 +5274 0 +5275 0 +5276 1 +5277 0 +5278 0 +5279 0 +5280 0 +5281 0 +5282 0 +5283 1 +5284 0 +5285 0 +5286 0 +5287 0 +5288 0 +5289 0 +5290 0 +5291 0 +5292 0 +5293 1 +5294 0 +5295 0 +5296 0 +5297 0 +5298 0 +5299 0 +5300 0 +5301 1 +5302 0 +5303 0 +5304 0 +5305 0 +5306 0 +5307 0 +5308 0 +5309 0 +5310 1 +5311 0 +5312 0 +5313 0 +5314 0 +5315 0 +5316 0 +5317 0 +5318 1 +5319 0 +5320 0 +5321 0 +5322 0 +5323 0 +5324 0 +5325 1 +5326 0 +5327 0 +5328 0 +5329 0 +5330 0 +5331 0 +5332 0 +5333 0 +5334 0 +5335 0 +5336 0 +5337 0 +5338 0 +5339 0 +5340 0 +5341 0 +5342 1 +5343 0 +5344 0 +5345 0 +5346 0 +5347 0 +5348 0 +5349 1 +5350 0 +5351 0 +5352 0 +5353 0 +5354 0 +5355 0 +5356 0 +5357 0 +5358 1 +5359 0 +5360 0 +5361 0 +5362 0 +5363 0 +5364 0 +5365 0 +5366 1 +5367 0 +5368 0 +5369 0 +5370 0 +5371 0 +5372 0 +5373 1 +5374 0 +5375 0 +5376 0 +5377 0 +5378 0 +5379 0 +5380 0 +5381 1 +5382 0 +5383 0 +5384 0 +5385 0 +5386 0 +5387 0 +5388 0 +5389 0 +5390 1 +5391 0 +5392 0 +5393 0 +5394 0 +5395 0 +5396 0 +5397 0 +5398 1 +5399 0 +5400 0 +5401 0 +5402 0 +5403 0 +5404 0 +5405 0 +5406 1 +5407 0 +5408 0 +5409 0 +5410 0 +5411 0 +5412 0 +5413 0 +5414 1 +5415 0 +5416 0 +5417 0 +5418 0 +5419 0 +5420 0 +5421 0 +5422 1 +5423 0 +5424 0 +5425 0 +5426 0 +5427 0 +5428 0 +5429 0 +5430 0 +5431 0 +5432 0 +5433 0 +5434 0 +5435 0 +5436 0 +5437 0 +5438 1 +5439 0 +5440 0 +5441 0 +5442 0 +5443 0 +5444 0 +5445 0 +5446 0 +5447 1 +5448 0 +5449 0 +5450 0 +5451 0 +5452 0 +5453 0 +5454 0 +5455 0 +5456 1 +5457 0 +5458 0 +5459 0 +5460 0 +5461 0 +5462 0 +5463 0 +5464 1 +5465 0 +5466 0 +5467 0 +5468 0 +5469 0 +5470 0 +5471 0 +5472 1 +5473 0 +5474 0 +5475 0 +5476 0 +5477 0 +5478 0 +5479 0 +5480 0 +5481 1 +5482 0 +5483 0 +5484 0 +5485 0 +5486 0 +5487 0 +5488 0 +5489 1 +5490 0 +5491 0 +5492 0 +5493 0 +5494 0 +5495 0 +5496 0 +5497 0 +5498 1 +5499 0 +5500 0 +5501 0 +5502 0 +5503 0 +5504 0 +5505 0 +5506 1 +5507 0 +5508 0 +5509 0 +5510 0 +5511 0 +5512 0 +5513 0 +5514 1 +5515 0 +5516 0 +5517 0 +5518 0 +5519 0 +5520 0 +5521 0 +5522 0 +5523 1 +5524 0 +5525 0 +5526 0 +5527 0 +5528 0 +5529 0 +5530 0 +5531 1 +5532 0 +5533 0 +5534 0 +5535 0 +5536 0 +5537 0 +5538 0 +5539 0 +5540 1 +5541 0 +5542 0 +5543 0 +5544 0 +5545 0 +5546 0 +5547 0 +5548 0 +5549 1 +5550 0 +5551 0 +5552 0 +5553 0 +5554 0 +5555 0 +5556 0 +5557 0 +5558 0 +5559 0 +5560 0 +5561 0 +5562 0 +5563 0 +5564 0 +5565 1 +5566 0 +5567 0 +5568 0 +5569 0 +5570 0 +5571 1 +5572 0 +5573 0 +5574 0 +5575 0 +5576 0 +5577 0 +5578 0 +5579 1 +5580 0 +5581 0 +5582 0 +5583 0 +5584 0 +5585 0 +5586 0 +5587 0 +5588 1 +5589 0 +5590 0 +5591 0 +5592 0 +5593 0 +5594 0 +5595 0 +5596 1 +5597 0 +5598 0 +5599 0 +5600 0 +5601 0 +5602 0 +5603 0 +5604 0 +5605 0 +5606 1 +5607 0 +5608 0 +5609 0 +5610 0 +5611 0 +5612 0 +5613 0 +5614 1 +5615 0 +5616 0 +5617 0 +5618 0 +5619 0 +5620 0 +5621 0 +5622 1 +5623 0 +5624 0 +5625 0 +5626 0 +5627 0 +5628 0 +5629 0 +5630 0 +5631 0 +5632 0 +5633 0 +5634 0 +5635 0 +5636 0 +5637 0 +5638 1 +5639 0 +5640 0 +5641 0 +5642 0 +5643 0 +5644 0 +5645 0 +5646 0 +5647 1 +5648 0 +5649 0 +5650 0 +5651 0 +5652 0 +5653 0 +5654 1 +5655 0 +5656 0 +5657 0 +5658 0 +5659 0 +5660 0 +5661 0 +5662 1 +5663 0 +5664 0 +5665 0 +5666 0 +5667 0 +5668 0 +5669 0 +5670 1 +5671 0 +5672 0 +5673 0 +5674 0 +5675 0 +5676 0 +5677 0 +5678 0 +5679 1 +5680 2 +5681 1 +5682 0 +5683 0 +5684 0 +5685 0 +5686 0 +5687 1 +5688 0 +5689 0 +5690 0 +5691 0 +5692 1 +5693 0 +5694 0 +5695 0 +5696 0 +5697 1 +5698 0 +5699 0 +5700 0 +5701 0 +5702 0 +5703 0 +5704 0 +5705 1 +5706 0 +5707 0 +5708 0 +5709 0 +5710 0 +5711 1 +5712 0 +5713 0 +5714 0 +5715 0 +5716 0 +5717 0 +5718 0 +5719 0 +5720 0 +5721 0 +5722 0 +5723 0 +5724 0 +5725 0 +5726 1 +5727 0 +5728 0 +5729 0 +5730 0 +5731 0 +5732 0 +5733 0 +5734 1 +5735 0 +5736 0 +5737 0 +5738 0 +5739 0 +5740 0 +5741 0 +5742 1 +5743 0 +5744 0 +5745 0 +5746 0 +5747 0 +5748 0 +5749 0 +5750 0 +5751 1 +5752 0 +5753 0 +5754 0 +5755 0 +5756 0 +5757 0 +5758 0 +5759 1 +5760 0 +5761 0 +5762 0 +5763 0 +5764 0 +5765 0 +5766 1 +5767 0 +5768 0 +5769 0 +5770 0 +5771 0 +5772 0 +5773 0 +5774 1 +5775 0 +5776 0 +5777 0 +5778 0 +5779 0 +5780 0 +5781 0 +5782 1 +5783 0 +5784 0 +5785 0 +5786 0 +5787 0 +5788 0 +5789 0 +5790 0 +5791 1 +5792 0 +5793 0 +5794 0 +5795 0 +5796 0 +5797 0 +5798 0 +5799 0 +5800 1 +5801 0 +5802 0 +5803 0 +5804 0 +5805 0 +5806 0 +5807 0 +5808 0 +5809 1 +5810 0 +5811 0 +5812 0 +5813 0 +5814 0 +5815 0 +5816 1 +5817 0 +5818 0 +5819 0 +5820 0 +5821 0 +5822 0 +5823 0 +5824 0 +5825 1 +5826 0 +5827 0 +5828 0 +5829 0 +5830 0 +5831 0 +5832 0 +5833 0 +5834 1 +5835 0 +5836 0 +5837 0 +5838 0 +5839 0 +5840 0 +5841 0 +5842 1 +5843 0 +5844 0 +5845 0 +5846 0 +5847 0 +5848 0 +5849 0 +5850 1 +5851 0 +5852 0 +5853 0 +5854 0 +5855 0 +5856 0 +5857 0 +5858 1 +5859 0 +5860 0 +5861 0 +5862 0 +5863 0 +5864 0 +5865 0 +5866 0 +5867 1 +5868 0 +5869 0 +5870 0 +5871 0 +5872 0 +5873 0 +5874 0 +5875 1 +5876 0 +5877 0 +5878 0 +5879 0 +5880 0 +5881 0 +5882 0 +5883 0 +5884 1 +5885 0 +5886 0 +5887 0 +5888 0 +5889 0 +5890 0 +5891 1 +5892 0 +5893 0 +5894 0 +5895 0 +5896 0 +5897 0 +5898 0 +5899 0 +5900 1 +5901 0 +5902 0 +5903 0 +5904 0 +5905 0 +5906 0 +5907 0 +5908 0 +5909 1 +5910 0 +5911 0 +5912 0 +5913 0 +5914 0 +5915 0 +5916 0 +5917 1 +5918 0 +5919 0 +5920 0 +5921 0 +5922 0 +5923 0 +5924 0 +5925 0 +5926 1 +5927 0 +5928 0 +5929 0 +5930 0 +5931 0 +5932 0 +5933 0 +5934 1 +5935 0 +5936 0 +5937 0 +5938 0 +5939 0 +5940 0 +5941 0 +5942 0 +5943 0 +5944 1 +5945 0 +5946 0 +5947 0 +5948 0 +5949 0 +5950 0 +5951 0 +5952 0 +5953 0 +5954 0 +5955 0 +5956 0 +5957 0 +5958 0 +5959 0 +5960 0 +5961 0 +5962 0 +5963 0 +5964 0 +5965 0 +5966 0 +5967 0 +5968 0 +5969 0 +5970 1 +5971 0 +5972 0 +5973 0 +5974 0 +5975 0 +5976 0 +5977 0 +5978 1 +5979 0 +5980 0 +5981 0 +5982 0 +5983 0 +5984 0 +5985 0 +5986 0 +5987 1 +5988 0 +5989 0 +5990 0 +5991 0 +5992 0 +5993 0 +5994 0 +5995 0 +5996 1 +5997 0 +5998 0 +5999 0 +6000 0 +6001 0 +6002 0 +6003 0 +6004 0 +6005 0 +6006 1 +6007 0 +6008 0 +6009 0 +6010 0 +6011 0 +6012 0 +6013 0 +6014 1 +6015 0 +6016 0 +6017 0 +6018 0 +6019 0 +6020 0 +6021 0 +6022 0 +6023 1 +6024 0 +6025 0 +6026 0 +6027 0 +6028 0 +6029 0 +6030 0 +6031 1 +6032 0 +6033 0 +6034 0 +6035 0 +6036 0 +6037 0 +6038 1 +6039 0 +6040 0 +6041 0 +6042 0 +6043 0 +6044 0 +6045 0 +6046 0 +6047 0 +6048 1 +6049 0 +6050 0 +6051 0 +6052 0 +6053 0 +6054 0 +6055 1 +6056 0 +6057 0 +6058 0 +6059 0 +6060 0 +6061 1 +6062 0 +6063 0 +6064 0 +6065 0 +6066 0 +6067 0 +6068 1 +6069 0 +6070 0 +6071 0 +6072 0 +6073 0 +6074 0 +6075 0 +6076 1 +6077 0 +6078 0 +6079 0 +6080 0 +6081 0 +6082 0 +6083 0 +6084 0 +6085 1 +6086 0 +6087 0 +6088 0 +6089 0 +6090 0 +6091 0 +6092 0 +6093 0 +6094 0 +6095 1 +6096 0 +6097 0 +6098 0 +6099 0 +6100 0 +6101 0 +6102 0 +6103 0 +6104 1 +6105 0 +6106 0 +6107 0 +6108 0 +6109 0 +6110 0 +6111 0 +6112 1 +6113 0 +6114 0 +6115 0 +6116 0 +6117 0 +6118 0 +6119 0 +6120 0 +6121 0 +6122 0 +6123 0 +6124 0 +6125 1 +6126 0 +6127 0 +6128 0 +6129 0 +6130 0 +6131 0 +6132 0 +6133 0 +6134 0 +6135 0 +6136 0 +6137 0 +6138 0 +6139 0 +6140 0 +6141 0 +6142 1 +6143 0 +6144 0 +6145 0 +6146 0 +6147 0 +6148 0 +6149 0 +6150 1 +6151 0 +6152 0 +6153 0 +6154 0 +6155 0 +6156 0 +6157 0 +6158 0 +6159 1 +6160 0 +6161 0 +6162 0 +6163 0 +6164 0 +6165 0 +6166 0 +6167 1 +6168 0 +6169 0 +6170 0 +6171 0 +6172 0 +6173 0 +6174 0 +6175 1 +6176 0 +6177 0 +6178 0 +6179 0 +6180 0 +6181 0 +6182 0 +6183 1 +6184 0 +6185 0 +6186 0 +6187 0 +6188 0 +6189 0 +6190 0 +6191 0 +6192 1 +6193 0 +6194 0 +6195 0 +6196 0 +6197 0 +6198 0 +6199 0 +6200 0 +6201 1 +6202 0 +6203 0 +6204 0 +6205 0 +6206 0 +6207 0 +6208 0 +6209 0 +6210 1 +6211 0 +6212 0 +6213 0 +6214 0 +6215 0 +6216 0 +6217 1 +6218 0 +6219 0 +6220 0 +6221 0 +6222 0 +6223 0 +6224 0 +6225 1 +6226 0 +6227 0 +6228 0 +6229 0 +6230 0 +6231 0 +6232 0 +6233 0 +6234 1 +6235 0 +6236 0 +6237 0 +6238 0 +6239 0 +6240 0 +6241 1 +6242 0 +6243 0 +6244 0 +6245 0 +6246 0 +6247 0 +6248 0 +6249 0 +6250 1 +6251 0 +6252 0 +6253 0 +6254 0 +6255 0 +6256 0 +6257 0 +6258 1 +6259 0 +6260 0 +6261 0 +6262 0 +6263 0 +6264 0 +6265 0 +6266 0 +6267 0 +6268 1 +6269 0 +6270 0 +6271 0 +6272 0 +6273 0 +6274 0 +6275 0 +6276 0 +6277 1 +6278 0 +6279 0 +6280 0 +6281 0 +6282 0 +6283 0 +6284 0 +6285 1 +6286 0 +6287 0 +6288 0 +6289 0 +6290 0 +6291 0 +6292 1 +6293 0 +6294 0 +6295 0 +6296 0 +6297 0 +6298 0 +6299 1 +6300 0 +6301 0 +6302 0 +6303 0 +6304 0 +6305 0 +6306 0 +6307 1 +6308 0 +6309 0 +6310 0 +6311 0 +6312 0 +6313 0 +6314 0 +6315 1 +6316 0 +6317 0 +6318 0 +6319 0 +6320 0 +6321 0 +6322 0 +6323 0 +6324 1 +6325 0 +6326 0 +6327 0 +6328 0 +6329 0 +6330 0 +6331 0 +6332 1 +6333 0 +6334 0 +6335 0 +6336 0 +6337 0 +6338 0 +6339 0 +6340 0 +6341 1 +6342 0 +6343 0 +6344 0 +6345 0 +6346 0 +6347 0 +6348 0 +6349 0 +6350 1 +6351 0 +6352 0 +6353 0 +6354 0 +6355 0 +6356 0 +6357 0 +6358 1 +6359 0 +6360 0 +6361 0 +6362 0 +6363 0 +6364 0 +6365 0 +6366 1 +6367 0 +6368 0 +6369 0 +6370 0 +6371 0 +6372 0 +6373 0 +6374 0 +6375 1 +6376 0 +6377 0 +6378 0 +6379 0 +6380 0 +6381 0 +6382 0 +6383 1 +6384 0 +6385 0 +6386 0 +6387 0 +6388 0 +6389 0 +6390 0 +6391 4 +6392 0 +6393 1 +6394 0 +6395 0 +6396 0 +6397 1 +6398 0 +6399 0 +6400 0 +6401 0 +6402 1 +6403 0 +6404 0 +6405 0 +6406 0 +6407 1 +6408 0 +6409 0 +6410 0 +6411 0 +6412 1 +6413 0 +6414 0 +6415 0 +6416 0 +6417 0 +6418 1 +6419 0 +6420 0 +6421 0 +6422 0 +6423 0 +6424 0 +6425 1 +6426 0 +6427 0 +6428 0 +6429 0 +6430 0 +6431 0 +6432 0 +6433 0 +6434 1 +6435 0 +6436 0 +6437 0 +6438 0 +6439 0 +6440 0 +6441 0 +6442 0 +6443 1 +6444 0 +6445 0 +6446 0 +6447 0 +6448 0 +6449 0 +6450 0 +6451 0 +6452 1 +6453 0 +6454 0 +6455 0 +6456 0 +6457 0 +6458 0 +6459 0 +6460 0 +6461 0 +6462 0 +6463 1 +6464 0 +6465 0 +6466 0 +6467 0 +6468 0 +6469 0 +6470 0 +6471 0 +6472 1 +6473 0 +6474 0 +6475 0 +6476 0 +6477 0 +6478 0 +6479 0 +6480 0 +6481 0 +6482 1 +6483 0 +6484 0 +6485 0 +6486 0 +6487 0 +6488 0 +6489 0 +6490 0 +6491 0 +6492 1 +6493 0 +6494 0 +6495 0 +6496 0 +6497 0 +6498 0 +6499 0 +6500 0 +6501 0 +6502 0 +6503 0 +6504 0 +6505 0 +6506 0 +6507 0 +6508 0 +6509 0 +6510 0 +6511 0 +6512 1 +6513 0 +6514 0 +6515 0 +6516 0 +6517 0 +6518 0 +6519 0 +6520 0 +6521 1 +6522 0 +6523 0 +6524 0 +6525 0 +6526 0 +6527 0 +6528 0 +6529 0 +6530 0 +6531 1 +6532 0 +6533 0 +6534 0 +6535 0 +6536 0 +6537 0 +6538 0 +6539 0 +6540 1 +6541 0 +6542 0 +6543 0 +6544 0 +6545 0 +6546 0 +6547 0 +6548 0 +6549 0 +6550 1 +6551 0 +6552 0 +6553 0 +6554 0 +6555 0 +6556 0 +6557 0 +6558 0 +6559 0 +6560 1 +6561 0 +6562 0 +6563 0 +6564 0 +6565 0 +6566 0 +6567 0 +6568 0 +6569 1 +6570 0 +6571 0 +6572 0 +6573 0 +6574 0 +6575 0 +6576 0 +6577 1 +6578 0 +6579 0 +6580 0 +6581 0 +6582 0 +6583 0 +6584 0 +6585 0 +6586 1 +6587 0 +6588 0 +6589 0 +6590 0 +6591 0 +6592 0 +6593 0 +6594 0 +6595 1 +6596 0 +6597 0 +6598 0 +6599 0 +6600 0 +6601 0 +6602 0 +6603 0 +6604 1 +6605 0 +6606 0 +6607 0 +6608 0 +6609 0 +6610 0 +6611 0 +6612 0 +6613 1 +6614 0 +6615 0 +6616 0 +6617 0 +6618 0 +6619 0 +6620 0 +6621 0 +6622 1 +6623 0 +6624 0 +6625 0 +6626 0 +6627 0 +6628 0 +6629 0 +6630 0 +6631 1 +6632 0 +6633 0 +6634 0 +6635 0 +6636 0 +6637 0 +6638 0 +6639 0 +6640 1 +6641 0 +6642 0 +6643 0 +6644 0 +6645 0 +6646 0 +6647 0 +6648 0 +6649 0 +6650 1 +6651 0 +6652 0 +6653 0 +6654 0 +6655 0 +6656 0 +6657 0 +6658 0 +6659 0 +6660 1 +6661 0 +6662 0 +6663 0 +6664 0 +6665 0 +6666 0 +6667 0 +6668 0 +6669 1 +6670 0 +6671 0 +6672 0 +6673 0 +6674 0 +6675 0 +6676 0 +6677 0 +6678 0 +6679 1 +6680 0 +6681 0 +6682 0 +6683 0 +6684 0 +6685 0 +6686 0 +6687 0 +6688 1 +6689 0 +6690 0 +6691 0 +6692 0 +6693 0 +6694 0 +6695 0 +6696 0 +6697 0 +6698 1 +6699 0 +6700 0 +6701 0 +6702 0 +6703 0 +6704 0 +6705 0 +6706 1 +6707 0 +6708 0 +6709 0 +6710 0 +6711 0 +6712 0 +6713 0 +6714 0 +6715 0 +6716 1 +6717 0 +6718 0 +6719 0 +6720 0 +6721 0 +6722 0 +6723 0 +6724 0 +6725 0 +6726 1 +6727 0 +6728 0 +6729 0 +6730 0 +6731 0 +6732 0 +6733 0 +6734 0 +6735 0 +6736 0 +6737 1 +6738 0 +6739 0 +6740 0 +6741 0 +6742 0 +6743 0 +6744 0 +6745 0 +6746 1 +6747 0 +6748 0 +6749 0 +6750 0 +6751 0 +6752 0 +6753 0 +6754 0 +6755 0 +6756 1 +6757 0 +6758 0 +6759 0 +6760 0 +6761 0 +6762 0 +6763 0 +6764 0 +6765 0 +6766 1 +6767 0 +6768 0 +6769 0 +6770 0 +6771 0 +6772 0 +6773 0 +6774 0 +6775 1 +6776 0 +6777 0 +6778 0 +6779 0 +6780 0 +6781 0 +6782 0 +6783 0 +6784 1 +6785 0 +6786 0 +6787 0 +6788 0 +6789 0 +6790 0 +6791 0 +6792 0 +6793 0 +6794 1 +6795 0 +6796 0 +6797 0 +6798 0 +6799 0 +6800 0 +6801 0 +6802 0 +6803 1 +6804 0 +6805 0 +6806 0 +6807 0 +6808 0 +6809 0 +6810 0 +6811 0 +6812 0 +6813 1 +6814 0 +6815 0 +6816 0 +6817 0 +6818 0 +6819 0 +6820 0 +6821 0 +6822 0 +6823 0 +6824 1 +6825 0 +6826 0 +6827 0 +6828 0 +6829 0 +6830 0 +6831 0 +6832 1 +6833 0 +6834 0 +6835 0 +6836 0 +6837 0 +6838 0 +6839 0 +6840 0 +6841 0 +6842 1 +6843 0 +6844 0 +6845 0 +6846 0 +6847 0 +6848 0 +6849 0 +6850 0 +6851 1 +6852 0 +6853 0 +6854 0 +6855 0 +6856 0 +6857 0 +6858 0 +6859 0 +6860 0 +6861 0 +6862 1 +6863 0 +6864 0 +6865 0 +6866 0 +6867 0 +6868 0 +6869 0 +6870 0 +6871 1 +6872 0 +6873 0 +6874 0 +6875 0 +6876 0 +6877 0 +6878 0 +6879 1 +6880 0 +6881 0 +6882 0 +6883 0 +6884 0 +6885 0 +6886 1 +6887 0 +6888 0 +6889 0 +6890 0 +6891 0 +6892 0 +6893 0 +6894 0 +6895 1 +6896 0 +6897 0 +6898 0 +6899 0 +6900 0 +6901 0 +6902 0 +6903 0 +6904 0 +6905 0 +6906 0 +6907 0 +6908 0 +6909 0 +6910 0 +6911 0 +6912 0 +6913 0 +6914 1 +6915 0 +6916 0 +6917 0 +6918 0 +6919 0 +6920 0 +6921 0 +6922 0 +6923 1 +6924 0 +6925 0 +6926 0 +6927 0 +6928 0 +6929 0 +6930 0 +6931 0 +6932 0 +6933 0 +6934 1 +6935 0 +6936 0 +6937 0 +6938 0 +6939 0 +6940 0 +6941 0 +6942 0 +6943 0 +6944 1 +6945 0 +6946 0 +6947 0 +6948 0 +6949 0 +6950 0 +6951 0 +6952 0 +6953 0 +6954 1 +6955 0 +6956 0 +6957 0 +6958 0 +6959 0 +6960 0 +6961 0 +6962 0 +6963 0 +6964 1 +6965 0 +6966 0 +6967 0 +6968 0 +6969 0 +6970 0 +6971 0 +6972 0 +6973 0 +6974 1 +6975 0 +6976 0 +6977 0 +6978 0 +6979 0 +6980 0 +6981 0 +6982 0 +6983 1 +6984 0 +6985 0 +6986 0 +6987 0 +6988 0 +6989 0 +6990 0 +6991 0 +6992 1 +6993 0 +6994 0 +6995 0 +6996 0 +6997 0 +6998 0 +6999 0 +7000 0 +7001 1 +7002 0 +7003 0 +7004 0 +7005 0 +7006 0 +7007 0 +7008 0 +7009 0 +7010 1 +7011 0 +7012 0 +7013 0 +7014 0 +7015 0 +7016 0 +7017 0 +7018 0 +7019 0 +7020 1 +7021 0 +7022 0 +7023 0 +7024 0 +7025 0 +7026 0 +7027 0 +7028 0 +7029 0 +7030 1 +7031 0 +7032 0 +7033 0 +7034 0 +7035 0 +7036 0 +7037 0 +7038 0 +7039 1 +7040 0 +7041 0 +7042 0 +7043 0 +7044 0 +7045 0 +7046 0 +7047 0 +7048 1 +7049 0 +7050 0 +7051 0 +7052 0 +7053 0 +7054 0 +7055 0 +7056 0 +7057 0 +7058 0 +7059 1 +7060 0 +7061 0 +7062 0 +7063 0 +7064 0 +7065 0 +7066 0 +7067 0 +7068 0 +7069 1 +7070 0 +7071 0 +7072 0 +7073 0 +7074 0 +7075 0 +7076 0 +7077 0 +7078 0 +7079 1 +7080 0 +7081 0 +7082 0 +7083 0 +7084 0 +7085 0 +7086 0 +7087 1 +7088 0 +7089 0 +7090 0 +7091 0 +7092 0 +7093 0 +7094 0 +7095 0 +7096 0 +7097 1 +7098 0 +7099 0 +7100 0 +7101 0 +7102 0 +7103 0 +7104 0 +7105 1 +7106 0 +7107 0 +7108 0 +7109 0 +7110 0 +7111 0 +7112 0 +7113 0 +7114 1 +7115 0 +7116 0 +7117 0 +7118 0 +7119 0 +7120 0 +7121 0 +7122 0 +7123 0 +7124 1 +7125 0 +7126 0 +7127 0 +7128 0 +7129 0 +7130 0 +7131 0 +7132 0 +7133 0 +7134 1 +7135 0 +7136 0 +7137 0 +7138 0 +7139 0 +7140 0 +7141 0 +7142 0 +7143 1 +7144 0 +7145 0 +7146 0 +7147 0 +7148 0 +7149 0 +7150 0 +7151 0 +7152 1 +7153 0 +7154 0 +7155 0 +7156 0 +7157 0 +7158 0 +7159 0 +7160 0 +7161 0 +7162 1 +7163 0 +7164 0 +7165 0 +7166 0 +7167 0 +7168 0 +7169 0 +7170 0 +7171 0 +7172 1 +7173 0 +7174 0 +7175 0 +7176 0 +7177 0 +7178 0 +7179 0 +7180 0 +7181 0 +7182 1 +7183 0 +7184 0 +7185 0 +7186 0 +7187 0 +7188 0 +7189 0 +7190 0 +7191 0 +7192 0 +7193 1 +7194 0 +7195 0 +7196 0 +7197 0 +7198 0 +7199 0 +7200 0 +7201 0 +7202 0 +7203 1 +7204 0 +7205 0 +7206 0 +7207 0 +7208 0 +7209 0 +7210 0 +7211 0 +7212 0 +7213 0 +7214 0 +7215 0 +7216 0 +7217 0 +7218 0 +7219 0 +7220 0 +7221 0 +7222 1 +7223 0 +7224 0 +7225 0 +7226 0 +7227 0 +7228 0 +7229 0 +7230 0 +7231 0 +7232 1 +7233 0 +7234 0 +7235 0 +7236 0 +7237 0 +7238 0 +7239 0 +7240 0 +7241 0 +7242 0 +7243 1 +7244 0 +7245 0 +7246 0 +7247 0 +7248 0 +7249 0 +7250 0 +7251 0 +7252 0 +7253 1 +7254 0 +7255 0 +7256 0 +7257 0 +7258 0 +7259 0 +7260 0 +7261 0 +7262 0 +7263 0 +7264 1 +7265 0 +7266 0 +7267 0 +7268 0 +7269 0 +7270 0 +7271 0 +7272 0 +7273 0 +7274 1 +7275 0 +7276 0 +7277 0 +7278 0 +7279 0 +7280 0 +7281 0 +7282 0 +7283 0 +7284 0 +7285 1 +7286 0 +7287 0 +7288 0 +7289 0 +7290 0 +7291 0 +7292 0 +7293 0 +7294 0 +7295 0 +7296 0 +7297 0 +7298 0 +7299 0 +7300 0 +7301 0 +7302 0 +7303 0 +7304 1 +7305 0 +7306 0 +7307 0 +7308 0 +7309 0 +7310 0 +7311 0 +7312 0 +7313 0 +7314 0 +7315 1 +7316 0 +7317 0 +7318 0 +7319 0 +7320 0 +7321 0 +7322 0 +7323 0 +7324 1 +7325 0 +7326 0 +7327 0 +7328 0 +7329 0 +7330 0 +7331 0 +7332 0 +7333 1 +7334 0 +7335 0 +7336 0 +7337 0 +7338 0 +7339 0 +7340 0 +7341 0 +7342 1 +7343 0 +7344 0 +7345 0 +7346 0 +7347 0 +7348 0 +7349 0 +7350 0 +7351 0 +7352 1 +7353 0 +7354 0 +7355 0 +7356 0 +7357 0 +7358 0 +7359 0 +7360 0 +7361 0 +7362 0 +7363 1 +7364 0 +7365 0 +7366 0 +7367 0 +7368 0 +7369 0 +7370 0 +7371 0 +7372 1 +7373 0 +7374 0 +7375 0 +7376 0 +7377 0 +7378 0 +7379 0 +7380 0 +7381 0 +7382 1 +7383 0 +7384 0 +7385 0 +7386 0 +7387 0 +7388 0 +7389 0 +7390 0 +7391 1 +7392 0 +7393 0 +7394 0 +7395 0 +7396 0 +7397 0 +7398 0 +7399 0 +7400 0 +7401 1 +7402 0 +7403 0 +7404 0 +7405 0 +7406 0 +7407 0 +7408 0 +7409 0 +7410 0 +7411 0 +7412 1 +7413 0 +7414 0 +7415 0 +7416 0 +7417 0 +7418 0 +7419 0 +7420 0 +7421 0 +7422 1 +7423 0 +7424 0 +7425 0 +7426 0 +7427 0 +7428 0 +7429 0 +7430 0 +7431 0 +7432 1 +7433 0 +7434 0 +7435 0 +7436 0 +7437 0 +7438 0 +7439 0 +7440 0 +7441 1 +7442 0 +7443 0 +7444 0 +7445 0 +7446 0 +7447 0 +7448 0 +7449 1 +7450 0 +7451 0 +7452 0 +7453 0 +7454 0 +7455 0 +7456 0 +7457 0 +7458 0 +7459 0 +7460 1 +7461 0 +7462 0 +7463 0 +7464 0 +7465 0 +7466 0 +7467 0 +7468 0 +7469 1 +7470 0 +7471 0 +7472 0 +7473 0 +7474 0 +7475 0 +7476 0 +7477 0 +7478 1 +7479 0 +7480 0 +7481 0 +7482 0 +7483 0 +7484 0 +7485 0 +7486 0 +7487 1 +7488 0 +7489 0 +7490 0 +7491 0 +7492 0 +7493 0 +7494 0 +7495 0 +7496 0 +7497 1 +7498 0 +7499 0 +7500 0 +7501 0 +7502 0 +7503 0 +7504 0 +7505 0 +7506 0 +7507 0 +7508 1 +7509 0 +7510 0 +7511 0 +7512 0 +7513 0 +7514 0 +7515 0 +7516 0 +7517 0 +7518 1 +7519 0 +7520 0 +7521 0 +7522 0 +7523 0 +7524 0 +7525 0 +7526 0 +7527 0 +7528 0 +7529 0 +7530 0 +7531 0 +7532 0 +7533 0 +7534 0 +7535 0 +7536 0 +7537 0 +7538 0 +7539 1 +7540 0 +7541 0 +7542 0 +7543 0 +7544 0 +7545 0 +7546 0 +7547 0 +7548 0 +7549 2 +7550 0 +7551 0 +7552 0 +7553 0 +7554 0 +7555 0 +7556 0 +7557 1 +7558 0 +7559 0 +7560 0 +7561 0 +7562 0 +7563 0 +7564 0 +7565 0 +7566 0 +7567 0 +7568 1 +7569 0 +7570 0 +7571 0 +7572 0 +7573 0 +7574 0 +7575 0 +7576 0 +7577 0 +7578 0 +7579 0 +7580 0 +7581 0 +7582 0 +7583 0 +7584 0 +7585 0 +7586 0 +7587 0 +7588 1 +7589 0 +7590 0 +7591 0 +7592 0 +7593 0 +7594 0 +7595 0 +7596 0 +7597 0 +7598 0 +7599 1 +7600 0 +7601 0 +7602 0 +7603 0 +7604 0 +7605 0 +7606 0 +7607 0 +7608 0 +7609 0 +7610 1 +7611 0 +7612 0 +7613 0 +7614 0 +7615 0 +7616 0 +7617 0 +7618 0 +7619 0 +7620 0 +7621 1 +7622 0 +7623 0 +7624 0 +7625 0 +7626 0 +7627 1 +7628 0 +7629 0 +7630 0 +7631 0 +7632 0 +7633 0 +7634 1 +7635 0 +7636 0 +7637 0 +7638 0 +7639 0 +7640 0 +7641 1 +7642 0 +7643 0 +7644 0 +7645 0 +7646 0 +7647 0 +7648 0 +7649 1 +7650 0 +7651 0 +7652 0 +7653 0 +7654 0 +7655 0 +7656 0 +7657 0 +7658 0 +7659 0 +7660 1 +7661 0 +7662 0 +7663 0 +7664 0 +7665 0 +7666 0 +7667 0 +7668 0 +7669 0 +7670 1 +7671 0 +7672 0 +7673 0 +7674 0 +7675 0 +7676 0 +7677 0 +7678 0 +7679 0 +7680 0 +7681 1 +7682 0 +7683 0 +7684 0 +7685 0 +7686 0 +7687 0 +7688 0 +7689 0 +7690 0 +7691 1 +7692 0 +7693 0 +7694 0 +7695 0 +7696 0 +7697 0 +7698 0 +7699 0 +7700 0 +7701 0 +7702 1 +7703 0 +7704 0 +7705 0 +7706 0 +7707 0 +7708 0 +7709 0 +7710 0 +7711 0 +7712 1 +7713 0 +7714 0 +7715 0 +7716 0 +7717 0 +7718 0 +7719 0 +7720 0 +7721 0 +7722 1 +7723 0 +7724 0 +7725 0 +7726 0 +7727 0 +7728 0 +7729 0 +7730 0 +7731 0 +7732 1 +7733 0 +7734 0 +7735 0 +7736 0 +7737 0 +7738 0 +7739 0 +7740 0 +7741 0 +7742 1 +7743 0 +7744 0 +7745 0 +7746 0 +7747 0 +7748 0 +7749 0 +7750 0 +7751 0 +7752 1 +7753 0 +7754 0 +7755 0 +7756 0 +7757 0 +7758 0 +7759 0 +7760 0 +7761 1 +7762 0 +7763 0 +7764 0 +7765 0 +7766 0 +7767 0 +7768 0 +7769 0 +7770 1 +7771 0 +7772 0 +7773 0 +7774 0 +7775 0 +7776 0 +7777 0 +7778 0 +7779 1 +7780 0 +7781 0 +7782 0 +7783 0 +7784 0 +7785 0 +7786 0 +7787 0 +7788 0 +7789 1 +7790 0 +7791 0 +7792 0 +7793 0 +7794 0 +7795 0 +7796 0 +7797 0 +7798 0 +7799 1 +7800 0 +7801 0 +7802 0 +7803 0 +7804 0 +7805 0 +7806 0 +7807 0 +7808 0 +7809 0 +7810 1 +7811 0 +7812 0 +7813 0 +7814 0 +7815 0 +7816 0 +7817 0 +7818 0 +7819 1 +7820 0 +7821 0 +7822 0 +7823 0 +7824 0 +7825 0 +7826 0 +7827 0 +7828 1 +7829 0 +7830 0 +7831 0 +7832 0 +7833 0 +7834 0 +7835 0 +7836 0 +7837 0 +7838 0 +7839 1 +7840 0 +7841 0 +7842 0 +7843 0 +7844 0 +7845 0 +7846 0 +7847 0 +7848 0 +7849 1 +7850 0 +7851 0 +7852 0 +7853 0 +7854 0 +7855 0 +7856 0 +7857 0 +7858 1 +7859 0 +7860 0 +7861 0 +7862 0 +7863 0 +7864 0 +7865 0 +7866 0 +7867 0 +7868 1 +7869 0 +7870 0 +7871 0 +7872 0 +7873 0 +7874 0 +7875 0 +7876 0 +7877 0 +7878 0 +7879 0 +7880 0 +7881 0 +7882 0 +7883 0 +7884 0 +7885 0 +7886 0 +7887 1 +7888 0 +7889 0 +7890 0 +7891 0 +7892 0 +7893 0 +7894 0 +7895 0 +7896 0 +7897 0 +7898 1 +7899 0 +7900 0 +7901 0 +7902 0 +7903 0 +7904 0 +7905 0 +7906 0 +7907 0 +7908 1 +7909 0 +7910 0 +7911 0 +7912 0 +7913 0 +7914 0 +7915 0 +7916 0 +7917 0 +7918 1 +7919 0 +7920 0 +7921 0 +7922 0 +7923 0 +7924 0 +7925 0 +7926 0 +7927 0 +7928 1 +7929 0 +7930 0 +7931 0 +7932 0 +7933 0 +7934 0 +7935 0 +7936 0 +7937 0 +7938 1 +7939 0 +7940 0 +7941 0 +7942 0 +7943 0 +7944 0 +7945 0 +7946 0 +7947 0 +7948 1 +7949 0 +7950 0 +7951 0 +7952 0 +7953 0 +7954 0 +7955 0 +7956 0 +7957 0 +7958 1 +7959 0 +7960 0 +7961 0 +7962 0 +7963 0 +7964 0 +7965 0 +7966 0 +7967 0 +7968 1 +7969 0 +7970 0 +7971 0 +7972 0 +7973 0 +7974 0 +7975 0 +7976 0 +7977 0 +7978 1 +7979 0 +7980 0 +7981 0 +7982 0 +7983 0 +7984 0 +7985 1 +7986 0 +7987 0 +7988 0 +7989 0 +7990 0 +7991 0 +7992 0 +7993 0 +7994 0 +7995 1 +7996 0 +7997 0 +7998 0 +7999 0 +8000 0 +8001 0 +8002 0 +8003 0 +8004 0 +8005 0 +8006 1 +8007 0 +8008 0 +8009 0 +8010 0 +8011 0 +8012 0 +8013 0 +8014 0 +8015 1 +8016 0 +8017 0 +8018 0 +8019 0 +8020 0 +8021 0 +8022 0 +8023 0 +8024 0 +8025 1 +8026 0 +8027 0 +8028 0 +8029 0 +8030 0 +8031 0 +8032 0 +8033 0 +8034 0 +8035 0 +8036 1 +8037 0 +8038 0 +8039 0 +8040 0 +8041 0 +8042 0 +8043 0 +8044 0 +8045 0 +8046 1 +8047 0 +8048 0 +8049 0 +8050 0 +8051 0 +8052 0 +8053 0 +8054 0 +8055 0 +8056 0 +8057 1 +8058 0 +8059 0 +8060 0 +8061 0 +8062 0 +8063 0 +8064 0 +8065 0 +8066 0 +8067 1 +8068 0 +8069 0 +8070 0 +8071 0 +8072 0 +8073 0 +8074 0 +8075 0 +8076 0 +8077 0 +8078 1 +8079 0 +8080 0 +8081 0 +8082 0 +8083 0 +8084 0 +8085 0 +8086 0 +8087 0 +8088 1 +8089 0 +8090 0 +8091 0 +8092 0 +8093 0 +8094 0 +8095 0 +8096 0 +8097 0 +8098 1 +8099 0 +8100 0 +8101 0 +8102 0 +8103 0 +8104 0 +8105 1 +8106 0 +8107 0 +8108 0 +8109 0 +8110 0 +8111 0 +8112 0 +8113 0 +8114 0 +8115 1 +8116 0 +8117 0 +8118 0 +8119 0 +8120 0 +8121 0 +8122 0 +8123 0 +8124 0 +8125 1 +8126 0 +8127 0 +8128 0 +8129 0 +8130 0 +8131 0 +8132 0 +8133 0 +8134 1 +8135 0 +8136 0 +8137 0 +8138 0 +8139 0 +8140 0 +8141 0 +8142 0 +8143 0 +8144 0 +8145 1 +8146 0 +8147 0 +8148 0 +8149 0 +8150 0 +8151 0 +8152 0 +8153 0 +8154 0 +8155 0 +8156 1 +8157 0 +8158 0 +8159 0 +8160 0 +8161 0 +8162 0 +8163 0 +8164 0 +8165 0 +8166 1 +8167 0 +8168 0 +8169 0 +8170 0 +8171 0 +8172 0 +8173 0 +8174 0 +8175 0 +8176 1 +8177 0 +8178 0 +8179 0 +8180 0 +8181 0 +8182 0 +8183 0 +8184 0 +8185 0 +8186 1 +8187 0 +8188 0 +8189 0 +8190 0 +8191 0 +8192 0 +8193 0 +8194 0 +8195 0 +8196 0 +8197 1 +8198 0 +8199 0 +8200 0 +8201 0 +8202 0 +8203 0 +8204 0 +8205 0 +8206 0 +8207 1 +8208 0 +8209 0 +8210 0 +8211 0 +8212 0 +8213 0 +8214 0 +8215 0 +8216 1 +8217 0 +8218 0 +8219 0 +8220 0 +8221 0 +8222 0 +8223 0 +8224 0 +8225 1 +8226 0 +8227 0 +8228 0 +8229 0 +8230 0 +8231 0 +8232 0 +8233 0 +8234 0 +8235 1 +8236 0 +8237 0 +8238 0 +8239 0 +8240 0 +8241 0 +8242 0 +8243 0 +8244 1 +8245 0 +8246 0 +8247 0 +8248 0 +8249 0 +8250 0 +8251 0 +8252 0 +8253 0 +8254 1 +8255 0 +8256 0 +8257 0 +8258 0 +8259 0 +8260 0 +8261 0 +8262 0 +8263 0 +8264 0 +8265 1 +8266 0 +8267 0 +8268 0 +8269 0 +8270 0 +8271 0 +8272 0 +8273 0 +8274 0 +8275 1 +8276 0 +8277 0 +8278 0 +8279 0 +8280 0 +8281 0 +8282 0 +8283 0 +8284 0 +8285 0 +8286 1 +8287 0 +8288 0 +8289 0 +8290 0 +8291 0 +8292 0 +8293 0 +8294 0 +8295 0 +8296 1 +8297 0 +8298 0 +8299 0 +8300 0 +8301 0 +8302 0 +8303 0 +8304 1 +8305 0 +8306 0 +8307 0 +8308 0 +8309 0 +8310 0 +8311 0 +8312 0 +8313 0 +8314 1 +8315 0 +8316 0 +8317 0 +8318 0 +8319 0 +8320 0 +8321 0 +8322 0 +8323 0 +8324 1 +8325 0 +8326 0 +8327 0 +8328 0 +8329 0 +8330 0 +8331 0 +8332 0 +8333 0 +8334 0 +8335 0 +8336 0 +8337 0 +8338 0 +8339 0 +8340 0 +8341 0 +8342 1 +8343 0 +8344 0 +8345 0 +8346 0 +8347 0 +8348 0 +8349 0 +8350 0 +8351 1 +8352 0 +8353 0 +8354 0 +8355 0 +8356 0 +8357 0 +8358 0 +8359 0 +8360 0 +8361 1 +8362 0 +8363 0 +8364 0 +8365 0 +8366 0 +8367 0 +8368 0 +8369 0 +8370 0 +8371 1 +8372 0 +8373 0 +8374 0 +8375 0 +8376 0 +8377 0 +8378 0 +8379 0 +8380 1 +8381 0 +8382 0 +8383 0 +8384 0 +8385 0 +8386 0 +8387 0 +8388 0 +8389 1 +8390 0 +8391 0 +8392 0 +8393 0 +8394 0 +8395 0 +8396 0 +8397 0 +8398 0 +8399 1 +8400 0 +8401 0 +8402 0 +8403 0 +8404 0 +8405 0 +8406 0 +8407 0 +8408 0 +8409 1 +8410 0 +8411 0 +8412 0 +8413 0 +8414 0 +8415 0 +8416 0 +8417 0 +8418 0 +8419 1 +8420 0 +8421 0 +8422 0 +8423 0 +8424 0 +8425 0 +8426 0 +8427 0 +8428 0 +8429 0 +8430 1 +8431 0 +8432 0 +8433 0 +8434 0 +8435 0 +8436 0 +8437 0 +8438 1 +8439 0 +8440 0 +8441 0 +8442 0 +8443 0 +8444 0 +8445 0 +8446 0 +8447 1 +8448 0 +8449 0 +8450 0 +8451 0 +8452 0 +8453 0 +8454 0 +8455 0 +8456 0 +8457 1 +8458 0 +8459 0 +8460 0 +8461 0 +8462 0 +8463 0 +8464 0 +8465 0 +8466 0 +8467 1 +8468 0 +8469 0 +8470 0 +8471 0 +8472 0 +8473 0 +8474 0 +8475 0 +8476 0 +8477 1 +8478 0 +8479 0 +8480 0 +8481 0 +8482 0 +8483 0 +8484 0 +8485 0 +8486 1 +8487 0 +8488 0 +8489 0 +8490 0 +8491 0 +8492 0 +8493 0 +8494 0 +8495 0 +8496 0 +8497 0 +8498 0 +8499 0 +8500 0 +8501 0 +8502 0 +8503 0 +8504 0 +8505 0 +8506 1 +8507 0 +8508 0 +8509 0 +8510 0 +8511 0 +8512 0 +8513 0 +8514 0 +8515 0 +8516 0 +8517 0 +8518 0 +8519 0 +8520 0 +8521 0 +8522 0 +8523 1 +8524 0 +8525 0 +8526 0 +8527 0 +8528 0 +8529 0 +8530 0 +8531 0 +8532 1 +8533 0 +8534 0 +8535 0 +8536 0 +8537 0 +8538 0 +8539 0 +8540 0 +8541 1 +8542 0 +8543 0 +8544 0 +8545 0 +8546 0 +8547 0 +8548 0 +8549 1 +8550 0 +8551 0 +8552 0 +8553 0 +8554 0 +8555 0 +8556 0 +8557 0 +8558 0 +8559 1 +8560 0 +8561 0 +8562 0 +8563 0 +8564 0 +8565 0 +8566 0 +8567 0 +8568 1 +8569 0 +8570 0 +8571 0 +8572 0 +8573 0 +8574 0 +8575 0 +8576 0 +8577 1 +8578 0 +8579 0 +8580 0 +8581 0 +8582 0 +8583 0 +8584 0 +8585 0 +8586 1 +8587 0 +8588 0 +8589 0 +8590 0 +8591 0 +8592 0 +8593 0 +8594 0 +8595 0 +8596 1 +8597 0 +8598 0 +8599 0 +8600 0 +8601 0 +8602 0 +8603 0 +8604 0 +8605 0 +8606 1 +8607 0 +8608 0 +8609 0 +8610 0 +8611 0 +8612 0 +8613 0 +8614 0 +8615 0 +8616 1 +8617 0 +8618 0 +8619 0 +8620 0 +8621 0 +8622 0 +8623 0 +8624 0 +8625 1 +8626 0 +8627 0 +8628 0 +8629 0 +8630 0 +8631 0 +8632 0 +8633 1 +8634 0 +8635 0 +8636 0 +8637 0 +8638 0 +8639 0 +8640 0 +8641 0 +8642 0 +8643 1 +8644 0 +8645 0 +8646 0 +8647 0 +8648 0 +8649 0 +8650 0 +8651 1 +8652 0 +8653 0 +8654 0 +8655 0 +8656 0 +8657 0 +8658 0 +8659 0 +8660 1 +8661 0 +8662 0 +8663 0 +8664 0 +8665 0 +8666 0 +8667 0 +8668 0 +8669 1 +8670 0 +8671 0 +8672 0 +8673 0 +8674 0 +8675 0 +8676 0 +8677 1 +8678 0 +8679 0 +8680 0 +8681 0 +8682 0 +8683 0 +8684 0 +8685 0 +8686 1 +8687 0 +8688 0 +8689 0 +8690 0 +8691 0 +8692 0 +8693 0 +8694 0 +8695 0 +8696 1 +8697 0 +8698 0 +8699 0 +8700 0 +8701 0 +8702 0 +8703 0 +8704 0 +8705 1 +8706 0 +8707 0 +8708 0 +8709 0 +8710 0 +8711 0 +8712 0 +8713 0 +8714 0 +8715 1 +8716 0 +8717 0 +8718 0 +8719 0 +8720 0 +8721 0 +8722 0 +8723 0 +8724 0 +8725 1 +8726 0 +8727 0 +8728 0 +8729 0 +8730 0 +8731 0 +8732 0 +8733 0 +8734 0 +8735 1 +8736 0 +8737 0 +8738 0 +8739 0 +8740 0 +8741 0 +8742 0 +8743 0 +8744 0 +8745 1 +8746 0 +8747 0 +8748 0 +8749 0 +8750 0 +8751 0 +8752 0 +8753 0 +8754 0 +8755 1 +8756 0 +8757 0 +8758 0 +8759 0 +8760 0 +8761 0 +8762 0 +8763 1 +8764 0 +8765 0 +8766 0 +8767 0 +8768 0 +8769 0 +8770 1 +8771 0 +8772 0 +8773 0 +8774 0 +8775 0 +8776 0 +8777 0 +8778 0 +8779 0 +8780 1 +8781 0 +8782 0 +8783 0 +8784 0 +8785 0 +8786 0 +8787 0 +8788 0 +8789 1 +8790 0 +8791 0 +8792 0 +8793 0 +8794 0 +8795 0 +8796 0 +8797 0 +8798 1 +8799 0 +8800 0 +8801 0 +8802 0 +8803 0 +8804 0 +8805 0 +8806 0 +8807 3 +8808 0 +8809 0 +8810 1 +8811 0 +8812 0 +8813 0 +8814 0 +8815 1 +8816 0 +8817 0 +8818 0 +8819 0 +8820 1 +8821 0 +8822 0 +8823 0 +8824 1 +8825 0 +8826 0 +8827 0 +8828 0 +8829 0 +8830 1 +8831 0 +8832 0 +8833 0 +8834 0 +8835 0 +8836 0 +8837 1 +8838 0 +8839 0 +8840 0 +8841 0 +8842 0 +8843 0 +8844 0 +8845 1 +8846 0 +8847 0 +8848 0 +8849 0 +8850 0 +8851 0 +8852 0 +8853 0 +8854 0 +8855 1 +8856 0 +8857 0 +8858 0 +8859 0 +8860 0 +8861 0 +8862 0 +8863 0 +8864 0 +8865 1 +8866 0 +8867 0 +8868 0 +8869 0 +8870 0 +8871 0 +8872 1 +8873 0 +8874 0 +8875 0 +8876 0 +8877 0 +8878 0 +8879 0 +8880 1 +8881 0 +8882 0 +8883 0 +8884 0 +8885 0 +8886 0 +8887 0 +8888 1 +8889 0 +8890 0 +8891 0 +8892 0 +8893 0 +8894 0 +8895 0 +8896 0 +8897 0 +8898 0 +8899 0 +8900 0 +8901 0 +8902 0 +8903 0 +8904 0 +8905 1 +8906 0 +8907 0 +8908 0 +8909 0 +8910 0 +8911 0 +8912 1 +8913 0 +8914 0 +8915 0 +8916 0 +8917 0 +8918 0 +8919 0 +8920 1 +8921 0 +8922 0 +8923 0 +8924 0 +8925 0 +8926 0 +8927 0 +8928 0 +8929 1 +8930 0 +8931 0 +8932 0 +8933 0 +8934 0 +8935 0 +8936 0 +8937 0 +8938 0 +8939 1 +8940 0 +8941 0 +8942 0 +8943 0 +8944 0 +8945 0 +8946 0 +8947 0 +8948 0 +8949 1 +8950 0 +8951 0 +8952 0 +8953 0 +8954 0 +8955 0 +8956 0 +8957 0 +8958 0 +8959 1 +8960 0 +8961 0 +8962 0 +8963 0 +8964 0 +8965 0 +8966 0 +8967 0 +8968 0 +8969 1 +8970 0 +8971 0 +8972 0 +8973 0 +8974 0 +8975 0 +8976 0 +8977 0 +8978 1 +8979 0 +8980 0 +8981 0 +8982 0 +8983 0 +8984 0 +8985 0 +8986 0 +8987 1 +8988 0 +8989 0 +8990 0 +8991 0 +8992 0 +8993 0 +8994 0 +8995 0 +8996 0 +8997 1 +8998 0 +8999 0 +9000 0 +9001 0 +9002 0 +9003 0 +9004 0 +9005 0 +9006 1 +9007 0 +9008 0 +9009 0 +9010 0 +9011 0 +9012 0 +9013 0 +9014 1 +9015 0 +9016 0 +9017 0 +9018 0 +9019 0 +9020 0 +9021 0 +9022 1 +9023 0 +9024 0 +9025 0 +9026 0 +9027 0 +9028 0 +9029 0 +9030 1 +9031 0 +9032 0 +9033 0 +9034 0 +9035 0 +9036 0 +9037 0 +9038 1 +9039 0 +9040 0 +9041 0 +9042 0 +9043 0 +9044 0 +9045 0 +9046 0 +9047 1 +9048 0 +9049 0 +9050 0 +9051 0 +9052 0 +9053 0 +9054 0 +9055 1 +9056 0 +9057 0 +9058 0 +9059 0 +9060 0 +9061 0 +9062 0 +9063 1 +9064 0 +9065 0 +9066 0 +9067 0 +9068 0 +9069 0 +9070 0 +9071 0 +9072 0 +9073 1 +9074 0 +9075 0 +9076 0 +9077 0 +9078 0 +9079 0 +9080 0 +9081 0 +9082 0 +9083 0 +9084 0 +9085 0 +9086 0 +9087 0 +9088 0 +9089 0 +9090 0 +9091 0 +9092 1 +9093 0 +9094 0 +9095 0 +9096 0 +9097 0 +9098 0 +9099 0 +9100 1 +9101 0 +9102 0 +9103 0 +9104 0 +9105 0 +9106 0 +9107 0 +9108 1 +9109 0 +9110 0 +9111 0 +9112 0 +9113 0 +9114 0 +9115 0 +9116 0 +9117 1 +9118 0 +9119 0 +9120 0 +9121 0 +9122 0 +9123 0 +9124 0 +9125 0 +9126 1 +9127 0 +9128 0 +9129 0 +9130 0 +9131 0 +9132 0 +9133 0 +9134 0 +9135 1 +9136 0 +9137 0 +9138 0 +9139 0 +9140 0 +9141 0 +9142 0 +9143 1 +9144 0 +9145 0 +9146 0 +9147 0 +9148 0 +9149 0 +9150 0 +9151 0 +9152 1 +9153 0 +9154 0 +9155 0 +9156 0 +9157 0 +9158 0 +9159 0 +9160 0 +9161 1 +9162 0 +9163 0 +9164 0 +9165 0 +9166 0 +9167 0 +9168 0 +9169 1 +9170 0 +9171 0 +9172 0 +9173 0 +9174 0 +9175 0 +9176 0 +9177 0 +9178 1 +9179 0 +9180 0 +9181 0 +9182 0 +9183 0 +9184 0 +9185 0 +9186 0 +9187 0 +9188 1 +9189 0 +9190 0 +9191 0 +9192 0 +9193 0 +9194 0 +9195 0 +9196 0 +9197 1 +9198 0 +9199 0 +9200 0 +9201 0 +9202 0 +9203 0 +9204 0 +9205 0 +9206 0 +9207 0 +9208 0 +9209 0 +9210 0 +9211 0 +9212 0 +9213 0 +9214 0 +9215 0 +9216 0 +9217 0 +9218 0 +9219 0 +9220 0 +9221 1 +9222 0 +9223 0 +9224 0 +9225 0 +9226 0 +9227 0 +9228 1 +9229 0 +9230 0 +9231 0 +9232 0 +9233 0 +9234 0 +9235 0 +9236 0 +9237 1 +9238 0 +9239 0 +9240 0 +9241 0 +9242 0 +9243 0 +9244 0 +9245 0 +9246 1 +9247 0 +9248 0 +9249 0 +9250 0 +9251 0 +9252 0 +9253 0 +9254 0 +9255 1 +9256 0 +9257 0 +9258 0 +9259 0 +9260 0 +9261 1 +9262 0 +9263 0 +9264 0 +9265 0 +9266 0 +9267 0 +9268 0 +9269 0 +9270 0 +9271 0 +9272 0 +9273 0 +9274 0 +9275 0 +9276 1 +9277 0 +9278 0 +9279 0 +9280 0 +9281 0 +9282 0 +9283 0 +9284 0 +9285 0 +9286 0 +9287 0 +9288 0 +9289 0 +9290 1 +9291 0 +9292 0 +9293 0 +9294 0 +9295 0 +9296 0 +9297 0 +9298 0 +9299 0 +9300 1 +9301 0 +9302 0 +9303 0 +9304 0 +9305 0 +9306 0 +9307 0 +9308 1 +9309 0 +9310 0 +9311 0 +9312 0 +9313 0 +9314 0 +9315 0 +9316 1 +9317 0 +9318 0 +9319 0 +9320 0 +9321 0 +9322 0 +9323 1 +9324 0 +9325 0 +9326 0 +9327 0 +9328 0 +9329 0 +9330 0 +9331 1 +9332 0 +9333 0 +9334 0 +9335 0 +9336 0 +9337 0 +9338 1 +9339 0 +9340 0 +9341 0 +9342 0 +9343 0 +9344 0 +9345 1 +9346 0 +9347 0 +9348 0 +9349 0 +9350 0 +9351 0 +9352 0 +9353 0 +9354 0 +9355 1 +9356 0 +9357 0 +9358 0 +9359 0 +9360 0 +9361 0 +9362 0 +9363 1 +9364 0 +9365 0 +9366 0 +9367 0 +9368 0 +9369 0 +9370 1 +9371 0 +9372 0 +9373 0 +9374 0 +9375 0 +9376 0 +9377 0 +9378 1 +9379 0 +9380 0 +9381 0 +9382 0 +9383 0 +9384 0 +9385 0 +9386 0 +9387 0 +9388 0 +9389 0 +9390 0 +9391 0 +9392 0 +9393 0 +9394 0 +9395 1 +9396 0 +9397 0 +9398 0 +9399 0 +9400 0 +9401 0 +9402 0 +9403 1 +9404 0 +9405 0 +9406 0 +9407 0 +9408 0 +9409 0 +9410 0 +9411 0 +9412 1 +9413 0 +9414 0 +9415 0 +9416 0 +9417 0 +9418 0 +9419 0 +9420 1 +9421 0 +9422 0 +9423 0 +9424 0 +9425 0 +9426 0 +9427 0 +9428 0 +9429 1 +9430 0 +9431 0 +9432 0 +9433 0 +9434 0 +9435 0 +9436 0 +9437 0 +9438 0 +9439 1 +9440 0 +9441 0 +9442 0 +9443 0 +9444 0 +9445 0 +9446 0 +9447 0 +9448 0 +9449 1 +9450 0 +9451 0 +9452 0 +9453 0 +9454 0 +9455 0 +9456 0 +9457 1 +9458 0 +9459 0 +9460 0 +9461 0 +9462 0 +9463 0 +9464 1 +9465 0 +9466 0 +9467 0 +9468 0 +9469 0 +9470 0 +9471 0 +9472 0 +9473 1 +9474 0 +9475 0 +9476 0 +9477 0 +9478 0 +9479 0 +9480 0 +9481 1 +9482 0 +9483 0 +9484 0 +9485 0 +9486 0 +9487 0 +9488 1 +9489 0 +9490 0 +9491 0 +9492 0 +9493 0 +9494 0 +9495 0 +9496 0 +9497 1 +9498 0 +9499 0 +9500 0 +9501 0 +9502 0 +9503 0 +9504 0 +9505 0 +9506 0 +9507 0 +9508 0 +9509 0 +9510 0 +9511 0 +9512 0 +9513 0 +9514 1 +9515 0 +9516 0 +9517 0 +9518 0 +9519 0 +9520 0 +9521 0 +9522 1 +9523 0 +9524 0 +9525 0 +9526 0 +9527 0 +9528 0 +9529 0 +9530 1 +9531 0 +9532 0 +9533 0 +9534 0 +9535 0 +9536 0 +9537 0 +9538 1 +9539 0 +9540 0 +9541 0 +9542 0 +9543 0 +9544 0 +9545 0 +9546 0 +9547 1 +9548 0 +9549 0 +9550 0 +9551 0 +9552 0 +9553 0 +9554 0 +9555 1 +9556 0 +9557 0 +9558 0 +9559 0 +9560 0 +9561 0 +9562 0 +9563 1 +9564 0 +9565 0 +9566 0 +9567 0 +9568 0 +9569 0 +9570 0 +9571 0 +9572 1 +9573 0 +9574 0 +9575 0 +9576 0 +9577 0 +9578 0 +9579 0 +9580 1 +9581 0 +9582 0 +9583 0 +9584 0 +9585 0 +9586 0 +9587 0 +9588 0 +9589 1 +9590 0 +9591 0 +9592 0 +9593 0 +9594 0 +9595 0 +9596 0 +9597 0 +9598 0 +9599 0 +9600 0 +9601 0 +9602 0 +9603 0 +9604 0 +9605 0 +9606 0 +9607 0 +9608 1 +9609 0 +9610 0 +9611 0 +9612 0 +9613 0 +9614 0 +9615 1 +9616 0 +9617 0 +9618 0 +9619 0 +9620 0 +9621 0 +9622 1 +9623 0 +9624 0 +9625 0 +9626 0 +9627 0 +9628 0 +9629 0 +9630 1 +9631 0 +9632 0 +9633 0 +9634 0 +9635 0 +9636 0 +9637 0 +9638 0 +9639 1 +9640 0 +9641 0 +9642 0 +9643 0 +9644 0 +9645 0 +9646 0 +9647 0 +9648 1 +9649 0 +9650 0 +9651 0 +9652 0 +9653 0 +9654 0 +9655 0 +9656 1 +9657 0 +9658 0 +9659 0 +9660 0 +9661 0 +9662 0 +9663 1 +9664 0 +9665 0 +9666 0 +9667 0 +9668 0 +9669 0 +9670 0 +9671 0 +9672 0 +9673 1 +9674 0 +9675 0 +9676 0 +9677 0 +9678 0 +9679 0 +9680 0 +9681 1 +9682 0 +9683 0 +9684 0 +9685 0 +9686 0 +9687 0 +9688 0 +9689 1 +9690 0 +9691 0 +9692 0 +9693 0 +9694 0 +9695 0 +9696 1 +9697 0 +9698 0 +9699 0 +9700 0 +9701 0 +9702 0 +9703 0 +9704 1 +9705 0 +9706 0 +9707 0 +9708 0 +9709 0 +9710 0 +9711 0 +9712 1 +9713 0 +9714 0 +9715 0 +9716 0 +9717 0 +9718 0 +9719 0 +9720 0 +9721 0 +9722 1 +9723 0 +9724 0 +9725 0 +9726 0 +9727 0 +9728 0 +9729 0 +9730 0 +9731 1 +9732 0 +9733 0 +9734 0 +9735 0 +9736 0 +9737 0 +9738 0 +9739 0 +9740 1 +9741 0 +9742 0 +9743 0 +9744 0 +9745 0 +9746 0 +9747 0 +9748 0 +9749 1 +9750 0 +9751 0 +9752 0 +9753 0 +9754 0 +9755 0 +9756 1 +9757 0 +9758 0 +9759 0 +9760 0 +9761 0 +9762 0 +9763 0 +9764 0 +9765 0 +9766 0 +9767 0 +9768 0 +9769 0 +9770 0 +9771 0 +9772 0 +9773 1 +9774 0 +9775 0 +9776 0 +9777 0 +9778 0 +9779 0 +9780 1 +9781 0 +9782 0 +9783 0 +9784 0 +9785 0 +9786 0 +9787 0 +9788 1 +9789 0 +9790 0 +9791 0 +9792 0 +9793 0 +9794 0 +9795 0 +9796 0 +9797 0 +9798 0 +9799 0 +9800 0 +9801 0 +9802 0 +9803 1 +9804 0 +9805 0 +9806 0 +9807 0 +9808 0 +9809 0 +9810 0 +9811 0 +9812 1 +9813 0 +9814 0 +9815 0 +9816 0 +9817 0 +9818 0 +9819 0 +9820 1 +9821 0 +9822 0 +9823 0 +9824 0 +9825 0 +9826 0 +9827 0 +9828 0 +9829 1 +9830 0 +9831 0 +9832 0 +9833 0 +9834 0 +9835 0 +9836 0 +9837 0 +9838 1 +9839 0 +9840 0 +9841 0 +9842 0 +9843 0 +9844 0 +9845 0 +9846 0 +9847 0 +9848 1 +9849 0 +9850 0 +9851 0 +9852 0 +9853 0 +9854 4 +9855 0 +9856 0 +9857 1 +9858 0 +9859 0 +9860 0 +9861 0 +9862 1 +9863 0 +9864 0 +9865 0 +9866 0 +9867 0 +9868 1 +9869 0 +9870 0 +9871 0 +9872 0 +9873 1 +9874 0 +9875 0 +9876 0 +9877 0 +9878 1 +9879 0 +9880 0 +9881 0 +9882 0 +9883 0 +9884 0 +9885 0 +9886 1 +9887 0 +9888 0 +9889 0 +9890 0 +9891 0 +9892 0 +9893 0 +9894 0 +9895 1 +9896 0 +9897 0 +9898 0 +9899 0 +9900 0 +9901 0 +9902 0 +9903 0 +9904 1 +9905 0 +9906 0 +9907 0 +9908 0 +9909 0 +9910 0 +9911 0 +9912 0 +9913 0 +9914 0 +9915 0 +9916 0 +9917 0 +9918 0 +9919 0 +9920 0 +9921 0 +9922 0 +9923 0 +9924 1 +9925 0 +9926 0 +9927 0 +9928 0 +9929 0 +9930 0 +9931 0 +9932 0 +9933 0 +9934 1 +9935 0 +9936 0 +9937 0 +9938 0 +9939 0 +9940 0 +9941 0 +9942 0 +9943 0 +9944 1 +9945 0 +9946 0 +9947 0 +9948 0 +9949 0 +9950 0 +9951 0 +9952 0 +9953 0 +9954 1 +9955 0 +9956 0 +9957 0 +9958 0 +9959 0 +9960 0 +9961 0 +9962 0 +9963 1 +9964 0 +9965 0 +9966 0 +9967 0 +9968 0 +9969 0 +9970 0 +9971 0 +9972 1 +9973 0 +9974 0 +9975 0 +9976 0 +9977 0 +9978 0 +9979 0 +9980 0 +9981 0 +9982 0 +9983 1 +9984 0 +9985 0 +9986 0 +9987 0 +9988 0 +9989 0 +9990 0 +9991 0 +9992 0 +9993 1 +9994 0 +9995 0 +9996 0 +9997 0 +9998 0 +9999 0 +10000 0 +10001 0 +10002 0 +10003 0 +10004 1 +10005 0 +10006 0 +10007 0 +10008 0 +10009 0 +10010 0 +10011 0 +10012 0 +10013 1 +10014 0 +10015 0 +10016 0 +10017 0 +10018 0 +10019 0 +10020 0 +10021 0 +10022 0 +10023 1 +10024 0 +10025 0 +10026 0 +10027 0 +10028 0 +10029 0 +10030 0 +10031 1 +10032 0 +10033 0 +10034 0 +10035 0 +10036 0 +10037 0 +10038 0 +10039 0 +10040 0 +10041 1 +10042 0 +10043 0 +10044 0 +10045 0 +10046 0 +10047 0 +10048 0 +10049 0 +10050 0 +10051 1 +10052 0 +10053 0 +10054 0 +10055 0 +10056 0 +10057 0 +10058 0 +10059 0 +10060 1 +10061 0 +10062 0 +10063 0 +10064 0 +10065 0 +10066 0 +10067 0 +10068 0 +10069 1 +10070 0 +10071 0 +10072 0 +10073 0 +10074 0 +10075 0 +10076 0 +10077 0 +10078 1 +10079 0 +10080 0 +10081 0 +10082 0 +10083 0 +10084 0 +10085 0 +10086 0 +10087 1 +10088 0 +10089 0 +10090 0 +10091 0 +10092 0 +10093 0 +10094 0 +10095 0 +10096 0 +10097 1 +10098 0 +10099 0 +10100 0 +10101 0 +10102 0 +10103 0 +10104 0 +10105 0 +10106 0 +10107 0 +10108 1 +10109 0 +10110 0 +10111 0 +10112 0 +10113 0 +10114 0 +10115 0 +10116 0 +10117 0 +10118 1 +10119 0 +10120 0 +10121 0 +10122 0 +10123 0 +10124 0 +10125 0 +10126 0 +10127 1 +10128 0 +10129 0 +10130 0 +10131 0 +10132 0 +10133 0 +10134 0 +10135 0 +10136 0 +10137 1 +10138 0 +10139 0 +10140 0 +10141 0 +10142 0 +10143 0 +10144 0 +10145 0 +10146 0 +10147 1 +10148 0 +10149 0 +10150 0 +10151 0 +10152 0 +10153 0 +10154 0 +10155 0 +10156 0 +10157 1 +10158 0 +10159 0 +10160 0 +10161 0 +10162 0 +10163 0 +10164 0 +10165 0 +10166 0 +10167 1 +10168 0 +10169 0 +10170 0 +10171 0 +10172 0 +10173 0 +10174 0 +10175 0 +10176 1 +10177 0 +10178 0 +10179 0 +10180 0 +10181 0 +10182 0 +10183 0 +10184 0 +10185 1 +10186 0 +10187 0 +10188 0 +10189 0 +10190 0 +10191 0 +10192 0 +10193 1 +10194 0 +10195 0 +10196 0 +10197 0 +10198 0 +10199 0 +10200 0 +10201 1 +10202 0 +10203 0 +10204 0 +10205 0 +10206 0 +10207 0 +10208 0 +10209 0 +10210 0 +10211 1 +10212 0 +10213 0 +10214 0 +10215 0 +10216 0 +10217 0 +10218 0 +10219 0 +10220 1 +10221 0 +10222 0 +10223 0 +10224 0 +10225 0 +10226 0 +10227 0 +10228 0 +10229 0 +10230 1 +10231 0 +10232 0 +10233 0 +10234 0 +10235 0 +10236 0 +10237 0 +10238 0 +10239 0 +10240 1 +10241 0 +10242 0 +10243 0 +10244 0 +10245 0 +10246 0 +10247 0 +10248 0 +10249 0 +10250 1 +10251 0 +10252 0 +10253 0 +10254 0 +10255 0 +10256 0 +10257 0 +10258 0 +10259 0 +10260 1 +10261 0 +10262 0 +10263 0 +10264 1 +10265 0 +10266 0 +10267 0 +10268 0 +10269 0 +10270 1 +10271 0 +10272 0 +10273 0 +10274 0 +10275 0 +10276 0 +10277 0 +10278 1 +10279 0 +10280 0 +10281 0 +10282 0 +10283 0 +10284 0 +10285 0 +10286 1 +10287 0 +10288 0 +10289 0 +10290 0 +10291 0 +10292 0 +10293 0 +10294 0 +10295 0 +10296 1 +10297 0 +10298 0 +10299 0 +10300 0 +10301 0 +10302 0 +10303 0 +10304 0 +10305 1 +10306 0 +10307 0 +10308 0 +10309 0 +10310 0 +10311 0 +10312 0 +10313 0 +10314 1 +10315 0 +10316 0 +10317 0 +10318 0 +10319 0 +10320 0 +10321 0 +10322 0 +10323 1 +10324 0 +10325 0 +10326 0 +10327 0 +10328 0 +10329 0 +10330 0 +10331 0 +10332 0 +10333 1 +10334 0 +10335 0 +10336 0 +10337 0 +10338 0 +10339 0 +10340 0 +10341 0 +10342 0 +10343 0 +10344 0 +10345 0 +10346 0 +10347 0 +10348 0 +10349 0 +10350 0 +10351 1 +10352 0 +10353 0 +10354 0 +10355 0 +10356 0 +10357 0 +10358 0 +10359 0 +10360 1 +10361 0 +10362 0 +10363 0 +10364 0 +10365 0 +10366 0 +10367 0 +10368 0 +10369 0 +10370 1 +10371 0 +10372 0 +10373 0 +10374 0 +10375 0 +10376 0 +10377 0 +10378 0 +10379 0 +10380 1 +10381 0 +10382 0 +10383 0 +10384 0 +10385 0 +10386 0 +10387 1 +10388 0 +10389 0 +10390 0 +10391 0 +10392 0 +10393 0 +10394 0 +10395 1 +10396 0 +10397 0 +10398 0 +10399 0 +10400 0 +10401 0 +10402 0 +10403 0 +10404 1 +10405 0 +10406 0 +10407 0 +10408 0 +10409 0 +10410 0 +10411 0 +10412 0 +10413 0 +10414 1 +10415 0 +10416 0 +10417 0 +10418 0 +10419 0 +10420 0 +10421 0 +10422 0 +10423 1 +10424 0 +10425 0 +10426 0 +10427 0 +10428 0 +10429 0 +10430 0 +10431 0 +10432 0 +10433 1 +10434 0 +10435 0 +10436 0 +10437 0 +10438 0 +10439 0 +10440 0 +10441 0 +10442 0 +10443 1 +10444 0 +10445 0 +10446 0 +10447 0 +10448 0 +10449 0 +10450 0 +10451 0 +10452 1 +10453 0 +10454 0 +10455 0 +10456 0 +10457 0 +10458 0 +10459 0 +10460 1 +10461 0 +10462 0 +10463 0 +10464 0 +10465 0 +10466 0 +10467 0 +10468 0 +10469 1 +10470 0 +10471 0 +10472 0 +10473 0 +10474 0 +10475 0 +10476 0 +10477 0 +10478 0 +10479 1 +10480 0 +10481 0 +10482 0 +10483 0 +10484 0 +10485 0 +10486 0 +10487 0 +10488 0 +10489 1 +10490 0 +10491 0 +10492 0 +10493 0 +10494 0 +10495 0 +10496 0 +10497 0 +10498 1 +10499 0 +10500 0 +10501 0 +10502 0 +10503 0 +10504 0 +10505 0 +10506 1 +10507 0 +10508 0 +10509 0 +10510 0 +10511 0 +10512 0 +10513 0 +10514 0 +10515 0 +10516 0 +10517 1 +10518 0 +10519 0 +10520 0 +10521 0 +10522 0 +10523 0 +10524 0 +10525 0 +10526 0 +10527 1 +10528 0 +10529 0 +10530 0 +10531 0 +10532 0 +10533 0 +10534 0 +10535 0 +10536 1 +10537 0 +10538 0 +10539 0 +10540 0 +10541 0 +10542 0 +10543 0 +10544 0 +10545 1 +10546 0 +10547 0 +10548 0 +10549 0 +10550 0 +10551 0 +10552 0 +10553 0 +10554 0 +10555 1 +10556 0 +10557 0 +10558 0 +10559 0 +10560 0 +10561 0 +10562 0 +10563 0 +10564 0 +10565 0 +10566 1 +10567 0 +10568 0 +10569 0 +10570 0 +10571 0 +10572 0 +10573 0 +10574 0 +10575 0 +10576 0 +10577 0 +10578 0 +10579 0 +10580 0 +10581 0 +10582 0 +10583 0 +10584 0 +10585 0 +10586 0 +10587 1 +10588 0 +10589 0 +10590 0 +10591 0 +10592 0 +10593 0 +10594 0 +10595 0 +10596 0 +10597 0 +10598 1 +10599 0 +10600 0 +10601 0 +10602 0 +10603 0 +10604 0 +10605 0 +10606 0 +10607 0 +10608 0 +10609 1 +10610 0 +10611 0 +10612 0 +10613 0 +10614 0 +10615 0 +10616 0 +10617 1 +10618 0 +10619 0 +10620 0 +10621 0 +10622 0 +10623 0 +10624 0 +10625 1 +10626 0 +10627 0 +10628 0 +10629 0 +10630 0 +10631 0 +10632 0 +10633 0 +10634 1 +10635 0 +10636 0 +10637 0 +10638 0 +10639 0 +10640 0 +10641 0 +10642 0 +10643 0 +10644 1 +10645 0 +10646 0 +10647 0 +10648 0 +10649 0 +10650 0 +10651 0 +10652 0 +10653 1 +10654 0 +10655 0 +10656 0 +10657 0 +10658 0 +10659 0 +10660 0 +10661 1 +10662 0 +10663 0 +10664 0 +10665 0 +10666 0 +10667 0 +10668 0 +10669 0 +10670 0 +10671 1 +10672 0 +10673 0 +10674 0 +10675 0 +10676 0 +10677 0 +10678 0 +10679 0 +10680 0 +10681 1 +10682 0 +10683 0 +10684 0 +10685 0 +10686 0 +10687 0 +10688 0 +10689 0 +10690 0 +10691 0 +10692 0 +10693 0 +10694 0 +10695 0 +10696 0 +10697 0 +10698 0 +10699 0 +10700 0 +10701 1 +10702 0 +10703 0 +10704 0 +10705 0 +10706 0 +10707 0 +10708 0 +10709 0 +10710 0 +10711 1 +10712 0 +10713 0 +10714 0 +10715 0 +10716 0 +10717 0 +10718 0 +10719 0 +10720 0 +10721 1 +10722 0 +10723 0 +10724 0 +10725 0 +10726 0 +10727 0 +10728 0 +10729 0 +10730 1 +10731 0 +10732 0 +10733 0 +10734 0 +10735 0 +10736 0 +10737 0 +10738 0 +10739 0 +10740 1 +10741 0 +10742 0 +10743 0 +10744 0 +10745 0 +10746 0 +10747 0 +10748 0 +10749 1 +10750 0 +10751 0 +10752 0 +10753 0 +10754 0 +10755 0 +10756 0 +10757 0 +10758 0 +10759 1 +10760 0 +10761 0 +10762 0 +10763 0 +10764 0 +10765 0 +10766 0 +10767 0 +10768 0 +10769 0 +10770 1 +10771 0 +10772 0 +10773 0 +10774 0 +10775 0 +10776 0 +10777 0 +10778 0 +10779 0 +10780 1 +10781 0 +10782 0 +10783 0 +10784 0 +10785 0 +10786 0 +10787 0 +10788 0 +10789 0 +10790 1 +10791 0 +10792 0 +10793 0 +10794 0 +10795 0 +10796 0 +10797 0 +10798 0 +10799 0 +10800 1 +10801 0 +10802 0 +10803 0 +10804 0 +10805 0 +10806 0 +10807 0 +10808 0 +10809 0 +10810 0 +10811 0 +10812 0 +10813 0 +10814 0 +10815 0 +10816 0 +10817 0 +10818 0 +10819 0 +10820 1 +10821 0 +10822 0 +10823 0 +10824 0 +10825 0 +10826 0 +10827 0 +10828 0 +10829 0 +10830 0 +10831 1 +10832 0 +10833 0 +10834 0 +10835 0 +10836 0 +10837 0 +10838 0 +10839 0 +10840 1 +10841 0 +10842 0 +10843 0 +10844 0 +10845 0 +10846 0 +10847 0 +10848 0 +10849 0 +10850 0 +10851 0 +10852 0 +10853 0 +10854 0 +10855 0 +10856 0 +10857 0 +10858 0 +10859 0 +10860 1 +10861 0 +10862 0 +10863 0 +10864 0 +10865 0 +10866 0 +10867 0 +10868 0 +10869 1 +10870 0 +10871 0 +10872 0 +10873 0 +10874 0 +10875 0 +10876 0 +10877 0 +10878 0 +10879 0 +10880 1 +10881 0 +10882 0 +10883 0 +10884 0 +10885 0 +10886 0 +10887 0 +10888 0 +10889 0 +10890 1 +10891 0 +10892 0 +10893 0 +10894 0 +10895 0 +10896 0 +10897 0 +10898 0 +10899 0 +10900 1 +10901 0 +10902 0 +10903 0 +10904 0 +10905 0 +10906 0 +10907 0 +10908 0 +10909 0 +10910 0 +10911 1 +10912 0 +10913 0 +10914 0 +10915 0 +10916 0 +10917 0 +10918 0 +10919 0 +10920 0 +10921 1 +10922 0 +10923 0 +10924 0 +10925 0 +10926 0 +10927 0 +10928 0 +10929 0 +10930 0 +10931 1 +10932 0 +10933 0 +10934 0 +10935 0 +10936 0 +10937 0 +10938 0 +10939 0 +10940 1 +10941 0 +10942 0 +10943 0 +10944 0 +10945 0 +10946 0 +10947 0 +10948 0 +10949 1 +10950 0 +10951 0 +10952 0 +10953 0 +10954 0 +10955 0 +10956 0 +10957 0 +10958 1 +10959 0 +10960 0 +10961 0 +10962 0 +10963 0 +10964 0 +10965 0 +10966 0 +10967 0 +10968 1 +10969 0 +10970 0 +10971 0 +10972 0 +10973 0 +10974 0 +10975 0 +10976 0 +10977 0 +10978 1 +10979 0 +10980 0 +10981 0 +10982 0 +10983 0 +10984 0 +10985 0 +10986 0 +10987 0 +10988 0 +10989 1 +10990 0 +10991 0 +10992 0 +10993 0 +10994 0 +10995 0 +10996 0 +10997 0 +10998 0 +10999 0 +11000 1 \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore new file mode 100644 index 0000000..38344f8 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore @@ -0,0 +1,5 @@ +build/ +test/ +examples/ +fs.js +zlib.js \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE new file mode 100644 index 0000000..0c44ae7 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) Isaac Z. Schlueter ("Author") +All rights reserved. + +The BSD License + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/README.md new file mode 100644 index 0000000..34c1189 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/README.md @@ -0,0 +1,15 @@ +# readable-stream + +***Node-core streams for userland*** + +[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true)](https://nodei.co/npm/readable-stream/) +[![NPM](https://nodei.co/npm-dl/readable-stream.png)](https://nodei.co/npm/readable-stream/) + +This package is a mirror of the Streams2 and Streams3 implementations in Node-core. + +If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. + +**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. + +**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js new file mode 100644 index 0000000..ca807af --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_duplex.js") diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js new file mode 100644 index 0000000..b513d61 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js @@ -0,0 +1,89 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +module.exports = Duplex; + +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) keys.push(key); + return keys; +} +/**/ + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +forEach(objectKeys(Writable.prototype), function(method) { + if (!Duplex.prototype[method]) + Duplex.prototype[method] = Writable.prototype[method]; +}); + +function Duplex(options) { + if (!(this instanceof Duplex)) + return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) + this.readable = false; + + if (options && options.writable === false) + this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) + this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) + return; + + // no more data can be written. + // But allow more writes to happen in this tick. + process.nextTick(this.end.bind(this)); +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js new file mode 100644 index 0000000..895ca50 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js @@ -0,0 +1,46 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) + return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function(chunk, encoding, cb) { + cb(null, chunk); +}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js new file mode 100644 index 0000000..6307220 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js @@ -0,0 +1,982 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Readable; + +/**/ +var isArray = require('isarray'); +/**/ + + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Readable.ReadableState = ReadableState; + +var EE = require('events').EventEmitter; + +/**/ +if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +var Stream = require('stream'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var StringDecoder; + +util.inherits(Readable, Stream); + +function ReadableState(options, stream) { + options = options || {}; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = false; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // In streams that never have any data, and do push(null) right away, + // the consumer can miss the 'end' event if they do some I/O before + // consuming the stream. So, we don't emit('end') until some reading + // happens. + this.calledRead = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +function Readable(options) { + if (!(this instanceof Readable)) + return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function(chunk, encoding) { + var state = this._readableState; + + if (typeof chunk === 'string' && !state.objectMode) { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = new Buffer(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function(chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null || chunk === undefined) { + state.reading = false; + if (!state.ended) + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var e = new Error('stream.unshift() after end event'); + stream.emit('error', e); + } else { + if (state.decoder && !addToFront && !encoding) + chunk = state.decoder.write(chunk); + + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) { + state.buffer.unshift(chunk); + } else { + state.reading = false; + state.buffer.push(chunk); + } + + if (state.needReadable) + emitReadable(stream); + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + + + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && + (state.needReadable || + state.length < state.highWaterMark || + state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function(enc) { + if (!StringDecoder) + StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; +}; + +// Don't raise the hwm > 128MB +var MAX_HWM = 0x800000; +function roundUpToNextPowerOf2(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + for (var p = 1; p < 32; p <<= 1) n |= n >> p; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) + return 0; + + if (state.objectMode) + return n === 0 ? 0 : 1; + + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) + return state.buffer[0].length; + else + return state.length; + } + + if (n <= 0) + return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) + state.highWaterMark = roundUpToNextPowerOf2(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else + return state.length; + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function(n) { + var state = this._readableState; + state.calledRead = true; + var nOrig = n; + var ret; + + if (typeof n !== 'number' || n > 0) + state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && + state.needReadable && + (state.length >= state.highWaterMark || state.ended)) { + emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + ret = null; + + // In cases where the decoder did not receive enough data + // to produce a full chunk, then immediately received an + // EOF, state.buffer will contain [, ]. + // howMuchToRead will see this and coerce the amount to + // read to zero (because it's looking at the length of the + // first in state.buffer), and we'll end up here. + // + // This can only happen via state.decoder -- no other venue + // exists for pushing a zero-length chunk into state.buffer + // and triggering this behavior. In this case, we return our + // remaining data and end the stream, if appropriate. + if (state.length > 0 && state.decoder) { + ret = fromList(n, state); + state.length -= ret.length; + } + + if (state.length === 0) + endReadable(this); + + return ret; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + + // if we currently have less than the highWaterMark, then also read some + if (state.length - n <= state.highWaterMark) + doRead = true; + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) + doRead = false; + + if (doRead) { + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) + state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read called its callback synchronously, then `reading` + // will be false, and we need to re-evaluate how much data we + // can return to the user. + if (doRead && !state.reading) + n = howMuchToRead(nOrig, state); + + if (n > 0) + ret = fromList(n, state); + else + ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) + state.needReadable = true; + + // If we happened to read() exactly the remaining amount in the + // buffer, and the EOF has been seen at this point, then make sure + // that we emit 'end' on the very next tick. + if (state.ended && !state.endEmitted && state.length === 0) + endReadable(this); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + + +function onEofChunk(stream, state) { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // if we've ended and we have some data left, then emit + // 'readable' now to make sure it gets picked up. + if (state.length > 0) + emitReadable(stream); + else + endReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (state.emittedReadable) + return; + + state.emittedReadable = true; + if (state.sync) + process.nextTick(function() { + emitReadable_(stream); + }); + else + emitReadable_(stream); +} + +function emitReadable_(stream) { + stream.emit('readable'); +} + + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + process.nextTick(function() { + maybeReadMore_(stream, state); + }); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && + state.length < state.highWaterMark) { + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break; + else + len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function(n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function(dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && + dest !== process.stdout && + dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) + process.nextTick(endFn); + else + src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + if (readable !== src) return; + cleanup(); + } + + function onend() { + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + function cleanup() { + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (!dest._writableState || dest._writableState.needDrain) + ondrain(); + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + unpipe(); + dest.removeListener('error', onerror); + if (EE.listenerCount(dest, 'error') === 0) + dest.emit('error', er); + } + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. + if (!dest._events || !dest._events.error) + dest.on('error', onerror); + else if (isArray(dest._events.error)) + dest._events.error.unshift(onerror); + else + dest._events.error = [onerror, dest._events.error]; + + + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + // the handler that waits for readable events after all + // the data gets sucked out in flow. + // This would be easier to follow with a .once() handler + // in flow(), but that is too slow. + this.on('readable', pipeOnReadable); + + state.flowing = true; + process.nextTick(function() { + flow(src); + }); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function() { + var dest = this; + var state = src._readableState; + state.awaitDrain--; + if (state.awaitDrain === 0) + flow(src); + }; +} + +function flow(src) { + var state = src._readableState; + var chunk; + state.awaitDrain = 0; + + function write(dest, i, list) { + var written = dest.write(chunk); + if (false === written) { + state.awaitDrain++; + } + } + + while (state.pipesCount && null !== (chunk = src.read())) { + + if (state.pipesCount === 1) + write(state.pipes, 0, null); + else + forEach(state.pipes, write); + + src.emit('data', chunk); + + // if anyone needs a drain, then we have to wait for that. + if (state.awaitDrain > 0) + return; + } + + // if every destination was unpiped, either before entering this + // function, or in the while loop, then stop flowing. + // + // NB: This is a pretty rare edge case. + if (state.pipesCount === 0) { + state.flowing = false; + + // if there were data event listeners added, then switch to old mode. + if (EE.listenerCount(src, 'data') > 0) + emitDataEvents(src); + return; + } + + // at this point, no one needed a drain, so we just ran out of data + // on the next readable event, start it over again. + state.ranOut = true; +} + +function pipeOnReadable() { + if (this._readableState.ranOut) { + this._readableState.ranOut = false; + flow(this); + } +} + + +Readable.prototype.unpipe = function(dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) + return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) + return this; + + if (!dest) + dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + if (dest) + dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + this.removeListener('readable', pipeOnReadable); + state.flowing = false; + + for (var i = 0; i < len; i++) + dests[i].emit('unpipe', this); + return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) + return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) + state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function(ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + if (ev === 'data' && !this._readableState.flowing) + emitDataEvents(this); + + if (ev === 'readable' && this.readable) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + this.read(0); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function() { + emitDataEvents(this); + this.read(0); + this.emit('resume'); +}; + +Readable.prototype.pause = function() { + emitDataEvents(this, true); + this.emit('pause'); +}; + +function emitDataEvents(stream, startPaused) { + var state = stream._readableState; + + if (state.flowing) { + // https://github.com/isaacs/readable-stream/issues/16 + throw new Error('Cannot switch to old mode now.'); + } + + var paused = startPaused || false; + var readable = false; + + // convert to an old-style stream. + stream.readable = true; + stream.pipe = Stream.prototype.pipe; + stream.on = stream.addListener = Stream.prototype.on; + + stream.on('readable', function() { + readable = true; + + var c; + while (!paused && (null !== (c = stream.read()))) + stream.emit('data', c); + + if (c === null) { + readable = false; + stream._readableState.needReadable = true; + } + }); + + stream.pause = function() { + paused = true; + this.emit('pause'); + }; + + stream.resume = function() { + paused = false; + if (readable) + process.nextTick(function() { + stream.emit('readable'); + }); + else + this.read(0); + this.emit('resume'); + }; + + // now make it start, just in case it hadn't already. + stream.emit('readable'); +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function(stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function() { + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) + self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function(chunk) { + if (state.decoder) + chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + //if (state.objectMode && util.isNullOrUndefined(chunk)) + if (state.objectMode && (chunk === null || chunk === undefined)) + return; + else if (!state.objectMode && (!chunk || !chunk.length)) + return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (typeof stream[i] === 'function' && + typeof this[i] === 'undefined') { + this[i] = function(method) { return function() { + return stream[method].apply(stream, arguments); + }}(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function(ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function(n) { + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + + + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) + return null; + + if (length === 0) + ret = null; + else if (objectMode) + ret = list.shift(); + else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) + ret = list.join(''); + else + ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) + ret = ''; + else + ret = new Buffer(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var buf = list[0]; + var cpy = Math.min(n - c, buf.length); + + if (stringMode) + ret += buf.slice(0, cpy); + else + buf.copy(ret, c, 0, cpy); + + if (cpy < buf.length) + list[0] = buf.slice(cpy); + else + list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) + throw new Error('endReadable called on non-empty stream'); + + if (!state.endEmitted && state.calledRead) { + state.ended = true; + process.nextTick(function() { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } + }); + } +} + +function forEach (xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf (xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js new file mode 100644 index 0000000..eb188df --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js @@ -0,0 +1,210 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + + +function TransformState(options, stream) { + this.afterTransform = function(er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) + return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) + stream.push(data); + + if (cb) + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + + +function Transform(options) { + if (!(this instanceof Transform)) + return new Transform(options); + + Duplex.call(this, options); + + var ts = this._transformState = new TransformState(options, this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + this.once('finish', function() { + if ('function' === typeof this._flush) + this._flush(function(er) { + done(stream, er); + }); + else + done(stream); + }); +} + +Transform.prototype.push = function(chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function(chunk, encoding, cb) { + throw new Error('not implemented'); +}; + +Transform.prototype._write = function(chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || + rs.needReadable || + rs.length < rs.highWaterMark) + this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function(n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + + +function done(stream, er) { + if (er) + return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var rs = stream._readableState; + var ts = stream._transformState; + + if (ws.length) + throw new Error('calling transform done when ws.length != 0'); + + if (ts.transforming) + throw new Error('calling transform done when still transforming'); + + return stream.push(null); +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js new file mode 100644 index 0000000..4bdaa4f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js @@ -0,0 +1,386 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// A bit simpler than readable streams. +// Implement an async ._write(chunk, cb), and it'll handle all +// the drain event emission and buffering. + +module.exports = Writable; + +/**/ +var Buffer = require('buffer').Buffer; +/**/ + +Writable.WritableState = WritableState; + + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Stream = require('stream'); + +util.inherits(Writable, Stream); + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; +} + +function WritableState(options, stream) { + options = options || {}; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + // cast to ints. + this.highWaterMark = ~~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, becuase any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function(er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.buffer = []; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; +} + +function Writable(options) { + var Duplex = require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) + return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function() { + this.emit('error', new Error('Cannot pipe. Not readable.')); +}; + + +function writeAfterEnd(stream, state, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + if (!Buffer.isBuffer(chunk) && + 'string' !== typeof chunk && + chunk !== null && + chunk !== undefined && + !state.objectMode) { + var er = new TypeError('Invalid non-string/buffer chunk'); + stream.emit('error', er); + process.nextTick(function() { + cb(er); + }); + valid = false; + } + return valid; +} + +Writable.prototype.write = function(chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + else if (!encoding) + encoding = state.defaultEncoding; + + if (typeof cb !== 'function') + cb = function() {}; + + if (state.ended) + writeAfterEnd(this, state, cb); + else if (validChunk(this, state, chunk, cb)) + ret = writeOrBuffer(this, state, chunk, encoding, cb); + + return ret; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && + state.decodeStrings !== false && + typeof chunk === 'string') { + chunk = new Buffer(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + if (Buffer.isBuffer(chunk)) + encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) + state.needDrain = true; + + if (state.writing) + state.buffer.push(new WriteReq(chunk, encoding, cb)); + else + doWrite(stream, state, len, chunk, encoding, cb); + + return ret; +} + +function doWrite(stream, state, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + if (sync) + process.nextTick(function() { + cb(er); + }); + else + cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) + onwriteError(stream, state, sync, er, cb); + else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(stream, state); + + if (!finished && !state.bufferProcessing && state.buffer.length) + clearBuffer(stream, state); + + if (sync) { + process.nextTick(function() { + afterWrite(stream, state, finished, cb); + }); + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) + onwriteDrain(stream, state); + cb(); + if (finished) + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + + for (var c = 0; c < state.buffer.length; c++) { + var entry = state.buffer[c]; + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, len, chunk, encoding, cb); + + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + c++; + break; + } + } + + state.bufferProcessing = false; + if (c < state.buffer.length) + state.buffer = state.buffer.slice(c); + else + state.buffer.length = 0; +} + +Writable.prototype._write = function(chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype.end = function(chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (typeof chunk !== 'undefined' && chunk !== null) + this.write(chunk, encoding); + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) + endWritable(this, state, cb); +}; + + +function needFinish(stream, state) { + return (state.ending && + state.length === 0 && + !state.finished && + !state.writing); +} + +function finishMaybe(stream, state) { + var need = needFinish(stream, state); + if (need) { + state.finished = true; + stream.emit('finish'); + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) + process.nextTick(cb); + else + stream.once('finish', cb); + } + state.ended = true; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md new file mode 100644 index 0000000..5a76b41 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md @@ -0,0 +1,3 @@ +# core-util-is + +The `util.is*` functions introduced in Node v0.12. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch new file mode 100644 index 0000000..a06d5c0 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch @@ -0,0 +1,604 @@ +diff --git a/lib/util.js b/lib/util.js +index a03e874..9074e8e 100644 +--- a/lib/util.js ++++ b/lib/util.js +@@ -19,430 +19,6 @@ + // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + // USE OR OTHER DEALINGS IN THE SOFTWARE. + +-var formatRegExp = /%[sdj%]/g; +-exports.format = function(f) { +- if (!isString(f)) { +- var objects = []; +- for (var i = 0; i < arguments.length; i++) { +- objects.push(inspect(arguments[i])); +- } +- return objects.join(' '); +- } +- +- var i = 1; +- var args = arguments; +- var len = args.length; +- var str = String(f).replace(formatRegExp, function(x) { +- if (x === '%%') return '%'; +- if (i >= len) return x; +- switch (x) { +- case '%s': return String(args[i++]); +- case '%d': return Number(args[i++]); +- case '%j': +- try { +- return JSON.stringify(args[i++]); +- } catch (_) { +- return '[Circular]'; +- } +- default: +- return x; +- } +- }); +- for (var x = args[i]; i < len; x = args[++i]) { +- if (isNull(x) || !isObject(x)) { +- str += ' ' + x; +- } else { +- str += ' ' + inspect(x); +- } +- } +- return str; +-}; +- +- +-// Mark that a method should not be used. +-// Returns a modified function which warns once by default. +-// If --no-deprecation is set, then it is a no-op. +-exports.deprecate = function(fn, msg) { +- // Allow for deprecating things in the process of starting up. +- if (isUndefined(global.process)) { +- return function() { +- return exports.deprecate(fn, msg).apply(this, arguments); +- }; +- } +- +- if (process.noDeprecation === true) { +- return fn; +- } +- +- var warned = false; +- function deprecated() { +- if (!warned) { +- if (process.throwDeprecation) { +- throw new Error(msg); +- } else if (process.traceDeprecation) { +- console.trace(msg); +- } else { +- console.error(msg); +- } +- warned = true; +- } +- return fn.apply(this, arguments); +- } +- +- return deprecated; +-}; +- +- +-var debugs = {}; +-var debugEnviron; +-exports.debuglog = function(set) { +- if (isUndefined(debugEnviron)) +- debugEnviron = process.env.NODE_DEBUG || ''; +- set = set.toUpperCase(); +- if (!debugs[set]) { +- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { +- var pid = process.pid; +- debugs[set] = function() { +- var msg = exports.format.apply(exports, arguments); +- console.error('%s %d: %s', set, pid, msg); +- }; +- } else { +- debugs[set] = function() {}; +- } +- } +- return debugs[set]; +-}; +- +- +-/** +- * Echos the value of a value. Trys to print the value out +- * in the best way possible given the different types. +- * +- * @param {Object} obj The object to print out. +- * @param {Object} opts Optional options object that alters the output. +- */ +-/* legacy: obj, showHidden, depth, colors*/ +-function inspect(obj, opts) { +- // default options +- var ctx = { +- seen: [], +- stylize: stylizeNoColor +- }; +- // legacy... +- if (arguments.length >= 3) ctx.depth = arguments[2]; +- if (arguments.length >= 4) ctx.colors = arguments[3]; +- if (isBoolean(opts)) { +- // legacy... +- ctx.showHidden = opts; +- } else if (opts) { +- // got an "options" object +- exports._extend(ctx, opts); +- } +- // set default options +- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; +- if (isUndefined(ctx.depth)) ctx.depth = 2; +- if (isUndefined(ctx.colors)) ctx.colors = false; +- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; +- if (ctx.colors) ctx.stylize = stylizeWithColor; +- return formatValue(ctx, obj, ctx.depth); +-} +-exports.inspect = inspect; +- +- +-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +-inspect.colors = { +- 'bold' : [1, 22], +- 'italic' : [3, 23], +- 'underline' : [4, 24], +- 'inverse' : [7, 27], +- 'white' : [37, 39], +- 'grey' : [90, 39], +- 'black' : [30, 39], +- 'blue' : [34, 39], +- 'cyan' : [36, 39], +- 'green' : [32, 39], +- 'magenta' : [35, 39], +- 'red' : [31, 39], +- 'yellow' : [33, 39] +-}; +- +-// Don't use 'blue' not visible on cmd.exe +-inspect.styles = { +- 'special': 'cyan', +- 'number': 'yellow', +- 'boolean': 'yellow', +- 'undefined': 'grey', +- 'null': 'bold', +- 'string': 'green', +- 'date': 'magenta', +- // "name": intentionally not styling +- 'regexp': 'red' +-}; +- +- +-function stylizeWithColor(str, styleType) { +- var style = inspect.styles[styleType]; +- +- if (style) { +- return '\u001b[' + inspect.colors[style][0] + 'm' + str + +- '\u001b[' + inspect.colors[style][1] + 'm'; +- } else { +- return str; +- } +-} +- +- +-function stylizeNoColor(str, styleType) { +- return str; +-} +- +- +-function arrayToHash(array) { +- var hash = {}; +- +- array.forEach(function(val, idx) { +- hash[val] = true; +- }); +- +- return hash; +-} +- +- +-function formatValue(ctx, value, recurseTimes) { +- // Provide a hook for user-specified inspect functions. +- // Check that value is an object with an inspect function on it +- if (ctx.customInspect && +- value && +- isFunction(value.inspect) && +- // Filter out the util module, it's inspect function is special +- value.inspect !== exports.inspect && +- // Also filter out any prototype objects using the circular check. +- !(value.constructor && value.constructor.prototype === value)) { +- var ret = value.inspect(recurseTimes, ctx); +- if (!isString(ret)) { +- ret = formatValue(ctx, ret, recurseTimes); +- } +- return ret; +- } +- +- // Primitive types cannot have properties +- var primitive = formatPrimitive(ctx, value); +- if (primitive) { +- return primitive; +- } +- +- // Look up the keys of the object. +- var keys = Object.keys(value); +- var visibleKeys = arrayToHash(keys); +- +- if (ctx.showHidden) { +- keys = Object.getOwnPropertyNames(value); +- } +- +- // Some type of object without properties can be shortcutted. +- if (keys.length === 0) { +- if (isFunction(value)) { +- var name = value.name ? ': ' + value.name : ''; +- return ctx.stylize('[Function' + name + ']', 'special'); +- } +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } +- if (isDate(value)) { +- return ctx.stylize(Date.prototype.toString.call(value), 'date'); +- } +- if (isError(value)) { +- return formatError(value); +- } +- } +- +- var base = '', array = false, braces = ['{', '}']; +- +- // Make Array say that they are Array +- if (isArray(value)) { +- array = true; +- braces = ['[', ']']; +- } +- +- // Make functions say that they are functions +- if (isFunction(value)) { +- var n = value.name ? ': ' + value.name : ''; +- base = ' [Function' + n + ']'; +- } +- +- // Make RegExps say that they are RegExps +- if (isRegExp(value)) { +- base = ' ' + RegExp.prototype.toString.call(value); +- } +- +- // Make dates with properties first say the date +- if (isDate(value)) { +- base = ' ' + Date.prototype.toUTCString.call(value); +- } +- +- // Make error with message first say the error +- if (isError(value)) { +- base = ' ' + formatError(value); +- } +- +- if (keys.length === 0 && (!array || value.length == 0)) { +- return braces[0] + base + braces[1]; +- } +- +- if (recurseTimes < 0) { +- if (isRegExp(value)) { +- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); +- } else { +- return ctx.stylize('[Object]', 'special'); +- } +- } +- +- ctx.seen.push(value); +- +- var output; +- if (array) { +- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); +- } else { +- output = keys.map(function(key) { +- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); +- }); +- } +- +- ctx.seen.pop(); +- +- return reduceToSingleString(output, base, braces); +-} +- +- +-function formatPrimitive(ctx, value) { +- if (isUndefined(value)) +- return ctx.stylize('undefined', 'undefined'); +- if (isString(value)) { +- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') +- .replace(/'/g, "\\'") +- .replace(/\\"/g, '"') + '\''; +- return ctx.stylize(simple, 'string'); +- } +- if (isNumber(value)) { +- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, +- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . +- if (value === 0 && 1 / value < 0) +- return ctx.stylize('-0', 'number'); +- return ctx.stylize('' + value, 'number'); +- } +- if (isBoolean(value)) +- return ctx.stylize('' + value, 'boolean'); +- // For some reason typeof null is "object", so special case here. +- if (isNull(value)) +- return ctx.stylize('null', 'null'); +-} +- +- +-function formatError(value) { +- return '[' + Error.prototype.toString.call(value) + ']'; +-} +- +- +-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { +- var output = []; +- for (var i = 0, l = value.length; i < l; ++i) { +- if (hasOwnProperty(value, String(i))) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- String(i), true)); +- } else { +- output.push(''); +- } +- } +- keys.forEach(function(key) { +- if (!key.match(/^\d+$/)) { +- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, +- key, true)); +- } +- }); +- return output; +-} +- +- +-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { +- var name, str, desc; +- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; +- if (desc.get) { +- if (desc.set) { +- str = ctx.stylize('[Getter/Setter]', 'special'); +- } else { +- str = ctx.stylize('[Getter]', 'special'); +- } +- } else { +- if (desc.set) { +- str = ctx.stylize('[Setter]', 'special'); +- } +- } +- if (!hasOwnProperty(visibleKeys, key)) { +- name = '[' + key + ']'; +- } +- if (!str) { +- if (ctx.seen.indexOf(desc.value) < 0) { +- if (isNull(recurseTimes)) { +- str = formatValue(ctx, desc.value, null); +- } else { +- str = formatValue(ctx, desc.value, recurseTimes - 1); +- } +- if (str.indexOf('\n') > -1) { +- if (array) { +- str = str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n').substr(2); +- } else { +- str = '\n' + str.split('\n').map(function(line) { +- return ' ' + line; +- }).join('\n'); +- } +- } +- } else { +- str = ctx.stylize('[Circular]', 'special'); +- } +- } +- if (isUndefined(name)) { +- if (array && key.match(/^\d+$/)) { +- return str; +- } +- name = JSON.stringify('' + key); +- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { +- name = name.substr(1, name.length - 2); +- name = ctx.stylize(name, 'name'); +- } else { +- name = name.replace(/'/g, "\\'") +- .replace(/\\"/g, '"') +- .replace(/(^"|"$)/g, "'"); +- name = ctx.stylize(name, 'string'); +- } +- } +- +- return name + ': ' + str; +-} +- +- +-function reduceToSingleString(output, base, braces) { +- var numLinesEst = 0; +- var length = output.reduce(function(prev, cur) { +- numLinesEst++; +- if (cur.indexOf('\n') >= 0) numLinesEst++; +- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; +- }, 0); +- +- if (length > 60) { +- return braces[0] + +- (base === '' ? '' : base + '\n ') + +- ' ' + +- output.join(',\n ') + +- ' ' + +- braces[1]; +- } +- +- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +-} +- +- + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray(ar) { +@@ -522,166 +98,10 @@ function isPrimitive(arg) { + exports.isPrimitive = isPrimitive; + + function isBuffer(arg) { +- return arg instanceof Buffer; ++ return Buffer.isBuffer(arg); + } + exports.isBuffer = isBuffer; + + function objectToString(o) { + return Object.prototype.toString.call(o); +-} +- +- +-function pad(n) { +- return n < 10 ? '0' + n.toString(10) : n.toString(10); +-} +- +- +-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', +- 'Oct', 'Nov', 'Dec']; +- +-// 26 Feb 16:19:34 +-function timestamp() { +- var d = new Date(); +- var time = [pad(d.getHours()), +- pad(d.getMinutes()), +- pad(d.getSeconds())].join(':'); +- return [d.getDate(), months[d.getMonth()], time].join(' '); +-} +- +- +-// log is just a thin wrapper to console.log that prepends a timestamp +-exports.log = function() { +- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +-}; +- +- +-/** +- * Inherit the prototype methods from one constructor into another. +- * +- * The Function.prototype.inherits from lang.js rewritten as a standalone +- * function (not on Function.prototype). NOTE: If this file is to be loaded +- * during bootstrapping this function needs to be rewritten using some native +- * functions as prototype setup using normal JavaScript does not work as +- * expected during bootstrapping (see mirror.js in r114903). +- * +- * @param {function} ctor Constructor function which needs to inherit the +- * prototype. +- * @param {function} superCtor Constructor function to inherit prototype from. +- */ +-exports.inherits = function(ctor, superCtor) { +- ctor.super_ = superCtor; +- ctor.prototype = Object.create(superCtor.prototype, { +- constructor: { +- value: ctor, +- enumerable: false, +- writable: true, +- configurable: true +- } +- }); +-}; +- +-exports._extend = function(origin, add) { +- // Don't do anything if add isn't an object +- if (!add || !isObject(add)) return origin; +- +- var keys = Object.keys(add); +- var i = keys.length; +- while (i--) { +- origin[keys[i]] = add[keys[i]]; +- } +- return origin; +-}; +- +-function hasOwnProperty(obj, prop) { +- return Object.prototype.hasOwnProperty.call(obj, prop); +-} +- +- +-// Deprecated old stuff. +- +-exports.p = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- console.error(exports.inspect(arguments[i])); +- } +-}, 'util.p: Use console.error() instead'); +- +- +-exports.exec = exports.deprecate(function() { +- return require('child_process').exec.apply(this, arguments); +-}, 'util.exec is now called `child_process.exec`.'); +- +- +-exports.print = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(String(arguments[i])); +- } +-}, 'util.print: Use console.log instead'); +- +- +-exports.puts = exports.deprecate(function() { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stdout.write(arguments[i] + '\n'); +- } +-}, 'util.puts: Use console.log instead'); +- +- +-exports.debug = exports.deprecate(function(x) { +- process.stderr.write('DEBUG: ' + x + '\n'); +-}, 'util.debug: Use console.error instead'); +- +- +-exports.error = exports.deprecate(function(x) { +- for (var i = 0, len = arguments.length; i < len; ++i) { +- process.stderr.write(arguments[i] + '\n'); +- } +-}, 'util.error: Use console.error instead'); +- +- +-exports.pump = exports.deprecate(function(readStream, writeStream, callback) { +- var callbackCalled = false; +- +- function call(a, b, c) { +- if (callback && !callbackCalled) { +- callback(a, b, c); +- callbackCalled = true; +- } +- } +- +- readStream.addListener('data', function(chunk) { +- if (writeStream.write(chunk) === false) readStream.pause(); +- }); +- +- writeStream.addListener('drain', function() { +- readStream.resume(); +- }); +- +- readStream.addListener('end', function() { +- writeStream.end(); +- }); +- +- readStream.addListener('close', function() { +- call(); +- }); +- +- readStream.addListener('error', function(err) { +- writeStream.end(); +- call(err); +- }); +- +- writeStream.addListener('error', function(err) { +- readStream.destroy(); +- call(err); +- }); +-}, 'util.pump(): Use readableStream.pipe() instead'); +- +- +-var uv; +-exports._errnoException = function(err, syscall) { +- if (isUndefined(uv)) uv = process.binding('uv'); +- var errname = uv.errname(err); +- var e = new Error(syscall + ' ' + errname); +- e.code = errname; +- e.errno = errname; +- e.syscall = syscall; +- return e; +-}; ++} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js new file mode 100644 index 0000000..9074e8e --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js @@ -0,0 +1,107 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return Buffer.isBuffer(arg); +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json new file mode 100644 index 0000000..466dfdf --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json @@ -0,0 +1,53 @@ +{ + "name": "core-util-is", + "version": "1.0.1", + "description": "The `util.is*` functions introduced in Node v0.12.", + "main": "lib/util.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/core-util-is.git" + }, + "keywords": [ + "util", + "isBuffer", + "isArray", + "isNumber", + "isString", + "isRegExp", + "isThis", + "isThat", + "polyfill" + ], + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/core-util-is/issues" + }, + "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", + "readmeFilename": "README.md", + "homepage": "https://github.com/isaacs/core-util-is", + "_id": "core-util-is@1.0.1", + "dist": { + "shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", + "tarball": "http://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" + }, + "_from": "core-util-is@>=1.0.0 <1.1.0", + "_npmVersion": "1.3.23", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", + "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js new file mode 100644 index 0000000..007fa10 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js @@ -0,0 +1,106 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && objectToString(e) === '[object Error]'; +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +function isBuffer(arg) { + return arg instanceof Buffer; +} +exports.isBuffer = isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE new file mode 100644 index 0000000..dea3013 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE @@ -0,0 +1,16 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md new file mode 100644 index 0000000..b1c5665 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md @@ -0,0 +1,42 @@ +Browser-friendly inheritance fully compatible with standard node.js +[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). + +This package exports standard `inherits` from node.js `util` module in +node environment, but also provides alternative browser-friendly +implementation through [browser +field](https://gist.github.com/shtylman/4339901). Alternative +implementation is a literal copy of standard one located in standalone +module to avoid requiring of `util`. It also has a shim for old +browsers with no `Object.create` support. + +While keeping you sure you are using standard `inherits` +implementation in node.js environment, it allows bundlers such as +[browserify](https://github.com/substack/node-browserify) to not +include full `util` package to your client code if all you need is +just `inherits` function. It worth, because browser shim for `util` +package is large and `inherits` is often the single function you need +from it. + +It's recommended to use this package instead of +`require('util').inherits` for any code that has chances to be used +not only in node.js but in browser too. + +## usage + +```js +var inherits = require('inherits'); +// then use exactly as the standard one +``` + +## note on version ~1.0 + +Version ~1.0 had completely different motivation and is not compatible +neither with 2.0 nor with standard node.js `inherits`. + +If you are using version ~1.0 and planning to switch to ~2.0, be +careful: + +* new version uses `super_` instead of `super` for referencing + superclass +* new version overwrites current prototype while old one preserves any + existing fields on it diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js new file mode 100644 index 0000000..29f5e24 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js @@ -0,0 +1 @@ +module.exports = require('util').inherits diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js new file mode 100644 index 0000000..c1e78a7 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js @@ -0,0 +1,23 @@ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json new file mode 100644 index 0000000..93d5078 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json @@ -0,0 +1,50 @@ +{ + "name": "inherits", + "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", + "version": "2.0.1", + "keywords": [ + "inheritance", + "class", + "klass", + "oop", + "object-oriented", + "inherits", + "browser", + "browserify" + ], + "main": "./inherits.js", + "browser": "./inherits_browser.js", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/inherits.git" + }, + "license": "ISC", + "scripts": { + "test": "node test" + }, + "bugs": { + "url": "https://github.com/isaacs/inherits/issues" + }, + "_id": "inherits@2.0.1", + "dist": { + "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" + }, + "_from": "inherits@>=2.0.1 <2.1.0", + "_npmVersion": "1.3.8", + "_npmUser": { + "name": "isaacs", + "email": "i@izs.me" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + } + ], + "directories": {}, + "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", + "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", + "readme": "ERROR: No README data found!", + "homepage": "https://github.com/isaacs/inherits#readme" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js new file mode 100644 index 0000000..fc53012 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js @@ -0,0 +1,25 @@ +var inherits = require('./inherits.js') +var assert = require('assert') + +function test(c) { + assert(c.constructor === Child) + assert(c.constructor.super_ === Parent) + assert(Object.getPrototypeOf(c) === Child.prototype) + assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) + assert(c instanceof Child) + assert(c instanceof Parent) +} + +function Child() { + Parent.call(this) + test(this) +} + +function Parent() {} + +inherits(Child, Parent) + +var c = new Child +test(c) + +console.log('ok') diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md new file mode 100644 index 0000000..052a62b --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md @@ -0,0 +1,54 @@ + +# isarray + +`Array#isArray` for older browsers. + +## Usage + +```js +var isArray = require('isarray'); + +console.log(isArray([])); // => true +console.log(isArray({})); // => false +``` + +## Installation + +With [npm](http://npmjs.org) do + +```bash +$ npm install isarray +``` + +Then bundle for the browser with +[browserify](https://github.com/substack/browserify). + +With [component](http://component.io) do + +```bash +$ component install juliangruber/isarray +``` + +## License + +(MIT) + +Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js new file mode 100644 index 0000000..ec58596 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js @@ -0,0 +1,209 @@ + +/** + * Require the given path. + * + * @param {String} path + * @return {Object} exports + * @api public + */ + +function require(path, parent, orig) { + var resolved = require.resolve(path); + + // lookup failed + if (null == resolved) { + orig = orig || path; + parent = parent || 'root'; + var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); + err.path = orig; + err.parent = parent; + err.require = true; + throw err; + } + + var module = require.modules[resolved]; + + // perform real require() + // by invoking the module's + // registered function + if (!module.exports) { + module.exports = {}; + module.client = module.component = true; + module.call(this, module.exports, require.relative(resolved), module); + } + + return module.exports; +} + +/** + * Registered modules. + */ + +require.modules = {}; + +/** + * Registered aliases. + */ + +require.aliases = {}; + +/** + * Resolve `path`. + * + * Lookup: + * + * - PATH/index.js + * - PATH.js + * - PATH + * + * @param {String} path + * @return {String} path or null + * @api private + */ + +require.resolve = function(path) { + if (path.charAt(0) === '/') path = path.slice(1); + var index = path + '/index.js'; + + var paths = [ + path, + path + '.js', + path + '.json', + path + '/index.js', + path + '/index.json' + ]; + + for (var i = 0; i < paths.length; i++) { + var path = paths[i]; + if (require.modules.hasOwnProperty(path)) return path; + } + + if (require.aliases.hasOwnProperty(index)) { + return require.aliases[index]; + } +}; + +/** + * Normalize `path` relative to the current path. + * + * @param {String} curr + * @param {String} path + * @return {String} + * @api private + */ + +require.normalize = function(curr, path) { + var segs = []; + + if ('.' != path.charAt(0)) return path; + + curr = curr.split('/'); + path = path.split('/'); + + for (var i = 0; i < path.length; ++i) { + if ('..' == path[i]) { + curr.pop(); + } else if ('.' != path[i] && '' != path[i]) { + segs.push(path[i]); + } + } + + return curr.concat(segs).join('/'); +}; + +/** + * Register module at `path` with callback `definition`. + * + * @param {String} path + * @param {Function} definition + * @api private + */ + +require.register = function(path, definition) { + require.modules[path] = definition; +}; + +/** + * Alias a module definition. + * + * @param {String} from + * @param {String} to + * @api private + */ + +require.alias = function(from, to) { + if (!require.modules.hasOwnProperty(from)) { + throw new Error('Failed to alias "' + from + '", it does not exist'); + } + require.aliases[to] = from; +}; + +/** + * Return a require function relative to the `parent` path. + * + * @param {String} parent + * @return {Function} + * @api private + */ + +require.relative = function(parent) { + var p = require.normalize(parent, '..'); + + /** + * lastIndexOf helper. + */ + + function lastIndexOf(arr, obj) { + var i = arr.length; + while (i--) { + if (arr[i] === obj) return i; + } + return -1; + } + + /** + * The relative require() itself. + */ + + function localRequire(path) { + var resolved = localRequire.resolve(path); + return require(resolved, parent, path); + } + + /** + * Resolve relative to the parent. + */ + + localRequire.resolve = function(path) { + var c = path.charAt(0); + if ('/' == c) return path.slice(1); + if ('.' == c) return require.normalize(p, path); + + // resolve deps by returning + // the dep in the nearest "deps" + // directory + var segs = parent.split('/'); + var i = lastIndexOf(segs, 'deps') + 1; + if (!i) i = 0; + path = segs.slice(0, i + 1).join('/') + '/deps/' + path; + return path; + }; + + /** + * Check if module is defined at `path`. + */ + + localRequire.exists = function(path) { + return require.modules.hasOwnProperty(localRequire.resolve(path)); + }; + + return localRequire; +}; +require.register("isarray/index.js", function(exports, require, module){ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; + +}); +require.alias("isarray/index.js", "isarray/index.js"); + diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json new file mode 100644 index 0000000..9e31b68 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json @@ -0,0 +1,19 @@ +{ + "name" : "isarray", + "description" : "Array#isArray for older browsers", + "version" : "0.0.1", + "repository" : "juliangruber/isarray", + "homepage": "https://github.com/juliangruber/isarray", + "main" : "index.js", + "scripts" : [ + "index.js" + ], + "dependencies" : {}, + "keywords": ["browser","isarray","array"], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js new file mode 100644 index 0000000..5f5ad45 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js @@ -0,0 +1,3 @@ +module.exports = Array.isArray || function (arr) { + return Object.prototype.toString.call(arr) == '[object Array]'; +}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json new file mode 100644 index 0000000..19228ab --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json @@ -0,0 +1,53 @@ +{ + "name": "isarray", + "description": "Array#isArray for older browsers", + "version": "0.0.1", + "repository": { + "type": "git", + "url": "git://github.com/juliangruber/isarray.git" + }, + "homepage": "https://github.com/juliangruber/isarray", + "main": "index.js", + "scripts": { + "test": "tap test/*.js" + }, + "dependencies": {}, + "devDependencies": { + "tap": "*" + }, + "keywords": [ + "browser", + "isarray", + "array" + ], + "author": { + "name": "Julian Gruber", + "email": "mail@juliangruber.com", + "url": "http://juliangruber.com" + }, + "license": "MIT", + "_id": "isarray@0.0.1", + "dist": { + "shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "tarball": "http://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz" + }, + "_from": "isarray@0.0.1", + "_npmVersion": "1.2.18", + "_npmUser": { + "name": "juliangruber", + "email": "julian@juliangruber.com" + }, + "maintainers": [ + { + "name": "juliangruber", + "email": "julian@juliangruber.com" + } + ], + "directories": {}, + "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", + "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", + "bugs": { + "url": "https://github.com/juliangruber/isarray/issues" + }, + "readme": "ERROR: No README data found!" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore new file mode 100644 index 0000000..206320c --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore @@ -0,0 +1,2 @@ +build +test diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE new file mode 100644 index 0000000..6de584a --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE @@ -0,0 +1,20 @@ +Copyright Joyent, Inc. and other Node contributors. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md new file mode 100644 index 0000000..4d2aa00 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md @@ -0,0 +1,7 @@ +**string_decoder.js** (`require('string_decoder')`) from Node.js core + +Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. + +Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** + +The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js new file mode 100644 index 0000000..b00e54f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js @@ -0,0 +1,221 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json new file mode 100644 index 0000000..0364d54 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json @@ -0,0 +1,54 @@ +{ + "name": "string_decoder", + "version": "0.10.31", + "description": "The string_decoder module from Node core", + "main": "index.js", + "dependencies": {}, + "devDependencies": { + "tap": "~0.4.8" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/rvagg/string_decoder.git" + }, + "homepage": "https://github.com/rvagg/string_decoder", + "keywords": [ + "string", + "decoder", + "browser", + "browserify" + ], + "license": "MIT", + "gitHead": "d46d4fd87cf1d06e031c23f1ba170ca7d4ade9a0", + "bugs": { + "url": "https://github.com/rvagg/string_decoder/issues" + }, + "_id": "string_decoder@0.10.31", + "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "_from": "string_decoder@>=0.10.0 <0.11.0", + "_npmVersion": "1.4.23", + "_npmUser": { + "name": "rvagg", + "email": "rod@vagg.org" + }, + "maintainers": [ + { + "name": "substack", + "email": "mail@substack.net" + }, + { + "name": "rvagg", + "email": "rod@vagg.org" + } + ], + "dist": { + "shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", + "tarball": "http://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/package.json new file mode 100644 index 0000000..2dc3a25 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/package.json @@ -0,0 +1,69 @@ +{ + "name": "readable-stream", + "version": "1.0.31", + "description": "Streams2, a user-land copy of the stream library from Node.js v0.10.x", + "main": "readable.js", + "dependencies": { + "core-util-is": "~1.0.0", + "isarray": "0.0.1", + "string_decoder": "~0.10.x", + "inherits": "~2.0.1" + }, + "devDependencies": { + "tap": "~0.2.6" + }, + "scripts": { + "test": "tap test/simple/*.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/isaacs/readable-stream.git" + }, + "keywords": [ + "readable", + "stream", + "pipe" + ], + "browser": { + "util": false + }, + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "license": "MIT", + "bugs": { + "url": "https://github.com/isaacs/readable-stream/issues" + }, + "homepage": "https://github.com/isaacs/readable-stream", + "_id": "readable-stream@1.0.31", + "_shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "_from": "readable-stream@1.0.31", + "_npmVersion": "1.4.9", + "_npmUser": { + "name": "rvagg", + "email": "rod@vagg.org" + }, + "maintainers": [ + { + "name": "isaacs", + "email": "i@izs.me" + }, + { + "name": "tootallnate", + "email": "nathan@tootallnate.net" + }, + { + "name": "rvagg", + "email": "rod@vagg.org" + } + ], + "dist": { + "shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", + "tarball": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz", + "readme": "ERROR: No README data found!" +} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js new file mode 100644 index 0000000..27e8d8a --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_passthrough.js") diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/readable.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/readable.js new file mode 100644 index 0000000..4d1ddfc --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/readable.js @@ -0,0 +1,6 @@ +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/transform.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/transform.js new file mode 100644 index 0000000..5d482f0 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/transform.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_transform.js") diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/writable.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/writable.js new file mode 100644 index 0000000..e1e9efd --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/writable.js @@ -0,0 +1 @@ +module.exports = require("./lib/_stream_writable.js") diff --git a/util/demographicsImporter/node_modules/mongodb/package.json b/util/demographicsImporter/node_modules/mongodb/package.json new file mode 100644 index 0000000..9036dce --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/package.json @@ -0,0 +1,66 @@ +{ + "name": "mongodb", + "version": "2.0.45", + "description": "MongoDB legacy driver emulation layer on top of mongodb-core", + "main": "index.js", + "repository": { + "type": "git", + "url": "git@github.com:mongodb/node-mongodb-native.git" + }, + "keywords": [ + "mongodb", + "driver", + "legacy" + ], + "dependencies": { + "mongodb-core": "1.2.14", + "readable-stream": "1.0.31", + "es6-promise": "2.1.1" + }, + "devDependencies": { + "integra": "0.1.8", + "optimist": "0.6.1", + "bson": "~0.4", + "jsdoc": "3.3.0-beta3", + "semver": "4.1.0", + "rimraf": "2.2.6", + "gleak": "0.5.0", + "mongodb-version-manager": "^0.7.1", + "mongodb-tools": "~1.0", + "co": "4.5.4", + "bluebird": "2.9.27" + }, + "author": { + "name": "Christian Kvalheim" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/mongodb/node-mongodb-native/issues" + }, + "scripts": { + "test": "node test/runner.js -t functional" + }, + "homepage": "https://github.com/mongodb/node-mongodb-native", + "gitHead": "45d433baa92cb160f895d47911ee5776fbaad3be", + "_id": "mongodb@2.0.45", + "_shasum": "c63d42b918f19a53b32d4c64043f6a9f66c9aba5", + "_from": "mongodb@*", + "_npmVersion": "2.14.4", + "_nodeVersion": "4.1.1", + "_npmUser": { + "name": "christkv", + "email": "christkv@gmail.com" + }, + "maintainers": [ + { + "name": "christkv", + "email": "christkv@gmail.com" + } + ], + "dist": { + "shasum": "c63d42b918f19a53b32d4c64043f6a9f66c9aba5", + "tarball": "http://registry.npmjs.org/mongodb/-/mongodb-2.0.45.tgz" + }, + "directories": {}, + "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-2.0.45.tgz" +} diff --git a/util/demographicsImporter/node_modules/mongodb/t.js b/util/demographicsImporter/node_modules/mongodb/t.js new file mode 100644 index 0000000..af73362 --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/t.js @@ -0,0 +1,73 @@ +var MongoClient = require('./').MongoClient + , assert = require('assert') + , cappedCollectionName = "capped_test"; + + +function capitalizeFirstLetter(string) { + return string.charAt(0).toUpperCase() + string.slice(1); +} + + function createTailedCursor(db, callback) { + var collection = db.collection(cappedCollectionName) + , cursor = collection.find({}, { tailable: true, awaitdata: true, numberOfRetries: Number.MAX_VALUE}) + , stream = cursor.stream() + , statusGetters = ['notified', 'closed', 'dead', 'killed']; + + console.log('After stream open'); + statusGetters.forEach(function (s) { + var getter = 'is' + capitalizeFirstLetter(s); + console.log("cursor " + getter + " => ", cursor[getter]()); + }); + + + stream.on('error', callback); + stream.on('end', callback.bind(null, 'end')); + stream.on('close', callback.bind(null, 'close')); + stream.on('readable', callback.bind(null, 'readable')); + stream.on('data', callback.bind(null, null, 'data')); + + console.log('After stream attach events'); + statusGetters.forEach(function (s) { + var getter = 'is' + capitalizeFirstLetter(s); + console.log("cursor " + getter + " => ", cursor[getter]()); + }); + } + + function cappedStreamEvent(err, evName, data) { + if (err) { + console.log("capped stream got error", err); + return; + } + + if (evName) { + console.log("capped stream got event", evName); + } + + if (data) { + console.log("capped stream got data", data); + } + } + + +// Connection URL +var url = 'mongodb://localhost:27017/myproject'; +// Use connect method to connect to the Server +MongoClient.connect(url, function(err, db) { + assert.equal(null, err); + console.log("Connected correctly to server"); + + db.createCollection(cappedCollectionName, + { "capped": true, + "size": 100000, + "max": 5000 }, + function(err, collection) { + + assert.equal(null, err); + console.log("Created capped collection " + cappedCollectionName); + + createTailedCursor(db, cappedStreamEvent); + }); + + + //db.close(); +}); \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/t1.js b/util/demographicsImporter/node_modules/mongodb/t1.js new file mode 100644 index 0000000..392ed8e --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/t1.js @@ -0,0 +1,77 @@ +var MongoClient = require('./').MongoClient; + +MongoClient.connect('mongodb://localhost:27017/page-testing', function (err, db) { + collection = db.collection('test'); + + collection.insertMany([{a:1}, {a:2}], {w:1}, function (err, docs) { + if (err) { + console.log("ERROR"); + } + + collection.find().sort({'a': -1}).toArray(function(err, items) { + if (err) { + console.log("ERROR"); + } + console.log("Items: ", items); + }); + }); +}); +// var database = null; +// +// var MongoClient = require('./').MongoClient; +// +// function connect_to_mongo(callback) { +// if (database != null) { +// callback(null, database); +// } else { +// var connection = "mongodb://127.0.0.1:27017/test_db"; +// MongoClient.connect(connection, { +// server : { +// reconnectTries : 5, +// reconnectInterval: 1000, +// autoReconnect : true +// } +// }, function (err, db) { +// database = db; +// callback(err, db); +// }); +// } +// } +// +// function log(message) { +// console.log(new Date(), message); +// } +// +// var queryNumber = 0; +// +// function make_query(db) { +// var currentNumber = queryNumber; +// ++queryNumber; +// log("query " + currentNumber + ": started"); +// +// setTimeout(function() { +// make_query(db); +// }, 5000); +// +// var collection = db.collection('test_collection'); +// collection.findOne({}, +// function (err, result) { +// if (err != null) { +// log("query " + currentNumber + ": find one error: " + err.message); +// return; +// } +// log("query " + currentNumber + ": find one result: " + result); +// } +// ); +// } +// +// connect_to_mongo( +// function(err, db) { +// if (err != null) { +// log(err.message); +// return; +// } +// +// make_query(db); +// } +// ); diff --git a/util/demographicsImporter/node_modules/mongodb/wercker.yml b/util/demographicsImporter/node_modules/mongodb/wercker.yml new file mode 100644 index 0000000..b64845f --- /dev/null +++ b/util/demographicsImporter/node_modules/mongodb/wercker.yml @@ -0,0 +1,19 @@ +box: wercker/nodejs +services: + - wercker/mongodb@1.0.1 +# Build definition +build: + # The steps that will be executed on build + steps: + # A step that executes `npm install` command + - npm-install + # A step that executes `npm test` command + - npm-test + + # A custom script step, name value is used in the UI + # and the code value contains the command that get executed + - script: + name: echo nodejs information + code: | + echo "node version $(node -v) running" + echo "npm version $(npm -v) running" diff --git a/util/demographicsImporter/package.json b/util/demographicsImporter/package.json new file mode 100644 index 0000000..317d037 --- /dev/null +++ b/util/demographicsImporter/package.json @@ -0,0 +1,15 @@ +{ + "name": "retroimporter", + "version": "1.0.0", + "description": "", + "main": "retroImporter.js", + "dependencies": { + "mongodb": "^2.0.45" + }, + "devDependencies": {}, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC" +} From 530292650346ad04bc38be8cbea335edfc5cdc69 Mon Sep 17 00:00:00 2001 From: Fieran Mason Date: Fri, 6 Nov 2015 23:28:29 +0000 Subject: [PATCH 08/10] fixed demographics importer --- removed install stuffs --- .../demographicsImporter.js | 6 +- .../node_modules/mongodb/HISTORY.md | 1218 -- .../node_modules/mongodb/LICENSE | 201 - .../node_modules/mongodb/Makefile | 11 - .../node_modules/mongodb/README.md | 322 - .../node_modules/mongodb/c.js | 24 - .../node_modules/mongodb/conf.json | 69 - .../node_modules/mongodb/index.js | 47 - .../node_modules/mongodb/lib/admin.js | 581 - .../mongodb/lib/aggregation_cursor.js | 432 - .../node_modules/mongodb/lib/apm.js | 571 - .../node_modules/mongodb/lib/bulk/common.js | 393 - .../node_modules/mongodb/lib/bulk/ordered.js | 532 - .../mongodb/lib/bulk/unordered.js | 541 - .../node_modules/mongodb/lib/collection.js | 3128 ----- .../mongodb/lib/command_cursor.js | 296 - .../node_modules/mongodb/lib/cursor.js | 1149 -- .../node_modules/mongodb/lib/db.js | 1731 --- .../node_modules/mongodb/lib/gridfs/chunk.js | 237 - .../mongodb/lib/gridfs/grid_store.js | 1919 --- .../node_modules/mongodb/lib/metadata.js | 64 - .../node_modules/mongodb/lib/mongo_client.js | 463 - .../node_modules/mongodb/lib/mongos.js | 491 - .../mongodb/lib/read_preference.js | 104 - .../node_modules/mongodb/lib/replset.js | 555 - .../node_modules/mongodb/lib/server.js | 437 - .../node_modules/mongodb/lib/topology_base.js | 152 - .../node_modules/mongodb/lib/url_parser.js | 295 - .../node_modules/mongodb/lib/utils.js | 234 - .../node_modules/mongodb/load.js | 32 - .../node_modules/es6-promise/CHANGELOG.md | 9 - .../mongodb/node_modules/es6-promise/LICENSE | 19 - .../node_modules/es6-promise/README.md | 61 - .../es6-promise/dist/es6-promise.js | 957 -- .../es6-promise/dist/es6-promise.min.js | 9 - .../es6-promise/dist/test/browserify.js | 11631 ---------------- .../es6-promise/dist/test/es6-promise.js | 950 -- .../es6-promise/dist/test/es6-promise.min.js | 1 - .../es6-promise/dist/test/index.html | 25 - .../es6-promise/dist/test/json3.js | 902 -- .../es6-promise/dist/test/mocha.css | 270 - .../es6-promise/dist/test/mocha.js | 6095 -------- .../es6-promise/dist/test/worker.js | 16 - .../es6-promise/lib/es6-promise.umd.js | 18 - .../es6-promise/lib/es6-promise/-internal.js | 250 - .../es6-promise/lib/es6-promise/asap.js | 111 - .../es6-promise/lib/es6-promise/enumerator.js | 113 - .../es6-promise/lib/es6-promise/polyfill.js | 26 - .../es6-promise/lib/es6-promise/promise.js | 408 - .../lib/es6-promise/promise/all.js | 52 - .../lib/es6-promise/promise/race.js | 104 - .../lib/es6-promise/promise/reject.js | 46 - .../lib/es6-promise/promise/resolve.js | 48 - .../es6-promise/lib/es6-promise/utils.js | 22 - .../node_modules/es6-promise/package.json | 88 - .../node_modules/mongodb-core/HISTORY.md | 246 - .../mongodb/node_modules/mongodb-core/LICENSE | 201 - .../node_modules/mongodb-core/Makefile | 11 - .../node_modules/mongodb-core/README.md | 225 - .../node_modules/mongodb-core/TESTING.md | 18 - .../node_modules/mongodb-core/conf.json | 60 - .../node_modules/mongodb-core/index.js | 18 - .../mongodb-core/lib/auth/gssapi.js | 244 - .../mongodb-core/lib/auth/mongocr.js | 160 - .../mongodb-core/lib/auth/plain.js | 150 - .../mongodb-core/lib/auth/scram.js | 317 - .../mongodb-core/lib/auth/sspi.js | 234 - .../mongodb-core/lib/auth/x509.js | 145 - .../mongodb-core/lib/connection/commands.js | 519 - .../mongodb-core/lib/connection/connection.js | 462 - .../mongodb-core/lib/connection/logger.js | 196 - .../mongodb-core/lib/connection/pool.js | 275 - .../mongodb-core/lib/connection/utils.js | 77 - .../node_modules/mongodb-core/lib/cursor.js | 756 - .../node_modules/mongodb-core/lib/error.js | 44 - .../mongodb-core/lib/tools/smoke_plugin.js | 59 - .../lib/topologies/command_result.js | 37 - .../mongodb-core/lib/topologies/mongos.js | 1000 -- .../lib/topologies/read_preference.js | 106 - .../mongodb-core/lib/topologies/replset.js | 1333 -- .../lib/topologies/replset_state.js | 483 - .../mongodb-core/lib/topologies/server.js | 1230 -- .../mongodb-core/lib/topologies/session.js | 93 - .../lib/topologies/strategies/ping.js | 276 - .../lib/wireprotocol/2_4_support.js | 559 - .../lib/wireprotocol/2_6_support.js | 291 - .../lib/wireprotocol/3_2_support.js | 494 - .../mongodb-core/lib/wireprotocol/commands.js | 357 - .../mongodb-core/node_modules/bson/HISTORY | 113 - .../mongodb-core/node_modules/bson/LICENSE | 201 - .../mongodb-core/node_modules/bson/README.md | 69 - .../bson/alternate_parsers/bson.js | 1574 --- .../bson/alternate_parsers/faster_bson.js | 429 - .../node_modules/bson/browser_build/bson.js | 4843 ------- .../bson/browser_build/package.json | 8 - .../node_modules/bson/lib/bson/binary.js | 344 - .../bson/lib/bson/binary_parser.js | 385 - .../node_modules/bson/lib/bson/bson.js | 323 - .../node_modules/bson/lib/bson/code.js | 24 - .../node_modules/bson/lib/bson/db_ref.js | 32 - .../node_modules/bson/lib/bson/double.js | 33 - .../bson/lib/bson/float_parser.js | 121 - .../node_modules/bson/lib/bson/index.js | 86 - .../node_modules/bson/lib/bson/long.js | 856 -- .../node_modules/bson/lib/bson/map.js | 126 - .../node_modules/bson/lib/bson/max_key.js | 14 - .../node_modules/bson/lib/bson/min_key.js | 14 - .../node_modules/bson/lib/bson/objectid.js | 273 - .../bson/lib/bson/parser/calculate_size.js | 310 - .../bson/lib/bson/parser/deserializer.js | 544 - .../bson/lib/bson/parser/serializer.js | 909 -- .../node_modules/bson/lib/bson/regexp.js | 30 - .../node_modules/bson/lib/bson/symbol.js | 47 - .../node_modules/bson/lib/bson/timestamp.js | 856 -- .../node_modules/bson/package.json | 70 - .../node_modules/bson/tools/gleak.js | 21 - .../node_modules/kerberos/.travis.yml | 20 - .../node_modules/kerberos/LICENSE | 201 - .../node_modules/kerberos/README.md | 4 - .../node_modules/kerberos/binding.gyp | 46 - .../node_modules/kerberos/build/Makefile | 324 - .../Release/.deps/Release/kerberos.node.d | 1 - .../.deps/Release/obj.target/kerberos.node.d | 1 - .../obj.target/kerberos/lib/base64.o.d | 4 - .../obj.target/kerberos/lib/kerberos.o.d | 71 - .../kerberos/lib/kerberos_context.o.d | 70 - .../obj.target/kerberos/lib/kerberosgss.o.d | 16 - .../obj.target/kerberos/lib/worker.o.d | 57 - .../kerberos/build/Release/kerberos.node | Bin 85259 -> 0 bytes .../build/Release/obj.target/kerberos.node | Bin 85259 -> 0 bytes .../Release/obj.target/kerberos/lib/base64.o | Bin 4176 -> 0 bytes .../obj.target/kerberos/lib/kerberos.o | Bin 86232 -> 0 bytes .../kerberos/lib/kerberos_context.o | Bin 31808 -> 0 bytes .../obj.target/kerberos/lib/kerberosgss.o | Bin 19608 -> 0 bytes .../Release/obj.target/kerberos/lib/worker.o | Bin 2720 -> 0 bytes .../kerberos/build/binding.Makefile | 6 - .../node_modules/kerberos/build/config.gypi | 138 - .../kerberos/build/kerberos.target.mk | 151 - .../node_modules/kerberos/builderror.log | 25 - .../node_modules/kerberos/index.js | 6 - .../kerberos/lib/auth_processes/mongodb.js | 281 - .../node_modules/kerberos/lib/base64.c | 134 - .../node_modules/kerberos/lib/base64.h | 22 - .../node_modules/kerberos/lib/kerberos.cc | 893 -- .../node_modules/kerberos/lib/kerberos.h | 50 - .../node_modules/kerberos/lib/kerberos.js | 164 - .../kerberos/lib/kerberos_context.cc | 134 - .../kerberos/lib/kerberos_context.h | 64 - .../node_modules/kerberos/lib/kerberosgss.c | 931 -- .../node_modules/kerberos/lib/kerberosgss.h | 73 - .../node_modules/kerberos/lib/sspi.js | 15 - .../node_modules/kerberos/lib/win32/base64.c | 121 - .../node_modules/kerberos/lib/win32/base64.h | 18 - .../kerberos/lib/win32/kerberos.cc | 51 - .../kerberos/lib/win32/kerberos.h | 60 - .../kerberos/lib/win32/kerberos_sspi.c | 244 - .../kerberos/lib/win32/kerberos_sspi.h | 106 - .../node_modules/kerberos/lib/win32/worker.cc | 7 - .../node_modules/kerberos/lib/win32/worker.h | 38 - .../lib/win32/wrappers/security_buffer.cc | 101 - .../lib/win32/wrappers/security_buffer.h | 48 - .../lib/win32/wrappers/security_buffer.js | 12 - .../wrappers/security_buffer_descriptor.cc | 182 - .../wrappers/security_buffer_descriptor.h | 46 - .../wrappers/security_buffer_descriptor.js | 3 - .../lib/win32/wrappers/security_context.cc | 856 -- .../lib/win32/wrappers/security_context.h | 74 - .../lib/win32/wrappers/security_context.js | 3 - .../win32/wrappers/security_credentials.cc | 348 - .../lib/win32/wrappers/security_credentials.h | 68 - .../win32/wrappers/security_credentials.js | 22 - .../node_modules/kerberos/lib/worker.cc | 7 - .../node_modules/kerberos/lib/worker.h | 38 - .../kerberos/node_modules/nan/.dntrc | 30 - .../kerberos/node_modules/nan/CHANGELOG.md | 374 - .../kerberos/node_modules/nan/LICENSE.md | 13 - .../kerberos/node_modules/nan/README.md | 367 - .../kerberos/node_modules/nan/appveyor.yml | 38 - .../kerberos/node_modules/nan/doc/.build.sh | 38 - .../node_modules/nan/doc/asyncworker.md | 97 - .../kerberos/node_modules/nan/doc/buffers.md | 54 - .../kerberos/node_modules/nan/doc/callback.md | 52 - .../node_modules/nan/doc/converters.md | 41 - .../kerberos/node_modules/nan/doc/errors.md | 226 - .../node_modules/nan/doc/maybe_types.md | 480 - .../kerberos/node_modules/nan/doc/methods.md | 624 - .../kerberos/node_modules/nan/doc/new.md | 141 - .../node_modules/nan/doc/node_misc.md | 114 - .../node_modules/nan/doc/persistent.md | 292 - .../kerberos/node_modules/nan/doc/scopes.md | 73 - .../kerberos/node_modules/nan/doc/script.md | 38 - .../node_modules/nan/doc/string_bytes.md | 62 - .../node_modules/nan/doc/v8_internals.md | 199 - .../kerberos/node_modules/nan/doc/v8_misc.md | 63 - .../kerberos/node_modules/nan/include_dirs.js | 1 - .../kerberos/node_modules/nan/nan.h | 2136 --- .../kerberos/node_modules/nan/nan_callbacks.h | 88 - .../node_modules/nan/nan_callbacks_12_inl.h | 512 - .../nan/nan_callbacks_pre_12_inl.h | 506 - .../node_modules/nan/nan_converters.h | 64 - .../node_modules/nan/nan_converters_43_inl.h | 42 - .../nan/nan_converters_pre_43_inl.h | 42 - .../nan/nan_implementation_12_inl.h | 399 - .../nan/nan_implementation_pre_12_inl.h | 259 - .../node_modules/nan/nan_maybe_43_inl.h | 224 - .../node_modules/nan/nan_maybe_pre_43_inl.h | 295 - .../kerberos/node_modules/nan/nan_new.h | 332 - .../node_modules/nan/nan_object_wrap.h | 155 - .../node_modules/nan/nan_persistent_12_inl.h | 129 - .../nan/nan_persistent_pre_12_inl.h | 238 - .../node_modules/nan/nan_string_bytes.h | 305 - .../kerberos/node_modules/nan/nan_weak.h | 422 - .../kerberos/node_modules/nan/package.json | 92 - .../kerberos/node_modules/nan/tools/1to2.js | 412 - .../kerberos/node_modules/nan/tools/README.md | 14 - .../node_modules/nan/tools/package.json | 19 - .../node_modules/kerberos/package.json | 55 - .../kerberos/test/kerberos_tests.js | 34 - .../kerberos/test/kerberos_win32_test.js | 15 - .../win32/security_buffer_descriptor_tests.js | 41 - .../test/win32/security_buffer_tests.js | 22 - .../test/win32/security_credentials_tests.js | 55 - .../node_modules/mongodb-core/package.json | 66 - .../simple_2_document_limit_toArray.dat | 11000 --------------- .../node_modules/readable-stream/.npmignore | 5 - .../node_modules/readable-stream/LICENSE | 27 - .../node_modules/readable-stream/README.md | 15 - .../node_modules/readable-stream/duplex.js | 1 - .../readable-stream/lib/_stream_duplex.js | 89 - .../lib/_stream_passthrough.js | 46 - .../readable-stream/lib/_stream_readable.js | 982 -- .../readable-stream/lib/_stream_transform.js | 210 - .../readable-stream/lib/_stream_writable.js | 386 - .../node_modules/core-util-is/README.md | 3 - .../node_modules/core-util-is/float.patch | 604 - .../node_modules/core-util-is/lib/util.js | 107 - .../node_modules/core-util-is/package.json | 53 - .../node_modules/core-util-is/util.js | 106 - .../node_modules/inherits/LICENSE | 16 - .../node_modules/inherits/README.md | 42 - .../node_modules/inherits/inherits.js | 1 - .../node_modules/inherits/inherits_browser.js | 23 - .../node_modules/inherits/package.json | 50 - .../node_modules/inherits/test.js | 25 - .../node_modules/isarray/README.md | 54 - .../node_modules/isarray/build/build.js | 209 - .../node_modules/isarray/component.json | 19 - .../node_modules/isarray/index.js | 3 - .../node_modules/isarray/package.json | 53 - .../node_modules/string_decoder/.npmignore | 2 - .../node_modules/string_decoder/LICENSE | 20 - .../node_modules/string_decoder/README.md | 7 - .../node_modules/string_decoder/index.js | 221 - .../node_modules/string_decoder/package.json | 54 - .../node_modules/readable-stream/package.json | 69 - .../readable-stream/passthrough.js | 1 - .../node_modules/readable-stream/readable.js | 6 - .../node_modules/readable-stream/transform.js | 1 - .../node_modules/readable-stream/writable.js | 1 - .../node_modules/mongodb/package.json | 66 - .../node_modules/mongodb/t.js | 73 - .../node_modules/mongodb/t1.js | 77 - .../node_modules/mongodb/wercker.yml | 19 - util/demographicsImporter/package.json | 15 - 264 files changed, 3 insertions(+), 93300 deletions(-) delete mode 100644 util/demographicsImporter/node_modules/mongodb/HISTORY.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/LICENSE delete mode 100644 util/demographicsImporter/node_modules/mongodb/Makefile delete mode 100644 util/demographicsImporter/node_modules/mongodb/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/c.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/conf.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/index.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/admin.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/aggregation_cursor.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/apm.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/bulk/common.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/bulk/ordered.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/bulk/unordered.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/collection.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/command_cursor.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/cursor.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/db.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/gridfs/chunk.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/gridfs/grid_store.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/metadata.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/mongo_client.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/mongos.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/read_preference.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/replset.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/server.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/topology_base.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/url_parser.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/lib/utils.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/load.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/browserify.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/index.html delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/index.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Makefile delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d delete mode 100755 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node delete mode 100755 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos.node delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml delete mode 100755 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/asyncworker.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/buffers.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/callback.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/converters.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/errors.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/maybe_types.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/methods.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/new.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/node_misc.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/persistent.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/scopes.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/script.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/string_bytes.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/v8_internals.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/v8_misc.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/include_dirs.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks_12_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks_pre_12_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters_43_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters_pre_43_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_maybe_43_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_maybe_pre_43_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_new.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_object_wrap.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_persistent_12_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_persistent_pre_12_inl.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_string_bytes.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_weak.h delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/package.json delete mode 100755 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/1to2.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/readable.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/transform.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/writable.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/package.json delete mode 100644 util/demographicsImporter/node_modules/mongodb/t.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/t1.js delete mode 100644 util/demographicsImporter/node_modules/mongodb/wercker.yml delete mode 100644 util/demographicsImporter/package.json diff --git a/util/demographicsImporter/demographicsImporter.js b/util/demographicsImporter/demographicsImporter.js index 086b3f7..7a1a59d 100644 --- a/util/demographicsImporter/demographicsImporter.js +++ b/util/demographicsImporter/demographicsImporter.js @@ -93,19 +93,19 @@ MongoClient.connect('mongodb://localhost:27017/query_composer_development', func { continue; } - + var execution = JSON.parse(key); var date = execution.date/1000;//leave in milliseconds var simulatedExecution; - if(!execution.gender || !execution.age || !execution.pid || !execution.date) + if(!execution.gender || !execution.ageRange || !execution.pid || !execution.date) { throw new Error('Error: Missing field'); } var ar_key = execution.gender + '_' + - execution.age + '_' + + execution.ageRange + '_' + execution.pid; if(!simulatedExecutions[date]) diff --git a/util/demographicsImporter/node_modules/mongodb/HISTORY.md b/util/demographicsImporter/node_modules/mongodb/HISTORY.md deleted file mode 100644 index 4d8fd75..0000000 --- a/util/demographicsImporter/node_modules/mongodb/HISTORY.md +++ /dev/null @@ -1,1218 +0,0 @@ -2.0.45 09-30-2015 ------------------ -* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. - -2.0.44 09-28-2015 ------------------ -* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. -* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. -* Updated mongodb-core to 1.2.14. -* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. -* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) -* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. -* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. -* NODE-572 Remove examples that use the second parameter to `find()`. - -2.0.43 09-14-2015 ------------------ -* Propagate timeout event correctly to db instances. -* Application Monitoring API (APM) implemented. -* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. -* Updated mongodb-core to 1.2.12. -* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. -* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) -* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) -* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) - -2.0.42 08-18-2015 ------------------ -* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. - -2.0.41 08-14-2015 ------------------ -* Added missing Mongos.prototype.parserType function. -* Updated mongodb-core to 1.2.10. - -2.0.40 07-14-2015 ------------------ -* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. -* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -* NODE-518 connectTimeoutMS is doubled in 2.0.39. -* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). -* NODE-526 Unique index not throwing duplicate key error. -* NODE-528 Ignore undefined fields in Collection.find(). -* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. - -2.0.39 07-14-2015 ------------------ -* Updated mongodb-core to 1.2.6 for NODE-505. - -2.0.38 07-14-2015 ------------------ -* NODE-505 Query fails to find records that have a 'result' property with an array value. - -2.0.37 07-14-2015 ------------------ -* NODE-504 Collection * Default options when using promiseLibrary. -* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. -* Updated mongodb-core to 1.2.5 to fix NODE-492. - -2.0.36 07-07-2015 ------------------ -* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). -* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. - -2.0.35 06-17-2015 ------------------ -* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. - -2.0.34 06-17-2015 ------------------ -* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. -* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. -* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -2.0.33 05-20-2015 ------------------ -* Bumped mongodb-core to 1.1.32. - -2.0.32 05-19-2015 ------------------ -* NODE-463 db.close immediately executes its callback. -* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). -* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. - -2.0.31 05-08-2015 ------------------ -* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. - -2.0.30 05-07-2015 ------------------ -* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. - -2.0.29 05-07-2015 ------------------ -* NODE-444 Possible memory leak, too many listeners added. -* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. -* Bumped mongodb-core to 1.1.26. - -2.0.28 04-24-2015 ------------------ -* Bumped mongodb-core to 1.1.25 -* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. -* NODE-430 Cursor.count() opts argument masked by var opts = {} -* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. -* NODE-438 replaceOne is not returning the result.ops property as described in the docs. -* NODE-433 _read, pipe and write all open gridstore automatically if not open. -* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. -* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. -* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). -* Minor fix in GridStore.exists for dealing with regular expressions searches. - -2.0.27 04-07-2015 ------------------ -* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. - -2.0.26 04-07-2015 ------------------ -* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. -* NODE-408 Expose GridStore.currentChunk.chunkNumber. - -2.0.25 03-26-2015 ------------------ -* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. - -2.0.24 03-24-2015 ------------------ -* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. -* Upgraded mongodb-core to 1.1.20. - -2.0.23 2015-03-21 ------------------ -* NODE-380 Correctly return MongoError from toError method. -* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. -* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. -* Upgraded mongodb-core to 1.1.19. - -2.0.22 2015-03-16 ------------------ -* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. -* Upgraded mongodb-core to 1.1.17. - -2.0.21 2015-03-06 ------------------ -* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. - -2.0.20 2015-03-04 ------------------ -* Updated mongodb-core 1.1.15 to relax pickserver method. - -2.0.19 2015-03-03 ------------------ -* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) -* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) -* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) - -2.0.18 2015-02-27 ------------------ -* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. - -2.0.17 2015-02-27 ------------------ -* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. -* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. - -2.0.16 2015-02-16 ------------------ -* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. -* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. -* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) - -2.0.15 2015-02-02 ------------------ -* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. -* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. -* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. -* Added ~1.0 mongodb-tools module for test running. -* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -2.0.14 2015-01-21 ------------------ -* Fixed some MongoClient.connect options pass through issues and added test coverage. -* Bumped mongodb-core to 1.1.9 including fixes for io.js - -2.0.13 2015-01-09 ------------------ -* Bumped mongodb-core to 1.1.8. -* Optimized query path for performance, moving Object.defineProperty outside of constructors. - -2.0.12 2014-12-22 ------------------ -* Minor fixes to listCollections to ensure correct querying of a collection when using a string. - -2.0.11 2014-12-19 ------------------ -* listCollections filters out index namespaces on < 2.8 correctly -* Bumped mongo-client to 1.1.7 - -2.0.10 2014-12-18 ------------------ -* NODE-328 fixed db.open return when no callback available issue and added test. -* NODE-327 Refactored listCollections to return cursor to support 2.8. -* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. -* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. -* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) -* Bumped mongo-client to 1.1.6 - -2.0.9 2014-12-01 ----------------- -* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. -* All classes are now strict (Issue #1233) -* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. -* Fixed recursion issues in debug logging due to JSON.stringify() -* Documentation fixes (Issue #1232, https://github.com/wsmoak) -* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) - -2.0.8 2014-11-28 ----------------- -* NODE-322 Finished up prototype refactoring of Db class. -* NODE-322 Exposed Cursor in index.js for New Relic. - -2.0.7 2014-11-20 ----------------- -* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. -* NODE-318 collection.update error while setting a function with serializeFunctions option. -* Documentation fixes. - -2.0.6 2014-11-14 ----------------- -* Refactored code to be prototype based instead of privileged methods. -* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. -* Implemented missing aspects of the CRUD specification. -* Fixed documentation issues. -* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) -* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) - -2.0.5 2014-10-29 ----------------- -* Minor fixes to documentation and generation of documentation. -* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. - -2.0.4 2014-10-23 ----------------- -* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) -* Made each rewind on each call allowing for re-using the cursor. -* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. -* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. - -2.0.3 2014-10-14 ----------------- -* NODE-297 Aggregate Broken for case of pipeline with no options. - -2.0.2 2014-10-08 ----------------- -* Bumped mongodb-core to 1.0.2. -* Fixed bson module dependency issue by relying on the mongodb-core one. -* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) - -2.0.1 2014-10-07 ----------------- -* Dependency fix - -2.0.0 2014-10-07 ----------------- -* First release of 2.0 driver - -2.0.0-alpha2 2014-10-02 ------------------------ -* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) -* Cluster Management Spec compatible. - -2.0.0-alpha1 2014-09-08 ------------------------ -* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode -* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package -* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node -* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) - * Might break some application -* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove -* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) -* Removed Grid class -* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data - + seek will fail if attempt to use with w or w+ - + write will fail if attempted with w+ or r - + w+ only works for updating metadata on a file -* Cursor toArray and each resets and re-runs the cursor -* FindAndModify returns whole result document instead of just value -* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find -* Removed db.dereference method -* Removed db.cursorInfo method -* Removed db.stats method -* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections -* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. -* Added db.listCollections to replace several methods above - -1.4.10 2014-09-04 ------------------ -* Fixed BSON and Kerberos compilation issues -* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series -* Fixed Kerberos and bumped to 0.0.4 - -1.4.9 2014-08-26 ----------------- -* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) -* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) -* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) -* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) -* NODE-240 Operations on SSL connection hang on node 0.11.x -* NODE-235 writeResult is not being passed on when error occurs in insert -* NODE-229 Allow count to work with query hints -* NODE-233 collection.save() does not support fullResult -* NODE-244 Should parseError also emit a `disconnected` event? -* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. -* NODE-248 Crash with X509 auth -* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks -* Bumped BSON parser to 0.2.12 - - -1.4.8 2014-08-01 ----------------- -* NODE-205 correctly emit authenticate event -* NODE-210 ensure no undefined connection error when checking server state -* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones -* NODE-220 don't throw error if ensureIndex errors out in Gridstore -* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes -* Fixed test running filters -* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) -* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) -* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) -* Fixed parsing issue for w:0 in url parser when in connection string -* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) - -1.4.7 2014-06-18 ----------------- -* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) -* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) - -1.4.6 2014-06-12 ----------------- -* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) -* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) -* Added missing type check before calling optional callback function (Issue #1180) - -1.4.5 2014-05-21 ----------------- -* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. -* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. -* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) - -1.4.4 2014-05-13 ----------------- -* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID -* Removed leaking global variable (Issue #1174, https://github.com/dainis) -* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) -* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) - -1.4.3 2014-05-01 ----------------- -* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) -* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) -* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) -* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) -* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) -* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) - -1.4.2 2014-04-15 ----------------- -* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 -* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) -* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) -* Fixed global variable leak (Issue #1160, https://github.com/vaseker) - -1.4.1 2014-04-09 ----------------- -* Correctly emit joined event when primary change -* Add _id to documents correctly when using bulk operations - -1.4.0 2014-04-03 ----------------- -* All node exceptions will no longer be caught if on('error') is defined -* Added X509 auth support -* Fix for MongoClient connection timeout issue (NODE-97) -* Pass through error messages from parseError instead of just text (Issue #1125) -* Close db connection on error (Issue #1128, https://github.com/benighted) -* Fixed documentation generation -* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) -* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 -* Insert/Update/Remove using new write commands when available -* Added support for new roles based API's in 2.6 for addUser/removeUser -* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries -* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes -* Support for OP_LOG_REPLAY flag (NODE-94) -* Fixes for SSL HA ping and discovery. -* Uses createIndexes if available for ensureIndex/createIndex -* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors -* Made CommandCursor behave as Readable stream. -* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. -* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. -* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) -* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. -* Refactored commands to all go through command function ensuring consistent command execution. -* Fixed issues where readPreferences where not correctly passed to mongos. -* Catch error == null and make err detection more prominent (NODE-130) -* Allow reads from arbiter for single server connection (NODE-117) -* Handle error coming back with no documents (NODE-130) -* Correctly use close parameter in Gridstore.write() (NODE-125) -* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) -* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) -* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) -* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) -* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) -* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) -* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) -* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) -* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) -* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) -* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) - -1.3.19 2013-08-21 ------------------ -* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. -* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) -* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) - -1.3.18 2013-08-10 ------------------ -* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) -* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. - -1.3.17 2013-08-07 ------------------ -* Ignore return commands that have no registered callback -* Made collection.count not use the db.command function -* Fix throw exception on ping command (Issue #1055) - -1.3.16 2013-08-02 ------------------ -* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) -* Bug in unlink mulit filename (Issue #1054) - -1.3.15 2013-08-01 ------------------ -* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time - -1.3.14 2013-08-01 ------------------ -* Fixed issue with checkKeys where it would error on X.X - -1.3.13 2013-07-31 ------------------ -* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) -* BSON size checking now done pre serialization (Issue #1037) -* Added isConnected returns false when no connection Pool exists (Issue #1043) -* Unified command handling to ensure same handling (Issue #1041, #1042) -* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) -* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. -* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. -* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. -* Fixed issue with Kerberos authentication on Windows for re-authentication. -* Fixed Mongos failover behavior to correctly throw out old servers. -* Ensure stored queries/write ops are executed correctly after connection timeout -* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. - -1.3.12 2013-07-19 ------------------ -* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) -* Fixed bug with callback third parameter on some commands (Issue #1033) -* Fixed possible issue where killcursor command might leave hanging functions -* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers -* Throw error if dbName or collection name contains null character (at command level and at collection level) -* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) - -1.3.11 2013-07-04 ------------------ -* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) -* Add driver version to export (Issue #1021, https://github.com/aheckmann) -* Add text to readpreference obedient commands (Issue #1019) -* Drivers should check the query failure bit even on getmore response (Issue #1018) -* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) -* Support SASL PLAIN authentication (Issue #1009) -* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) -* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) -* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) - -1.3.10 2013-06-17 ------------------ -* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) -* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) -* Introduced write and read concerns for GridFS (Issue #996) -* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) -* Fixed issue with pool size on replicaset connections (Issue #1000) -* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) - -1.3.9 2013-06-05 ----------------- -* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. - -1.3.8 2013-05-31 ----------------- -* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) -* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) -* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. - -1.3.7 2013-05-29 ----------------- -* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) -* Updated Bson to 0.1.9 to fix ARM support (Issue #985) - -1.3.6 2013-05-21 ----------------- -* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) -* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) - -1.3.5 2013-05-14 ----------------- -* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. - -1.3.4 2013-05-14 ----------------- -* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) -* Fixed bug when passing a named index hint (Issue #974) - -1.3.3 2013-05-09 ----------------- -* Fixed auto-reconnect issue with single server instance. - -1.3.2 2013-05-08 ----------------- -* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. - -1.3.1 2013-05-06 ----------------- -* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly -* Applied auth before server instance is set as connected when single server connection -* Throw error if array of documents passed to save method - -1.3.0 2013-04-25 ----------------- -* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. -* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) -* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) -* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) -* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition -* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) - -1.2.14 2013-03-14 ------------------ -* Refactored test suite to speed up running of replicaset tests -* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) -* Corrected a slaveOk setting issue (Issue #906, #905) -* Fixed HA issue where ping's would not go to correct server on HA server connection failure. -* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream -* Fixed race condition in Cursor stream (NODE-31) -* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 -* Added support for maxMessageSizeBytes if available (DRIVERS-1) -* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) -* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) - -1.2.13 2013-02-22 ------------------ -* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) -* Fixed missing MongoErrors on some cursor methods (Issue #882) -* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) -* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) -* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) - -1.2.12 2013-02-13 ------------------ -* Added limit/skip options to Collection.count (Issue #870) -* Added applySkipLimit option to Cursor.count (Issue #870) -* Enabled ping strategy as default for Replicaset if none specified (Issue #876) -* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) - -1.2.11 2013-01-29 ------------------ -* Added fixes for handling type 2 binary due to PHP driver (Issue #864) -* Moved callBackStore to Base class to have single unified store (Issue #866) -* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead - -1.2.10 2013-01-25 ------------------ -* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. -* Only open a new HA socket when previous one dead (Issue #859, #857) -* Minor fixes - -1.2.9 2013-01-15 ----------------- -* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) -* Connection string with no db specified should default to admin db (Issue #848) -* Support port passed as string to Server class (Issue #844) -* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) -* Included toError wrapper code moved to utils.js file (Issue #839, #840) -* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% - -1.2.8 2013-01-07 ----------------- -* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) -* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) -* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) -* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) -* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) -* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) -* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) -* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) - -1.2.7 2012-12-23 ----------------- -* Rolled back batches as they hang in certain situations -* Fixes for NODE-25, keep reading from secondaries when primary goes down - -1.2.6 2012-12-21 ----------------- -* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) -* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) -* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) -* Cursor readPreference bug for non-supported read preferences (Issue #817) - -1.2.5 2012-12-12 ----------------- -* Fixed ssl regression, added more test coverage (Issue #800) -* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) - -1.2.4 2012-12-11 ----------------- -* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. - -1.2.3 2012-12-10 ----------------- -* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) -* Fixed seek issue in gridstore when using stream (Issue #790) - -1.2.2 2012-12-03 ----------------- -* Fix for journal write concern not correctly being passed under some circumstances. -* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). - -1.2.1 2012-11-30 ----------------- -* Fix for double callback on insert with w:0 specified (Issue #783) -* Small cleanup of urlparser. - -1.2.0 2012-11-27 ----------------- -* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) -* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) -* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) -* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) -* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) -* Force correct setting of read_secondary based on the read preference (Issue #741) -* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) -* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type -* Mongos connection with auth not working (Issue #737) -* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") -* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db - * open/close/db/connect methods implemented -* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. -* Fixed a bug with aggregation helper not properly accepting readPreference - -1.1.11 2012-10-10 ------------------ -* Removed strict mode and introduced normal handling of safe at DB level. - -1.1.10 2012-10-08 ------------------ -* fix Admin.serverStatus (Issue #723, https://github.com/Contra) -* logging on connection open/close(Issue #721, https://github.com/asiletto) -* more fixes for windows bson install (Issue #724) - -1.1.9 2012-10-05 ----------------- -* Updated bson to 0.1.5 to fix build problem on sunos/windows. - -1.1.8 2012-10-01 ----------------- -* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) -* Cleanup of non-closing connections (Issue #706) -* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) -* Set keepalive on as default, override if not needed -* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) -* Added domain socket support new Server("/tmp/mongodb.sock") style - -1.1.7 2012-09-10 ----------------- -* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) -* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) -* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) -* Proper stopping of strategy on replicaset stop -* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) -* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) - -1.1.6 2012-09-01 ----------------- -* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) -* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) - -1.1.5 2012-08-29 ----------------- -* Fix for eval on replicaset Issue #684 -* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) -* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) -* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X -* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes -* Added exhaust option for find for feature completion (not recommended for normal use) -* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval -* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) - -1.1.4 2012-08-12 ----------------- -* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. -* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. -* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). -* Fix gridfs readstream (Issue #607, https://github.com/tedeh). -* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). -* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). -* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). -* Cleanup map reduce (Issue #614, https://github.com/aheckmann). -* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). -* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. -* Date identification handled correctly in bson js parser when running in vm context. -* Documentation updates -* GridStore filename not set on read (Issue #621) -* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls -* Added support for awaitdata for tailable cursors (Issue #624) -* Implementing read preference setting at collection and cursor level - * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) - * db.collection("some", {readPreference:Server.SECONDARY}) -* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. - * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to -* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) -* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 -* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) -* Fixed auth to work better when multiple connections are involved. -* Default connection pool size increased to 5 connections. -* Fixes for the ReadStream class to work properly with 0.8 of Node.js -* Added explain function support to aggregation helper -* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js -* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required -* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) -* Fixed Always emit db events (Issue #657) -* Close event not correctly resets DB openCalled variable to allow reconnect -* Added open event on connection established for replicaset, mongos and server -* Much faster BSON C++ parser thanks to Lucasfilm Singapore. -* Refactoring of replicaset connection logic to simplify the code. -* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) -* Minor optimization for findAndModify when not using j,w or fsync for safe - -1.0.2 2012-05-15 ----------------- -* Reconnect functionality for replicaset fix for mongodb 2.0.5 - -1.0.1 2012-05-12 ----------------- -* Passing back getLastError object as 3rd parameter on findAndModify command. -* Fixed a bunch of performance regressions in objectId and cursor. -* Fixed issue #600 allowing for single document delete to be passed in remove command. - -1.0.0 2012-04-25 ----------------- -* Fixes to handling of failover on server error -* Only emits error messages if there are error listeners to avoid uncaught events -* Server.isConnected using the server state variable not the connection pool state - -0.9.9.8 2012-04-12 ------------------- -* _id=0 is being turned into an ObjectID (Issue #551) -* fix for error in GridStore write method (Issue #559) -* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) -* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) -* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) -* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) -* Connection pools handles closing themselves down and clearing the state -* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) -* Returning update status document at the end of the callback for updates, (Issue #569) -* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) - -0.9.9.7 2012-03-16 ------------------- -* Stats not returned from map reduce with inline results (Issue #542) -* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) -* Streaming large files from GridFS causes truncation (Issue #540) -* Make callback type checks agnostic to V8 context boundaries (Issue #545) -* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback -* Db.open throws if the application attemps to call open again without calling close first - -0.9.9.6 2012-03-12 ------------------- -* BSON parser is externalized in it's own repository, currently using git master -* Fixes for Replicaset connectivity issue (Issue #537) -* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) -* Removed SimpleEmitter and replaced with standard EventEmitter -* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) - -0.9.9.5 2012-03-07 ------------------- -* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) -* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) -* Fixed memory leak in C++ bson parser (Issue #526) -* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) -* Cannot save files with the same file name to GridFS (Issue #531) - -0.9.9.4 2012-02-26 ------------------- -* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) - -0.9.9.3 2012-02-23 ------------------- -* document: save callback arguments are both undefined, (Issue #518) -* Native BSON parser install error with npm, (Issue #517) - -0.9.9.2 2012-02-17 ------------------- -* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. -* Added wrap error around db.dropDatabase to catch all errors (Issue #512) -* Added aggregate helper to collection, only for MongoDB >= 2.1 - -0.9.9.1 2012-02-15 ------------------- -* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. -* Mapreduce now throws error if out parameter is not specified. - -0.9.9 2012-02-13 ----------------- -* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. -* Db.close(true) now makes connection unusable as it's been force closed by app. -* Fixed mapReduce and group functions to correctly send slaveOk on queries. -* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). -* A fix for connection error handling when using the SSL on MongoDB. - -0.9.8-7 2012-02-06 ------------------- -* Simplified findOne to use the find command instead of the custom code (Issue #498). -* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). - -0.9.8-6 2012-02-04 ------------------- -* Removed the check for replicaset change code as it will never work with node.js. - -0.9.8-5 2012-02-02 ------------------- -* Added geoNear command to Collection. -* Added geoHaystackSearch command to Collection. -* Added indexes command to collection to retrieve the indexes on a Collection. -* Added stats command to collection to retrieve the statistics on a Collection. -* Added listDatabases command to admin object to allow retrieval of all available dbs. -* Changed createCreateIndexCommand to work better with options. -* Fixed dereference method on Db class to correctly dereference Db reference objects. -* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. -* Removed writeBuffer method from gridstore, write handles switching automatically now. -* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. -* Moved Long class to bson directory. - -0.9.8-4 2012-01-28 ------------------- -* Added reIndex command to collection and db level. -* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. -* Added dropDups and v option to createIndex and ensureIndex. -* Added isCapped method to Collection. -* Added indexExists method to Collection. -* Added findAndRemove method to Collection. -* Fixed bug for replicaset connection when no active servers in the set. -* Fixed bug for replicaset connections when errors occur during connection. -* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. - -0.9.8-3 2012-01-21 ------------------- -* Workaround for issue with Object.defineProperty (Issue #484) -* ObjectID generation with date does not set rest of fields to zero (Issue #482) - -0.9.8-2 2012-01-20 ------------------- -* Fixed a missing this in the ReplSetServers constructor. - -0.9.8-1 2012-01-17 ------------------- -* FindAndModify bug fix for duplicate errors (Issue #481) - -0.9.8 2012-01-17 ----------------- -* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. - * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) -* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh -* Removed duplicate code for formattedOrderClause and moved to utils module -* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members -* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations -* Correct handling of illegal BSON messages during deserialization -* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) -* Correctly update existing user password when using addUser (Issue #470) - -0.9.7.3-5 2012-01-04 --------------------- -* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' -* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors - -0.9.7.3-4 2012-01-04 --------------------- -* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) -* Sanity checks for GridFS performance with benchmark added - -0.9.7.3-3 2012-01-04 --------------------- -* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux -* BSON bug fixes for performance - -0.9.7.3-2 2012-01-02 --------------------- -* Fixed up documentation to reflect the preferred way of instantiating bson types -* GC bug fix for JS bson parser to avoid stop-and-go GC collection - -0.9.7.3-1 2012-01-02 --------------------- -* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously - -0.9.7.3 2011-12-30 --------------------- -* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes -* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) -* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 -* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) -* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) - -0.9.7.2-5 2011-12-22 --------------------- -* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann - -0.9.7.2-4 2011-12-21 --------------------- -* Refactoring of callback code to work around performance regression on linux -* Fixed group function to correctly use the command mode as default - -0.9.7.2-3 2011-12-18 --------------------- -* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). -* Allow for force send query to primary, pass option (read:'primary') on find command. - * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` - -0.9.7.2-2 2011-12-16 --------------------- -* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) - -0.9.7.2-1 2011-12-16 --------------------- -* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) -* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver -* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents - -0.9.7.2 2011-12-15 ------------------- -* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) - * pass in the ssl:true option to the server or replicaset server config to enable - * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). -* Added getTimestamp() method to objectID that returns a date object -* Added finalize function to collection.group - * function group (keys, condition, initial, reduce, finalize, command, callback) -* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. - * reaperInterval, set interval for reaper (default 10000 miliseconds) - * reaperTimeout, set timeout for calls (default 30000 miliseconds) - * reaper, enable/disable reaper (default false) -* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb -* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close -* EnsureIndex command can be executed without a callback (Issue #438) -* Eval function no accepts options including nolock (Issue #432) - * eval(code, parameters, options, callback) (where options = {nolock:true}) - -0.9.7.1-4 2011-11-27 --------------------- -* Replaced install.sh with install.js to install correctly on all supported os's - -0.9.7.1-3 2011-11-27 --------------------- -* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch - -0.9.7.1-2 2011-11-27 --------------------- -* Set statistical selection strategy as default for secondary choice. - -0.9.7.1-1 2011-11-27 --------------------- -* Better handling of single server reconnect (fixes some bugs) -* Better test coverage of single server failure -* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect - -0.9.7.1 2011-11-24 ------------------- -* Better handling of dead server for single server instances -* FindOne and find treats selector == null as {}, Issue #403 -* Possible to pass in a strategy for the replicaset to pick secondary reader node - * parameter strategy - * ping (default), pings the servers and picks the one with the lowest ping time - * statistical, measures each request and pick the one with the lowest mean and std deviation -* Set replicaset read preference replicaset.setReadPreference() - * Server.READ_PRIMARY (use primary server for reads) - * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) - * tags, {object of tags} -* Added replay of commands issued to a closed connection when the connection is re-established -* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) -* Moved reaper to db.open instead of constructor (Issue #406) -* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions - * timeout = set seconds before connection times out (default 0) - * noDelay = Disables the Nagle algorithm (default true) - * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) - * encoding = ['ascii', 'utf8', or 'base64'] (default null) -* Fixes for handling of errors during shutdown off a socket connection -* Correctly applies socket options including timeout -* Cleanup of test management code to close connections correctly -* Handle parser errors better, closing down the connection and emitting an error -* Correctly emit errors from server.js only wrapping errors that are strings - -0.9.7 2011-11-10 ----------------- -* Added priority setting to replicaset manager -* Added correct handling of passive servers in replicaset -* Reworked socket code for simpler clearer handling -* Correct handling of connections in test helpers -* Added control of retries on failure - * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance -* Added reaper that will timeout and cleanup queries that never return - * control with parameters reaperInterval and reaperTimeout when creating a db instance -* Refactored test helper classes for replicaset tests -* Allows raw (no bson parser mode for insert, update, remove, find and findOne) - * control raw mode passing in option raw:true on the commands - * will return buffers with the binary bson objects -* Fixed memory leak in cursor.toArray -* Fixed bug in command creation for mongodb server with wrong scope of call -* Added db(dbName) method to db.js to allow for reuse of connections against other databases -* Serialization of functions in an object is off by default, override with parameter - * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify -* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) -* FindOne and find now share same code execution and will work in the same manner, Issue #399 -* Fix for tailable cursors, Issue #384 -* Fix for Cursor rewind broken, Issue #389 -* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) -* Updated documentation on https://github.com/christkv/node-mongodb-native -* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data - -0.9.6-22 2011-10-15 -------------------- -* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 -* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 - -0.9.6-21 2011-10-05 -------------------- -* Reworked reconnect code to work correctly -* Handling errors in different parts of the code to ensure that it does not lock the connection -* Consistent error handling for Object.createFromHexString for JS and C++ - -0.9.6-20 2011-10-04 -------------------- -* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc -* Reworked bson.cc to throw error when trying to serialize js bson types -* Added MinKey, MaxKey and Double support for JS and C++ parser -* Reworked socket handling code to emit errors on unparsable messages -* Added logger option for Db class, lets you pass in a function in the shape - { - log : function(message, object) {}, - error : function(errorMessage, errorObject) {}, - debug : function(debugMessage, object) {}, - } - - Usage is new Db(new Server(..), {logger: loggerInstance}) - -0.9.6-19 2011-09-29 -------------------- -* Fixing compatibility issues between C++ bson parser and js parser -* Added Symbol support to C++ parser -* Fixed socket handling bug for seldom misaligned message from mongodb -* Correctly handles serialization of functions using the C++ bson parser - -0.9.6-18 2011-09-22 -------------------- -* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 - -0.9.6-17 2011-09-21 -------------------- -* Fixed broken exception test causing bamboo to hang -* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 - -0.9.6-16 2011-09-14 -------------------- -* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. -* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 - -0.9.6-15 2011-09-09 -------------------- -* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 -* Fixed authentication issue with secondary servers in Replicaset, Issue #334 -* Duplicate replica-set servers when omitting port, Issue #341 -* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 -* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks - -0.9.6-14 2011-09-05 -------------------- -* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 -* Minor doc fixes -* Some more cursor sort tests added, Issue #333 -* Fixes to work with 0.5.X branch -* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 -* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 -* Implement correct safe/strict mode for findAndModify. - -0.9.6-13 2011-08-24 -------------------- -* Db names correctly error checked for illegal characters - -0.9.6-12 2011-08-24 -------------------- -* Nasty bug in GridFS if you changed the default chunk size -* Fixed error handling bug in findOne - -0.9.6-11 2011-08-23 -------------------- -* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) -* Fixes for memory leaks when using buffers and C++ parser -* Fixes to make tests pass on 0.5.X -* Cleanup of bson.js to remove duplicated code paths -* Fix for errors occurring in ensureIndex, Issue #326 -* Removing require.paths to make tests work with the 0.5.X branch - -0.9.6-10 2011-08-11 -------------------- -* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 -* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 -* Implementing fixes for mongodb 1.9.1 and higher to make tests pass -* Admin validateCollection now takes an options argument for you to pass in full option -* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 -* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 - -0.9.6-9 -------- -* Bug fix for bson parsing the key '':'' correctly without crashing - -0.9.6-8 -------- -* Changed to using node.js crypto library MD5 digest -* Connect method support documented mongodb: syntax by (https://github.com/sethml) -* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 -* Code object without scope serializing to correct BSON type -* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 -* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) -* Fixed C++ parser to reflect JS parser handling of long deserialization -* Bson small optimizations - -0.9.6-7 2011-07-13 ------------------- -* JS Bson deserialization bug #287 - -0.9.6-6 2011-07-12 ------------------- -* FindAndModify not returning error message as other methods Issue #277 -* Added test coverage for $push, $pushAll and $inc atomic operations -* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 -* Fixed terrible deserialization bug in js bson code #285 -* Fix by andrewjstone to avoid throwing errors when this.primary not defined - -0.9.6-5 2011-07-06 ------------------- -* Rewritten BSON js parser now faster than the C parser on my core2duo laptop -* Added option full to indexInformation to get all index info Issue #265 -* Passing in ObjectID for new Gridstore works correctly Issue #272 - -0.9.6-4 2011-07-01 ------------------- -* Added test and bug fix for insert/update/remove without callback supplied - -0.9.6-3 2011-07-01 ------------------- -* Added simple grid class called Grid with put, get, delete methods -* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly -* Automatic handling of buffers when using write method on GridStore -* GridStore now accepts a ObjectID instead of file name for write and read methods -* GridStore.list accepts id option to return of file ids instead of filenames -* GridStore close method returns document for the file allowing user to reference _id field - -0.9.6-2 2011-06-30 ------------------- -* Fixes for reconnect logic for server object (replays auth correctly) -* More testcases for auth -* Fixes in error handling for replicaset -* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout -* Fixed slaveOk bug for findOne method -* Implemented auth support for replicaset and test cases -* Fixed error when not passing in rs_name - -0.9.6-1 2011-06-25 ------------------- -* Fixes for test to run properly using c++ bson parser -* Fixes for dbref in native parser (correctly handles ref without db component) -* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) -* Fixes for timestamp in js bson parser (distinct timestamp type now) - -0.9.6 2011-06-21 ----------------- -* Worked around npm version handling bug -* Race condition fix for cygwin (https://github.com/vincentcr) - -0.9.5-1 2011-06-21 ------------------- -* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems -* Fixed driver strict mode issue - -0.9.5 2011-06-20 ----------------- -* Replicaset support (failover and reading from secondary servers) -* Removed ServerPair and ServerCluster -* Added connection pool functionality -* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences -* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} - -0.6.8 ------ -* Removed multiple message concept from bson -* Changed db.open(db) to be db.open(err, db) - -0.1 2010-01-30 --------------- -* Initial release support of driver using native node.js interface -* Supports gridfs specification -* Supports admin functionality diff --git a/util/demographicsImporter/node_modules/mongodb/LICENSE b/util/demographicsImporter/node_modules/mongodb/LICENSE deleted file mode 100644 index ad410e1..0000000 --- a/util/demographicsImporter/node_modules/mongodb/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/Makefile b/util/demographicsImporter/node_modules/mongodb/Makefile deleted file mode 100644 index 36e1202..0000000 --- a/util/demographicsImporter/node_modules/mongodb/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -NODE = node -NPM = npm -JSDOC = jsdoc -name = all - -generate_docs: - # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md - hugo -s docs/reference -d ../../public - $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api - cp -R ./public/api/scripts ./public/. - cp -R ./public/api/styles ./public/. diff --git a/util/demographicsImporter/node_modules/mongodb/README.md b/util/demographicsImporter/node_modules/mongodb/README.md deleted file mode 100644 index 2828713..0000000 --- a/util/demographicsImporter/node_modules/mongodb/README.md +++ /dev/null @@ -1,322 +0,0 @@ -[![NPM](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![NPM](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) - -[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.png)](http://travis-ci.org/mongodb/node-mongodb-native) - -[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -# Description - -The MongoDB driver is the high level part of the 2.0 or higher MongoDB driver and is meant for end users. - -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native/ | -| api-doc | http://mongodb.github.io/node-mongodb-native/2.0/api/ | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org/ | - -### Blogs of Engineers involved in the driver -- Christian Kvalheim [@christkv](https://twitter.com/christkv) - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a -case in our issue management tool, JIRA: - -- Create an account and login . -- Navigate to the NODE project . -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Questions and Bug Reports - - * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native - * jira: http://jira.mongodb.org/ - -### Change Log - -http://jira.mongodb.org/browse/NODE - -QuickStart -========== -The quick start guide will show you how to setup a simple application using node.js and MongoDB. Its scope is only how to set up the driver and perform the simple crud operations. For more in depth coverage we encourage reading the tutorials. - -Create the package.json file ----------------------------- -Let's create a directory where our application will live. In our case we will put this under our projects directory. - -``` -mkdir myproject -cd myproject -``` - -Enter the following command and answer the questions to create the initial structure for your new project - -``` -npm init -``` - -Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init` - -``` -{ - "name": "myproject", - "version": "1.0.0", - "description": "My first project", - "main": "index.js", - "repository": { - "type": "git", - "url": "git://github.com/christkv/myfirstproject.git" - }, - "dependencies": { - "mongodb": "~2.0" - }, - "author": "Christian Kvalheim", - "license": "Apache 2.0", - "bugs": { - "url": "https://github.com/christkv/myfirstproject/issues" - }, - "homepage": "https://github.com/christkv/myfirstproject" -} -``` - -Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. - -``` -npm install -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -Booting up a MongoDB Server ---------------------------- -Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). - -``` -mongod --dbpath=/data --port 27017 -``` - -You should see the **mongod** process start up and print some status information. - -Connecting to MongoDB ---------------------- -Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. - -First let's add code to connect to the server and the database **myproject**. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - db.close(); -}); -``` - -Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console. - -Let's Add some code to show the different CRUD operations available. - -Inserting a Document --------------------- -Let's create a function that will insert some documents for us. - -```js -var insertDocuments = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Insert some documents - collection.insert([ - {a : 1}, {a : 2}, {a : 3} - ], function(err, result) { - assert.equal(err, null); - assert.equal(3, result.result.n); - assert.equal(3, result.ops.length); - console.log("Inserted 3 documents into the document collection"); - callback(result); - }); -} -``` - -The insert command will return a results object that contains several fields that might be useful. - -* **result** Contains the result document from MongoDB -* **ops** Contains the documents inserted with added **_id** fields -* **connection** Contains the connection used to perform the insert - -Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - db.close(); - }); -}); -``` - -We can now run the update **app.js** file. - -``` -node app.js -``` - -You should see the following output after running the **app.js** file. - -``` -Connected correctly to server -Inserted 3 documents into the document collection -``` - -Updating a document -------------------- -Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**. - -```js -var updateDocument = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Update document where a is 2, set b equal to 1 - collection.update({ a : 2 } - , { $set: { b : 1 } }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Updated the document with the field a equal to 2"); - callback(result); - }); -} -``` - -The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - updateDocument(db, function() { - db.close(); - }); - }); -}); -``` - -Remove a document ------------------ -Next lets remove the document where the field **a** equals to **3**. - -```js -var removeDocument = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Insert some documents - collection.remove({ a : 3 }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Removed the document with the field a equal to 3"); - callback(result); - }); -} -``` - -This will remove the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient.connect** callback function. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - db.close(); - }); - }); - }); -}); -``` - -Finally let's retrieve all the documents using a simple find. - -Find All Documents ------------------- -We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query. - -```js -var findDocuments = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Find some documents - collection.find({}).toArray(function(err, docs) { - assert.equal(err, null); - assert.equal(2, docs.length); - console.log("Found the following records"); - console.dir(docs); - callback(docs); - }); -} -``` - -This query will return all the documents in the **documents** collection. Since we removed a document the total documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - findDocuments(db, function() { - db.close(); - }); - }); - }); - }); -}); -``` - -This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest. - -## Next Steps - - * [MongoDB Documentation](http://mongodb.org/) - * [Read about Schemas](http://learnmongodbthehardway.com/) - * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) diff --git a/util/demographicsImporter/node_modules/mongodb/c.js b/util/demographicsImporter/node_modules/mongodb/c.js deleted file mode 100644 index 5b6bc1e..0000000 --- a/util/demographicsImporter/node_modules/mongodb/c.js +++ /dev/null @@ -1,24 +0,0 @@ -var MongoClient = require('./').MongoClient; - -var index = 0; - -MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { - setInterval(function() { - db = db.db("index" + index, {noListener:true}); - var collection = db.collection("index" + index); - collection.insert({a:index}) - }, 1); -}); - -// var Server = require('./').Server, -// Db = require('./').Db, -// ReadPreference = require('./').ReadPreference; -// -// new Db('test', new Server('localhost', 31001), {readPreference: ReadPreference.SECONDARY}).open(function(err, db) { -// -// db.collection('test').find().toArray(function(err, docs) { -// console.dir(err) -// console.dir(docs) -// db.close(); -// }); -// }); diff --git a/util/demographicsImporter/node_modules/mongodb/conf.json b/util/demographicsImporter/node_modules/mongodb/conf.json deleted file mode 100644 index 15f3021..0000000 --- a/util/demographicsImporter/node_modules/mongodb/conf.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], - "source": { - "include": [ - "test/functional/operation_example_tests.js", - "test/functional/operation_promises_example_tests.js", - "test/functional/operation_generators_example_tests.js", - "test/functional/authentication_tests.js", - "lib/admin.js", - "lib/collection.js", - "lib/cursor.js", - "lib/aggregation_cursor.js", - "lib/command_cursor.js", - "lib/db.js", - "lib/mongo_client.js", - "lib/mongos.js", - "lib/read_preference.js", - "lib/replset.js", - "lib/server.js", - "lib/bulk/common.js", - "lib/bulk/ordered.js", - "lib/bulk/unordered.js", - "lib/gridfs/grid_store.js", - "node_modules/mongodb-core/lib/error.js", - "node_modules/mongodb-core/lib/connection/logger.js", - "node_modules/bson/lib/bson/binary.js", - "node_modules/bson/lib/bson/code.js", - "node_modules/bson/lib/bson/db_ref.js", - "node_modules/bson/lib/bson/double.js", - "node_modules/bson/lib/bson/long.js", - "node_modules/bson/lib/bson/objectid.js", - "node_modules/bson/lib/bson/symbol.js", - "node_modules/bson/lib/bson/timestamp.js", - "node_modules/bson/lib/bson/max_key.js", - "node_modules/bson/lib/bson/min_key.js" - ] - }, - "templates": { - "cleverLinks": true, - "monospaceLinks": true, - "default": { - "outputSourceFiles" : true - }, - "applicationName": "Node.js MongoDB Driver API", - "disqus": true, - "googleAnalytics": "UA-29229787-1", - "openGraph": { - "title": "", - "type": "website", - "image": "", - "site_name": "", - "url": "" - }, - "meta": { - "title": "", - "description": "", - "keyword": "" - }, - "linenums": true - }, - "markdown": { - "parser": "gfm", - "hardwrap": true, - "tags": ["examples"] - }, - "examples": { - "indent": 4 - } -} diff --git a/util/demographicsImporter/node_modules/mongodb/index.js b/util/demographicsImporter/node_modules/mongodb/index.js deleted file mode 100644 index df24555..0000000 --- a/util/demographicsImporter/node_modules/mongodb/index.js +++ /dev/null @@ -1,47 +0,0 @@ -// Core module -var core = require('mongodb-core'), - Instrumentation = require('./lib/apm'); - -// Set up the connect function -var connect = require('./lib/mongo_client').connect; - -// Expose error class -connect.MongoError = core.MongoError; - -// Actual driver classes exported -connect.MongoClient = require('./lib/mongo_client'); -connect.Db = require('./lib/db'); -connect.Collection = require('./lib/collection'); -connect.Server = require('./lib/server'); -connect.ReplSet = require('./lib/replset'); -connect.Mongos = require('./lib/mongos'); -connect.ReadPreference = require('./lib/read_preference'); -connect.GridStore = require('./lib/gridfs/grid_store'); -connect.Chunk = require('./lib/gridfs/chunk'); -connect.Logger = core.Logger; -connect.Cursor = require('./lib/cursor'); - -// BSON types exported -connect.Binary = core.BSON.Binary; -connect.Code = core.BSON.Code; -connect.DBRef = core.BSON.DBRef; -connect.Double = core.BSON.Double; -connect.Long = core.BSON.Long; -connect.MinKey = core.BSON.MinKey; -connect.MaxKey = core.BSON.MaxKey; -connect.ObjectID = core.BSON.ObjectID; -connect.ObjectId = core.BSON.ObjectID; -connect.Symbol = core.BSON.Symbol; -connect.Timestamp = core.BSON.Timestamp; - -// Add connect method -connect.connect = connect; - -// Set up the instrumentation method -connect.instrument = function(options, callback) { - if(typeof options == 'function') callback = options, options = {}; - return new Instrumentation(core, options, callback); -} - -// Set our exports to be the connect function -module.exports = connect; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/admin.js b/util/demographicsImporter/node_modules/mongodb/lib/admin.js deleted file mode 100644 index 1f89512..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/admin.js +++ /dev/null @@ -1,581 +0,0 @@ -"use strict"; - -var toError = require('./utils').toError, - Define = require('./metadata'), - shallowClone = require('./utils').shallowClone; - -/** - * @fileOverview The **Admin** class is an internal class that allows convenient access to - * the admin functionality and commands for MongoDB. - * - * **ADMIN Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Use the admin database for the operation - * var adminDb = db.admin(); - * - * // List all the available databases - * adminDb.listDatabases(function(err, dbs) { - * test.equal(null, err); - * test.ok(dbs.databases.length > 0); - * db.close(); - * }); - * }); - */ - -/** - * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {Admin} a collection instance. - */ -var Admin = function(db, topology, promiseLibrary) { - if(!(this instanceof Admin)) return new Admin(db, topology); - var self = this; - - // Internal state - this.s = { - db: db - , topology: topology - , promiseLibrary: promiseLibrary - } -} - -var define = Admin.define = new Define('Admin', Admin, false); - -/** - * The callback format for results - * @callback Admin~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.command = function(command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - - // Execute using callback - if(typeof callback == 'function') return this.s.db.executeDbAdminCommand(command, options, function(err, doc) { - return callback != null ? callback(err, doc) : null; - }); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand(command, options, function(err, doc) { - if(err) return reject(err); - resolve(doc); - }); - }); -} - -define.classMethod('command', {callback: true, promise:true}); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.buildInfo = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return this.serverInfo(callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.serverInfo(function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('buildInfo', {callback: true, promise:true}); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverInfo = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err != null) return callback(err, null); - callback(null, doc); - }); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err) return reject(err); - resolve(doc); - }); - }); -} - -define.classMethod('serverInfo', {callback: true, promise:true}); - -/** - * Retrieve this db's server status. - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverStatus = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return serverStatus(self, callback) - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - serverStatus(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var serverStatus = function(self, callback) { - self.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { - if(err == null && doc.ok === 1) { - callback(null, doc); - } else { - if(err) return callback(err, false); - return callback(toError(doc), false); - } - }); -} - -define.classMethod('serverStatus', {callback: true, promise:true}); - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.profilingLevel = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return profilingLevel(self, callback) - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - profilingLevel(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var profilingLevel = function(self, callback) { - self.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) { - doc = doc; - - if(err == null && doc.ok === 1) { - var was = doc.was; - if(was == 0) return callback(null, "off"); - if(was == 1) return callback(null, "slow_only"); - if(was == 2) return callback(null, "all"); - return callback(new Error("Error: illegal profiling level value " + was), null); - } else { - err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - } - }); -} - -define.classMethod('profilingLevel', {callback: true, promise:true}); - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.ping = function(options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - - // Execute using callback - if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({ping: 1}, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand({ping: 1}, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('ping', {callback: true, promise:true}); - -/** - * Authenticate a user against the server. - * @method - * @param {string} username The username. - * @param {string} [password] The password. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.authenticate = function(username, password, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options); - options.authdb = 'admin'; - - // Execute using callback - if(typeof callback == 'function') return this.s.db.authenticate(username, password, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.authenticate(username, password, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('authenticate', {callback: true, promise:true}); - -/** - * Logout user from server, fire off on all connections and remove all auth info - * @method - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.logout = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return this.s.db.logout({authdb: 'admin'}, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.logout({authdb: 'admin'}, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('logout', {callback: true, promise:true}); - -// Get write concern -var writeConcern = function(options, db) { - options = shallowClone(options); - - // If options already contain write concerns return it - if(options.w || options.wtimeout || options.j || options.fsync) { - return options; - } - - // Set db write concern if available - if(db.writeConcern) { - if(options.w) options.w = db.writeConcern.w; - if(options.wtimeout) options.wtimeout = db.writeConcern.wtimeout; - if(options.j) options.j = db.writeConcern.j; - if(options.fsync) options.fsync = db.writeConcern.fsync; - } - - // Return modified options - return options; -} - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.addUser = function(username, password, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - // Get the options - options = writeConcern(options, self.s.db) - // Set the db name to admin - options.dbName = 'admin'; - - // Execute using callback - if(typeof callback == 'function') - return self.s.db.addUser(username, password, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.addUser(username, password, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('addUser', {callback: true, promise:true}); - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.removeUser = function(username, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - // Get the options - options = writeConcern(options, self.s.db) - // Set the db name - options.dbName = 'admin'; - - // Execute using callback - if(typeof callback == 'function') - return self.s.db.removeUser(username, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.removeUser(username, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('removeUser', {callback: true, promise:true}); - -/** - * Set the current profiling level of MongoDB - * - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.setProfilingLevel = function(level, callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return setProfilingLevel(self, level, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - setProfilingLevel(self, level, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var setProfilingLevel = function(self, level, callback) { - var command = {}; - var profile = 0; - - if(level == "off") { - profile = 0; - } else if(level == "slow_only") { - profile = 1; - } else if(level == "all") { - profile = 2; - } else { - return callback(new Error("Error: illegal profiling level value " + level)); - } - - // Set up the profile number - command['profile'] = profile; - - self.s.db.executeDbAdminCommand(command, function(err, doc) { - doc = doc; - - if(err == null && doc.ok === 1) - return callback(null, level); - return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - }); -} - -define.classMethod('setProfilingLevel', {callback: true, promise:true}); - -/** - * Retrive the current profiling information for MongoDB - * - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.profilingInfo = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return profilingInfo(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - profilingInfo(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var profilingInfo = function(self, callback) { - try { - self.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback); - } catch (err) { - return callback(err, null); - } -} - -define.classMethod('profilingLevel', {callback: true, promise:true}); - -/** - * Validate an existing collection - * - * @param {string} collectionName The name of the collection to validate. - * @param {object} [options=null] Optional settings. - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') - return validateCollection(self, collectionName, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - validateCollection(self, collectionName, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var validateCollection = function(self, collectionName, options, callback) { - var command = {validate: collectionName}; - var keys = Object.keys(options); - - // Decorate command with extra options - for(var i = 0; i < keys.length; i++) { - if(options.hasOwnProperty(keys[i])) { - command[keys[i]] = options[keys[i]]; - } - } - - self.s.db.command(command, function(err, doc) { - if(err != null) return callback(err, null); - - if(doc.ok === 0) - return callback(new Error("Error with validate command"), null); - if(doc.result != null && doc.result.constructor != String) - return callback(new Error("Error with validation data"), null); - if(doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error("Error: invalid collection " + collectionName), null); - if(doc.valid != null && !doc.valid) - return callback(new Error("Error: invalid collection " + collectionName), null); - - return callback(null, doc); - }); -} - -define.classMethod('validateCollection', {callback: true, promise:true}); - -/** - * List the available databases - * - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.listDatabases = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return self.s.db.executeDbAdminCommand({listDatabases:1}, {}, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('listDatabases', {callback: true, promise:true}); - -/** - * Get ReplicaSet status - * - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.replSetGetStatus = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return replSetGetStatus(self, callback); - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - replSetGetStatus(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var replSetGetStatus = function(self, callback) { - self.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { - if(err == null && doc.ok === 1) - return callback(null, doc); - if(err) return callback(err, false); - callback(toError(doc), false); - }); -} - -define.classMethod('replSetGetStatus', {callback: true, promise:true}); - -module.exports = Admin; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/aggregation_cursor.js b/util/demographicsImporter/node_modules/mongodb/lib/aggregation_cursor.js deleted file mode 100644 index 3663229..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/aggregation_cursor.js +++ /dev/null @@ -1,432 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , toError = require('./utils').toError - , getSingleProperty = require('./utils').getSingleProperty - , formattedOrderClause = require('./utils').formattedOrderClause - , handleCallback = require('./utils').handleCallback - , Logger = require('mongodb-core').Logger - , EventEmitter = require('events').EventEmitter - , ReadPreference = require('./read_preference') - , MongoError = require('mongodb-core').MongoError - , Readable = require('stream').Readable || require('readable-stream').Readable - , Define = require('./metadata') - , CoreCursor = require('./cursor') - , Query = require('mongodb-core').Query - , CoreReadPreference = require('mongodb-core').ReadPreference; - -/** - * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X - * or higher stream - * - * **AGGREGATIONCURSOR Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * db.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class AggregationCursor - * @extends external:Readable - * @fires AggregationCursor#data - * @fires AggregationCursor#end - * @fires AggregationCursor#close - * @fires AggregationCursor#readable - * @return {AggregationCursor} an AggregationCursor instance. - */ -var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - var self = this; - var state = AggregationCursor.INIT; - var streamOptions = {}; - - // MaxTimeMS - var maxTimeMS = null; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set up - Readable.call(this, {objectMode: true}); - - // Internal state - this.s = { - // MaxTimeMS - maxTimeMS: maxTimeMS - // State - , state: state - // Stream options - , streamOptions: streamOptions - // BSON - , bson: bson - // Namespae - , ns: ns - // Command - , cmd: cmd - // Options - , options: options - // Topology - , topology: topology - // Topology Options - , topologyOptions: topologyOptions - // Promise library - , promiseLibrary: promiseLibrary - } -} - -/** - * AggregationCursor stream data event, fired for each document in the cursor. - * - * @event AggregationCursor#data - * @type {object} - */ - -/** - * AggregationCursor stream end event - * - * @event AggregationCursor#end - * @type {null} - */ - -/** - * AggregationCursor stream close event - * - * @event AggregationCursor#close - * @type {null} - */ - -/** - * AggregationCursor stream readable event - * - * @event AggregationCursor#readable - * @type {null} - */ - -// Inherit from Readable -inherits(AggregationCursor, Readable); - -// Set the methods to inherit from prototype -var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' - , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' - , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified']; - -// Extend the Cursor -for(var name in CoreCursor.prototype) { - AggregationCursor.prototype[name] = CoreCursor.prototype[name]; -} - -var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true); - -/** - * Set the batch size for the cursor. - * @method - * @param {number} value The batchSize for the cursor. - * @throws {MongoError} - * @return {AggregationCursor} - */ -AggregationCursor.prototype.batchSize = function(value) { - if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true }); - if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", drvier:true }); - if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; - this.setCursorBatchSize(value); - return this; -} - -define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a geoNear stage to the aggregation pipeline - * @method - * @param {object} document The geoNear stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.geoNear = function(document) { - this.s.cmd.pipeline.push({$geoNear: document}); - return this; -} - -define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a group stage to the aggregation pipeline - * @method - * @param {object} document The group stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.group = function(document) { - this.s.cmd.pipeline.push({$group: document}); - return this; -} - -define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a limit stage to the aggregation pipeline - * @method - * @param {number} value The state limit value. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.limit = function(value) { - this.s.cmd.pipeline.push({$limit: value}); - return this; -} - -define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a match stage to the aggregation pipeline - * @method - * @param {object} document The match stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.match = function(document) { - this.s.cmd.pipeline.push({$match: document}); - return this; -} - -define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.maxTimeMS = function(value) { - if(this.s.topology.lastIsMaster().minWireVersion > 2) { - this.s.cmd.maxTimeMS = value; - } - return this; -} - -define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a out stage to the aggregation pipeline - * @method - * @param {number} destination The destination name. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.out = function(destination) { - this.s.cmd.pipeline.push({$out: destination}); - return this; -} - -define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a project stage to the aggregation pipeline - * @method - * @param {object} document The project stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.project = function(document) { - this.s.cmd.pipeline.push({$project: document}); - return this; -} - -define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a redact stage to the aggregation pipeline - * @method - * @param {object} document The redact stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.redact = function(document) { - this.s.cmd.pipeline.push({$redact: document}); - return this; -} - -define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a skip stage to the aggregation pipeline - * @method - * @param {number} value The state skip value. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.skip = function(value) { - this.s.cmd.pipeline.push({$skip: value}); - return this; -} - -define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a sort stage to the aggregation pipeline - * @method - * @param {object} document The sort stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.sort = function(document) { - this.s.cmd.pipeline.push({$sort: document}); - return this; -} - -define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a unwind stage to the aggregation pipeline - * @method - * @param {number} field The unwind field name. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.unwind = function(field) { - this.s.cmd.pipeline.push({$unwind: field}); - return this; -} - -define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]}); - -AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; - -// Inherited methods -define.classMethod('toArray', {callback: true, promise:true}); -define.classMethod('each', {callback: true, promise:false}); -define.classMethod('forEach', {callback: true, promise:false}); -define.classMethod('next', {callback: true, promise:true}); -define.classMethod('close', {callback: true, promise:true}); -define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); -define.classMethod('rewind', {callback: false, promise:false}); -define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); -define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function AggregationCursor.prototype.next - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method AggregationCursor.prototype.toArray - * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method AggregationCursor.prototype.each - * @param {AggregationCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a AggregationCursor command and emitting close. - * @method AggregationCursor.prototype.close - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method AggregationCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Execute the explain for the cursor - * @method AggregationCursor.prototype.explain - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Clone the cursor - * @function AggregationCursor.prototype.clone - * @return {AggregationCursor} - */ - -/** - * Resets the cursor - * @function AggregationCursor.prototype.rewind - * @return {AggregationCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback AggregationCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback AggregationCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method AggregationCursor.prototype.forEach - * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. - * @param {AggregationCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -AggregationCursor.INIT = 0; -AggregationCursor.OPEN = 1; -AggregationCursor.CLOSED = 2; - -module.exports = AggregationCursor; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/apm.js b/util/demographicsImporter/node_modules/mongodb/lib/apm.js deleted file mode 100644 index aba5b86..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/apm.js +++ /dev/null @@ -1,571 +0,0 @@ -var EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits; - -// Get prototypes -var AggregationCursor = require('./aggregation_cursor'), - CommandCursor = require('./command_cursor'), - OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation, - UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation, - GridStore = require('./gridfs/grid_store'), - Server = require('./server'), - ReplSet = require('./replset'), - Mongos = require('./mongos'), - Cursor = require('./cursor'), - Collection = require('./collection'), - Db = require('./db'), - Admin = require('./admin'); - -var basicOperationIdGenerator = { - operationId: 1, - - next: function() { - return this.operationId++; - } -} - -var basicTimestampGenerator = { - current: function() { - return new Date().getTime(); - }, - - duration: function(start, end) { - return end - start; - } -} - -var senstiveCommands = ['authenticate', 'saslStart', 'saslContinue', 'getnonce', - 'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb']; - -var Instrumentation = function(core, options, callback) { - options = options || {}; - - // Optional id generators - var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator; - // Optional timestamp generator - var timestampGenerator = options.timestampGenerator || basicTimestampGenerator; - // Extend with event emitter functionality - EventEmitter.call(this); - - // Contains all the instrumentation overloads - this.overloads = []; - - // --------------------------------------------------------- - // - // Instrument prototype - // - // --------------------------------------------------------- - - var instrumentPrototype = function(callback) { - var instrumentations = [] - - // Classes to support - var classes = [GridStore, OrderedBulkOperation, UnorderedBulkOperation, - CommandCursor, AggregationCursor, Cursor, Collection, Db]; - - // Add instrumentations to the available list - for(var i = 0; i < classes.length; i++) { - if(classes[i].define) { - instrumentations.push(classes[i].define.generate()); - } - } - - // Return the list of instrumentation points - callback(null, instrumentations); - } - - // Did the user want to instrument the prototype - if(typeof callback == 'function') { - instrumentPrototype(callback); - } - - // --------------------------------------------------------- - // - // Server - // - // --------------------------------------------------------- - - // Reference - var self = this; - // Names of methods we need to wrap - var methods = ['command', 'insert', 'update', 'remove']; - // Prototype - var proto = core.Server.prototype; - // Core server method we are going to wrap - methods.forEach(function(x) { - var func = proto[x]; - - // Add to overloaded methods - self.overloads.push({proto: proto, name:x, func:func}); - - // The actual prototype - proto[x] = function() { - var requestId = core.Query.nextRequestId(); - // Get the aruments - var args = Array.prototype.slice.call(arguments, 0); - var ns = args[0]; - var commandObj = args[1]; - var options = args[2] || {}; - var keys = Object.keys(commandObj); - var commandName = keys[0]; - var db = ns.split('.')[0]; - - // Do we have a legacy insert/update/remove command - if(x == 'insert' && !this.lastIsMaster().maxWireVersion) { - commandName = 'insert'; - // Get the collection - var col = ns.split('.'); - col.shift(); - col = col.join('.'); - - // Re-write the command - commandObj = { - insert: col, documents: commandObj - } - - if(options.writeConcern) commandObj.writeConcern = options.writeConcern; - commandObj.ordered = options.ordered != undefined ? options.ordered : true; - } else if(x == 'update' && !this.lastIsMaster().maxWireVersion) { - commandName = 'update'; - - // Get the collection - var col = ns.split('.'); - col.shift(); - col = col.join('.'); - - // Re-write the command - commandObj = { - update: col, updates: commandObj - } - - if(options.writeConcern) commandObj.writeConcern = options.writeConcern; - commandObj.ordered = options.ordered != undefined ? options.ordered : true; - } else if(x == 'remove' && !this.lastIsMaster().maxWireVersion) { - commandName = 'delete'; - - // Get the collection - var col = ns.split('.'); - col.shift(); - col = col.join('.'); - - // Re-write the command - commandObj = { - delete: col, deletes: commandObj - } - - if(options.writeConcern) commandObj.writeConcern = options.writeConcern; - commandObj.ordered = options.ordered != undefined ? options.ordered : true; - } else if(x == 'insert' || x == 'update' || x == 'remove' && this.lastIsMaster().maxWireVersion >= 2) { - // Skip the insert/update/remove commands as they are executed as actual write commands in 2.6 or higher - return func.apply(this, args); - } - - // Get the callback - var callback = args.pop(); - // Set current callback operation id from the current context or create - // a new one - var ourOpId = callback.operationId || operationIdGenerator.next(); - - // Get a connection reference for this server instance - var connection = this.s.pool.get() - - // Emit the start event for the command - var command = { - // Returns the command. - command: commandObj, - // Returns the database name. - databaseName: db, - // Returns the command name. - commandName: commandName, - // Returns the driver generated request id. - requestId: requestId, - // Returns the driver generated operation id. - // This is used to link events together such as bulk write operations. OPTIONAL. - operationId: ourOpId, - // Returns the connection id for the command. For languages that do not have this, - // this MUST return the driver equivalent which MUST include the server address and port. - // The name of this field is flexible to match the object that is returned from the driver. - connectionId: connection - }; - - // Filter out any sensitive commands - if(senstiveCommands.indexOf(commandName.toLowerCase())) { - command.commandObj = {}; - command.commandObj[commandName] = true; - } - - // Emit the started event - self.emit('started', command) - - // Start time - var startTime = timestampGenerator.current(); - - // Push our handler callback - args.push(function(err, r) { - var endTime = timestampGenerator.current(); - var command = { - duration: timestampGenerator.duration(startTime, endTime), - commandName: commandName, - requestId: requestId, - operationId: ourOpId, - connectionId: connection - }; - - // If we have an error - if(err || (r.result.ok == 0)) { - command.failure = err || r.result.writeErrors || r.result; - - // Filter out any sensitive commands - if(senstiveCommands.indexOf(commandName.toLowerCase())) { - command.failure = {}; - } - - self.emit('failed', command); - } else { - command.reply = r; - - // Filter out any sensitive commands - if(senstiveCommands.indexOf(commandName.toLowerCase())) { - command.reply = {}; - } - - self.emit('succeeded', command); - } - - // Return to caller - callback(err, r); - }); - - // Apply the call - func.apply(this, args); - } - }); - - // --------------------------------------------------------- - // - // Bulk Operations - // - // --------------------------------------------------------- - - // Inject ourselves into the Bulk methods - var methods = ['execute']; - var prototypes = [ - require('./bulk/ordered').Bulk.prototype, - require('./bulk/unordered').Bulk.prototype - ] - - prototypes.forEach(function(proto) { - // Core server method we are going to wrap - methods.forEach(function(x) { - var func = proto[x]; - - // Add to overloaded methods - self.overloads.push({proto: proto, name:x, func:func}); - - // The actual prototype - proto[x] = function() { - var bulk = this; - // Get the aruments - var args = Array.prototype.slice.call(arguments, 0); - // Set an operation Id on the bulk object - this.operationId = operationIdGenerator.next(); - - // Get the callback - var callback = args.pop(); - // If we have a callback use this - if(typeof callback == 'function') { - args.push(function(err, r) { - // Return to caller - callback(err, r); - }); - - // Apply the call - func.apply(this, args); - } else { - return func.apply(this, args); - } - } - }); - }); - - // --------------------------------------------------------- - // - // Cursor - // - // --------------------------------------------------------- - - // Inject ourselves into the Cursor methods - var methods = ['_find', '_getmore', '_killcursor']; - var prototypes = [ - require('./cursor').prototype, - require('./command_cursor').prototype, - require('./aggregation_cursor').prototype - ] - - // Command name translation - var commandTranslation = { - '_find': 'find', '_getmore': 'getMore', '_killcursor': 'killCursors', '_explain': 'explain' - } - - prototypes.forEach(function(proto) { - - // Core server method we are going to wrap - methods.forEach(function(x) { - var func = proto[x]; - - // Add to overloaded methods - self.overloads.push({proto: proto, name:x, func:func}); - - // The actual prototype - proto[x] = function() { - var cursor = this; - var requestId = core.Query.nextRequestId(); - var ourOpId = operationIdGenerator.next(); - var parts = this.ns.split('.'); - var db = parts[0]; - - // Get the collection - parts.shift(); - var collection = parts.join('.'); - - // Set the command - var command = this.query; - var cmd = this.s.cmd; - - // If we have a find method, set the operationId on the cursor - if(x == '_find') { - cursor.operationId = ourOpId; - } - - // Do we have a find command rewrite it - if(cmd.find) { - command = { - find: collection, filter: cmd.query - } - - if(cmd.sort) command.sort = cmd.sort; - if(cmd.fields) command.projection = cmd.fields; - if(cmd.limit && cmd.limit < 0) { - command.limit = Math.abs(cmd.limit); - command.singleBatch = true; - } else if(cmd.limit) { - command.limit = Math.abs(cmd.limit); - } - - // Options - if(cmd.skip) command.skip = cmd.skip; - if(cmd.hint) command.hint = cmd.hint; - if(cmd.batchSize) command.batchSize = cmd.batchSize; - if(cmd.returnKey) command.returnKey = cmd.returnKey; - if(cmd.comment) command.comment = cmd.comment; - if(cmd.min) command.min = cmd.min; - if(cmd.max) command.max = cmd.max; - if(cmd.maxScan) command.maxScan = cmd.maxScan; - if(cmd.readPreference) command['$readPreference'] = cmd.readPreference; - if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; - - // Flags - if(cmd.awaitData) command.awaitData = cmd.awaitData; - if(cmd.snapshot) command.snapshot = cmd.snapshot; - if(cmd.tailable) command.tailable = cmd.tailable; - if(cmd.oplogReplay) command.oplogReplay = cmd.oplogReplay; - if(cmd.noCursorTimeout) command.noCursorTimeout = cmd.noCursorTimeout; - if(cmd.partial) command.partial = cmd.partial; - if(cmd.showDiskLoc) command.showRecordId = cmd.showDiskLoc; - - // Read Concern - if(cmd.readConcern) command.readConcern = cmd.readConcern; - - // Override method - if(cmd.explain) command.explain = cmd.explain; - if(cmd.exhaust) command.exhaust = cmd.exhaust; - - // If we have a explain flag - if(cmd.explain) { - // Create fake explain command - command = { - explain: command, - verbosity: 'allPlansExecution' - } - - // Set readConcern on the command if available - if(cmd.readConcern) command.readConcern = cmd.readConcern - - // Set up the _explain name for the command - x = '_explain'; - } - } else if(x == '_getmore') { - command = { - getMore: this.cursorState.cursorId, - collection: collection, - batchSize: cmd.batchSize - } - - if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; - } else if(x == '_killcursors') { - command = { - killCursors: collection, - cursors: [this.cursorState.cursorId] - } - } else { - command = cmd; - } - - // Set up the connection - var connectionId = null; - - // Set local connection - if(this.connection) connectionId = this.connection; - if(!connectionId && this.server && this.server.getConnection) connectionId = this.server.getConnection(); - - // Get the command Name - var commandName = x == '_find' ? Object.keys(command)[0] : commandTranslation[x]; - - // Emit the start event for the command - var command = { - // Returns the command. - command: command, - // Returns the database name. - databaseName: db, - // Returns the command name. - commandName: commandName, - // Returns the driver generated request id. - requestId: requestId, - // Returns the driver generated operation id. - // This is used to link events together such as bulk write operations. OPTIONAL. - operationId: this.operationId, - // Returns the connection id for the command. For languages that do not have this, - // this MUST return the driver equivalent which MUST include the server address and port. - // The name of this field is flexible to match the object that is returned from the driver. - connectionId: connectionId - }; - - // Get the aruments - var args = Array.prototype.slice.call(arguments, 0); - - // Get the callback - var callback = args.pop(); - - // We do not have a callback but a Promise - if(typeof callback == 'function' || command.commandName == 'killCursors') { - var startTime = timestampGenerator.current(); - // Emit the started event - self.emit('started', command) - - // Emit succeeded event with killcursor if we have a legacy protocol - if(command.commandName == 'killCursors' - && this.server.lastIsMaster() - && this.server.lastIsMaster().maxWireVersion < 4) { - // Emit the succeeded command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: cursor.operationId, - connectionId: cursor.server.getConnection(), - reply: [{ok:1}] - }; - - // Emit the command - return self.emit('succeeded', command) - } - - // Add our callback handler - args.push(function(err, r) { - - if(err) { - // Command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: ourOpId, - connectionId: cursor.server.getConnection(), - failure: err }; - - // Emit the command - self.emit('failed', command) - } else { - // cursor id is zero, we can issue success command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: cursor.operationId, - connectionId: cursor.server.getConnection(), - reply: cursor.cursorState.documents - }; - - // Emit the command - self.emit('succeeded', command) - } - - // Return - if(!callback) return; - - // Return to caller - callback(err, r); - }); - - // Apply the call - func.apply(this, args); - } else { - // Assume promise, push back the missing value - args.push(callback); - // Get the promise - var promise = func.apply(this, args); - // Return a new promise - return new cursor.s.promiseLibrary(function(resolve, reject) { - var startTime = timestampGenerator.current(); - // Emit the started event - self.emit('started', command) - // Execute the function - promise.then(function(r) { - // cursor id is zero, we can issue success command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: cursor.operationId, - connectionId: cursor.server.getConnection(), - reply: cursor.cursorState.documents - }; - - // Emit the command - self.emit('succeeded', command) - }).catch(function(err) { - // Command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: ourOpId, - connectionId: cursor.server.getConnection(), - failure: err }; - - // Emit the command - self.emit('failed', command) - // reject the promise - reject(err); - }); - }); - } - } - }); - }); -} - -inherits(Instrumentation, EventEmitter); - -Instrumentation.prototype.uninstrument = function() { - for(var i = 0; i < this.overloads.length; i++) { - var obj = this.overloads[i]; - obj.proto[obj.name] = obj.func; - } - - // Remove all listeners - this.removeAllListeners('started'); - this.removeAllListeners('succeeded'); - this.removeAllListeners('failed'); -} - -module.exports = Instrumentation; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/lib/bulk/common.js b/util/demographicsImporter/node_modules/mongodb/lib/bulk/common.js deleted file mode 100644 index 7ec023e..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/bulk/common.js +++ /dev/null @@ -1,393 +0,0 @@ -"use strict"; - -var utils = require('../utils'); - -// Error codes -var UNKNOWN_ERROR = 8; -var INVALID_BSON_ERROR = 22; -var WRITE_CONCERN_ERROR = 64; -var MULTIPLE_ERROR = 65; - -// Insert types -var INSERT = 1; -var UPDATE = 2; -var REMOVE = 3 - - -// Get write concern -var writeConcern = function(target, col, options) { - if(options.w != null || options.j != null || options.fsync != null) { - target.writeConcern = options; - } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { - target.writeConcern = col.writeConcern; - } - - return target -} - -/** - * Helper function to define properties - * @ignore - */ -var defineReadOnlyProperty = function(self, name, value) { - Object.defineProperty(self, name, { - enumerable: true - , get: function() { - return value; - } - }); -} - -/** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - * @ignore - */ -var Batch = function(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; -} - -/** - * Wraps a legacy operation so we can correctly rewrite it's error - * @ignore - */ -var LegacyOp = function(batchType, operation, index) { - this.batchType = batchType; - this.index = index; - this.operation = operation; -} - -/** - * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @property {boolean} ok Did bulk operation correctly execute - * @property {number} nInserted number of inserted documents - * @property {number} nUpdated number of documents updated logically - * @property {number} nUpserted Number of upserted documents - * @property {number} nModified Number of documents updated physically on disk - * @property {number} nRemoved Number of removed documents - * @return {BulkWriteResult} a BulkWriteResult instance - */ -var BulkWriteResult = function(bulkResult) { - defineReadOnlyProperty(this, "ok", bulkResult.ok); - defineReadOnlyProperty(this, "nInserted", bulkResult.nInserted); - defineReadOnlyProperty(this, "nUpserted", bulkResult.nUpserted); - defineReadOnlyProperty(this, "nMatched", bulkResult.nMatched); - defineReadOnlyProperty(this, "nModified", bulkResult.nModified); - defineReadOnlyProperty(this, "nRemoved", bulkResult.nRemoved); - - /** - * Return an array of inserted ids - * - * @return {object[]} - */ - this.getInsertedIds = function() { - return bulkResult.insertedIds; - } - - /** - * Return an array of upserted ids - * - * @return {object[]} - */ - this.getUpsertedIds = function() { - return bulkResult.upserted; - } - - /** - * Return the upserted id at position x - * - * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index - * @return {object} - */ - this.getUpsertedIdAt = function(index) { - return bulkResult.upserted[index]; - } - - /** - * Return raw internal result - * - * @return {object} - */ - this.getRawResponse = function() { - return bulkResult; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - this.hasWriteErrors = function() { - return bulkResult.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - this.getWriteErrorCount = function() { - return bulkResult.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @return {WriteError} - */ - this.getWriteErrorAt = function(index) { - if(index < bulkResult.writeErrors.length) { - return bulkResult.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {object[]} - */ - this.getWriteErrors = function() { - return bulkResult.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {object} - */ - this.getLastOp = function() { - return bulkResult.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - */ - this.getWriteConcernError = function() { - if(bulkResult.writeConcernErrors.length == 0) { - return null; - } else if(bulkResult.writeConcernErrors.length == 1) { - // Return the error - return bulkResult.writeConcernErrors[0]; - } else { - - // Combine the errors - var errmsg = ""; - for(var i = 0; i < bulkResult.writeConcernErrors.length; i++) { - var err = bulkResult.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if(i == 0) errmsg = errmsg + " and "; - } - - return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_ERROR }); - } - } - - this.toJSON = function() { - return bulkResult; - } - - this.toString = function() { - return "BulkWriteResult(" + this.toJSON(bulkResult) + ")"; - } - - this.isOk = function() { - return bulkResult.ok == 1; - } -} - -/** - * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @property {number} code Write concern error code. - * @property {string} errmsg Write concern error message. - * @return {WriteConcernError} a WriteConcernError instance - */ -var WriteConcernError = function(err) { - if(!(this instanceof WriteConcernError)) return new WriteConcernError(err); - - // Define properties - defineReadOnlyProperty(this, "code", err.code); - defineReadOnlyProperty(this, "errmsg", err.errmsg); - - this.toJSON = function() { - return {code: err.code, errmsg: err.errmsg}; - } - - this.toString = function() { - return "WriteConcernError(" + err.errmsg + ")"; - } -} - -/** - * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @property {number} code Write concern error code. - * @property {number} index Write concern error original bulk operation index. - * @property {string} errmsg Write concern error message. - * @return {WriteConcernError} a WriteConcernError instance - */ -var WriteError = function(err) { - if(!(this instanceof WriteError)) return new WriteError(err); - - // Define properties - defineReadOnlyProperty(this, "code", err.code); - defineReadOnlyProperty(this, "index", err.index); - defineReadOnlyProperty(this, "errmsg", err.errmsg); - - // - // Define access methods - this.getOperation = function() { - return err.op; - } - - this.toJSON = function() { - return {code: err.code, index: err.index, errmsg: err.errmsg, op: err.op}; - } - - this.toString = function() { - return "WriteError(" + JSON.stringify(this.toJSON()) + ")"; - } -} - -/** - * Merges results into shared data structure - * @ignore - */ -var mergeBatchResults = function(ordered, batch, bulkResult, err, result) { - // If we have an error set the result to be the err object - if(err) { - result = err; - } else if(result && result.result) { - result = result.result; - } else if(result == null) { - return; - } - - // Do we have a top level error stop processing and return - if(result.ok == 0 && bulkResult.ok == 1) { - bulkResult.ok = 0; - // bulkResult.error = utils.toError(result); - var writeError = { - index: 0 - , code: result.code || 0 - , errmsg: result.message - , op: batch.operations[0] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if(result.ok == 0 && bulkResult.ok == 0) { - return; - } - - // Add lastop if available - if(result.lastOp) { - bulkResult.lastOp = result.lastOp; - } - - // If we have an insert Batch type - if(batch.batchType == INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } - - // If we have an insert Batch type - if(batch.batchType == REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } - - var nUpserted = 0; - - // We have an array of upserted values, we need to rewrite the indexes - if(Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - - for(var i = 0; i < result.upserted.length; i++) { - bulkResult.upserted.push({ - index: result.upserted[i].index + batch.originalZeroIndex - , _id: result.upserted[i]._id - }); - } - } else if(result.upserted) { - - nUpserted = 1; - - bulkResult.upserted.push({ - index: batch.originalZeroIndex - , _id: result.upserted - }); - } - - // If we have an update Batch type - if(batch.batchType == UPDATE && result.n) { - var nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - - if(typeof nModified == 'number') { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } - - if(Array.isArray(result.writeErrors)) { - for(var i = 0; i < result.writeErrors.length; i++) { - - var writeError = { - index: batch.originalZeroIndex + result.writeErrors[i].index - , code: result.writeErrors[i].code - , errmsg: result.writeErrors[i].errmsg - , op: batch.operations[result.writeErrors[i].index] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } - - if(result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); - } -} - -// -// Clone the options -var cloneOptions = function(options) { - var clone = {}; - var keys = Object.keys(options); - for(var i = 0; i < keys.length; i++) { - clone[keys[i]] = options[keys[i]]; - } - - return clone; -} - -// Exports symbols -exports.BulkWriteResult = BulkWriteResult; -exports.WriteError = WriteError; -exports.Batch = Batch; -exports.LegacyOp = LegacyOp; -exports.mergeBatchResults = mergeBatchResults; -exports.cloneOptions = cloneOptions; -exports.writeConcern = writeConcern; -exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR; -exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR; -exports.MULTIPLE_ERROR = MULTIPLE_ERROR; -exports.UNKNOWN_ERROR = UNKNOWN_ERROR; -exports.INSERT = INSERT; -exports.UPDATE = UPDATE; -exports.REMOVE = REMOVE; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/bulk/ordered.js b/util/demographicsImporter/node_modules/mongodb/lib/bulk/ordered.js deleted file mode 100644 index 319a030..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/bulk/ordered.js +++ /dev/null @@ -1,532 +0,0 @@ -"use strict"; - -var common = require('./common') - , utils = require('../utils') - , toError = require('../utils').toError - , f = require('util').format - , shallowClone = utils.shallowClone - , WriteError = common.WriteError - , BulkWriteResult = common.BulkWriteResult - , LegacyOp = common.LegacyOp - , ObjectID = require('mongodb-core').BSON.ObjectID - , Define = require('../metadata') - , Batch = common.Batch - , mergeBatchResults = common.mergeBatchResults; - -/** - * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. - */ -var FindOperatorsOrdered = function(self) { - this.s = self.s; -} - -/** - * Add a single update document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.update = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: true - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a single update one document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: false - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} doc the new document to replace the existing one with - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { - this.updateOne(updateDocument); -} - -/** - * Upsert modifier for update bulk operation - * - * @method - * @throws {MongoError} - * @return {FindOperatorsOrdered} - */ -FindOperatorsOrdered.prototype.upsert = function() { - this.s.currentOp.upsert = true; - return this; -} - -/** - * Add a remove one operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.deleteOne = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 1 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -// Backward compatibility -FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; - -/** - * Add a remove operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.delete = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 0 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -// Backward compatibility -FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; - -// Add to internal list of documents -var addToOperationsList = function(_self, docType, document) { - // Get the bsonSize - var bsonSize = _self.s.bson.calculateObjectSize(document, false); - - // Throw error if the doc is bigger than the max BSON size - if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); - // Create a new batch object if we don't have a current one - if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - - // Check if we need to create a new batch - if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize) - || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes) - || (_self.s.currentBatch.batchType != docType)) { - // Save the batch to the execution stack - _self.s.batches.push(_self.s.currentBatch); - - // Create a new batch - _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - - // Reset the current size trackers - _self.s.currentBatchSize = 0; - _self.s.currentBatchSizeBytes = 0; - } else { - // Update current batch size - _self.s.currentBatchSize = _self.s.currentBatchSize + 1; - _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; - } - - if(docType == common.INSERT) { - _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); - } - - // We have an array of documents - if(Array.isArray(document)) { - throw toError("operation passed in cannot be an Array"); - } else { - _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); - _self.s.currentBatch.operations.push(document) - _self.s.currentIndex = _self.s.currentIndex + 1; - } - - // Return self - return _self; -} - -/** - * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {number} length Get the number of operations in the bulk. - * @return {OrderedBulkOperation} a OrderedBulkOperation instance. - */ -function OrderedBulkOperation(topology, collection, options) { - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - var self = this; - var executed = false; - - // Current item - var currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - var bson = topology.bson; - - // Namespace for the operation - var namespace = collection.collectionName; - - // Set max byte size - var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; - var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; - - // Get the capabilities - var capabilities = topology.capabilities(); - - // Get the write concern - var writeConcern = common.writeConcern(shallowClone(options), collection, options); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Current batch - var currentBatch = null; - var currentIndex = 0; - var currentBatchSize = 0; - var currentBatchSizeBytes = 0; - var batches = []; - - // Final results - var bulkResult = { - ok: 1 - , writeErrors: [] - , writeConcernErrors: [] - , insertedIds: [] - , nInserted: 0 - , nUpserted: 0 - , nMatched: 0 - , nModified: 0 - , nRemoved: 0 - , upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult - // Current batch state - , currentBatch: null - , currentIndex: 0 - , currentBatchSize: 0 - , currentBatchSizeBytes: 0 - , batches: [] - // Write concern - , writeConcern: writeConcern - // Capabilities - , capabilities: capabilities - // Max batch size options - , maxBatchSizeBytes: maxBatchSizeBytes - , maxWriteBatchSize: maxWriteBatchSize - // Namespace - , namespace: namespace - // BSON - , bson: bson - // Topology - , topology: topology - // Options - , options: options - // Current operation - , currentOp: currentOp - // Executed - , executed: executed - // Collection - , collection: collection - // Promise Library - , promiseLibrary: promiseLibrary - // Fundamental error - , err: null - // Bypass validation - , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false - } -} - -var define = OrderedBulkOperation.define = new Define('OrderedBulkOperation', OrderedBulkOperation, false); - -OrderedBulkOperation.prototype.raw = function(op) { - var key = Object.keys(op)[0]; - - // Set up the force server object id - var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' - ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if((op.updateOne && op.updateOne.q) - || (op.updateMany && op.updateMany.q) - || (op.replaceOne && op.replaceOne.q)) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return addToOperationsList(this, common.UPDATE, op[key]); - } - - // Crud spec update format - if(op.updateOne || op.updateMany || op.replaceOne) { - var multi = op.updateOne || op.replaceOne ? false : true; - var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} - if(op[key].upsert) operation.upsert = true; - return addToOperationsList(this, common.UPDATE, operation); - } - - // Remove operations - if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { - op[key].limit = op.removeOne ? 1 : 0; - return addToOperationsList(this, common.REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if(op.deleteOne || op.deleteMany) { - var limit = op.deleteOne ? 1 : 0; - var operation = {q: op[key].filter, limit: limit} - return addToOperationsList(this, common.REMOVE, operation); - } - - // Insert operations - if(op.insertOne && op.insertOne.document == null) { - if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne); - } else if(op.insertOne && op.insertOne.document) { - if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne.document); - } - - if(op.insertMany) { - for(var i = 0; i < op.insertMany.length; i++) { - if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); - addToOperationsList(this, common.INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); -} - -/** - * Add a single insert document to the bulk operation - * - * @param {object} doc the document to insert - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -OrderedBulkOperation.prototype.insert = function(document) { - if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, document); -} - -/** - * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne - * - * @method - * @param {object} selector The selector for the bulk operation. - * @throws {MongoError} - * @return {FindOperatorsOrdered} - */ -OrderedBulkOperation.prototype.find = function(selector) { - if (!selector) { - throw toError("Bulk find operation must specify a selector"); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - } - - return new FindOperatorsOrdered(this); -} - -Object.defineProperty(OrderedBulkOperation.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -// -// Execute next write command in a chain -var executeCommands = function(self, callback) { - if(self.s.batches.length == 0) { - return callback(null, new BulkWriteResult(self.s.bulkResult)); - } - - // Ordered execution of the command - var batch = self.s.batches.shift(); - - var resultHandler = function(err, result) { - // Error is a driver related error not a bulk op error, terminate - if(err && err.driver || err && err.message) { - return callback(err); - } - - // If we have and error - if(err) err.ok = 0; - // Merge the results together - var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); - if(mergeResult != null) { - return callback(null, new BulkWriteResult(self.s.bulkResult)); - } - - // If we are ordered and have errors and they are - // not all replication errors terminate the operation - if(self.s.bulkResult.writeErrors.length > 0) { - return callback(toError(self.s.bulkResult.writeErrors[0]), new BulkWriteResult(self.s.bulkResult)); - } - - // Execute the next command in line - executeCommands(self, callback); - } - - var finalOptions = {ordered: true} - if(self.s.writeConcern != null) { - finalOptions.writeConcern = self.s.writeConcern; - } - - // Set an operationIf if provided - if(self.operationId) { - resultHandler.operationId = self.operationId; - } - - // Serialize functions - if(self.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true - } - - // Serialize functions - if(self.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true - } - - // Is the bypassDocumentValidation options specific - if(self.s.bypassDocumentValidation == true) { - finalOptions.bypassDocumentValidation = true; - } - - try { - if(batch.batchType == common.INSERT) { - self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.UPDATE) { - self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.REMOVE) { - self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } - } catch(err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); - } -} - -/** - * The callback format for results - * @callback OrderedBulkOperation~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - -/** - * Execute the ordered bulk operation - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {OrderedBulkOperation~resultCallback} [callback] The result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) { - var self = this; - if(this.s.executed) throw new toError("batch cannot be re-executed"); - if(typeof _writeConcern == 'function') { - callback = _writeConcern; - } else { - this.s.writeConcern = _writeConcern; - } - - // If we have current batch - if(this.s.currentBatch) this.s.batches.push(this.s.currentBatch); - - // If we have no operations in the bulk raise an error - if(this.s.batches.length == 0) { - throw toError("Invalid Operation, No operations in bulk"); - } - - // Execute using callback - if(typeof callback == 'function') { - return executeCommands(this, callback); - } - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - executeCommands(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('execute', {callback: true, promise:false}); - -/** - * Returns an unordered batch object - * @ignore - */ -var initializeOrderedBulkOp = function(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); -} - -initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; -module.exports = initializeOrderedBulkOp; -module.exports.Bulk = OrderedBulkOperation; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/bulk/unordered.js b/util/demographicsImporter/node_modules/mongodb/lib/bulk/unordered.js deleted file mode 100644 index ca45b96..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/bulk/unordered.js +++ /dev/null @@ -1,541 +0,0 @@ -"use strict"; - -var common = require('./common') - , utils = require('../utils') - , toError = require('../utils').toError - , f = require('util').format - , shallowClone = utils.shallowClone - , WriteError = common.WriteError - , BulkWriteResult = common.BulkWriteResult - , LegacyOp = common.LegacyOp - , ObjectID = require('mongodb-core').BSON.ObjectID - , Define = require('../metadata') - , Batch = common.Batch - , mergeBatchResults = common.mergeBatchResults; - -/** - * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {number} length Get the number of operations in the bulk. - * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. - */ -var FindOperatorsUnordered = function(self) { - this.s = self.s; -} - -/** - * Add a single update document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.update = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: true - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a single update one document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: false - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} doc the new document to replace the existing one with - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { - this.updateOne(updateDocument); -} - -/** - * Upsert modifier for update bulk operation - * - * @method - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.upsert = function() { - this.s.currentOp.upsert = true; - return this; -} - -/** - * Add a remove one operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.removeOne = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 1 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -/** - * Add a remove operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.remove = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 0 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -// -// Add to the operations list -// -var addToOperationsList = function(_self, docType, document) { - // Get the bsonSize - var bsonSize = _self.s.bson.calculateObjectSize(document, false); - // Throw error if the doc is bigger than the max BSON size - if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); - // Holds the current batch - _self.s.currentBatch = null; - // Get the right type of batch - if(docType == common.INSERT) { - _self.s.currentBatch = _self.s.currentInsertBatch; - } else if(docType == common.UPDATE) { - _self.s.currentBatch = _self.s.currentUpdateBatch; - } else if(docType == common.REMOVE) { - _self.s.currentBatch = _self.s.currentRemoveBatch; - } - - // Create a new batch object if we don't have a current one - if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - - // Check if we need to create a new batch - if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize) - || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes) - || (_self.s.currentBatch.batchType != docType)) { - // Save the batch to the execution stack - _self.s.batches.push(_self.s.currentBatch); - - // Create a new batch - _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - } - - // We have an array of documents - if(Array.isArray(document)) { - throw toError("operation passed in cannot be an Array"); - } else { - _self.s.currentBatch.operations.push(document); - _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); - _self.s.currentIndex = _self.s.currentIndex + 1; - } - - // Save back the current Batch to the right type - if(docType == common.INSERT) { - _self.s.currentInsertBatch = _self.s.currentBatch; - _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); - } else if(docType == common.UPDATE) { - _self.s.currentUpdateBatch = _self.s.currentBatch; - } else if(docType == common.REMOVE) { - _self.s.currentRemoveBatch = _self.s.currentBatch; - } - - // Update current batch size - _self.s.currentBatch.size = _self.s.currentBatch.size + 1; - _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; - - // Return self - return _self; -} - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. - */ -var UnorderedBulkOperation = function(topology, collection, options) { - options = options == null ? {} : options; - - // Contains reference to self - var self = this; - // Get the namesspace for the write operations - var namespace = collection.collectionName; - // Used to mark operation as executed - var executed = false; - - // Current item - // var currentBatch = null; - var currentOp = null; - var currentIndex = 0; - var batches = []; - - // The current Batches for the different operations - var currentInsertBatch = null; - var currentUpdateBatch = null; - var currentRemoveBatch = null; - - // Handle to the bson serializer, used to calculate running sizes - var bson = topology.bson; - - // Get the capabilities - var capabilities = topology.capabilities(); - - // Set max byte size - var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; - var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; - - // Get the write concern - var writeConcern = common.writeConcern(shallowClone(options), collection, options); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Final results - var bulkResult = { - ok: 1 - , writeErrors: [] - , writeConcernErrors: [] - , insertedIds: [] - , nInserted: 0 - , nUpserted: 0 - , nMatched: 0 - , nModified: 0 - , nRemoved: 0 - , upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult - // Current batch state - , currentInsertBatch: null - , currentUpdateBatch: null - , currentRemoveBatch: null - , currentBatch: null - , currentIndex: 0 - , batches: [] - // Write concern - , writeConcern: writeConcern - // Capabilities - , capabilities: capabilities - // Max batch size options - , maxBatchSizeBytes: maxBatchSizeBytes - , maxWriteBatchSize: maxWriteBatchSize - // Namespace - , namespace: namespace - // BSON - , bson: bson - // Topology - , topology: topology - // Options - , options: options - // Current operation - , currentOp: currentOp - // Executed - , executed: executed - // Collection - , collection: collection - // Promise Library - , promiseLibrary: promiseLibrary - // Bypass validation - , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false - } -} - -var define = UnorderedBulkOperation.define = new Define('UnorderedBulkOperation', UnorderedBulkOperation, false); - -/** - * Add a single insert document to the bulk operation - * - * @param {object} doc the document to insert - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -UnorderedBulkOperation.prototype.insert = function(document) { - if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, document); -} - -/** - * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne - * - * @method - * @param {object} selector The selector for the bulk operation. - * @throws {MongoError} - * @return {FindOperatorsUnordered} - */ -UnorderedBulkOperation.prototype.find = function(selector) { - if (!selector) { - throw toError("Bulk find operation must specify a selector"); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - } - - return new FindOperatorsUnordered(this); -} - -Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -UnorderedBulkOperation.prototype.raw = function(op) { - var key = Object.keys(op)[0]; - - // Set up the force server object id - var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' - ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if((op.updateOne && op.updateOne.q) - || (op.updateMany && op.updateMany.q) - || (op.replaceOne && op.replaceOne.q)) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return addToOperationsList(this, common.UPDATE, op[key]); - } - - // Crud spec update format - if(op.updateOne || op.updateMany || op.replaceOne) { - var multi = op.updateOne || op.replaceOne ? false : true; - var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} - if(op[key].upsert) operation.upsert = true; - return addToOperationsList(this, common.UPDATE, operation); - } - - // Remove operations - if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { - op[key].limit = op.removeOne ? 1 : 0; - return addToOperationsList(this, common.REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if(op.deleteOne || op.deleteMany) { - var limit = op.deleteOne ? 1 : 0; - var operation = {q: op[key].filter, limit: limit} - return addToOperationsList(this, common.REMOVE, operation); - } - - // Insert operations - if(op.insertOne && op.insertOne.document == null) { - if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne); - } else if(op.insertOne && op.insertOne.document) { - if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne.document); - } - - if(op.insertMany) { - for(var i = 0; i < op.insertMany.length; i++) { - if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); - addToOperationsList(this, common.INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); -} - -// -// Execute the command -var executeBatch = function(self, batch, callback) { - var finalOptions = {ordered: false} - if(self.s.writeConcern != null) { - finalOptions.writeConcern = self.s.writeConcern; - } - - var resultHandler = function(err, result) { - // Error is a driver related error not a bulk op error, terminate - if(err && err.driver || err && err.message) { - return callback(err); - } - - // If we have and error - if(err) err.ok = 0; - callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); - } - - // Set an operationIf if provided - if(self.operationId) { - resultHandler.operationId = self.operationId; - } - - // Serialize functions - if(self.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true - } - - // Is the bypassDocumentValidation options specific - if(self.s.bypassDocumentValidation == true) { - finalOptions.bypassDocumentValidation = true; - } - - try { - if(batch.batchType == common.INSERT) { - self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.UPDATE) { - self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.REMOVE) { - self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } - } catch(err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); - } -} - -// -// Execute all the commands -var executeBatches = function(self, callback) { - var numberOfCommandsToExecute = self.s.batches.length; - var error = null; - // Execute over all the batches - for(var i = 0; i < self.s.batches.length; i++) { - executeBatch(self, self.s.batches[i], function(err, result) { - // Driver layer error capture it - if(err) error = err; - // Count down the number of commands left to execute - numberOfCommandsToExecute = numberOfCommandsToExecute - 1; - - // Execute - if(numberOfCommandsToExecute == 0) { - // Driver level error - if(error) return callback(error); - // Treat write errors - var error = self.s.bulkResult.writeErrors.length > 0 ? toError(self.s.bulkResult.writeErrors[0]) : null; - callback(error, new BulkWriteResult(self.s.bulkResult)); - } - }); - } -} - -/** - * The callback format for results - * @callback UnorderedBulkOperation~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - -/** - * Execute the ordered bulk operation - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) { - var self = this; - if(this.s.executed) throw toError("batch cannot be re-executed"); - if(typeof _writeConcern == 'function') { - callback = _writeConcern; - } else { - this.s.writeConcern = _writeConcern; - } - - // If we have current batch - if(this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); - if(this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); - if(this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); - - // If we have no operations in the bulk raise an error - if(this.s.batches.length == 0) { - throw toError("Invalid Operation, No operations in bulk"); - } - - // Execute using callback - if(typeof callback == 'function') return executeBatches(this, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - executeBatches(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('execute', {callback: true, promise:false}); - -/** - * Returns an unordered batch object - * @ignore - */ -var initializeUnorderedBulkOp = function(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); -} - -initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; -module.exports = initializeUnorderedBulkOp; -module.exports.Bulk = UnorderedBulkOperation; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/collection.js b/util/demographicsImporter/node_modules/mongodb/lib/collection.js deleted file mode 100644 index 5ae1ebc..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/collection.js +++ /dev/null @@ -1,3128 +0,0 @@ -"use strict"; - -var checkCollectionName = require('./utils').checkCollectionName - , ObjectID = require('mongodb-core').BSON.ObjectID - , Long = require('mongodb-core').BSON.Long - , Code = require('mongodb-core').BSON.Code - , f = require('util').format - , AggregationCursor = require('./aggregation_cursor') - , MongoError = require('mongodb-core').MongoError - , shallowClone = require('./utils').shallowClone - , isObject = require('./utils').isObject - , toError = require('./utils').toError - , normalizeHintField = require('./utils').normalizeHintField - , handleCallback = require('./utils').handleCallback - , decorateCommand = require('./utils').decorateCommand - , formattedOrderClause = require('./utils').formattedOrderClause - , ReadPreference = require('./read_preference') - , CoreReadPreference = require('mongodb-core').ReadPreference - , CommandCursor = require('./command_cursor') - , Define = require('./metadata') - , Cursor = require('./cursor') - , unordered = require('./bulk/unordered') - , ordered = require('./bulk/ordered'); - -/** - * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection - * allowing for insert/update/remove/find and other command operation on that MongoDB collection. - * - * **COLLECTION Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('createIndexExample1'); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * db.close(); - * }); - * }); - */ - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {string} collectionName Get the collection name. - * @property {string} namespace Get the full collection namespace. - * @property {object} writeConcern The current write concern values. - * @property {object} readConcern The current read concern values. - * @property {object} hint Get current index hint for collection. - * @return {Collection} a Collection instance. - */ -var Collection = function(db, topology, dbName, name, pkFactory, options) { - checkCollectionName(name); - var self = this; - // Unpack variables - var internalHint = null; - var opts = options != null && ('object' === typeof options) ? options : {}; - var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - var serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; - var raw = options == null || options.raw == null ? db.raw : options.raw; - var readPreference = null; - var collectionHint = null; - var namespace = f("%s.%s", dbName, name); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Assign the right collection level readPreference - if(options && options.readPreference) { - readPreference = options.readPreference; - } else if(db.options.readPreference) { - readPreference = db.options.readPreference; - } - - // Set custom primary key factory if provided - pkFactory = pkFactory == null - ? ObjectID - : pkFactory; - - // Internal state - this.s = { - // Set custom primary key factory if provided - pkFactory: pkFactory - // Db - , db: db - // Topology - , topology: topology - // dbName - , dbName: dbName - // Options - , options: options - // Namespace - , namespace: namespace - // Read preference - , readPreference: readPreference - // Raw - , raw: raw - // SlaveOK - , slaveOk: slaveOk - // Serialize functions - , serializeFunctions: serializeFunctions - // internalHint - , internalHint: internalHint - // collectionHint - , collectionHint: collectionHint - // Name - , name: name - // Promise library - , promiseLibrary: promiseLibrary - // Read Concern - , readConcern: options.readConcern - } -} - -var define = Collection.define = new Define('Collection', Collection, false); - -Object.defineProperty(Collection.prototype, 'collectionName', { - enumerable: true, get: function() { return this.s.name; } -}); - -Object.defineProperty(Collection.prototype, 'namespace', { - enumerable: true, get: function() { return this.s.namespace; } -}); - -Object.defineProperty(Collection.prototype, 'readConcern', { - enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; } -}); - -Object.defineProperty(Collection.prototype, 'writeConcern', { - enumerable:true, - get: function() { - var ops = {}; - if(this.s.options.w != null) ops.w = this.s.options.w; - if(this.s.options.j != null) ops.j = this.s.options.j; - if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; - if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; - return ops; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Collection.prototype, "hint", { - enumerable: true - , get: function () { return this.s.collectionHint; } - , set: function (v) { this.s.collectionHint = normalizeHintField(v); } -}); - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * @method - * @param {object} query The cursor query object. - * @throws {MongoError} - * @return {Cursor} - */ -Collection.prototype.find = function() { - var options - , args = Array.prototype.slice.call(arguments, 0) - , has_callback = typeof args[args.length - 1] === 'function' - , has_weird_callback = typeof args[0] === 'function' - , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) - , len = args.length - , selector = len >= 1 ? args[0] : {} - , fields = len >= 2 ? args[1] : undefined; - - if(len === 1 && has_weird_callback) { - // backwards compat for callback?, options case - selector = {}; - options = args[0]; - } - - if(len === 2 && fields !== undefined && !Array.isArray(fields)) { - var fieldKeys = Object.keys(fields); - var is_option = false; - - for(var i = 0; i < fieldKeys.length; i++) { - if(testForFields[fieldKeys[i]] != null) { - is_option = true; - break; - } - } - - if(is_option) { - options = fields; - fields = undefined; - } else { - options = {}; - } - } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { - var newFields = {}; - // Rewrite the array - for(var i = 0; i < fields.length; i++) { - newFields[fields[i]] = 1; - } - // Set the fields - fields = newFields; - } - - if(3 === len) { - options = args[2]; - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Validate correctness of the field selector - var object = fields; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) { - selector = {_id:selector}; - } - - // If it's a serialized fields field we need to just let it through - // user be warned it better be good - if(options && options.fields && !(Buffer.isBuffer(options.fields))) { - fields = {}; - - if(Array.isArray(options.fields)) { - if(!options.fields.length) { - fields['_id'] = 1; - } else { - for (var i = 0, l = options.fields.length; i < l; i++) { - fields[options.fields[i]] = 1; - } - } - } else { - fields = options.fields; - } - } - - if (!options) options = {}; - - var newOptions = {}; - // Make a shallow copy of options - for (var key in options) { - newOptions[key] = options[key]; - } - - // Unpack options - newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; - newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; - newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.s.raw; - newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; - newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; - // // If we have overridden slaveOk otherwise use the default db setting - newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; - - // Add read preference if needed - newOptions = getReadPreference(this, newOptions, this.s.db, this); - // Set slave ok to true if read preference different from primary - if(newOptions.readPreference != null - && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) { - newOptions.slaveOk = true; - } - - // Ensure the query is an object - if(selector != null && typeof selector != 'object') { - throw MongoError.create({message: "query selector must be an object", driver:true }); - } - - // Build the find command - var findCommand = { - find: this.s.namespace - , limit: newOptions.limit - , skip: newOptions.skip - , query: selector - } - - // Ensure we use the right await data option - if(typeof newOptions.awaitdata == 'boolean') { - newOptions.awaitData = newOptions.awaitdata - }; - - // Translate to new command option noCursorTimeout - if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout; - - // Merge in options to command - for(var name in newOptions) { - if(newOptions[name] != null) findCommand[name] = newOptions[name]; - } - - // Format the fields - var formatFields = function(fields) { - var object = {}; - if(Array.isArray(fields)) { - for(var i = 0; i < fields.length; i++) { - if(Array.isArray(fields[i])) { - object[fields[i][0]] = fields[i][1]; - } else { - object[fields[i][0]] = 1; - } - } - } else { - object = fields; - } - - return object; - } - - // Special treatment for the fields selector - if(fields) findCommand.fields = formatFields(fields); - - // Add db object to the new options - newOptions.db = this.s.db; - - // Add the promise library - newOptions.promiseLibrary = this.s.promiseLibrary; - - // Set raw if available at collection level - if(newOptions.raw == null && this.s.raw) newOptions.raw = this.s.raw; - - // Sort options - if(findCommand.sort) - findCommand.sort = formattedOrderClause(findCommand.sort); - - // Set the readConcern - if(this.s.readConcern) { - findCommand.readConcern = this.s.readConcern; - } - - // Create the cursor - if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions)); - return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); -} - -define.classMethod('find', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Inserts a single document into MongoDB. - * @method - * @param {object} doc Document to insert. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertOne = function(doc, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - if(Array.isArray(doc)) return callback(MongoError.create({message: 'doc parameter must be an object', driver:true })); - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return insertOne(self, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - insertOne(self, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var insertOne = function(self, doc, options, callback) { - insertDocuments(self, [doc], options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - // Workaround for pre 2.6 servers - if(r == null) return callback(null, {result: {ok:1}}); - // Add values to top level to ensure crud spec compatibility - r.insertedCount = r.result.n; - r.insertedId = doc._id; - if(callback) callback(null, r); - }); -} - -var mapInserManyResults = function(docs, r) { - var ids = r.getInsertedIds(); - var keys = Object.keys(ids); - var finalIds = new Array(keys); - - for(var i = 0; i < keys.length; i++) { - if(ids[keys[i]]._id) { - finalIds[ids[keys[i]].index] = ids[keys[i]]._id; - } - } - - return { - result: {ok: 1, n: r.insertedCount}, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: finalIds - } -} - -define.classMethod('insertOne', {callback: true, promise:true}); - -/** - * Inserts an array of documents into MongoDB. - * @method - * @param {object[]} docs Documents to insert. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertMany = function(docs, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {ordered:true}; - if(!Array.isArray(docs)) return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); - - // Get the write concern options - if(typeof options.checkKeys != 'boolean') { - options.checkKeys = true; - } - - // If keep going set unordered - options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; - - // Set up the force server object id - var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' - ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; - - // Do we want to force the server to assign the _id key - if(forceServerObjectId !== true) { - // Add _id if not specified - for(var i = 0; i < docs.length; i++) { - if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); - } - } - - // Generate the bulk write operations - var operations = [{ - insertMany: docs - }]; - - // Execute using callback - if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) { - if(err) return callback(err, r); - callback(null, mapInserManyResults(docs, r)); - }); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - bulkWrite(self, operations, options, function(err, r) { - if(err) return reject(err); - resolve(mapInserManyResults(docs, r)); - }); - }); -} - -define.classMethod('insertMany', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~BulkWriteOpResult - * @property {number} insertedCount Number of documents inserted. - * @property {number} matchedCount Number of documents matched for update. - * @property {number} modifiedCount Number of documents modified. - * @property {number} deletedCount Number of documents deleted. - * @property {number} upsertedCount Number of documents upserted. - * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation - * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~bulkWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Perform a bulkWrite operation without a fluent API - * - * Legal operation types are - * - * { insertOne: { document: { a: 1 } } } - * - * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { deleteOne: { filter: {c:1} } } - * - * { deleteMany: { filter: {c:1} } } - * - * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} - * - * @method - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.bulkWrite = function(operations, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {ordered:true}; - - if(!Array.isArray(operations)) { - throw MongoError.create({message: "operations must be an array of documents", driver:true }); - } - - // Execute using callback - if(typeof callback == 'function') return bulkWrite(self, operations, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - bulkWrite(self, operations, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var bulkWrite = function(self, operations, options, callback) { - // Add ignoreUndfined - if(self.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = self.s.options.ignoreUndefined; - } - - // Create the bulk operation - var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options); - - // for each op go through and add to the bulk - for(var i = 0; i < operations.length; i++) { - bulk.raw(operations[i]); - } - - // Final options for write concern - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; - - // Execute the bulk - bulk.execute(writeCon, function(err, r) { - // We have connection level error - if(!r && err) return callback(err, null); - // We have single error - if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) { - return callback(toError(r.getWriteErrorAt(0)), r); - } - - // if(err) return callback(err); - r.insertedCount = r.nInserted; - r.matchedCount = r.nMatched; - r.modifiedCount = r.nModified || 0; - r.deletedCount = r.nRemoved; - r.upsertedCount = r.getUpsertedIds().length; - r.upsertedIds = {}; - r.insertedIds = {}; - - // Update the n - r.n = r.insertedCount; - - // Inserted documents - var inserted = r.getInsertedIds(); - // Map inserted ids - for(var i = 0; i < inserted.length; i++) { - r.insertedIds[inserted[i].index] = inserted[i]._id; - } - - // Upserted documents - var upserted = r.getUpsertedIds(); - // Map upserted ids - for(var i = 0; i < upserted.length; i++) { - r.upsertedIds[upserted[i].index] = upserted[i]._id; - } - - // Check if we have write errors - if(r.hasWriteErrors()) { - // Get all the errors - var errors = r.getWriteErrors(); - // Return the MongoError object - return callback(toError({ - message: 'write operation failed', code: errors[0].code, writeErrors: errors - }), r); - } - - // Check if we have a writeConcern error - if(r.getWriteConcernError()) { - // Return the MongoError object - return callback(toError(r.getWriteConcernError()), r); - } - - // Return the results - callback(null, r); - }); -} - -var insertDocuments = function(self, docs, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Ensure we are operating on an array op docs - docs = Array.isArray(docs) ? docs : [docs]; - - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true; - - // If keep going set unordered - if(finalOptions.keepGoing == true) finalOptions.ordered = false; - finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; - - // Set up the force server object id - var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' - ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; - - // Add _id if not specified - if(forceServerObjectId !== true){ - for(var i = 0; i < docs.length; i++) { - if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); - } - } - - // File inserts - self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err); - if(result == null) return handleCallback(callback, null, null); - if(result.result.code) return handleCallback(callback, toError(result.result)); - if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); - // Add docs to the list - result.ops = docs; - // Return the results - handleCallback(callback, null, result); - }); -} - -define.classMethod('bulkWrite', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~WriteOpResult - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {object} connection The connection object used for the operation. - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~writeOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * @typedef {Object} Collection~insertWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * @typedef {Object} Collection~insertOneWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * The callback format for inserts - * @callback Collection~insertWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * The callback format for inserts - * @callback Collection~insertOneWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Inserts a single document or a an array of documents into MongoDB. - * @method - * @param {(object|object[])} docs Documents to insert. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated Use insertOne, insertMany or bulkWrite - */ -Collection.prototype.insert = function(docs, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {ordered:false}; - docs = !Array.isArray(docs) ? [docs] : docs; - - if(options.keepGoing == true) { - options.ordered = false; - } - - return this.insertMany(docs, options, callback); -} - -define.classMethod('insert', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~updateWriteOpResult - * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents scanned. - * @property {Number} result.nModified The total count of documents modified. - * @property {Object} connection The connection object used for the operation. - * @property {Number} matchedCount The number of documents that matched the filter. - * @property {Number} modifiedCount The number of documents that were modified. - * @property {Number} upsertedCount The number of documents upserted. - * @property {Object} upsertedId The upserted id. - * @property {ObjectId} upsertedId._id The upserted _id returned from the server. - */ - -/** - * The callback format for inserts - * @callback Collection~updateWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Update a single document on MongoDB - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateOne = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options) - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return updateOne(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - updateOne(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var updateOne = function(self, filter, update, options, callback) { - // Set single document update - options.multi = false; - // Execute update - updateDocuments(self, filter, update, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.matchedCount = r.result.n; - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; - r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - if(callback) callback(null, r); - }); -} - -define.classMethod('updateOne', {callback: true, promise:true}); - -/** - * Replace a document on MongoDB - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} doc The Document that replaces the matching document - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.replaceOne = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options) - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return replaceOne(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - replaceOne(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var replaceOne = function(self, filter, update, options, callback) { - // Set single document update - options.multi = false; - // Execute update - updateDocuments(self, filter, update, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.matchedCount = r.result.n; - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; - r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.ops = [update]; - if(callback) callback(null, r); - }); -} - -define.classMethod('replaceOne', {callback: true, promise:true}); - -/** - * Update multiple documents on MongoDB - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateMany = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options) - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return updateMany(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - updateMany(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var updateMany = function(self, filter, update, options, callback) { - // Set single document update - options.multi = true; - // Execute update - updateDocuments(self, filter, update, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.matchedCount = r.result.n; - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; - r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - if(callback) callback(null, r); - }); -} - -define.classMethod('updateMany', {callback: true, promise:true}); - -var updateDocuments = function(self, selector, document, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // If we are not providing a selector or document throw - if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object")); - if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object")); - - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - - // Do we return the actual result document - // Either use override on the function, or go back to default on either the collection - // level or db - finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; - - // Execute the operation - var op = {q: selector, u: document}; - if(options.upsert) op.upsert = true; - if(options.multi) op.multi = true; - - // Update options - self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - if(result == null) return handleCallback(callback, null, null); - if(result.result.code) return handleCallback(callback, toError(result.result)); - if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -/** - * Updates documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} document The update document. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {boolean} [options.multi=false] Update one/all documents with operation. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - * @deprecated use updateOne, updateMany or bulkWrite - */ -Collection.prototype.update = function(selector, document, options, callback) { - var self = this; - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - updateDocuments(self, selector, document, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('update', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~deleteWriteOpResult - * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents deleted. - * @property {Object} connection The connection object used for the operation. - * @property {Number} deletedCount The number of documents deleted. - */ - -/** - * The callback format for inserts - * @callback Collection~deleteWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Delete a document on MongoDB - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteOne = function(filter, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - var options = shallowClone(options); - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return deleteOne(self, filter, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - deleteOne(self, filter, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var deleteOne = function(self, filter, options, callback) { - options.single = true; - removeDocuments(self, filter, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.deletedCount = r.result.n; - if(callback) callback(null, r); - }); -} - -define.classMethod('deleteOne', {callback: true, promise:true}); - -Collection.prototype.removeOne = Collection.prototype.deleteOne; - -define.classMethod('removeOne', {callback: true, promise:true}); - -/** - * Delete multiple documents on MongoDB - * @method - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteMany = function(filter, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - var options = shallowClone(options); - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return deleteMany(self, filter, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - deleteMany(self, filter, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var deleteMany = function(self, filter, options, callback) { - options.single = false; - removeDocuments(self, filter, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.deletedCount = r.result.n; - if(callback) callback(null, r); - }); -} - -var removeDocuments = function(self, selector, options, callback) { - if(typeof options == 'function') { - callback = options, options = {}; - } else if (typeof selector === 'function') { - callback = selector; - options = {}; - selector = {}; - } - - // Create an empty options object if the provided one is null - options = options || {}; - - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - - // If selector is null set empty - if(selector == null) selector = {}; - - // Build the op - var op = {q: selector, limit: 0}; - if(options.single) op.limit = 1; - - // Execute the remove - self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - if(result == null) return handleCallback(callback, null, null); - if(result.result.code) return handleCallback(callback, toError(result.result)); - if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -define.classMethod('deleteMany', {callback: true, promise:true}); - -Collection.prototype.removeMany = Collection.prototype.deleteMany; - -define.classMethod('removeMany', {callback: true, promise:true}); - -/** - * Remove documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.single=false] Removes the first document found. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use deleteOne, deleteMany or bulkWrite - */ -Collection.prototype.remove = function(selector, options, callback) { - var self = this; - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return removeDocuments(self, selector, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - removeDocuments(self, selector, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('remove', {callback: true, promise:true}); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * @method - * @param {object} doc Document to save - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -Collection.prototype.save = function(doc, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return save(self, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - save(self, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var save = function(self, doc, options, callback) { - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - // Establish if we need to perform an insert or update - if(doc._id != null) { - finalOptions.upsert = true; - return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback); - } - - // Insert the document - insertDocuments(self, [doc], options, function(err, r) { - if(callback == null) return; - if(doc == null) return handleCallback(callback, null, null); - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, r); - }); -} - -define.classMethod('save', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Collection~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Fetches the first document that matches the query - * @method - * @param {object} query Query for find Operation - * @param {object} [options=null] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan=null] Limit the number of items to scan. - * @param {number} [options.min=null] Set index bounds. - * @param {number} [options.max=null] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use find().limit(1).next(function(err, doc){}) - */ -Collection.prototype.findOne = function() { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - - // Execute using callback - if(typeof callback == 'function') return findOne(self, args, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - findOne(self, args, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOne = function(self, args, callback) { - var cursor = self.find.apply(self, args).limit(-1).batchSize(1); - // Return the item - cursor.next(function(err, item) { - if(err != null) return handleCallback(callback, toError(err), null); - handleCallback(callback, null, item); - }); -} - -define.classMethod('findOne', {callback: true, promise:true}); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Collection~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Rename the collection. - * - * @method - * @param {string} newName New name of of the collection. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {Collection~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.rename = function(newName, opt, callback) { - var self = this; - if(typeof opt == 'function') callback = opt, opt = {}; - opt = opt || {}; - - // Execute using callback - if(typeof callback == 'function') return rename(self, newName, opt, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - rename(self, newName, opt, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var rename = function(self, newName, opt, callback) { - // Check the collection name - checkCollectionName(newName); - // Build the command - var renameCollection = f("%s.%s", self.s.dbName, self.s.name); - var toCollection = f("%s.%s", self.s.dbName, newName); - var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false; - var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; - - // Execute against admin - self.s.db.admin().command(cmd, opt, function(err, doc) { - if(err) return handleCallback(callback, err, null); - // We have an error - if(doc.errmsg) return handleCallback(callback, toError(doc), null); - try { - return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options)); - } catch(err) { - return handleCallback(callback, toError(err), null); - } - }); -} - -define.classMethod('rename', {callback: true, promise:true}); - -/** - * Drop the collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.drop = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, callback); - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.dropCollection(self.s.name, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('drop', {callback: true, promise:true}); - -/** - * Returns the options of the collection. - * - * @method - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.options = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return options(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var options = function(self, callback) { - self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) { - if(err) return handleCallback(callback, err); - if(collections.length == 0) { - return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true })); - } - - handleCallback(callback, err, collections[0].options || null); - }); -} - -define.classMethod('options', {callback: true, promise:true}); - -/** - * Returns if the collection is a capped collection - * - * @method - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.isCapped = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return isCapped(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - isCapped(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var isCapped = function(self, callback) { - self.options(function(err, document) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, document && document.capped); - }); -} - -define.classMethod('isCapped', {callback: true, promise:true}); - -/** - * Creates an index on the db and collection collection. - * @method - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Execute using callback - if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - createIndex(self, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var createIndex = function(self, fieldOrSpec, options, callback) { - self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback); -} - -define.classMethod('createIndex', {callback: true, promise:true}); - -/** - * Creates multiple indexes in the collection, this method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. - * @method - * @param {array} indexSpecs An array of index specifications to be created - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.createIndexes = function(indexSpecs, callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - createIndexes(self, indexSpecs, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var createIndexes = function(self, indexSpecs, callback) { - // Ensure we generate the correct name if the parameter is not set - for(var i = 0; i < indexSpecs.length; i++) { - if(indexSpecs[i].name == null) { - var keys = []; - - for(var name in indexSpecs[i].key) { - keys.push(f('%s_%s', name, indexSpecs[i].key[name])); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - // Execute the index - self.s.db.command({ - createIndexes: self.s.name, indexes: indexSpecs - }, callback); -} - -define.classMethod('createIndexes', {callback: true, promise:true}); - -/** - * Drops an index from this collection. - * @method - * @param {string} indexName Name of the index to drop. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndex = function(indexName, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - // Execute using callback - if(typeof callback == 'function') return dropIndex(self, indexName, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - dropIndex(self, indexName, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var dropIndex = function(self, indexName, options, callback) { - // Delete index command - var cmd = {'deleteIndexes':self.s.name, 'index':indexName}; - - // Execute command - self.s.db.command(cmd, options, function(err, result) { - if(typeof callback != 'function') return; - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -define.classMethod('dropIndex', {callback: true, promise:true}); - -/** - * Drops all indexes from this collection. - * @method - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndexes = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return dropIndexes(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - dropIndexes(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var dropIndexes = function(self, callback) { - self.dropIndex('*', function (err, result) { - if(err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); -} - -define.classMethod('dropIndexes', {callback: true, promise:true}); - -/** - * Drops all indexes from this collection. - * @method - * @deprecated use dropIndexes - * @param {Collection~resultCallback} callback The command result callback - * @return {Promise} returns Promise if no [callback] passed - */ -Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; - -define.classMethod('dropAllIndexes', {callback: true, promise:true}); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * @method - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.reIndex = function(options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return reIndex(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - reIndex(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var reIndex = function(self, options, callback) { - // Reindex - var cmd = {'reIndex':self.s.name}; - - // Execute the command - self.s.db.command(cmd, options, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); -} - -define.classMethod('reIndex', {callback: true, promise:true}); - -/** - * Get the list of all indexes information for the collection. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @return {CommandCursor} - */ -Collection.prototype.listIndexes = function(options) { - options = options || {}; - // Clone the options - options = shallowClone(options); - // Set the CommandCursor constructor - options.cursorFactory = CommandCursor; - // Set the promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // We have a list collections command - if(this.s.db.serverConfig.capabilities().hasListIndexesCommand) { - // Cursor options - var cursor = options.batchSize ? {batchSize: options.batchSize} : {} - // Build the command - var command = { listIndexes: this.s.name, cursor: cursor }; - // Execute the cursor - return this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); - } - - // Get the namespace - var ns = f('%s.system.indexes', this.s.dbName); - // Get the query - return this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options); -}; - -define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]}); - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated use createIndexes instead - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - ensureIndex(self, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var ensureIndex = function(self, fieldOrSpec, options, callback) { - self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback); -} - -define.classMethod('ensureIndex', {callback: true, promise:true}); - -/** - * Checks if one or more indexes exist on the collection, fails on first non-existing index - * @method - * @param {(string|array)} indexes One or more index names to check. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexExists = function(indexes, callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return indexExists(self, indexes, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexExists(self, indexes, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var indexExists = function(self, indexes, callback) { - self.indexInformation(function(err, indexInformation) { - // If we have an error return - if(err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for(var i = 0; i < indexes.length; i++) { - if(indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); -} - -define.classMethod('indexExists', {callback: true, promise:true}); - -/** - * Retrieves this collections index info. - * @method - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexInformation = function(options, callback) { - var self = this; - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return indexInformation(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexInformation(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var indexInformation = function(self, options, callback) { - self.s.db.indexInformation(self.s.name, options, callback); -} - -define.classMethod('indexInformation', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Collection~countCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} result The count of documents that matched the query. - */ - -/** - * Count number of matching documents in the db to a query. - * @method - * @param {object} query The query for the count. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.limit=null] The limit of documents to count. - * @param {boolean} [options.skip=null] The number of documents to skip for the count. - * @param {string} [options.hint=null] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Collection~countCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.count = function(query, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - var queryOption = args.length ? args.shift() || {} : {}; - var optionsOption = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback); - - // Check if query is empty - query = query || {}; - options = options || {}; - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - count(self, query, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var count = function(self, query, options, callback) { - var skip = options.skip; - var limit = options.limit; - var hint = options.hint; - var maxTimeMS = options.maxTimeMS; - - // Final query - var cmd = { - 'count': self.s.name, 'query': query - , 'fields': null - }; - - // Add limit and skip if defined - if(typeof skip == 'number') cmd.skip = skip; - if(typeof limit == 'number') cmd.limit = limit; - if(hint) options.hint = hint; - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - cmd.readConcern = self.s.readConcern; - } - - // Execute command - self.s.db.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.n); - }); -} - -define.classMethod('count', {callback: true, promise:true}); - -/** - * The distinct command returns returns a list of distinct values for the given key across a collection. - * @method - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.distinct = function(key, query, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - var queryOption = args.length ? args.shift() || {} : {}; - var optionsOption = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback); - - // Ensure the query and options are set - query = query || {}; - options = options || {}; - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - distinct(self, key, query, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var distinct = function(self, key, query, options, callback) { - // maxTimeMS option - var maxTimeMS = options.maxTimeMS; - - // Distinct command - var cmd = { - 'distinct': self.s.name, 'key': key, 'query': query - }; - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - cmd.readConcern = self.s.readConcern; - } - - // Execute the command - self.s.db.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.values); - }); -} - -define.classMethod('distinct', {callback: true, promise:true}); - -/** - * Retrieve all the indexes on the collection. - * @method - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexes = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return indexes(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexes(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var indexes = function(self, callback) { - self.s.db.indexInformation(self.s.name, {full:true}, callback); -} - -define.classMethod('indexes', {callback: true, promise:true}); - -/** - * Get all the collection statistics. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {number} [options.scale=null] Divide the returned sizes by scale value. - * @param {Collection~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.stats = function(options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return stats(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - stats(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var stats = function(self, options, callback) { - // Build command object - var commandObject = { - collStats:self.s.name - } - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Execute the command - self.s.db.command(commandObject, options, callback); -} - -define.classMethod('stats', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~findAndModifyWriteOpResult - * @property {object} value Document returned from findAndModify command. - * @property {object} lastErrorObject The raw lastErrorObject returned from the command. - * @property {Number} ok Is 1 if the command executed correctly. - */ - -/** - * The callback format for inserts - * @callback Collection~findAndModifyCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter Document selection filter. - * @param {object} [options=null] Optional settings. - * @param {object} [options.projection=null] Limits the fields to return for all matching documents. - * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndDelete = function(filter, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findOneAndDelete(self, filter, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOneAndDelete = function(self, filter, options, callback) { - // Final options - var finalOptions = shallowClone(options); - finalOptions['fields'] = options.projection; - finalOptions['remove'] = true; - // Execute find and Modify - self.findAndModify( - filter - , options.sort - , null - , finalOptions - , callback - ); -} - -define.classMethod('findOneAndDelete', {callback: true, promise:true}); - -/** - * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter Document selection filter. - * @param {object} replacement Document replacing the matching document. - * @param {object} [options=null] Optional settings. - * @param {object} [options.projection=null] Limits the fields to return for all matching documents. - * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findOneAndReplace(self, filter, replacement, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOneAndReplace = function(self, filter, replacement, options, callback) { - // Final options - var finalOptions = shallowClone(options); - finalOptions['fields'] = options.projection; - finalOptions['update'] = true; - finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; - finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Execute findAndModify - self.findAndModify( - filter - , options.sort - , replacement - , finalOptions - , callback - ); -} - -define.classMethod('findOneAndReplace', {callback: true, promise:true}); - -/** - * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter Document selection filter. - * @param {object} update Update operations to be performed on the document - * @param {object} [options=null] Optional settings. - * @param {object} [options.projection=null] Limits the fields to return for all matching documents. - * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findOneAndUpdate(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOneAndUpdate = function(self, filter, update, options, callback) { - // Final options - var finalOptions = shallowClone(options); - finalOptions['fields'] = options.projection; - finalOptions['update'] = true; - finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; - finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Execute findAndModify - self.findAndModify( - filter - , options.sort - , update - , finalOptions - , callback - ); -} - -define.classMethod('findOneAndUpdate', {callback: true, promise:true}); - -/** - * Find and update a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.remove=false] Set to true to remove the object before returning. - * @param {boolean} [options.upsert=false] Perform an upsert operation. - * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. - * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Clone options - var options = shallowClone(options); - // Force read preference primary - options.readPreference = ReadPreference.PRIMARY; - - // Execute using callback - if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findAndModify(self, query, sort, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findAndModify = function(self, query, sort, doc, options, callback) { - // Create findAndModify command object - var queryObject = { - 'findandmodify': self.s.name - , 'query': query - }; - - sort = formattedOrderClause(sort); - if(sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - if(options.fields) { - queryObject.fields = options.fields; - } - - if(doc && !options.remove) { - queryObject.update = doc; - } - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = self.s.serializeFunctions; - } - - // No check on the documents - options.checkKeys = false; - - // Get the write concern settings - var finalOptions = writeConcern(options, self.s.db, self, options); - - // Decorate the findAndModify command with the write Concern - if(finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } - - // Have we specified bypassDocumentValidation - if(typeof finalOptions.bypassDocumentValidation == 'boolean') { - queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; - } - - // Execute the command - self.s.db.command(queryObject - , options, function(err, result) { - if(err) return handleCallback(callback, err, null); - return handleCallback(callback, null, result); - }); -} - -define.classMethod('findAndModify', {callback: true, promise:true}); - -/** - * Find and remove a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndDelete instead - */ -Collection.prototype.findAndRemove = function(query, sort, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - findAndRemove(self, query, sort, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findAndRemove = function(self, query, sort, options, callback) { - // Add the remove option - options['remove'] = true; - // Execute the callback - self.findAndModify(query, sort, null, options, callback); -} - -define.classMethod('findAndRemove', {callback: true, promise:true}); - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * @method - * @param {object} pipeline Array containing all the aggregation framework commands for the execution. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~resultCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - var self = this; - if(Array.isArray(pipeline)) { - // Set up callback if one is provided - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if(options == null && callback == null) { - options = {}; - } - } else { - // Aggregation pipeline passed as arguments on the method - var args = Array.prototype.slice.call(arguments, 0); - // Get the callback - callback = args.pop(); - // Get the possible options object - var opts = args[args.length - 1]; - // If it contains any of the admissible options pop it of the args - options = opts && (opts.readPreference - || opts.explain || opts.cursor || opts.out - || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {}; - // Left over arguments is the pipeline - pipeline = args; - } - - // If out was specified - if(typeof options.out == 'string') { - pipeline.push({$out: options.out}); - } - - // Build the command - var command = { aggregate : this.s.name, pipeline : pipeline}; - - // If we have bypassDocumentValidation set - if(typeof options.bypassDocumentValidation == 'boolean') { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Do we have a readConcern specified - if(this.s.readConcern) { - command.readConcern = this.s.readConcern; - } - - // If we have allowDiskUse defined - if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; - if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; - - // Ensure we have the right read preference inheritance - options = getReadPreference(this, options, this.s.db, this); - - // If explain has been specified add it - if(options.explain) command.explain = options.explain; - - // Validate that cursor options is valid - if(options.cursor != null && typeof options.cursor != 'object') { - throw toError('cursor options must be an object'); - } - - // promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // Set the AggregationCursor constructor - options.cursorFactory = AggregationCursor; - if(typeof callback != 'function') { - if(this.s.topology.capabilities().hasAggregationCursor) { - options.cursor = options.cursor || { batchSize : 1000 }; - command.cursor = options.cursor; - } - - // Allow disk usage command - if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse; - if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; - - // Execute the cursor - return this.s.topology.cursor(this.s.namespace, command, options); - } - - var cursor = null; - // We do not allow cursor - if(options.cursor) { - return this.s.topology.cursor(this.s.namespace, command, options); - } - - // Execute the command - this.s.db.command(command, options, function(err, result) { - if(err) { - handleCallback(callback, err); - } else if(result['err'] || result['errmsg']) { - handleCallback(callback, toError(result)); - } else if(typeof result == 'object' && result['serverPipeline']) { - handleCallback(callback, null, result['serverPipeline']); - } else if(typeof result == 'object' && result['stages']) { - handleCallback(callback, null, result['stages']); - } else { - handleCallback(callback, null, result.result); - } - }); -} - -define.classMethod('aggregate', {callback: true, promise:false}); - -/** - * The callback format for results - * @callback Collection~parallelCollectionScanCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. - */ - -/** - * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are - * no ordering guarantees for returned results. - * @method - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.parallelCollectionScan = function(options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {numCursors: 1}; - // Set number of cursors to 1 - options.numCursors = options.numCursors || 1; - options.batchSize = options.batchSize || 1000; - - // Ensure we have the right read preference inheritance - options = getReadPreference(this, options, this.s.db, this); - - // Add a promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // Execute using callback - if(typeof callback == 'function') return parallelCollectionScan(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - parallelCollectionScan(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var parallelCollectionScan = function(self, options, callback) { - // Create command object - var commandObject = { - parallelCollectionScan: self.s.name - , numCursors: options.numCursors - } - - // Do we have a readConcern specified - if(self.s.readConcern) { - commandObject.readConcern = self.s.readConcern; - } - - // Execute the command - self.s.db.command(commandObject, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null); - - var cursors = []; - // Create command cursors for each item - for(var i = 0; i < result.cursors.length; i++) { - var rawId = result.cursors[i].cursor.id - // Convert cursorId to Long if needed - var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId; - - // Command cursor options - var cmd = { - batchSize: options.batchSize - , cursorId: cursorId - , items: result.cursors[i].cursor.firstBatch - } - - // Add a command cursor - cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); - } - - handleCallback(callback, null, cursors); - }); -} - -define.classMethod('parallelCollectionScan', {callback: true, promise:true}); - -/** - * Execute the geoNear command to search for items in the collection - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.num=null] Max number of results to return. - * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher) - * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. - * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions. - * @param {object} [options.query=null] Filter the results by a query. - * @param {boolean} [options.spherical=false] Perform query using a spherical model. - * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X. - * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoNear = function(x, y, options, callback) { - var self = this; - var point = typeof(x) == 'object' && x - , args = Array.prototype.slice.call(arguments, point?1:2); - - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - geoNear(self, x, y, point, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var geoNear = function(self, x, y, point, options, callback) { - // Build command object - var commandObject = { - geoNear:self.s.name, - near: point || [x, y] - } - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Exclude readPreference and existing options to prevent user from - // shooting themselves in the foot - var exclude = { - readPreference: true, - geoNear: true, - near: true - }; - - // Filter out any excluded objects - commandObject = decorateCommand(commandObject, options, exclude); - - // Do we have a readConcern specified - if(self.s.readConcern) { - commandObject.readConcern = self.s.readConcern; - } - - // Execute the command - self.s.db.command(commandObject, options, function (err, res) { - if(err) return handleCallback(callback, err); - if(res.err || res.errmsg) return handleCallback(callback, toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); -} - -define.classMethod('geoNear', {callback: true, promise:true}); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. - * @param {object} [options.search=null] Filter the results by a query. - * @param {number} [options.limit=false] Max number of results to return. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - geoHaystackSearch(self, x, y, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var geoHaystackSearch = function(self, x, y, options, callback) { - // Build command object - var commandObject = { - geoSearch: self.s.name, - near: [x, y] - } - - // Remove read preference from hash if it exists - commandObject = decorateCommand(commandObject, options, {readPreference: true}); - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - commandObject.readConcern = self.s.readConcern; - } - - // Execute the command - self.s.db.command(commandObject, options, function (err, res) { - if(err) return handleCallback(callback, err); - if(res.err || res.errmsg) handleCallback(callback, utils.toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); -} - -define.classMethod('geoHaystackSearch', {callback: true, promise:true}); - -/** - * Group function helper - * @ignore - */ -var groupFunction = function () { - var c = db[ns].find(condition); - var map = new Map(); - var reduce_function = reduce; - - while (c.hasNext()) { - var obj = c.next(); - var key = {}; - - for (var i = 0, len = keys.length; i < len; ++i) { - var k = keys[i]; - key[k] = obj[k]; - } - - var aggObj = map.get(key); - - if (aggObj == null) { - var newObj = Object.extend({}, key); - aggObj = Object.extend(newObj, initial); - map.put(key, aggObj); - } - - reduce_function(obj, aggObj); - } - - return { "result": map.values() }; -}.toString(); - -/** - * Run a group command across a collection - * - * @method - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 3); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if(!(typeof finalize == 'function')) { - command = finalize; - finalize = null; - } - - if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) { - keys = Object.keys(keys); - } - - if(typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if(typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - // Execute using callback - if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) { - // Execute using the command - if(command) { - var reduceFunction = reduce instanceof Code - ? reduce - : new Code(reduce); - - var selector = { - group: { - 'ns': self.s.name - , '$reduce': reduceFunction - , 'cond': condition - , 'initial': initial - , 'out': "inline" - } - }; - - // if finalize is defined - if(finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || keys instanceof Code) { - selector.group.$keyf = keys instanceof Code - ? keys - : new Code(keys); - } else { - var hash = {}; - keys.forEach(function (key) { - hash[key] = 1; - }); - selector.group.key = hash; - } - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - selector.readConcern = self.s.readConcern; - } - - // Execute command - self.s.db.command(selector, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.retval); - }); - } else { - // Create execution scope - var scope = reduce != null && reduce instanceof Code - ? reduce.scope - : {}; - - scope.ns = self.s.name; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - self.s.db.eval(new Code(groupfn, scope), function (err, results) { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, results.result || results); - }); - } -} - -define.classMethod('group', {callback: true, promise:true}); - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope (scope) { - if(!isObject(scope)) { - return scope; - } - - var keys = Object.keys(scope); - var i = keys.length; - var key; - var new_scope = {}; - - while (i--) { - key = keys[i]; - if ('function' == typeof scope[key]) { - new_scope[key] = new Code(String(scope[key])); - } else { - new_scope[key] = processScope(scope[key]); - } - } - - return new_scope; -} - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @method - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * @param {object} [options.query=null] Query filter object. - * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * @param {number} [options.limit=null] Number of objects to return from collection. - * @param {boolean} [options.keeptemp=false] Keep temporary data. - * @param {(function|string)} [options.finalize=null] Finalize function. - * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. - * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * @param {boolean} [options.verbose=false] Provide statistics on job execution time. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~resultCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.mapReduce = function(map, reduce, options, callback) { - var self = this; - if('function' === typeof options) callback = options, options = {}; - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if(null == options.out) { - throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); - } - - if('function' === typeof map) { - map = map.toString(); - } - - if('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - - // Execute using callback - if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - mapReduce(self, map, reduce, options, function(err, r, r1) { - if(err) return reject(err); - if(r instanceof Collection) return resolve(r); - resolve({results: r, stats: r1}); - }); - }); -} - -var mapReduce = function(self, map, reduce, options, callback) { - var mapCommandHash = { - mapreduce: self.s.name - , map: map - , reduce: reduce - }; - - // Add any other options passed in - for(var n in options) { - if('scope' == n) { - mapCommandHash[n] = processScope(options[n]); - } else { - mapCommandHash[n] = options[n]; - } - } - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // If we have a read preference and inline is not set as output fail hard - if((options.readPreference != false && options.readPreference != 'primary') - && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { - options.readPreference = 'primary'; - } - - // Is bypassDocumentValidation specified - if(typeof options.bypassDocumentValidation == 'boolean') { - mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Do we have a readConcern specified - if(self.s.readConcern) { - mapCommandHash.readConcern = self.s.readConcern; - } - - // Execute command - self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) { - if(err) return handleCallback(callback, err); - // Check if we have an error - if(1 != result.ok || result.err || result.errmsg) { - return handleCallback(callback, toError(result)); - } - - // Create statistics value - var stats = {}; - if(result.timeMillis) stats['processtime'] = result.timeMillis; - if(result.counts) stats['counts'] = result.counts; - if(result.timing) stats['timing'] = result.timing; - - // invoked with inline? - if(result.results) { - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, null, result.results); - } - - return handleCallback(callback, null, result.results, stats); - } - - // The returned collection - var collection = null; - - // If we have an object it's a different db - if(result.result != null && typeof result.result == 'object') { - var doc = result.result; - collection = self.s.db.db(doc.db).collection(doc.collection); - } else { - // Create a collection object that wraps the result collection - collection = self.s.db.collection(result.result) - } - - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, err, collection); - } - - // Return stats as third set of values - handleCallback(callback, err, collection, stats); - }); -} - -define.classMethod('mapReduce', {callback: true, promise:true}); - -/** - * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @return {UnorderedBulkOperation} - */ -Collection.prototype.initializeUnorderedBulkOp = function(options) { - options = options || {}; - options.promiseLibrary = this.s.promiseLibrary; - return unordered(this.s.topology, this, options); -} - -define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]}); - -/** - * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {OrderedBulkOperation} callback The command result callback - * @return {null} - */ -Collection.prototype.initializeOrderedBulkOp = function(options) { - options = options || {}; - options.promiseLibrary = this.s.promiseLibrary; - return ordered(this.s.topology, this, options); -} - -define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]}); - -// Get write concern -var writeConcern = function(target, db, col, options) { - if(options.w != null || options.j != null || options.fsync != null) { - var opts = {}; - if(options.w != null) opts.w = options.w; - if(options.wtimeout != null) opts.wtimeout = options.wtimeout; - if(options.j != null) opts.j = options.j; - if(options.fsync != null) opts.fsync = options.fsync; - target.writeConcern = opts; - } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { - target.writeConcern = col.writeConcern; - } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { - target.writeConcern = db.writeConcern; - } - - return target -} - -// Figure out the read preference -var getReadPreference = function(self, options, db, coll) { - var r = null - if(options.readPreference) { - r = options.readPreference - } else if(self.s.readPreference) { - r = self.s.readPreference - } else if(db.readPreference) { - r = db.readPreference; - } - - if(r instanceof ReadPreference) { - options.readPreference = new CoreReadPreference(r.mode, r.tags); - } else if(typeof r == 'string') { - options.readPreference = new CoreReadPreference(r); - } - - return options; -} - -var testForFields = { - limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 - , numberOfRetries: 1, awaitdata: 1, awaitData: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 - , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms: 1 -} - -module.exports = Collection; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/command_cursor.js b/util/demographicsImporter/node_modules/mongodb/lib/command_cursor.js deleted file mode 100644 index 37df593..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/command_cursor.js +++ /dev/null @@ -1,296 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , toError = require('./utils').toError - , getSingleProperty = require('./utils').getSingleProperty - , formattedOrderClause = require('./utils').formattedOrderClause - , handleCallback = require('./utils').handleCallback - , Logger = require('mongodb-core').Logger - , EventEmitter = require('events').EventEmitter - , ReadPreference = require('./read_preference') - , MongoError = require('mongodb-core').MongoError - , Readable = require('stream').Readable || require('readable-stream').Readable - , Define = require('./metadata') - , CoreCursor = require('./cursor') - , Query = require('mongodb-core').Query - , CoreReadPreference = require('mongodb-core').ReadPreference; - -/** - * @fileOverview The **CommandCursor** class is an internal class that embodies a - * generalized cursor based on a MongoDB command allowing for iteration over the - * results returned. It supports one by one document iteration, conversion to an - * array or can be iterated as a Node 0.10.X or higher stream - * - * **CommandCursor Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('listCollectionsExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * - * // List the database collections available - * db.listCollections().toArray(function(err, items) { - * test.equal(null, err); - * db.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class CommandCursor - * @extends external:Readable - * @fires CommandCursor#data - * @fires CommandCursor#end - * @fires CommandCursor#close - * @fires CommandCursor#readable - * @return {CommandCursor} an CommandCursor instance. - */ -var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - var self = this; - var state = CommandCursor.INIT; - var streamOptions = {}; - - // MaxTimeMS - var maxTimeMS = null; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set up - Readable.call(this, {objectMode: true}); - - // Internal state - this.s = { - // MaxTimeMS - maxTimeMS: maxTimeMS - // State - , state: state - // Stream options - , streamOptions: streamOptions - // BSON - , bson: bson - // Namespae - , ns: ns - // Command - , cmd: cmd - // Options - , options: options - // Topology - , topology: topology - // Topology Options - , topologyOptions: topologyOptions - // Promise library - , promiseLibrary: promiseLibrary - } -} - -/** - * CommandCursor stream data event, fired for each document in the cursor. - * - * @event CommandCursor#data - * @type {object} - */ - -/** - * CommandCursor stream end event - * - * @event CommandCursor#end - * @type {null} - */ - -/** - * CommandCursor stream close event - * - * @event CommandCursor#close - * @type {null} - */ - -/** - * CommandCursor stream readable event - * - * @event CommandCursor#readable - * @type {null} - */ - -// Inherit from Readable -inherits(CommandCursor, Readable); - -// Set the methods to inherit from prototype -var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' - , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' - , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled']; - -// Only inherit the types we need -for(var i = 0; i < methodsToInherit.length; i++) { - CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; -} - -var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true); - -/** - * Set the batch size for the cursor. - * @method - * @param {number} value The batchSize for the cursor. - * @throws {MongoError} - * @return {CommandCursor} - */ -CommandCursor.prototype.batchSize = function(value) { - if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); - if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; - this.setCursorBatchSize(value); - return this; -} - -define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]}); - -/** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {CommandCursor} - */ -CommandCursor.prototype.maxTimeMS = function(value) { - if(this.s.topology.lastIsMaster().minWireVersion > 2) { - this.s.cmd.maxTimeMS = value; - } - return this; -} - -define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]}); - -CommandCursor.prototype.get = CommandCursor.prototype.toArray; - -define.classMethod('get', {callback: true, promise:false}); - -// Inherited methods -define.classMethod('toArray', {callback: true, promise:true}); -define.classMethod('each', {callback: true, promise:false}); -define.classMethod('forEach', {callback: true, promise:false}); -define.classMethod('next', {callback: true, promise:true}); -define.classMethod('close', {callback: true, promise:true}); -define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); -define.classMethod('rewind', {callback: false, promise:false}); -define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); -define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function CommandCursor.prototype.next - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. - * @method CommandCursor.prototype.toArray - * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method CommandCursor.prototype.each - * @param {CommandCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method CommandCursor.prototype.close - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method CommandCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Clone the cursor - * @function CommandCursor.prototype.clone - * @return {CommandCursor} - */ - -/** - * Resets the cursor - * @function CommandCursor.prototype.rewind - * @return {CommandCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback CommandCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback CommandCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method CommandCursor.prototype.forEach - * @param {CommandCursor~iteratorCallback} iterator The iteration callback. - * @param {CommandCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -CommandCursor.INIT = 0; -CommandCursor.OPEN = 1; -CommandCursor.CLOSED = 2; - -module.exports = CommandCursor; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/cursor.js b/util/demographicsImporter/node_modules/mongodb/lib/cursor.js deleted file mode 100644 index 1a446a8..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/cursor.js +++ /dev/null @@ -1,1149 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , toError = require('./utils').toError - , getSingleProperty = require('./utils').getSingleProperty - , formattedOrderClause = require('./utils').formattedOrderClause - , handleCallback = require('./utils').handleCallback - , Logger = require('mongodb-core').Logger - , EventEmitter = require('events').EventEmitter - , ReadPreference = require('./read_preference') - , MongoError = require('mongodb-core').MongoError - , Readable = require('stream').Readable || require('readable-stream').Readable - , Define = require('./metadata') - , CoreCursor = require('mongodb-core').Cursor - , Query = require('mongodb-core').Query - , CoreReadPreference = require('mongodb-core').ReadPreference; - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X - * or higher stream - * - * **CURSORS Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * db.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the mongodb-core and node.js - * @external CoreCursor - * @external Readable - */ - -// Flags allowed for cursor -var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; -var fields = ['numberOfRetries', 'tailableRetryInterval']; - -/** - * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class Cursor - * @extends external:CoreCursor - * @extends external:Readable - * @property {string} sortValue Cursor query sort setting. - * @property {boolean} timeout Is Cursor able to time out. - * @property {ReadPreference} readPreference Get cursor ReadPreference. - * @fires Cursor#data - * @fires Cursor#end - * @fires Cursor#close - * @fires Cursor#readable - * @return {Cursor} a Cursor instance. - * @example - * Cursor cursor options. - * - * collection.find({}).project({a:1}) // Create a projection of field a - * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 - * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 - * collection.find({}).filter({a:1}) // Set query on the cursor - * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries - * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable - * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay - * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout - * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData - * collection.find({}).addCursorFlag('exhaust', true) // Set cursor as exhaust - * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial - * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} - * collection.find({}).max(10) // Set the cursor maxScan - * collection.find({}).maxScan(10) // Set the cursor maxScan - * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS - * collection.find({}).min(100) // Set the cursor min - * collection.find({}).returnKey(10) // Set the cursor returnKey - * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference - * collection.find({}).showRecordId(true) // Set the cursor showRecordId - * collection.find({}).snapshot(true) // Set the cursor snapshot - * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query - * collection.find({}).hint('a_1') // Set the cursor hint - * - * All options are chainable, so one can do the following. - * - * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) - */ -var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - var self = this; - var state = Cursor.INIT; - var streamOptions = {}; - - // Tailable cursor options - var numberOfRetries = options.numberOfRetries || 5; - var tailableRetryInterval = options.tailableRetryInterval || 500; - var currentNumberOfRetries = numberOfRetries; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set up - Readable.call(this, {objectMode: true}); - - // Internal cursor state - this.s = { - // Tailable cursor options - numberOfRetries: numberOfRetries - , tailableRetryInterval: tailableRetryInterval - , currentNumberOfRetries: currentNumberOfRetries - // State - , state: state - // Stream options - , streamOptions: streamOptions - // BSON - , bson: bson - // Namespace - , ns: ns - // Command - , cmd: cmd - // Options - , options: options - // Topology - , topology: topology - // Topology options - , topologyOptions: topologyOptions - // Promise library - , promiseLibrary: promiseLibrary - // Current doc - , currentDoc: null - } - - // Legacy fields - this.timeout = self.s.options.noCursorTimeout == true; - this.sortValue = self.s.cmd.sort; - this.readPreference = self.s.options.readPreference; -} - -/** - * Cursor stream data event, fired for each document in the cursor. - * - * @event Cursor#data - * @type {object} - */ - -/** - * Cursor stream end event - * - * @event Cursor#end - * @type {null} - */ - -/** - * Cursor stream close event - * - * @event Cursor#close - * @type {null} - */ - -/** - * Cursor stream readable event - * - * @event Cursor#readable - * @type {null} - */ - -// Inherit from Readable -inherits(Cursor, Readable); - -// Map core cursor _next method so we can apply mapping -CoreCursor.prototype._next = CoreCursor.prototype.next; - -for(var name in CoreCursor.prototype) { - Cursor.prototype[name] = CoreCursor.prototype[name]; -} - -var define = Cursor.define = new Define('Cursor', Cursor, true); - -/** - * Check if there is any document still available in the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.hasNext = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') { - if(self.s.currentDoc){ - return callback(null, true); - } else { - return nextObject(self, function(err, doc) { - if(!doc) return callback(null, false); - self.s.currentDoc = doc; - callback(null, true); - }); - } - } - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - if(self.s.currentDoc){ - resolve(true); - } else { - nextObject(self, function(err, doc) { - if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false); - if(err) return reject(err); - if(!doc) return resolve(false); - self.s.currentDoc = doc; - resolve(true); - }); - } - }); -} - -define.classMethod('hasNext', {callback: true, promise:true}); - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.next = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') { - // Return the currentDoc if someone called hasNext first - if(self.s.currentDoc) { - var doc = self.s.currentDoc; - self.s.currentDoc = null; - return callback(null, doc); - } - - // Return the next object - return nextObject(self, callback) - }; - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - // Return the currentDoc if someone called hasNext first - if(self.s.currentDoc) { - var doc = self.s.currentDoc; - self.s.currentDoc = null; - return resolve(doc); - } - - nextObject(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('next', {callback: true, promise:true}); - -/** - * Set the cursor query - * @method - * @param {object} filter The filter object used for the cursor. - * @return {Cursor} - */ -Cursor.prototype.filter = function(filter) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.query = filter; - return this; -} - -define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor maxScan - * @method - * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query - * @return {Cursor} - */ -Cursor.prototype.maxScan = function(maxScan) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.maxScan = maxScan; - return this; -} - -define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor hint - * @method - * @param {object} hint If specified, then the query system will only consider plans using the hinted index. - * @return {Cursor} - */ -Cursor.prototype.hint = function(hint) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.hint = hint; - return this; -} - -define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor min - * @method - * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. - * @return {Cursor} - */ -Cursor.prototype.min = function(min) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.min = min; - return this; -} - -define.classMethod('min', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor max - * @method - * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. - * @return {Cursor} - */ -Cursor.prototype.max = function(max) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.max = max; - return this; -} - -define.classMethod('max', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor returnKey - * @method - * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms: - * @return {Cursor} - */ -Cursor.prototype.returnKey = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.returnKey = value; - return this; -} - -define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor showRecordId - * @method - * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. - * @return {Cursor} - */ -Cursor.prototype.showRecordId = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.showDiskLoc = value; - return this; -} - -define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor snapshot - * @method - * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. - * @return {Cursor} - */ -Cursor.prototype.snapshot = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.snapshot = value; - return this; -} - -define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set a node.js specific cursor option - * @method - * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. - * @param {object} value The field value. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.setCursorOption = function(field, value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true }); - this.s[field] = value; - if(field == 'numberOfRetries') - this.s.currentNumberOfRetries = value; - return this; -} - -define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Add a cursor flag to the cursor - * @method - * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']. - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.addCursorFlag = function(flag, value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true }); - if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true}); - this.s.cmd[flag] = value; - return this; -} - -define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Add a query modifier to the cursor query - * @method - * @param {string} name The query modifier (must start with $, such as $orderby etc) - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.addQueryModifier = function(name, value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true}); - // Strip of the $ - var field = name.substr(1); - // Set on the command - this.s.cmd[field] = value; - // Deal with the special case for sort - if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field]; - return this; -} - -define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Add a comment to the cursor query allowing for tracking the comment in the log. - * @method - * @param {string} value The comment attached to this query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.comment = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.comment = value; - return this; -} - -define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) - * @method - * @param {number} value Number of milliseconds to wait before aborting the query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.maxTimeMS = function(value) { - if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true}); - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.maxTimeMS = value; - return this; -} - -define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]}); - -Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; - -define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Sets a field projection for the query. - * @method - * @param {object} value The field projection object. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.project = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.fields = value; - return this; -} - -define.classMethod('project', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Sets the sort order of the cursor query. - * @method - * @param {(string|array|object)} keyOrList The key or keys set for the sort. - * @param {number} [direction] The direction of the sorting (1 or -1). - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.sort = function(keyOrList, direction) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true}); - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - var order = keyOrList; - - if(direction != null) { - order = [[keyOrList, direction]]; - } - - this.s.cmd.sort = order; - this.sortValue = order; - return this; -} - -define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the batch size for the cursor. - * @method - * @param {number} value The batchSize for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.batchSize = function(value) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true}); - if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); - this.s.cmd.batchSize = value; - this.setCursorBatchSize(value); - return this; -} - -define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the limit for the cursor. - * @method - * @param {number} value The limit for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.limit = function(value) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true}); - if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true}); - this.s.cmd.limit = value; - // this.cursorLimit = value; - this.setCursorLimit(value); - return this; -} - -define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the skip for the cursor. - * @method - * @param {number} value The skip for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.skip = function(value) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true}); - if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true}); - this.s.cmd.skip = value; - this.setCursorSkip(value); - return this; -} - -define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]}); - -/** - * The callback format for results - * @callback Cursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null|boolean)} result The result object if the command was executed successfully. - */ - -/** - * Clone the cursor - * @function external:CoreCursor#clone - * @return {Cursor} - */ - -/** - * Resets the cursor - * @function external:CoreCursor#rewind - * @return {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @deprecated - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.nextObject = Cursor.prototype.next; - -var nextObject = function(self, callback) { - if(self.s.state == Cursor.CLOSED || self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); - if(self.s.state == Cursor.INIT && self.s.cmd.sort) { - try { - self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort); - } catch(err) { - return handleCallback(callback, err); - } - } - - // Get the next object - self._next(function(err, doc) { - if(err && err.tailable && self.s.currentNumberOfRetries == 0) return callback(err); - if(err && err.tailable && self.s.currentNumberOfRetries > 0) { - self.s.currentNumberOfRetries = self.s.currentNumberOfRetries - 1; - - return setTimeout(function() { - // Rewind the cursor only when it has not actually read any documents yet - if(self.cursorState.currentLimit == 0) self.rewind(); - // Read the next document, forcing a re-issue of query if no cursorId exists - self.nextObject(callback); - }, self.s.tailableRetryInterval); - } - - self.s.state = Cursor.OPEN; - if(err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -define.classMethod('nextObject', {callback: true, promise:true}); - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -var loop = function(self, callback) { - // No more items we are done - if(self.bufferedCount() == 0) return; - // Get the next document - self._next(callback); - // Loop - return loop; -} - -Cursor.prototype.next = Cursor.prototype.nextObject; - -define.classMethod('next', {callback: true, promise:true}); - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method - * @deprecated - * @param {Cursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ -Cursor.prototype.each = function(callback) { - // Rewind cursor state - this.rewind(); - // Set current cursor to INIT - this.s.state = Cursor.INIT; - // Run the query - _each(this, callback); -}; - -define.classMethod('each', {callback: true, promise:false}); - -// Run the each loop -var _each = function(self, callback) { - if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true}); - if(self.isNotified()) return; - if(self.s.state == Cursor.CLOSED || self.isDead()) { - return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); - } - - if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN; - - // Define function to avoid global scope escape - var fn = null; - // Trampoline all the entries - if(self.bufferedCount() > 0) { - while(fn = loop(self, callback)) fn(self, callback); - _each(self, callback); - } else { - self.next(function(err, item) { - if(err) return handleCallback(callback, err); - if(item == null) { - self.s.state = Cursor.CLOSED; - return handleCallback(callback, null, null); - } - - if(handleCallback(callback, null, item) == false) return; - _each(self, callback); - }) - } -} - -/** - * The callback format for the forEach iterator method - * @callback Cursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback Cursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method - * @param {Cursor~iteratorCallback} iterator The iteration callback. - * @param {Cursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ -Cursor.prototype.forEach = function(iterator, callback) { - this.each(function(err, doc){ - if(err) { callback(err); return false; } - if(doc != null) { iterator(doc); return true; } - if(doc == null && callback) { - var internalCallback = callback; - callback = null; - internalCallback(null); - return false; - } - }); -} - -define.classMethod('forEach', {callback: true, promise:false}); - -/** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.setReadPreference = function(r) { - if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); - if(r instanceof ReadPreference) { - this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags); - } else { - this.s.options.readPreference = new CoreReadPreference(r); - } - - return this; -} - -define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]}); - -/** - * The callback format for results - * @callback Cursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.toArray = function(callback) { - var self = this; - if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true}); - - // Execute using callback - if(typeof callback == 'function') return toArray(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - toArray(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var toArray = function(self, callback) { - var items = []; - - // Reset cursor - self.rewind(); - self.s.state = Cursor.INIT; - - // Fetch all the documents - var fetchDocs = function() { - self._next(function(err, doc) { - if(err) return handleCallback(callback, err); - if(doc == null) { - self.s.state = Cursor.CLOSED; - return handleCallback(callback, null, items); - } - - // Add doc to items - items.push(doc) - - // Get all buffered objects - if(self.bufferedCount() > 0) { - var docs = self.readBufferedDocuments(self.bufferedCount()) - - // Transform the doc if transform method added - if(self.s.transforms && typeof self.s.transforms.doc == 'function') { - docs = docs.map(self.s.transforms.doc); - } - - items = items.concat(docs); - } - - // Attempt a fetch - fetchDocs(); - }) - } - - fetchDocs(); -} - -define.classMethod('toArray', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Cursor~countResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} count The count of documents. - */ - -/** - * Get the count of documents for this cursor - * @method - * @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options. - * @param {object} [options=null] Optional settings. - * @param {number} [options.skip=null] The number of documents to skip. - * @param {number} [options.limit=null] The maximum amounts to count before aborting. - * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. - * @param {string} [options.hint=null] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Cursor~countResultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.count = function(applySkipLimit, opts, callback) { - var self = this; - if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true}); - if(typeof opts == 'function') callback = opts, opts = {}; - opts = opts || {}; - - // Execute using callback - if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - count(self, applySkipLimit, opts, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var count = function(self, applySkipLimit, opts, callback) { - if(typeof applySkipLimit == 'function') { - callback = applySkipLimit; - applySkipLimit = true; - } - - if(applySkipLimit) { - if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip(); - if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit(); - } - - // Command - var delimiter = self.s.ns.indexOf('.'); - - var command = { - 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query - } - - if(typeof opts.maxTimeMS == 'number') { - command.maxTimeMS = opts.maxTimeMS; - } else if(typeof self.s.maxTimeMS == 'number') { - command.maxTimeMS = self.s.maxTimeMS; - } - - // Get a server - var server = self.s.topology.getServer(opts); - // Get a connection - var connection = self.s.topology.getConnection(opts); - // Get the callbacks - var callbacks = server.getCallbacks(); - - // Merge in any options - if(opts.skip) command.skip = opts.skip; - if(opts.limit) command.limit = opts.limit; - if(self.s.options.hint) command.hint = self.s.options.hint; - - // Build Query object - var query = new Query(self.s.bson, f("%s.$cmd", self.s.ns.substr(0, delimiter)), command, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false - }); - - // Set up callback - callbacks.register(query.requestId, function(err, result) { - if(err) return handleCallback(callback, err); - if(result.documents.length == 1 - && (result.documents[0].errmsg - || result.documents[0].err - || result.documents[0]['$err'])) { - return handleCallback(callback, MongoError.create(result.documents[0])); - } - handleCallback(callback, null, result.documents[0].n); - }); - - // Write the initial command out - connection.write(query.toBin()); -} - -define.classMethod('count', {callback: true, promise:true}); - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.close = function(callback) { - this.s.state = Cursor.CLOSED; - // Kill the cursor - this.kill(); - // Emit the close event for the cursor - this.emit('close'); - // Callback if provided - if(typeof callback == 'function') return handleCallback(callback, null, this); - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - resolve(); - }); -} - -define.classMethod('close', {callback: true, promise:true}); - -/** - * Map all documents using the provided function - * @method - * @param {function} [transform] The mapping transformation method. - * @return {null} - */ -Cursor.prototype.map = function(transform) { - this.cursorState.transforms = { doc: transform }; - return this; -} - -define.classMethod('map', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Is the cursor closed - * @method - * @return {boolean} - */ -Cursor.prototype.isClosed = function() { - return this.isDead(); -} - -define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); - -Cursor.prototype.destroy = function(err) { - this.pause(); - this.close(); - if(err) this.emit('error', err); -} - -define.classMethod('destroy', {callback: false, promise:false}); - -/** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options=null] Optional settings. - * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - */ -Cursor.prototype.stream = function(options) { - this.s.streamOptions = options || {}; - return this; -} - -define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Execute the explain for the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.explain = function(callback) { - var self = this; - this.s.cmd.explain = true; - - // Execute using callback - if(typeof callback == 'function') return this._next(callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self._next(function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('explain', {callback: true, promise:true}); - -Cursor.prototype._read = function(n) { - var self = this; - if(self.s.state == Cursor.CLOSED || self.isDead()) { - return self.push(null); - } - - // Get the next item - self.nextObject(function(err, result) { - if(err) { - if(!self.isDead()) self.close(); - if(self.listeners('error') && self.listeners('error').length > 0) { - self.emit('error', err); - } - - // Emit end event - self.emit('end'); - return self.emit('finish'); - } - - // If we provided a transformation method - if(typeof self.s.streamOptions.transform == 'function' && result != null) { - return self.push(self.s.streamOptions.transform(result)); - } - - // If we provided a map function - if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) { - return self.push(self.cursorState.transforms.doc(result)); - } - - // Return the result - self.push(result); - }); -} - -Object.defineProperty(Cursor.prototype, 'namespace', { - enumerable: true, - get: function() { - if (!this || !this.s) { - return null; - } - - // TODO: refactor this logic into core - var ns = this.s.ns || ''; - var firstDot = ns.indexOf('.'); - if (firstDot < 0) { - return { - database: this.s.ns, - collection: '' - }; - } - return { - database: ns.substr(0, firstDot), - collection: ns.substr(firstDot + 1) - }; - } -}); - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Readable#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Readable#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Readable#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Readable#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Readable#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Readable#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Readable#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Readable#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -Cursor.INIT = 0; -Cursor.OPEN = 1; -Cursor.CLOSED = 2; -Cursor.GET_MORE = 3; - -module.exports = Cursor; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/db.js b/util/demographicsImporter/node_modules/mongodb/lib/db.js deleted file mode 100644 index 6667297..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/db.js +++ /dev/null @@ -1,1731 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , getSingleProperty = require('./utils').getSingleProperty - , shallowClone = require('./utils').shallowClone - , parseIndexOptions = require('./utils').parseIndexOptions - , debugOptions = require('./utils').debugOptions - , CommandCursor = require('./command_cursor') - , handleCallback = require('./utils').handleCallback - , toError = require('./utils').toError - , ReadPreference = require('./read_preference') - , f = require('util').format - , Admin = require('./admin') - , Code = require('mongodb-core').BSON.Code - , CoreReadPreference = require('mongodb-core').ReadPreference - , MongoError = require('mongodb-core').MongoError - , ObjectID = require('mongodb-core').ObjectID - , Define = require('./metadata') - , Logger = require('mongodb-core').Logger - , Collection = require('./collection') - , crypto = require('crypto'); - -var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId' - , 'serializeFunctions', 'raw', 'promoteLongs', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds' - , 'readPreference', 'pkFactory']; - -/** - * @fileOverview The **Db** class is a class that represents a MongoDB Database. - * - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Get an additional db - * var testDb = db.db('test'); - * db.close(); - * }); - */ - -/** - * Creates a new Db instance - * @class - * @param {string} databaseName The name of the database this instance represents. - * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. - * @param {object} [options=null] Optional settings. - * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.native_parser=true] Select C++ bson parser instead of JavaScript parser. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {number} [options.numberOfRetries=5] Number of times a tailable cursor will re-poll when it gets nothing back. - * @param {number} [options.retryMiliSeconds=500] Number of milliseconds between retries. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. - * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database - * @property {string} databaseName The name of the database this instance represents. - * @property {object} options The options associated with the db instance. - * @property {boolean} native_parser The current value of the parameter native_parser. - * @property {boolean} slaveOk The current slaveOk value for the db instance. - * @property {object} writeConcern The current write concern values. - * @fires Db#close - * @fires Db#authenticated - * @fires Db#reconnect - * @fires Db#error - * @fires Db#timeout - * @fires Db#parseError - * @fires Db#fullsetup - * @return {Db} a Db instance. - */ -var Db = function(databaseName, topology, options) { - options = options || {}; - if(!(this instanceof Db)) return new Db(databaseName, topology, options); - EventEmitter.call(this); - var self = this; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Ensure we put the promiseLib in the options - options.promiseLibrary = promiseLibrary; - - // var self = this; // Internal state of the db object - this.s = { - // Database name - databaseName: databaseName - // DbCache - , dbCache: {} - // Children db's - , children: [] - // Topology - , topology: topology - // Options - , options: options - // Logger instance - , logger: Logger('Db', options) - // Get the bson parser - , bson: topology ? topology.bson : null - // Authsource if any - , authSource: options.authSource - // Unpack read preference - , readPreference: options.readPreference - // Set buffermaxEntries - , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1 - // Parent db (if chained) - , parentDb: options.parentDb || null - // Set up the primary key factory or fallback to ObjectID - , pkFactory: options.pkFactory || ObjectID - // Get native parser - , nativeParser: options.nativeParser || options.native_parser - // Promise library - , promiseLibrary: promiseLibrary - // No listener - , noListener: typeof options.noListener == 'boolean' ? options.noListener : false - // ReadConcern - , readConcern: options.readConcern - } - - // Ensure we have a valid db name - validateDatabaseName(self.s.databaseName); - - // If we have specified the type of parser - if(typeof self.s.nativeParser == 'boolean') { - if(self.s.nativeParser) { - topology.setBSONParserType("c++"); - } else { - topology.setBSONParserType("js"); - } - } - - // Add a read Only property - getSingleProperty(this, 'serverConfig', self.s.topology); - getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); - getSingleProperty(this, 'databaseName', self.s.databaseName); - - // Last ismaster - Object.defineProperty(this, 'options', { - enumerable:true, - get: function() { return self.s.options; } - }); - - // Last ismaster - Object.defineProperty(this, 'native_parser', { - enumerable:true, - get: function() { return self.s.topology.parserType() == 'c++'; } - }); - - // Last ismaster - Object.defineProperty(this, 'slaveOk', { - enumerable:true, - get: function() { - if(self.s.options.readPreference != null - && (self.s.options.readPreference != 'primary' || self.s.options.readPreference.mode != 'primary')) { - return true; - } - return false; - } - }); - - Object.defineProperty(this, 'writeConcern', { - enumerable:true, - get: function() { - var ops = {}; - if(self.s.options.w != null) ops.w = self.s.options.w; - if(self.s.options.j != null) ops.j = self.s.options.j; - if(self.s.options.fsync != null) ops.fsync = self.s.options.fsync; - if(self.s.options.wtimeout != null) ops.wtimeout = self.s.options.wtimeout; - return ops; - } - }); - - // This is a child db, do not register any listeners - if(options.parentDb) return; - if(this.s.noListener) return; - - // Add listeners - topology.on('error', createListener(self, 'error', self)); - topology.on('timeout', createListener(self, 'timeout', self)); - topology.on('close', createListener(self, 'close', self)); - topology.on('parseError', createListener(self, 'parseError', self)); - topology.once('open', createListener(self, 'open', self)); - topology.once('fullsetup', createListener(self, 'fullsetup', self)); - topology.once('all', createListener(self, 'all', self)); - topology.on('reconnect', createListener(self, 'reconnect', self)); -} - -inherits(Db, EventEmitter); - -var define = Db.define = new Define('Db', Db, false); - -/** - * The callback format for the Db.open method - * @callback Db~openCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Db} db The Db instance if the open method was successful. - */ - -// Internal method -var open = function(self, callback) { - self.s.topology.connect(self, self.s.options, function(err, topology) { - if(callback == null) return; - var internalCallback = callback; - callback == null; - - if(err) { - self.close(); - return internalCallback(err); - } - - internalCallback(null, self); - }); -} - -/** - * Open the database - * @method - * @param {Db~openCallback} [callback] Callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.open = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return open(self, callback); - // Return promise - return new self.s.promiseLibrary(function(resolve, reject) { - open(self, function(err, db) { - if(err) return reject(err); - resolve(db); - }) - }); -} - -define.classMethod('open', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Db~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -var executeCommand = function(self, command, options, callback) { - var dbName = options.dbName || options.authdb || self.s.databaseName; - // If we have a readPreference set - if(options.readPreference == null && self.s.readPreference) { - options.readPreference = self.s.readPreference; - } - - // Convert the readPreference - if(options.readPreference && typeof options.readPreference == 'string') { - options.readPreference = new CoreReadPreference(options.readPreference); - } else if(options.readPreference instanceof ReadPreference) { - options.readPreference = new CoreReadPreference(options.readPreference.mode - , options.readPreference.tags); - } - - // Debug information - if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]' - , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)))); - - // Execute command - self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); -} - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.command = function(command, options, callback) { - var self = this; - // Change the callback - if(typeof options == 'function') callback = options, options = {}; - // Clone the options - options = shallowClone(options); - - // Do we have a callback - if(typeof callback == 'function') return executeCommand(self, command, options, callback); - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - executeCommand(self, command, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('command', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Db~noResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {null} result Is not set to a value - */ - -/** - * Close the db and it's underlying connections - * @method - * @param {boolean} force Force close, emitting no events - * @param {Db~noResultCallback} [callback] The result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.close = function(force, callback) { - if(typeof force == 'function') callback = force, force = false; - this.s.topology.close(force); - var self = this; - - // Fire close event if any listeners - if(this.listeners('close').length > 0) { - this.emit('close'); - - // If it's the top level db emit close on all children - if(this.parentDb == null) { - // Fire close on all children - for(var i = 0; i < this.s.children.length; i++) { - this.s.children[i].emit('close'); - } - } - - // Remove listeners after emit - self.removeAllListeners('close'); - } - - // Close parent db if set - if(this.s.parentDb) this.s.parentDb.close(); - // Callback after next event loop tick - if(typeof callback == 'function') return process.nextTick(function() { - handleCallback(callback, null); - }) - - // Return dummy promise - return new this.s.promiseLibrary(function(resolve, reject) { - resolve(); - }); -} - -define.classMethod('close', {callback: true, promise:true}); - -/** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ -Db.prototype.admin = function() { - return new Admin(this, this.s.topology, this.s.promiseLibrary); -}; - -define.classMethod('admin', {callback: false, promise:false, returns: [Admin]}); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Db~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can - * can use it without a callback in the following way. var collection = db.collection('mycollection'); - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @param {Db~collectionResultCallback} callback The collection result callback - * @return {Collection} return the new Collection instance if not in strict mode - */ -Db.prototype.collection = function(name, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - options = shallowClone(options); - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // If we have not set a collection level readConcern set the db level one - options.readConcern = options.readConcern || this.s.readConcern; - - // Do we have ignoreUndefined set - if(this.s.options.ignoreUndefined) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute - if(options == null || !options.strict) { - try { - var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options); - if(callback) callback(null, collection); - return collection; - } catch(err) { - if(callback) return callback(err); - throw err; - } - } - - // Strict mode - if(typeof callback != 'function') { - throw toError(f("A callback is required in strict mode. While getting collection %s.", name)); - } - - // Strict mode - this.listCollections({name:name}).toArray(function(err, collections) { - if(err != null) return handleCallback(callback, err, null); - if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null); - - try { - return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); - } catch(err) { - return handleCallback(callback, err, null); - } - }); -} - -define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); - -var createCollection = function(self, name, options, callback) { - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self, options); - - // Check if we have the name - self.listCollections({name: name}).toArray(function(err, collections) { - if(err != null) return handleCallback(callback, err, null); - if(collections.length > 0 && finalOptions.strict) { - return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null); - } else if (collections.length > 0) { - try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); } - catch(err) { return handleCallback(callback, err); } - } - - // Create collection command - var cmd = {'create':name}; - - // Add all optional parameters - for(var n in options) { - if(options[n] != null && typeof options[n] != 'function') - cmd[n] = options[n]; - } - - // Execute command - self.command(cmd, finalOptions, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); - }); - }); -} - -/** - * Creates a collection on a server pre-allocating space, need to create f.ex capped collections. - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {boolean} [options.capped=false] Create a capped collection. - * @param {number} [options.size=null] The size of the capped collection in bytes. - * @param {number} [options.max=null] The maximum number of documents in the capped collection. - * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createCollection = function(name, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - name = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Do we have a promisesLibrary - options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; - - // Check if the callback is in fact a string - if(typeof callback == 'string') name = callback; - - // Execute the fallback callback - if(typeof callback == 'function') return createCollection(self, name, options, callback); - return new this.s.promiseLibrary(function(resolve, reject) { - createCollection(self, name, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('createCollection', {callback: true, promise:true}); - -/** - * Get all the db statistics. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {number} [options.scale=null] Divide the returned sizes by scale value. - * @param {Db~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.stats = function(options, callback) { - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Build command object - var commandObject = { dbStats:true }; - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - // Execute the command - return this.command(commandObject, options, callback); -} - -define.classMethod('stats', {callback: true, promise:true}); - -// Transformation methods for cursor results -var listCollectionsTranforms = function(databaseName) { - var matching = f('%s.', databaseName); - - return { - doc: function(doc) { - var index = doc.name.indexOf(matching); - // Remove database name if available - if(doc.name && index == 0) { - doc.name = doc.name.substr(index + matching.length); - } - - return doc; - } - } -} - -/** - * Get the list of all collection information for the specified db. - * - * @method - * @param {object} filter Query to filter collections by - * @param {object} [options=null] Optional settings. - * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @return {CommandCursor} - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - // Shallow clone the object - options = shallowClone(options); - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // We have a list collections command - if(this.serverConfig.capabilities().hasListCollectionsCommand) { - // Cursor options - var cursor = options.batchSize ? {batchSize: options.batchSize} : {} - // Build the command - var command = { listCollections : true, filter: filter, cursor: cursor }; - // Set the AggregationCursor constructor - options.cursorFactory = CommandCursor; - // Filter out the correct field values - options.transforms = listCollectionsTranforms(this.s.databaseName); - // Execute the cursor - return this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); - } - - // We cannot use the listCollectionsCommand - if(!this.serverConfig.capabilities().hasListCollectionsCommand) { - // If we have legacy mode and have not provided a full db name filter it - if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { - filter = shallowClone(filter); - filter.name = f('%s.%s', this.s.databaseName, filter.name); - } - } - - // No filter, filter by current database - if(filter == null) { - filter.name = f('/%s/', this.s.databaseName); - } - - // Rewrite the filter to use $and to filter out indexes - if(filter.name) { - filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]}; - } else { - filter = {name:/^((?!\$).)*$/}; - } - - // Return options - var options = {transforms: listCollectionsTranforms(this.s.databaseName)} - // Get the cursor - var cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, options); - // Set the passed in batch size if one was provided - if(options.batchSize) cursor = cursor.batchSize(options.batchSize); - // We have a fallback mode using legacy systems collections - return cursor; -}; - -define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]}); - -var evaluate = function(self, code, parameters, options, callback) { - var finalCode = code; - var finalParameters = []; - - // If not a code object translate to one - if(!(finalCode instanceof Code)) finalCode = new Code(finalCode); - // Ensure the parameters are correct - if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if(parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - var cmd = {'$eval':finalCode, 'args':finalParameters}; - // Check if the nolock parameter is passed in - if(options['nolock']) { - cmd['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY); - - // Execute the command - self.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - if(result && result.ok == 1) return handleCallback(callback, null, result.retval); - if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null); - handleCallback(callback, err, result); - }); -} - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.eval = function(code, parameters, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - // Check if the callback is in fact a string - if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback); - // Execute the command - return new this.s.promiseLibrary(function(resolve, reject) { - evaluate(self, code, parameters, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('eval', {callback: true, promise:true}); - -/** - * Rename a collection. - * - * @method - * @param {string} fromCollection Name of current collection to rename. - * @param {string} toCollection New name of of the collection. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Add return new collection - options.new_collection = true; - - // Check if the callback is in fact a string - if(typeof callback == 'function') { - return this.collection(fromCollection).rename(toCollection, options, callback); - } - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.collection(fromCollection).rename(toCollection, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('renameCollection', {callback: true, promise:true}); - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {string} name Name of collection to drop - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropCollection = function(name, callback) { - var self = this; - - // Command to execute - var cmd = {'drop':name} - - // Check if the callback is in fact a string - if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { - if(err) return handleCallback(callback, err); - if(result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); - - // Execute the command - return new this.s.promiseLibrary(function(resolve, reject) { - // Execute command - self.command(cmd, self.s.options, function(err, result) { - if(err) return reject(err); - if(result.ok) return resolve(true); - resolve(false); - }); - }); -}; - -define.classMethod('dropCollection', {callback: true, promise:true}); - -/** - * Drop a database. - * - * @method - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropDatabase = function(callback) { - var self = this; - // Drop database command - var cmd = {'dropDatabase':1}; - - // Check if the callback is in fact a string - if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); - - // Execute the command - return new this.s.promiseLibrary(function(resolve, reject) { - // Execute command - self.command(cmd, self.s.options, function(err, result) { - if(err) return reject(err); - if(result.ok) return resolve(true); - resolve(false); - }); - }); -} - -define.classMethod('dropDatabase', {callback: true, promise:true}); - -/** - * The callback format for the collections method. - * @callback Db~collectionsResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection[]} collections An array of all the collections objects for the db instance. - */ -var collections = function(self, callback) { - // Let's get the collection names - self.listCollections().toArray(function(err, documents) { - if(err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(function(doc) { - return doc.name.indexOf('$') == -1; - }); - - // Return the collection objects - handleCallback(callback, null, documents.map(function(d) { - return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options); - })); - }); -} - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Db~collectionsResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.collections = function(callback) { - var self = this; - - // Return the callback - if(typeof callback == 'function') return collections(self, callback); - // Return the promise - return new self.s.promiseLibrary(function(resolve, reject) { - collections(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('collections', {callback: true, promise:true}); - -/** - * Runs a command on the database as admin. - * @method - * @param {object} command The command hash - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.executeDbAdminCommand = function(selector, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - if(options.readPreference) { - options.readPreference = options.readPreference; - } - - // Return the callback - if(typeof callback == 'function') return self.s.topology.command('admin.$cmd', selector, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - - // Return promise - return new self.s.promiseLibrary(function(resolve, reject) { - self.s.topology.command('admin.$cmd', selector, options, function(err, result) { - if(err) return reject(err); - resolve(result.result); - }); - }); -}; - -define.classMethod('executeDbAdminCommand', {callback: true, promise:true}); - -/** - * Creates an index on the db and collection collection. - * @method - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - // Shallow clone the options - options = shallowClone(options); - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - // If we have a callback fallback - if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback); - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - createIndex(self, name, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var createIndex = function(self, name, fieldOrSpec, options, callback) { - // Get the write concern options - var finalOptions = writeConcern({}, self, options); - // Ensure we have a callback - if(finalOptions.writeConcern && typeof callback != 'function') { - throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true}); - } - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { - if(err == null) return handleCallback(callback, err, result); - // Create command - var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); - // Set no key checking - finalOptions.checkKeys = false; - // Insert document - self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err); - if(result == null) return handleCallback(callback, null, null); - if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); - handleCallback(callback, null, doc.name); - }); - }); -} - -define.classMethod('createIndex', {callback: true, promise:true}); - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated since version 2.0 - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // If we have a callback fallback - if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - ensureIndex(self, name, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var ensureIndex = function(self, name, fieldOrSpec, options, callback) { - // Get the write concern options - var finalOptions = writeConcern({}, self, options); - // Create command - var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); - var index_name = selector.name; - - // Default command options - var commandOptions = {}; - // Check if the index allready exists - self.indexInformation(name, finalOptions, function(err, indexInformation) { - if(err != null && err.code != 26) return handleCallback(callback, err, null); - // If the index does not exist, create it - if(indexInformation == null || !indexInformation[index_name]) { - self.createIndex(name, fieldOrSpec, options, callback); - } else { - if(typeof callback === 'function') return handleCallback(callback, null, index_name); - } - }); -} - -define.classMethod('ensureIndex', {callback: true, promise:true}); - -Db.prototype.addChild = function(db) { - if(this.s.parentDb) return this.s.parentDb.addChild(db); - this.s.children.push(db); -} - -/** - * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are - * related in a parent-child relationship to the original instance so that events are correctly emitted on child - * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. - * You can control these behaviors with the options noListener and returnNonCachedInstance. - * - * @method - * @param {string} name The name of the database we want to use. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {Db} - */ -Db.prototype.db = function(dbName, options) { - options = options || {}; - // Copy the options and add out internal override of the not shared flag - for(var key in this.options) { - options[key] = this.options[key]; - } - - // Do we have the db in the cache already - if(this.s.dbCache[dbName] && options.returnNonCachedInstance !== true) { - return this.s.dbCache[dbName]; - } - - // Add current db as parentDb - if(options.noListener == null || options.noListener == false) { - options.parentDb = this; - } - - // Add promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // Return the db object - var db = new Db(dbName, this.s.topology, options) - - // Add as child - if(options.noListener == null || options.noListener == false) { - this.addChild(db); - } - - // Add the db to the cache - this.s.dbCache[dbName] = db; - // Return the database - return db; -}; - -define.classMethod('db', {callback: false, promise:false, returns: [Db]}); - -var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { - // Special case where there is no password ($external users) - if(typeof username == 'string' - && password != null && typeof password == 'object') { - options = password; - password = null; - } - - // Unpack all options - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Error out if we digestPassword set - if(options.digestPassword != null) { - throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."); - } - - // Get additional values - var customData = options.customData != null ? options.customData : {}; - var roles = Array.isArray(options.roles) ? options.roles : []; - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // If not roles defined print deprecated message - if(roles.length == 0) { - console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"); - } - - // Get the error options - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Check the db name and add roles if needed - if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) { - roles = ['root'] - } else if(!Array.isArray(options.roles)) { - roles = ['dbOwner'] - } - - // Build the command to execute - var command = { - createUser: username - , customData: customData - , roles: roles - , digestPassword:false - } - - // Apply write concern to command - command = writeConcern(command, self, options); - - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - - // No password - if(typeof password == 'string') { - command.pwd = userPassword; - } - - // Force write using primary - commandOptions.readPreference = CoreReadPreference.primary; - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null); - if(err) return handleCallback(callback, err, null); - handleCallback(callback, !result.ok ? toError(result) : null - , result.ok ? [{user: username, pwd: ''}] : null); - }) -} - -var addUser = function(self, username, password, options, callback) { - // Attempt to execute auth command - _executeAuthCreateUserCommand(self, username, password, options, function(err, r) { - // We need to perform the backward compatible insert operation - if(err && err.code == -5000) { - var finalOptions = writeConcern(shallowClone(options), self, options); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - - // If we have another db set - var db = options.dbName ? self.db(options.dbName) : self; - - // Fetch a user collection - var collection = db.collection(Db.SYSTEM_USER_COLLECTION); - - // Check if we are inserting the first user - collection.count({}, function(err, count) { - // We got an error (f.ex not authorized) - if(err != null) return handleCallback(callback, err, null); - // Check if the user exists and update i - collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) { - // We got an error (f.ex not authorized) - if(err != null) return handleCallback(callback, err, null); - // Add command keys - finalOptions.upsert = true; - - // We have a user, let's update the password or upsert if not - collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err, results, full) { - if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]); - if(err) return handleCallback(callback, err, null) - handleCallback(callback, null, [{user:username, pwd:userPassword}]); - }); - }); - }); - - return; - } - - if(err) return handleCallback(callback, err); - handleCallback(callback, err, r); - }); -} - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.addUser = function(username, password, options, callback) { - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // If we have a callback fallback - if(typeof callback == 'function') return addUser(self, username, password, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - addUser(self, username, password, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('addUser', {callback: true, promise:true}); - -var _executeAuthRemoveUserCommand = function(self, username, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - // Get the error options - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Get additional values - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Build the command to execute - var command = { - dropUser: username - } - - // Apply write concern to command - command = writeConcern(command, self, options); - - // Force write using primary - commandOptions.readPreference = CoreReadPreference.primary; - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000}); - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }) -} - -var removeUser = function(self, username, options, callback) { - // Attempt to execute command - _executeAuthRemoveUserCommand(self, username, options, function(err, result) { - if(err && err.code == -5000) { - var finalOptions = writeConcern(shallowClone(options), self, options); - // If we have another db set - var db = options.dbName ? self.db(options.dbName) : self; - - // Fetch a user collection - var collection = db.collection(Db.SYSTEM_USER_COLLECTION); - - // Locate the user - collection.findOne({user: username}, {}, function(err, user) { - if(user == null) return handleCallback(callback, err, false); - collection.remove({user: username}, finalOptions, function(err, result) { - handleCallback(callback, err, true); - }); - }); - - return; - } - - if(err) return handleCallback(callback, err); - handleCallback(callback, err, result); - }); -} - -define.classMethod('removeUser', {callback: true, promise:true}); - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.removeUser = function(username, options, callback) { - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // If we have a callback fallback - if(typeof callback == 'function') return removeUser(self, username, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - removeUser(self, username, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var authenticate = function(self, username, password, options, callback) { - // the default db to authenticate against is 'self' - // if authententicate is called from a retry context, it may be another one, like admin - var authdb = options.authdb ? options.authdb : options.dbName; - authdb = options.authSource ? options.authSource : authdb; - authdb = authdb ? authdb : self.databaseName; - - // Callback - var _callback = function(err, result) { - if(self.listeners('authenticated').length > 0) { - self.emit('authenticated', err, result); - } - - // Return to caller - handleCallback(callback, err, result); - } - - // authMechanism - var authMechanism = options.authMechanism || ''; - authMechanism = authMechanism.toUpperCase(); - - // If classic auth delegate to auth command - if(authMechanism == 'MONGODB-CR') { - self.s.topology.auth('mongocr', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'PLAIN') { - self.s.topology.auth('plain', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'MONGODB-X509') { - self.s.topology.auth('x509', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'SCRAM-SHA-1') { - self.s.topology.auth('scram-sha-1', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'GSSAPI') { - if(process.platform == 'win32') { - self.s.topology.auth('sspi', authdb, username, password, options, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else { - self.s.topology.auth('gssapi', authdb, username, password, options, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } - } else if(authMechanism == 'DEFAULT') { - self.s.topology.auth('default', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else { - handleCallback(callback, MongoError.create({message: f("authentication mechanism %s not supported", options.authMechanism), driver:true})); - } -} - -/** - * Authenticate a user against the server. - * @method - * @param {string} username The username. - * @param {string} [password] The password. - * @param {object} [options=null] Optional settings. - * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.authenticate = function(username, password, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - // Shallow copy the options - options = shallowClone(options); - - // Set default mechanism - if(!options.authMechanism) { - options.authMechanism = 'DEFAULT'; - } else if(options.authMechanism != 'GSSAPI' - && options.authMechanism != 'MONGODB-CR' - && options.authMechanism != 'MONGODB-X509' - && options.authMechanism != 'SCRAM-SHA-1' - && options.authMechanism != 'PLAIN') { - return handleCallback(callback, MongoError.create({message: "only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism", driver:true})); - } - - // If we have a callback fallback - if(typeof callback == 'function') return authenticate(self, username, password, options, function(err, r) { - // Support failed auth method - if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; - // Reject error - if(err) return callback(err, r); - callback(null, r); - }); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - authenticate(self, username, password, options, function(err, r) { - // Support failed auth method - if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; - // Reject error - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('authenticate', {callback: true, promise:true}); - -/** - * Logout user from server, fire off on all connections and remove all auth info - * @method - * @param {object} [options=null] Optional settings. - * @param {string} [options.dbName=null] Logout against different database than current. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.logout = function(options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // logout command - var cmd = {'logout':1}; - - // Add onAll to login to ensure all connection are logged out - options.onAll = true; - - // We authenticated against a different db use that - if(this.s.authSource) options.dbName = this.s.authSource; - - // Execute the command - if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err, false); - handleCallback(callback, null, true) - }); - - // Return promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.command(cmd, options, function(err, result) { - if(err) return reject(err); - resolve(true); - }); - }); -} - -define.classMethod('logout', {callback: true, promise:true}); - -// Figure out the read preference -var getReadPreference = function(options, db) { - if(options.readPreference) return options; - if(db.readPreference) options.readPreference = db.readPreference; - return options; -} - -/** - * Retrieves this collections index info. - * @method - * @param {string} name The name of the collection. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.indexInformation = function(name, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // If we have a callback fallback - if(typeof callback == 'function') return indexInformation(self, name, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexInformation(self, name, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var indexInformation = function(self, name, options, callback) { - // If we specified full information - var full = options['full'] == null ? false : options['full']; - - // Process all the results from the index command and collection - var processResults = function(indexes) { - // Contains all the information - var info = {}; - // Process all the indexes - for(var i = 0; i < indexes.length; i++) { - var index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for(var name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - self.collection(name).listIndexes().toArray(function(err, indexes) { - if(err) return callback(toError(err)); - if(!Array.isArray(indexes)) return handleCallback(callback, null, []); - if(full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -define.classMethod('indexInformation', {callback: true, promise:true}); - -var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { - var indexParameters = parseIndexOptions(fieldOrSpec); - var fieldHash = indexParameters.fieldHash; - var keys = indexParameters.keys; - - // Generate the index name - var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; - var selector = { - 'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName - } - - // Ensure we have a correct finalUnique - var finalUnique = options == null || 'object' === typeof options ? false : options; - // Set up options - options = options == null || typeof options == 'boolean' ? {} : options; - - // Add all the options - var keysToOmit = Object.keys(selector); - for(var optionName in options) { - if(keysToOmit.indexOf(optionName) == -1) { - selector[optionName] = options[optionName]; - } - } - - if(selector['unique'] == null) selector['unique'] = finalUnique; - - // Remove any write concern operations - var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; - for(var i = 0; i < removeKeys.length; i++) { - delete selector[removeKeys[i]]; - } - - // Return the command creation selector - return selector; -} - -var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { - // Build the index - var indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; - // Set up the index - var indexes = [{ name: indexName, key: indexParameters.fieldHash }]; - // merge all the options - var keysToOmit = Object.keys(indexes[0]); - for(var optionName in options) { - if(keysToOmit.indexOf(optionName) == -1) { - indexes[0][optionName] = options[optionName]; - } - - // Remove any write concern operations - var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; - for(var i = 0; i < removeKeys.length; i++) { - delete indexes[0][removeKeys[i]]; - } - } - - // Create command - var cmd = {createIndexes: name, indexes: indexes}; - - // Apply write concern to command - cmd = writeConcern(cmd, self, options); - - // Build the command - self.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - if(result.ok == 0) return handleCallback(callback, toError(result), null); - // Return the indexName for backward compatibility - handleCallback(callback, null, indexName); - }); -} - -// Validate the database name -var validateDatabaseName = function(databaseName) { - if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true}); - if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true}); - if(databaseName == '$external') return; - - var invalidChars = [" ", ".", "$", "/", "\\"]; - for(var i = 0; i < invalidChars.length; i++) { - if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true}); - } -} - -// Get write concern -var writeConcern = function(target, db, options) { - if(options.w != null || options.j != null || options.fsync != null) { - var opts = {}; - if(options.w) opts.w = options.w; - if(options.wtimeout) opts.wtimeout = options.wtimeout; - if(options.j) opts.j = options.j; - if(options.fsync) opts.fsync = options.fsync; - target.writeConcern = opts; - } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { - target.writeConcern = db.writeConcern; - } - - return target -} - -// Add listeners to topology -var createListener = function(self, e, object) { - var listener = function(err) { - if(e != 'error') { - object.emit(e, err, self); - - // Emit on all associated db's if available - for(var i = 0; i < self.s.children.length; i++) { - self.s.children[i].emit(e, err, self.s.children[i]); - } - } - } - return listener; -} - -/** - * Db close event - * - * Emitted after a socket closed against a single server or mongos proxy. - * - * @event Db#close - * @type {MongoError} - */ - -/** - * Db authenticated event - * - * Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated. - * - * @event Db#authenticated - * @type {object} - */ - -/** - * Db reconnect event - * - * * Server: Emitted when the driver has reconnected and re-authenticated. - * * ReplicaSet: N/A - * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. - * - * @event Db#reconnect - * @type {object} - */ - -/** - * Db error event - * - * Emitted after an error occurred against a single server or mongos proxy. - * - * @event Db#error - * @type {MongoError} - */ - -/** - * Db timeout event - * - * Emitted after a socket timeout occurred against a single server or mongos proxy. - * - * @event Db#timeout - * @type {MongoError} - */ - -/** - * Db parseError event - * - * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. - * - * @event Db#parseError - * @type {MongoError} - */ - -/** - * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. - * - * * Server: Emitted when the driver has connected to the single server and has authenticated. - * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. - * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. - * - * @event Db#fullsetup - * @type {Db} - */ - -// Constants -Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; -Db.SYSTEM_INDEX_COLLECTION = "system.indexes"; -Db.SYSTEM_PROFILE_COLLECTION = "system.profile"; -Db.SYSTEM_USER_COLLECTION = "system.users"; -Db.SYSTEM_COMMAND_COLLECTION = "$cmd"; -Db.SYSTEM_JS_COLLECTION = "system.js"; - -module.exports = Db; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/gridfs/chunk.js b/util/demographicsImporter/node_modules/mongodb/lib/gridfs/chunk.js deleted file mode 100644 index d96095f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/gridfs/chunk.js +++ /dev/null @@ -1,237 +0,0 @@ -"use strict"; - -var Binary = require('mongodb-core').BSON.Binary, - ObjectID = require('mongodb-core').BSON.ObjectID; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = function(file, mongoObject, writeConcern) { - if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var self = this; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || {w:1}; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if(mongoObjectFinal.data == null) { - } else if(typeof mongoObjectFinal.data == "string") { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); - this.data = new Binary(buffer); - } else if(Array.isArray(mongoObjectFinal.data)) { - var buffer = new Buffer(mongoObjectFinal.data.length); - var data = mongoObjectFinal.data.join(''); - buffer.write(data, 0, data.length, 'binary'); - this.data = new Binary(buffer); - } else if(mongoObjectFinal.data._bsontype === 'Binary') { - this.data = mongoObjectFinal.data; - } else if(Buffer.isBuffer(mongoObjectFinal.data)) { - } else { - throw Error("Illegal chunk format"); - } - - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition, data.length, 'binary'); - this.internalPosition = this.data.length(); - if(callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length == 0 ? this.length() : length; - - if(this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if ((this.length() - this.internalPosition) >= length) { - var data = null; - if (this.data.buffer != null) { //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { //Native BSON - data = new Buffer(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition == this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {}; - } - - self.file.chunkCollection(function(err, collection) { - if(err) return callback(err); - - // Merge the options - var writeOptions = {}; - for(var name in options) writeOptions[name] = options[name]; - for(var name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - // collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) { - collection.remove({'_id':self.objectId}, writeOptions, function(err, result) { - if(err) return callback(err); - - if(self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = {forceServerObjectId:true}; - for(var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.insert(mongoObject, writeOptions, function(err, collection) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *
      
      - *        {
      - *          '_id' : , // {number} id for this chunk
      - *          'files_id' : , // {number} foreign key to the file collection
      - *          'n' : , // {number} chunk number
      - *          'data' : , // {bson#Binary} the chunk data itself
      - *        }
      - *        
      - * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - 'files_id': this.file.fileId, - 'n': this.chunkNumber, - 'data': this.data}; - // If we are saving using a specific ObjectId - if(this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, "position", { enumerable: true - , get: function () { - return this.internalPosition; - } - , set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; - -module.exports = Chunk; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/gridfs/grid_store.js b/util/demographicsImporter/node_modules/mongodb/lib/gridfs/grid_store.js deleted file mode 100644 index 62943bd..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/gridfs/grid_store.js +++ /dev/null @@ -1,1919 +0,0 @@ -"use strict"; - -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - * - * @example - * var MongoClient = require('mongodb').MongoClient, - * GridStore = require('mongodb').GridStore, - * ObjectID = require('mongodb').ObjectID, - * test = require('assert'); - * - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * var gridStore = new GridStore(db, null, "w"); - * gridStore.open(function(err, gridStore) { - * gridStore.write("hello world!", function(err, gridStore) { - * gridStore.close(function(err, result) { - * - * // Let's read the file using object Id - * GridStore.read(db, result._id, function(err, data) { - * test.equal('hello world!', data); - * db.close(); - * test.done(); - * }); - * }); - * }); - * }); - * }); - */ -var Chunk = require('./chunk'), - ObjectID = require('mongodb-core').BSON.ObjectID, - ReadPreference = require('../read_preference'), - Buffer = require('buffer').Buffer, - Collection = require('../collection'), - fs = require('fs'), - timers = require('timers'), - f = require('util').format, - util = require('util'), - Define = require('../metadata'), - MongoError = require('mongodb-core').MongoError, - inherits = util.inherits, - Duplex = require('stream').Duplex || require('readable-stream').Duplex; - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -/** - * Namespace provided by the mongodb-core and node.js - * @external Duplex - */ - -/** - * Create a new GridStore instance - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwriten. - * - * @class - * @param {Db} db A database instance to interact with. - * @param {object} [id] optional unique id for this file - * @param {string} [filename] optional filename for this file, no unique constrain on the field - * @param {string} mode set the mode for this file. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * @param {object} [options.metadata=null] Arbitrary data the user wants to store. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @property {number} chunkSize Get the gridstore chunk size. - * @property {number} md5 The md5 checksum for this file. - * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory - * @return {GridStore} a GridStore instance. - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - var self = this; - this.db = db; - - // Handle options - if(typeof options === 'undefined') options = {}; - // Handle mode - if(typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if(typeof mode == 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if(id instanceof ObjectID) { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if(typeof filename == 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? "r" : mode; - this.options = options || {}; - - // Opened - this.isOpen = false; - - // Set the root if overridden - this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = this.options.readPreference || db.options.readPreference || ReadPreference.PRIMARY; - this.writeConcern = _getWriteConcern(db, this.options); - // Set default chunk size - this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; - - // Get the promiseLibrary - var promiseLibrary = this.options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set the promiseLibrary - this.promiseLibrary = promiseLibrary; - - Object.defineProperty(this, "chunkSize", { enumerable: true - , get: function () { - return this.internalChunkSize; - } - , set: function(value) { - if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } - }); - - Object.defineProperty(this, "md5", { enumerable: true - , get: function () { - return this.internalMd5; - } - }); - - Object.defineProperty(this, "chunkNumber", { enumerable: true - , get: function () { - return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; - } - }); -} - -var define = GridStore.define = new Define('Gridstore', GridStore, true); - -/** - * The callback format for the Gridstore.open method - * @callback GridStore~openCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The GridStore instance if the open method was successful. - */ - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @method - * @param {GridStore~openCallback} [callback] this will be called after executing this method - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.open = function(callback) { - var self = this; - if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ - throw MongoError.create({message: "Illegal mode " + this.mode, driver:true}); - } - - // We provided a callback leg - if(typeof callback == 'function') return open(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - open(self, function(err, store) { - if(err) return reject(err); - resolve(store); - }) - }); -}; - -var open = function(self, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(self.db, self.options); - - // If we are writing we need to ensure we have the right indexes for md5's - if((self.mode == "w" || self.mode == "w+")) { - // Get files collection - var collection = self.collection(); - // Put index on filename - collection.ensureIndex([['filename', 1]], writeConcern, function(err, index) { - // Get chunk collection - var chunkCollection = self.chunkCollection(); - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], writeConcern, function(err, index) { - // Open the connection - _open(self, writeConcern, function(err, r) { - if(err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - }); - }); - } else { - // Open the gridstore - _open(self, writeConcern, function(err, r) { - if(err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - } -} - -// Push the definition for open -define.classMethod('open', {callback: true, promise:true}); - -/** - * Verify if the file is at EOF. - * - * @method - * @return {boolean} true if the read/write head is at the end of this file. - */ -GridStore.prototype.eof = function() { - return this.position == this.length ? true : false; -} - -define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]}); - -/** - * The callback result format. - * @callback GridStore~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result from the callback. - */ - -/** - * Retrieves a single character from this file. - * - * @method - * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.getc = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return eof(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - eof(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -var eof = function(self, callback) { - if(self.eof()) { - callback(null, null); - } else if(self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -} - -define.classMethod('getc', {callback: true, promise:true}); - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @method - * @param {string} string the string to write. - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.puts = function(string, callback) { - var self = this; - var finalString = string.match(/\n$/) == null ? string + "\n" : string; - // We provided a callback leg - if(typeof callback == 'function') return this.write(finalString, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - self.write(finalString, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -define.classMethod('puts', {callback: true, promise:true}); - -/** - * Return a modified Readable stream including a possible transform method. - * - * @method - * @return {GridStoreStream} - */ -GridStore.prototype.stream = function() { - return new GridStoreStream(this); -} - -define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]}); - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @method - * @param {(string|Buffer)} data the data to write. - * @param {boolean} [close] closes this file after writing if set to true. - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.write = function write(data, close, callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return _writeNormal(this, data, close, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - _writeNormal(self, data, close, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -define.classMethod('write', {callback: true, promise:true}); - -/** - * Handles the destroy part of a stream - * - * @method - * @result {null} - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if(!this.writable) return; - this.readable = false; - if(this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -} - -define.classMethod('destroy', {callback: false, promise:false}); - -/** - * Stores a file from the file system to the GridFS database. - * - * @method - * @param {(string|Buffer|FileHandle)} file the file to store. - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.writeFile = function (file, callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return writeFile(self, file, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - writeFile(self, file, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var writeFile = function(self, file, callback) { - if (typeof file === 'string') { - fs.open(file, 'r', function (err, fd) { - if(err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function (err, self) { - if(err) return callback(err, self); - - fs.fstat(file, function (err, stats) { - if(err) return callback(err, self); - - var offset = 0; - var index = 0; - var numberOfChunksLeft = Math.min(stats.size / self.chunkSize); - - // Write a chunk - var writeChunk = function() { - fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { - if(err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, {n:index++}, self.writeConcern); - chunk.write(data, function(err, chunk) { - if(err) return callback(err, self); - - chunk.save({}, function(err, result) { - if(err) return callback(err, self); - - self.position = self.position + data.length; - - // Point to current chunk - self.currentChunk = chunk; - - if(offset >= stats.size) { - fs.close(file); - self.close(function(err, result) { - if(err) return callback(err, self); - return callback(null, self); - }); - } else { - return process.nextTick(writeChunk); - } - }); - }); - }); - } - - // Process the first write - process.nextTick(writeChunk); - }); - }); -} - -define.classMethod('writeFile', {callback: true, promise:true}); - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @method - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.close = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return close(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - close(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var close = function(self, callback) { - if(self.mode[0] == "w") { - // Set up options - var options = self.writeConcern; - - if(self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save({}, function(err, chunk) { - if(err && typeof callback == 'function') return callback(err); - - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - // Build the mongo object - if(self.uploadDate != null) { - files.remove({'_id':self.fileId}, self.writeConcern, function(err, collection) { - if(err && typeof callback == 'function') return callback(err); - - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } - } else if(self.mode[0] == "r") { - if(typeof callback == 'function') - callback(null, null); - } else { - if(typeof callback == 'function') - callback(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true})); - } -} - -define.classMethod('close', {callback: true, promise:true}); - -/** - * The collection callback format. - * @callback GridStore~collectionCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection from the command execution. - */ - -/** - * Retrieve this file's chunks collection. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - */ -GridStore.prototype.chunkCollection = function(callback) { - if(typeof callback == 'function') - return this.db.collection((this.root + ".chunks"), callback); - return this.db.collection((this.root + ".chunks")); -}; - -define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]}); - -/** - * Deletes all the chunks of this file in the database. - * - * @method - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.unlink = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return unlink(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - unlink(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var unlink = function(self, callback) { - deleteChunks(self, function(err) { - if(err!==null) { - err.message = "at deleteChunks: " + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if(err!==null) { - err.message = "at collection: " + err.message; - return callback(err); - } - - collection.remove({'_id':self.fileId}, self.writeConcern, function(err) { - callback(err, self); - }); - }); - }); -} - -define.classMethod('unlink', {callback: true, promise:true}); - -/** - * Retrieves the file collection associated with this object. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - */ -GridStore.prototype.collection = function(callback) { - if(typeof callback == 'function') - this.db.collection(this.root + ".files", callback); - return this.db.collection(this.root + ".files"); -}; - -define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); - -/** - * The readlines callback format. - * @callback GridStore~readlinesCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {string[]} strings The array of strings returned. - */ - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.readlines = function(separator, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - separator = args.length ? args.shift() : "\n"; - separator = separator || "\n"; - - // We provided a callback leg - if(typeof callback == 'function') return readlines(self, separator, callback); - - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - readlines(self, separator, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var readlines = function(self, separator, callback) { - self.read(function(err, data) { - if(err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for(var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -} - -define.classMethod('readlines', {callback: true, promise:true}); - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @method - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.rewind = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return rewind(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - rewind(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var rewind = function(self, callback) { - if(self.currentChunk.chunkNumber != 0) { - if(self.mode[0] == "w") { - deleteChunks(self, function(err, gridStore) { - if(err) return callback(err); - self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if(err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -} - -define.classMethod('rewind', {callback: true, promise:true}); - -/** - * The read callback format. - * @callback GridStore~readCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Buffer} data The data read from the GridStore object - */ - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.read = function(length, buffer, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - // We provided a callback leg - if(typeof callback == 'function') return read(self, length, buffer, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - read(self, length, buffer, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -var read = function(self, length, buffer, callback) { - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if(finalLength == 0 && finalBuffer.length == 0) return callback(MongoError.create({message: "File does not exist", driver:true}), null); - // Else return data - return callback(null, finalBuffer); - } - - // Read the next chunk - var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) return callback(err); - - if(chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if(finalBuffer._index > 0) { - callback(null, finalBuffer) - } else { - callback(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null); - } - } - }); -} - -define.classMethod('read', {callback: true, promise:true}); - -/** - * The tell callback format. - * @callback GridStore~tellCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} position The current read position in the GridStore. - */ - -/** - * Retrieves the position of the read/write head of this file. - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {GridStore~tellCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.tell = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return callback(null, this.position); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - resolve(self.position); - }); -}; - -define.classMethod('tell', {callback: true, promise:true}); - -/** - * The tell callback format. - * @callback GridStore~gridStoreCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The gridStore. - */ - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @method - * @param {number} [position] the position to seek to - * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {GridStore~gridStoreCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.seek = function(position, seekLocation, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - seekLocation = args.length ? args.shift() : null; - - // We provided a callback leg - if(typeof callback == 'function') return seek(self, position, seekLocation, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - seek(self, position, seekLocation, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -var seek = function(self, position, seekLocation, callback) { - // Seek only supports read mode - if(self.mode != 'r') { - return callback(MongoError.create({message: "seek is only supported for mode r", driver:true})) - } - - var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if(seekLocationFinal == GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if(seekLocationFinal == GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition/self.chunkSize); - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(err, self); - }); - }; - - seekChunk(); -} - -define.classMethod('seek', {callback: true, promise:true}); - -/** - * @ignore - */ -var _open = function(self, options, callback) { - var collection = self.collection(); - // Create the query - var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; - query = null == self.fileId && self.filename == null ? null : query; - options.readPreference = self.readPreference; - - // Fetch the chunks - if(query != null) { - collection.findOne(query, options, function(err, doc) { - if(err) return error(err); - - // Check if the collection for the files exists otherwise prepare the new one - if(doc != null) { - self.fileId = doc._id; - // Prefer a new filename over the existing one if this is a write - self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode != 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId; - return error(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename)), driver:true}), self); - } - - // Process the mode of the object - if(self.mode == "r") { - nthChunk(self, 0, options, function(err, chunk) { - if(err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, options, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - var collection2 = self.chunkCollection(); - // No file exists set up write mode - if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, options, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - } - - // only pass error to callback once - function error (err) { - if(error.err) return; - callback(error.err = err); - } -}; - -/** - * @ignore - */ -var writeBuffer = function(self, buffer, close, callback) { - if(typeof close === "function") { callback = close; close = null; } - var finalClose = typeof close == 'boolean' ? close : false; - - if(self.mode != "w") { - callback(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename)), driver:true}), null); - } else { - if(self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while(leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - var firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - // If we have left over data write it - if(leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - - for(var i = 0; i < chunksToWrite.length; i++) { - chunksToWrite[i].save({}, function(err, result) { - if(err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if(numberOfChunksToWrite <= 0) { - // We care closing the file before returning - if(finalClose) { - return self.close(function(err, result) { - callback(err, self); - }); - } - - // Return normally - return callback(null, self); - } - }); - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - // We care closing the file before returning - if(finalClose) { - return self.close(function(err, result) { - callback(err, self); - }); - } - // Return normally - return callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - *
      
      - *        {
      - *          '_id' : , // {number} id for this file
      - *          'filename' : , // {string} name for this file
      - *          'contentType' : , // {string} mime type for this file
      - *          'length' : , // {number} size of this file?
      - *          'chunksize' : , // {number} chunk size used by this file
      - *          'uploadDate' : , // {Date}
      - *          'aliases' : , // {array of string}
      - *          'metadata' : , // {string}
      - *        }
      - *        
      - * - * @ignore - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - '_id': self.fileId, - 'filename': self.filename, - 'contentType': self.contentType, - 'length': self.position ? self.position : 0, - 'chunkSize': self.chunkSize, - 'uploadDate': self.uploadDate, - 'aliases': self.aliases, - 'metadata': self.metadata - }; - - var md5Command = {filemd5:self.fileId, root:self.root}; - self.db.command(md5Command, function(err, results) { - if(err) return callback(err); - - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); -}; - -/** - * Gets the nth chunk of this file. - * @ignore - */ -var nthChunk = function(self, chunkNumber, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - options.readPreference = self.readPreference; - // Get the nth chunk - self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) { - if(err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); -}; - -/** - * @ignore - */ -var lastChunkNumber = function(self) { - return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @ignore - */ -var deleteChunks = function(self, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - - if(self.fileId != null) { - self.chunkCollection().remove({'files_id':self.fileId}, options, function(err, result) { - if(err) return callback(err, false); - callback(null, true); - }); - } else { - callback(null, true); - } -}; - -/** -* The collection to be used for holding the files and chunks collection. -* -* @classconstant DEFAULT_ROOT_COLLECTION -**/ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** -* Default file mime type -* -* @classconstant DEFAULT_CONTENT_TYPE -**/ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** -* Seek mode where the given length is absolute. -* -* @classconstant IO_SEEK_SET -**/ -GridStore.IO_SEEK_SET = 0; - -/** -* Seek mode where the given length is an offset to the current read/write head. -* -* @classconstant IO_SEEK_CUR -**/ -GridStore.IO_SEEK_CUR = 1; - -/** -* Seek mode where the given length is an offset to the end of the file. -* -* @classconstant IO_SEEK_END -**/ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file to look for. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - exists(db, fileIdObject, rootCollection, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var exists = function(db, fileIdObject, rootCollection, options, callback) { - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Fetch collection - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + ".files", function(err, collection) { - if(err) return callback(err); - - // Build query - var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) - ? {'filename':fileIdObject} - : {'_id':fileIdObject}; // Attempt to locate file - - // We have a specific query - if(fileIdObject != null - && typeof fileIdObject == 'object' - && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') { - query = fileIdObject; - } - - // Check if the entry exists - collection.findOne(query, {readPreference:readPreference}, function(err, item) { - if(err) return callback(err); - callback(null, item == null ? false : true); - }); - }); -} - -define.staticMethod('exist', {callback: true, promise:true}); - -/** - * Gets the list of files stored in the GridFS. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return list(db, rootCollection, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - list(db, rootCollection, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var list = function(db, rootCollection, options, callback) { - // Ensure we have correct values - if(rootCollection != null && typeof rootCollection == 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection((rootCollectionFinal + ".files"), function(err, collection) { - if(err) return callback(err); - - collection.find({}, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.each(function(err, item) { - if(item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -} - -define.staticMethod('list', {callback: true, promise:true}); - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file. - * @param {number} [length] The size of data to read. - * @param {number} [offset] The offset from the head of the file of which to start reading from. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ - -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options ? options.promiseLibrary : null; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - readStatic(db, name, length, offset, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var readStatic = function(db, name, length, offset, options, callback) { - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - // Make sure we are not reading out of bounds - if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); - if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); - if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); - - if(offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if(err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -} - -define.staticMethod('read', {callback: true, promise:true}); - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {(String|object)} name the name of the file. - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options ? options.promiseLibrary : null; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - readlinesStatic(db, name, separator, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var readlinesStatic = function(db, name, separator, options, callback) { - var finalSeperator = separator == null ? "\n" : separator; - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -} - -define.staticMethod('readlines', {callback: true, promise:true}); - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @method - * @static - * @param {Db} db The database to query. - * @param {(string|array)} names The name/names of the files to delete. - * @param {object} [options=null] Optional settings. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.unlink = function(db, names, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback); - - // Return promise - return new promiseLibrary(function(resolve, reject) { - unlinkStatic(self, db, names, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var unlinkStatic = function(self, db, names, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(db, options); - - // List of names - if(names.constructor == Array) { - var tc = 0; - for(var i = 0; i < names.length; i++) { - ++tc; - GridStore.unlink(db, names[i], options, function(result) { - if(--tc == 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, "w", options).open(function(err, gridStore) { - if(err) return callback(err); - deleteChunks(gridStore, function(err, result) { - if(err) return callback(err); - gridStore.collection(function(err, collection) { - if(err) return callback(err); - collection.remove({'_id':gridStore.fileId}, writeConcern, function(err, result) { - callback(err, self); - }); - }); - }); - }); - } -} - -define.staticMethod('unlink', {callback: true, promise:true}); - -/** - * @ignore - */ -var _writeNormal = function(self, data, close, callback) { - // If we have a buffer write it using the writeBuffer method - if(Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - return writeBuffer(self, new Buffer(data, 'binary'), close, callback); - } -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = {w:1}; - options = options || {}; - - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.options); - } else if(self.safe && (self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean')) { - finalOptions = _setWriteConcernHash(self.safe); - } else if(typeof self.safe == "boolean") { - finalOptions = {w: (self.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw MongoError.create({message: "No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true", driver:true}); - - // Return the options - return finalOptions; -} - -/** - * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @extends external:Duplex - * @return {GridStoreStream} a GridStoreStream instance. - */ -var GridStoreStream = function(gs) { - var self = this; - // Initialize the duplex stream - Duplex.call(this); - - // Get the gridstore - this.gs = gs; - - // End called - this.endCalled = false; - - // If we have a seek - this.totalBytesToRead = this.gs.length - this.gs.position; - this.seekPosition = this.gs.position; -} - -// -// Inherit duplex -inherits(GridStoreStream, Duplex); - -GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; - -// Set up override -GridStoreStream.prototype.pipe = function(destination) { - var self = this; - - // Only open gridstore if not already open - if(!self.gs.isOpen) { - self.gs.open(function(err) { - if(err) return self.emit('error', err); - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - }); - } else { - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - } -} - -// Called by stream -GridStoreStream.prototype._read = function(n) { - var self = this; - - var read = function() { - // Read data - self.gs.read(length, function(err, buffer) { - if(err && !self.endCalled) return self.emit('error', err); - - // Stream is closed - if(self.endCalled || buffer == null) return self.push(null); - // Remove bytes read - if(buffer.length <= self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer.length; - self.push(buffer); - } else if(buffer.length > self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer._index; - self.push(buffer.slice(0, buffer._index)); - } - - // Finished reading - if(self.totalBytesToRead <= 0) { - self.endCalled = true; - } - }); - } - - // Set read length - var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; - if(!self.gs.isOpen) { - self.gs.open(function(err, gs) { - self.totalBytesToRead = self.gs.length - self.gs.position; - if(err) return self.emit('error', err); - read(); - }); - } else { - read(); - } -} - -GridStoreStream.prototype.destroy = function() { - this.pause(); - this.endCalled = true; - this.gs.close(); - this.emit('end'); -} - -GridStoreStream.prototype.write = function(chunk, encoding, callback) { - var self = this; - if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true})) - // Do we have to open the gridstore - if(!self.gs.isOpen) { - self.gs.open(function() { - self.gs.isOpen = true; - self.gs.write(chunk, function() { - process.nextTick(function() { - self.emit('drain'); - }); - }); - }); - return false; - } else { - self.gs.write(chunk, function() { - self.emit('drain'); - }); - return true; - } -} - -GridStoreStream.prototype.end = function(chunk, encoding, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - chunk = args.length ? args.shift() : null; - encoding = args.length ? args.shift() : null; - self.endCalled = true; - - if(chunk) { - self.gs.write(chunk, function() { - self.gs.close(function() { - if(typeof callback == 'function') callback(); - self.emit('end') - }); - }); - } - - self.gs.close(function() { - if(typeof callback == 'function') callback(); - self.emit('end') - }); -} - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Duplex#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Duplex#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Duplex#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Duplex#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Duplex#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Duplex#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Duplex#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Duplex#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -/** - * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. - * @function external:Duplex#write - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {boolean} - */ - -/** - * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. - * @function external:Duplex#end - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {null} - */ - -/** - * GridStoreStream stream data event, fired for each document in the cursor. - * - * @event GridStoreStream#data - * @type {object} - */ - -/** - * GridStoreStream stream end event - * - * @event GridStoreStream#end - * @type {null} - */ - -/** - * GridStoreStream stream close event - * - * @event GridStoreStream#close - * @type {null} - */ - -/** - * GridStoreStream stream readable event - * - * @event GridStoreStream#readable - * @type {null} - */ - -/** - * GridStoreStream stream drain event - * - * @event GridStoreStream#drain - * @type {null} - */ - -/** - * GridStoreStream stream finish event - * - * @event GridStoreStream#finish - * @type {null} - */ - -/** - * GridStoreStream stream pipe event - * - * @event GridStoreStream#pipe - * @type {null} - */ - -/** - * GridStoreStream stream unpipe event - * - * @event GridStoreStream#unpipe - * @type {null} - */ - -/** - * GridStoreStream stream error event - * - * @event GridStoreStream#error - * @type {null} - */ - -/** - * @ignore - */ -module.exports = GridStore; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/metadata.js b/util/demographicsImporter/node_modules/mongodb/lib/metadata.js deleted file mode 100644 index 7dae562..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/metadata.js +++ /dev/null @@ -1,64 +0,0 @@ -var f = require('util').format; - -var Define = function(name, object, stream) { - this.name = name; - this.object = object; - this.stream = typeof stream == 'boolean' ? stream : false; - this.instrumentations = {}; -} - -Define.prototype.classMethod = function(name, options) { - var keys = Object.keys(options).sort(); - var key = generateKey(keys, options); - - // Add a list of instrumentations - if(this.instrumentations[key] == null) { - this.instrumentations[key] = { - methods: [], options: options - } - } - - // Push to list of method for this instrumentation - this.instrumentations[key].methods.push(name); -} - -var generateKey = function(keys, options) { - var parts = []; - for(var i = 0; i < keys.length; i++) { - parts.push(f('%s=%s', keys[i], options[keys[i]])); - } - - return parts.join(); -} - -Define.prototype.staticMethod = function(name, options) { - options.static = true; - var keys = Object.keys(options).sort(); - var key = generateKey(keys, options); - - // Add a list of instrumentations - if(this.instrumentations[key] == null) { - this.instrumentations[key] = { - methods: [], options: options - } - } - - // Push to list of method for this instrumentation - this.instrumentations[key].methods.push(name); -} - -Define.prototype.generate = function(keys, options) { - // Generate the return object - var object = { - name: this.name, obj: this.object, stream: this.stream, - instrumentations: [] - } - - for(var name in this.instrumentations) { - object.instrumentations.push(this.instrumentations[name]); - } - - return object; -} - -module.exports = Define; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/lib/mongo_client.js b/util/demographicsImporter/node_modules/mongodb/lib/mongo_client.js deleted file mode 100644 index 3ce2ad6..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/mongo_client.js +++ /dev/null @@ -1,463 +0,0 @@ -"use strict"; - -var parse = require('./url_parser') - , Server = require('./server') - , Mongos = require('./mongos') - , ReplSet = require('./replset') - , Define = require('./metadata') - , ReadPreference = require('./read_preference') - , Db = require('./db'); - -/** - * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. - * - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - -/** - * Creates a new MongoClient instance - * @class - * @return {MongoClient} a MongoClient instance. - */ -function MongoClient() { - /** - * The callback format for results - * @callback MongoClient~connectCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Db} db The connected database. - */ - - /** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @param {string} url The connection URI string - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication - * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** - * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** - * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** - * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ - this.connect = MongoClient.connect; -} - -var define = MongoClient.define = new Define('MongoClient', MongoClient, false); - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @static - * @param {string} url The connection URI string - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication - * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** - * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** - * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** - * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.connect = function(url, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Return a promise - if(typeof callback != 'function') { - return new promiseLibrary(function(resolve, reject) { - connect(url, options, function(err, db) { - if(err) return reject(err); - resolve(db); - }); - }); - } - - // Fallback to callback based connect - connect(url, options, callback); -} - -define.staticMethod('connect', {callback: true, promise:true}); - -var connect = function(url, options, callback) { - var serverOptions = options.server || {}; - var mongosOptions = options.mongos || {}; - var replSetServersOptions = options.replSet || options.replSetServers || {}; - var dbOptions = options.db || {}; - - // If callback is null throw an exception - if(callback == null) - throw new Error("no callback function provided"); - - // Parse the string - var object = parse(url, options); - - // Merge in any options for db in options object - if(dbOptions) { - for(var name in dbOptions) object.db_options[name] = dbOptions[name]; - } - - // Added the url to the options - object.db_options.url = url; - - // Merge in any options for server in options object - if(serverOptions) { - for(var name in serverOptions) object.server_options[name] = serverOptions[name]; - } - - // Merge in any replicaset server options - if(replSetServersOptions) { - for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; - } - - if(replSetServersOptions.ssl - || replSetServersOptions.sslValidate - || replSetServersOptions.sslCA - || replSetServersOptions.sslCert - || replSetServersOptions.sslKey - || replSetServersOptions.sslPass) { - object.server_options.ssl = replSetServersOptions.ssl; - object.server_options.sslValidate = replSetServersOptions.sslValidate; - object.server_options.sslCA = replSetServersOptions.sslCA; - object.server_options.sslCert = replSetServersOptions.sslCert; - object.server_options.sslKey = replSetServersOptions.sslKey; - object.server_options.sslPass = replSetServersOptions.sslPass; - } - - // Merge in any replicaset server options - if(mongosOptions) { - for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; - } - - if(typeof object.server_options.poolSize == 'number') { - if(!object.mongos_options.poolSize) object.mongos_options.poolSize = object.server_options.poolSize; - if(!object.rs_options.poolSize) object.rs_options.poolSize = object.server_options.poolSize; - } - - if(mongosOptions.ssl - || mongosOptions.sslValidate - || mongosOptions.sslCA - || mongosOptions.sslCert - || mongosOptions.sslKey - || mongosOptions.sslPass) { - object.server_options.ssl = mongosOptions.ssl; - object.server_options.sslValidate = mongosOptions.sslValidate; - object.server_options.sslCA = mongosOptions.sslCA; - object.server_options.sslCert = mongosOptions.sslCert; - object.server_options.sslKey = mongosOptions.sslKey; - object.server_options.sslPass = mongosOptions.sslPass; - } - - // Set the promise library - object.db_options.promiseLibrary = options.promiseLibrary; - - // We need to ensure that the list of servers are only either direct members or mongos - // they cannot be a mix of monogs and mongod's - var totalNumberOfServers = object.servers.length; - var totalNumberOfMongosServers = 0; - var totalNumberOfMongodServers = 0; - var serverConfig = null; - var errorServers = {}; - - // Failure modes - if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host"); - - // If we have no db setting for the native parser try to set the c++ one first - object.db_options.native_parser = _setNativeParser(object.db_options); - // If no auto_reconnect is set, set it to true as default for single servers - if(typeof object.server_options.auto_reconnect != 'boolean') { - object.server_options.auto_reconnect = true; - } - - // If we have more than a server, it could be replicaset or mongos list - // need to verify that it's one or the other and fail if it's a mix - // Connect to all servers and run ismaster - for(var i = 0; i < object.servers.length; i++) { - // Set up socket options - var providedSocketOptions = object.server_options.socketOptions || {}; - - var _server_options = { - poolSize:1 - , socketOptions: { - connectTimeoutMS: providedSocketOptions.connectTimeoutMS || 30000 - , socketTimeoutMS: providedSocketOptions.socketTimeoutMS || 30000 - } - , auto_reconnect:false}; - - // Ensure we have ssl setup for the servers - if(object.server_options.ssl) { - _server_options.ssl = object.server_options.ssl; - _server_options.sslValidate = object.server_options.sslValidate; - _server_options.sslCA = object.server_options.sslCA; - _server_options.sslCert = object.server_options.sslCert; - _server_options.sslKey = object.server_options.sslKey; - _server_options.sslPass = object.server_options.sslPass; - } else if(object.rs_options.ssl) { - _server_options.ssl = object.rs_options.ssl; - _server_options.sslValidate = object.rs_options.sslValidate; - _server_options.sslCA = object.rs_options.sslCA; - _server_options.sslCert = object.rs_options.sslCert; - _server_options.sslKey = object.rs_options.sslKey; - _server_options.sslPass = object.rs_options.sslPass; - } - - // Error - var error = null; - // Set up the Server object - var _server = object.servers[i].domain_socket - ? new Server(object.servers[i].domain_socket, _server_options) - : new Server(object.servers[i].host, object.servers[i].port, _server_options); - - var connectFunction = function(__server) { - // Attempt connect - new Db(object.dbName, __server, {w:1, native_parser:false, promiseLibrary:options.promiseLibrary}).open(function(err, db) { - // Update number of servers - totalNumberOfServers = totalNumberOfServers - 1; - - // If no error do the correct checks - if(!err) { - // Close the connection - db.close(); - var isMasterDoc = db.serverConfig.isMasterDoc; - - // Check what type of server we have - if(isMasterDoc.setName) { - totalNumberOfMongodServers++; - } - - if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; - } else { - error = err; - errorServers[__server.host + ":" + __server.port] = __server; - } - - if(totalNumberOfServers == 0) { - // Error out - if(totalNumberOfMongodServers == 0 && totalNumberOfMongosServers == 0 && error) { - return callback(error, null); - } - - // If we have a mix of mongod and mongos, throw an error - if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { - if(db) db.close(); - return process.nextTick(function() { - try { - callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); - } catch (err) { - throw err - } - }) - } - - if(totalNumberOfMongodServers == 0 - && totalNumberOfMongosServers == 0 - && object.servers.length == 1 - && (!object.rs_options.replicaSet || !object.rs_options.rs_name)) { - - var obj = object.servers[0]; - serverConfig = obj.domain_socket ? - new Server(obj.domain_socket, object.server_options) - : new Server(obj.host, obj.port, object.server_options); - - } else if(totalNumberOfMongodServers > 0 - || totalNumberOfMongosServers > 0 - || object.rs_options.replicaSet || object.rs_options.rs_name) { - - var finalServers = object.servers - .filter(function(serverObj) { - return errorServers[serverObj.host + ":" + serverObj.port] == null; - }) - .map(function(serverObj) { - return new Server(serverObj.host, serverObj.port, object.server_options); - }); - - // Clean out any error servers - errorServers = {}; - - // Set up the final configuration - if(totalNumberOfMongodServers > 0) { - try { - - // If no replicaset name was provided, we wish to perform a - // direct connection - if(totalNumberOfMongodServers == 1 - && (!object.rs_options.replicaSet && !object.rs_options.rs_name)) { - serverConfig = finalServers[0]; - } else if(totalNumberOfMongodServers == 1) { - object.rs_options.replicaSet = object.rs_options.replicaSet || object.rs_options.rs_name; - serverConfig = new ReplSet(finalServers, object.rs_options); - } else { - serverConfig = new ReplSet(finalServers, object.rs_options); - } - - } catch(err) { - return callback(err, null); - } - } else { - serverConfig = new Mongos(finalServers, object.mongos_options); - } - } - - if(serverConfig == null) { - return process.nextTick(function() { - try { - callback(new Error("Could not locate any valid servers in initial seed list")); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - - // Ensure no firing of open event before we are ready - serverConfig.emitOpen = false; - // Set up all options etc and connect to the database - _finishConnecting(serverConfig, object, options, callback) - } - }); - } - - // Wrap the context of the call - connectFunction(_server); - } -} - -var _setNativeParser = function(db_options) { - if(typeof db_options.native_parser == 'boolean') return db_options.native_parser; - - try { - require('mongodb-core').BSON.BSONNative.BSON; - return true; - } catch(err) { - return false; - } -} - -var _finishConnecting = function(serverConfig, object, options, callback) { - // If we have a readPreference passed in by the db options - if(typeof object.db_options.readPreference == 'string') { - object.db_options.readPreference = new ReadPreference(object.db_options.readPreference); - } else if(typeof object.db_options.read_preference == 'string') { - object.db_options.readPreference = new ReadPreference(object.db_options.read_preference); - } - - // Do we have readPreference tags - if(object.db_options.readPreference && object.db_options.readPreferenceTags) { - object.db_options.readPreference.tags = object.db_options.readPreferenceTags; - } else if(object.db_options.readPreference && object.db_options.read_preference_tags) { - object.db_options.readPreference.tags = object.db_options.read_preference_tags; - } - - // Get the socketTimeoutMS - var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0; - - // If we have a replset, override with replicaset socket timeout option if available - if(serverConfig instanceof ReplSet) { - socketTimeoutMS = object.rs_options.socketOptions.socketTimeoutMS || socketTimeoutMS; - } - - // Set socketTimeout to the same as the connectTimeoutMS or 30 sec - serverConfig.connectTimeoutMS = serverConfig.connectTimeoutMS || 30000; - serverConfig.socketTimeoutMS = serverConfig.connectTimeoutMS; - - // Set up the db options - var db = new Db(object.dbName, serverConfig, object.db_options); - // Open the db - db.open(function(err, db){ - - if(err) { - return process.nextTick(function() { - try { - callback(err, null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - - // Reset the socket timeout - serverConfig.socketTimeoutMS = socketTimeoutMS || 0; - - // Return object - if(err == null && object.auth){ - // What db to authenticate against - var authentication_db = db; - if(object.db_options && object.db_options.authSource) { - authentication_db = db.db(object.db_options.authSource); - } - - // Build options object - var options = {}; - if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism; - if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName; - - // Authenticate - authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){ - if(success){ - process.nextTick(function() { - try { - callback(null, db); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } else { - if(db) db.close(); - process.nextTick(function() { - try { - callback(err ? err : new Error('Could not authenticate user ' + object.auth[0]), null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - }); - } else { - process.nextTick(function() { - try { - callback(err, db); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - }); -} - -module.exports = MongoClient diff --git a/util/demographicsImporter/node_modules/mongodb/lib/mongos.js b/util/demographicsImporter/node_modules/mongodb/lib/mongos.js deleted file mode 100644 index 6087d76..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/mongos.js +++ /dev/null @@ -1,491 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , f = require('util').format - , ServerCapabilities = require('./topology_base').ServerCapabilities - , MongoCR = require('mongodb-core').MongoCR - , CMongos = require('mongodb-core').Mongos - , Cursor = require('./cursor') - , AggregationCursor = require('./aggregation_cursor') - , CommandCursor = require('./command_cursor') - , Define = require('./metadata') - , Server = require('./server') - , Store = require('./topology_base').Store - , shallowClone = require('./utils').shallowClone; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * **Mongos Should not be used, use MongoClient.connect** - * @example - * var Db = require('mongodb').Db, - * Mongos = require('mongodb').Mongos, - * Server = require('mongodb').Server, - * test = require('assert'); - * // Connect using Mongos - * var server = new Server('localhost', 27017); - * var db = new Db('test', new Mongos([server])); - * db.open(function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - -/** - * Creates a new Mongos instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options=null] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {object} [options.socketOptions=null] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @fires Mongos#connect - * @fires Mongos#ha - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#fullsetup - * @fires Mongos#open - * @fires Mongos#close - * @fires Mongos#error - * @fires Mongos#timeout - * @fires Mongos#parseError - * @return {Mongos} a Mongos instance. - */ -var Mongos = function(servers, options) { - if(!(this instanceof Mongos)) return new Mongos(servers, options); - options = options || {}; - var self = this; - - // Ensure all the instances are Server - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) { - throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); - } - } - - // Store option defaults - var storeOptions = { - force: false - , bufferMaxEntries: -1 - } - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Set up event emitter - EventEmitter.call(this); - - // Debug tag - var tag = options.tag; - - // Build seed list - var seedlist = servers.map(function(x) { - return {host: x.host, port: x.port} - }); - - // Final options - var finalOptions = shallowClone(options); - - // Default values - finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; - finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; - finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; - finalOptions.cursorFactory = Cursor; - - // Add the store - finalOptions.disconnectHandler = store; - - // Ensure we change the sslCA option to ca if available - if(options.sslCA) finalOptions.ca = options.sslCA; - if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; - if(options.sslKey) finalOptions.key = options.sslKey; - if(options.sslCert) finalOptions.cert = options.sslCert; - if(options.sslPass) finalOptions.passphrase = options.sslPass; - - // Socket options passed down - if(options.socketOptions) { - if(options.socketOptions.connectTimeoutMS) { - this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; - finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; - } - if(options.socketOptions.socketTimeoutMS) - finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; - } - - // Are we running in debug mode - var debug = typeof options.debug == 'boolean' ? options.debug : false; - if(debug) { - finalOptions.debug = debug; - } - - // Map keep alive setting - if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { - finalOptions.keepAlive = true; - if(typeof options.socketOptions.keepAlive == 'number') { - finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; - } - } - - // Connection timeout - if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { - finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; - } - - // Socket timeout - if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { - finalOptions.socketTimeout = options.socketOptions.socketTimeout; - } - - // noDelay - if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { - finalOptions.noDelay = options.socketOptions.noDelay; - } - - if(typeof options.secondaryAcceptableLatencyMS == 'number') { - finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; - } - - // Add the non connection store - finalOptions.disconnectHandler = store; - - // Create the Mongos - var mongos = new CMongos(seedlist, finalOptions) - // Server capabilities - var sCapabilities = null; - // Add auth prbufferMaxEntriesoviders - mongos.addAuthProvider('mongocr', new MongoCR()); - - // Internal state - this.s = { - // Create the Mongos - mongos: mongos - // Server capabilities - , sCapabilities: sCapabilities - // Debug turned on - , debug: debug - // Store option defaults - , storeOptions: storeOptions - // Cloned options - , clonedOptions: finalOptions - // Actual store of callbacks - , store: store - // Options - , options: options - } - - - // Last ismaster - Object.defineProperty(this, 'isMasterDoc', { - enumerable:true, get: function() { return self.s.mongos.lastIsMaster(); } - }); - - // Last ismaster - Object.defineProperty(this, 'numberOfConnectedServers', { - enumerable:true, get: function() { - return self.s.mongos.s.mongosState.connectedServers().length; - } - }); - - // BSON property - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - return self.s.mongos.bson; - } - }); - - Object.defineProperty(this, 'haInterval', { - enumerable:true, get: function() { return self.s.mongos.haInterval; } - }); -} - -/** - * @ignore - */ -inherits(Mongos, EventEmitter); - -var define = Mongos.define = new Define('Mongos', Mongos, false); - -// Connect -Mongos.prototype.connect = function(db, _options, callback) { - var self = this; - if('function' === typeof _options) callback = _options, _options = {}; - if(_options == null) _options = {}; - if(!('function' === typeof callback)) callback = null; - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; - - // Error handler - var connectErrorHandler = function(event) { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.removeListener(e, connectErrorHandler); - }); - - self.s.mongos.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - } - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if(event != 'error') { - self.emit(event, err); - } - } - } - - // Error handler - var reconnectHandler = function(err) { - self.emit('reconnect'); - self.s.store.execute(); - } - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ["timeout", "error", "close"].forEach(function(e) { - self.s.mongos.removeAllListeners(e); - }); - - // Set up listeners - self.s.mongos.once('timeout', errorHandler('timeout')); - self.s.mongos.once('error', errorHandler('error')); - self.s.mongos.once('close', errorHandler('close')); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - } - } - - // Set up serverConfig listeners - self.s.mongos.on('joined', relay('joined')); - self.s.mongos.on('left', relay('left')); - self.s.mongos.on('fullsetup', relay('fullsetup')); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - - // Set up listeners - self.s.mongos.once('timeout', connectErrorHandler('timeout')); - self.s.mongos.once('error', connectErrorHandler('error')); - self.s.mongos.once('close', connectErrorHandler('close')); - self.s.mongos.once('connect', connectHandler); - // Reconnect server - self.s.mongos.on('reconnect', reconnectHandler); - - // Start connection - self.s.mongos.connect(_options); -} - -Mongos.prototype.parserType = function() { - return this.s.mongos.parserType(); -} - -define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); - -// Server capabilities -Mongos.prototype.capabilities = function() { - if(this.s.sCapabilities) return this.s.sCapabilities; - if(this.s.mongos.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); - this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); - return this.s.sCapabilities; -} - -define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); - -// Command -Mongos.prototype.command = function(ns, cmd, options, callback) { - this.s.mongos.command(ns, cmd, options, callback); -} - -define.classMethod('command', {callback: true, promise:false}); - -// Insert -Mongos.prototype.insert = function(ns, ops, options, callback) { - this.s.mongos.insert(ns, ops, options, function(e, m) { - callback(e, m) - }); -} - -define.classMethod('insert', {callback: true, promise:false}); - -// Update -Mongos.prototype.update = function(ns, ops, options, callback) { - this.s.mongos.update(ns, ops, options, callback); -} - -define.classMethod('update', {callback: true, promise:false}); - -// Remove -Mongos.prototype.remove = function(ns, ops, options, callback) { - this.s.mongos.remove(ns, ops, options, callback); -} - -define.classMethod('remove', {callback: true, promise:false}); - -// IsConnected -Mongos.prototype.isConnected = function() { - return this.s.mongos.isConnected(); -} - -define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); - -// Insert -Mongos.prototype.cursor = function(ns, cmd, options) { - options.disconnectHandler = this.s.store; - return this.s.mongos.cursor(ns, cmd, options); -} - -define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); - -Mongos.prototype.setBSONParserType = function(type) { - return this.s.mongos.setBSONParserType(type); -} - -Mongos.prototype.lastIsMaster = function() { - return this.s.mongos.lastIsMaster(); -} - -Mongos.prototype.close = function(forceClosed) { - this.s.mongos.destroy(); - // We need to wash out all stored processes - if(forceClosed == true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } -} - -define.classMethod('close', {callback: false, promise:false}); - -Mongos.prototype.auth = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.mongos.auth.apply(this.s.mongos, args); -} - -define.classMethod('auth', {callback: true, promise:false}); - -/** - * All raw connections - * @method - * @return {array} - */ -Mongos.prototype.connections = function() { - return this.s.mongos.connections(); -} - -define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * The mongos high availability event - * - * @event Mongos#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the mongos set - * - * @event Mongos#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos set - * - * @event Mongos#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * Mongos open event, emitted when mongos can start processing commands. - * - * @event Mongos#open - * @type {Mongos} - */ - -/** - * Mongos close event - * - * @event Mongos#close - * @type {object} - */ - -/** - * Mongos error event, emitted if there is an error listener. - * - * @event Mongos#error - * @type {MongoError} - */ - -/** - * Mongos timeout event - * - * @event Mongos#timeout - * @type {object} - */ - -/** - * Mongos parseError event - * - * @event Mongos#parseError - * @type {object} - */ - -module.exports = Mongos; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/read_preference.js b/util/demographicsImporter/node_modules/mongodb/lib/read_preference.js deleted file mode 100644 index 73b253a..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/read_preference.js +++ /dev/null @@ -1,104 +0,0 @@ -"use strict"; - -/** - * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * - * @example - * var Db = require('mongodb').Db, - * ReplSet = require('mongodb').ReplSet, - * Server = require('mongodb').Server, - * ReadPreference = require('mongodb').ReadPreference, - * test = require('assert'); - * // Connect using ReplSet - * var server = new Server('localhost', 27017); - * var db = new Db('test', new ReplSet([server])); - * db.open(function(err, db) { - * test.equal(null, err); - * // Perform a read - * var cursor = db.collection('t').find({}); - * cursor.setReadPreference(ReadPreference.PRIMARY); - * cursor.toArray(function(err, docs) { - * test.equal(null, err); - * db.close(); - * }); - * }); - */ - -/** - * Creates a new ReadPreference instance - * - * Read Preferences - * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). - * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. - * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. - * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. - * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. - * - * @class - * @param {string} mode The ReadPreference mode as listed above. - * @param {object} tags An object representing read preference tags. - * @property {string} mode The ReadPreference mode. - * @property {object} tags The ReadPreference tags. - * @return {ReadPreference} a ReadPreference instance. - */ -var ReadPreference = function(mode, tags) { - if(!(this instanceof ReadPreference)) - return new ReadPreference(mode, tags); - this._type = 'ReadPreference'; - this.mode = mode; - this.tags = tags; -} - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} - */ -ReadPreference.isValid = function(_mode) { - return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED - || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED - || _mode == ReadPreference.NEAREST - || _mode == true || _mode == false || _mode == null); -} - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} - */ -ReadPreference.prototype.isValid = function(mode) { - var _mode = typeof mode == 'string' ? mode : this.mode; - return ReadPreference.isValid(_mode); -} - -/** - * @ignore - */ -ReadPreference.prototype.toObject = function() { - var object = {mode:this.mode}; - - if(this.tags != null) { - object['tags'] = this.tags; - } - - return object; -} - -/** - * @ignore - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest' - -/** - * @ignore - */ -module.exports = ReadPreference; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/lib/replset.js b/util/demographicsImporter/node_modules/mongodb/lib/replset.js deleted file mode 100644 index 8a71b42..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/replset.js +++ /dev/null @@ -1,555 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , f = require('util').format - , Server = require('./server') - , Mongos = require('./mongos') - , Cursor = require('./cursor') - , AggregationCursor = require('./aggregation_cursor') - , CommandCursor = require('./command_cursor') - , ReadPreference = require('./read_preference') - , MongoCR = require('mongodb-core').MongoCR - , MongoError = require('mongodb-core').MongoError - , ServerCapabilities = require('./topology_base').ServerCapabilities - , Store = require('./topology_base').Store - , Define = require('./metadata') - , CServer = require('mongodb-core').Server - , CReplSet = require('mongodb-core').ReplSet - , CoreReadPreference = require('mongodb-core').ReadPreference - , shallowClone = require('./utils').shallowClone; - -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connections. - * - * **ReplSet Should not be used, use MongoClient.connect** - * @example - * var Db = require('mongodb').Db, - * ReplSet = require('mongodb').ReplSet, - * Server = require('mongodb').Server, - * test = require('assert'); - * // Connect using ReplSet - * var server = new Server('localhost', 27017); - * var db = new Db('test', new ReplSet([server])); - * db.open(function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - -/** - * Creates a new ReplSet instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options=null] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {string} options.replicaSet The name of the replicaset to connect to. - * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {object} [options.socketOptions=null] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#fullsetup - * @fires ReplSet#open - * @fires ReplSet#close - * @fires ReplSet#error - * @fires ReplSet#timeout - * @fires ReplSet#parseError - * @return {ReplSet} a ReplSet instance. - */ -var ReplSet = function(servers, options) { - if(!(this instanceof ReplSet)) return new ReplSet(servers, options); - options = options || {}; - var self = this; - - // Ensure all the instances are Server - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) { - throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); - } - } - - // Store option defaults - var storeOptions = { - force: false - , bufferMaxEntries: -1 - } - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Set up event emitter - EventEmitter.call(this); - - // Debug tag - var tag = options.tag; - - // Build seed list - var seedlist = servers.map(function(x) { - return {host: x.host, port: x.port} - }); - - // Final options - var finalOptions = shallowClone(options); - - // Default values - finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; - finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; - finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; - finalOptions.cursorFactory = Cursor; - - // Add the store - finalOptions.disconnectHandler = store; - - // Socket options passed down - if(options.socketOptions) { - if(options.socketOptions.connectTimeoutMS) { - this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; - finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; - } - - if(options.socketOptions.socketTimeoutMS) { - finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; - } - } - - // Get the name - var replicaSet = options.replicaSet || options.rs_name; - - // Set up options - finalOptions.setName = replicaSet; - - // Are we running in debug mode - var debug = typeof options.debug == 'boolean' ? options.debug : false; - if(debug) { - finalOptions.debug = debug; - } - - // Map keep alive setting - if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { - finalOptions.keepAlive = true; - if(typeof options.socketOptions.keepAlive == 'number') { - finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; - } - } - - // Connection timeout - if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { - finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; - } - - // Socket timeout - if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { - finalOptions.socketTimeout = options.socketOptions.socketTimeout; - } - - // noDelay - if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { - finalOptions.noDelay = options.socketOptions.noDelay; - } - - if(typeof options.secondaryAcceptableLatencyMS == 'number') { - finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; - } - - if(options.connectWithNoPrimary == true) { - finalOptions.secondaryOnlyConnectionAllowed = true; - } - - // Add the non connection store - finalOptions.disconnectHandler = store; - - // Translate the options - if(options.sslCA) finalOptions.ca = options.sslCA; - if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; - if(options.sslKey) finalOptions.key = options.sslKey; - if(options.sslCert) finalOptions.cert = options.sslCert; - if(options.sslPass) finalOptions.passphrase = options.sslPass; - - // Create the ReplSet - var replset = new CReplSet(seedlist, finalOptions) - // Server capabilities - var sCapabilities = null; - // Add auth prbufferMaxEntriesoviders - replset.addAuthProvider('mongocr', new MongoCR()); - - // Listen to reconnect event - replset.on('reconnect', function() { - self.emit('reconnect'); - store.execute(); - }); - - // Internal state - this.s = { - // Replicaset - replset: replset - // Server capabilities - , sCapabilities: null - // Debug tag - , tag: options.tag - // Store options - , storeOptions: storeOptions - // Cloned options - , clonedOptions: finalOptions - // Store - , store: store - // Options - , options: options - } - - // Debug - if(debug) { - // Last ismaster - Object.defineProperty(this, 'replset', { - enumerable:true, get: function() { return replset; } - }); - } - - // Last ismaster - Object.defineProperty(this, 'isMasterDoc', { - enumerable:true, get: function() { return replset.lastIsMaster(); } - }); - - // BSON property - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - return replset.bson; - } - }); - - Object.defineProperty(this, 'haInterval', { - enumerable:true, get: function() { return replset.haInterval; } - }); -} - -/** - * @ignore - */ -inherits(ReplSet, EventEmitter); - -var define = ReplSet.define = new Define('ReplSet', ReplSet, false); - -// Ensure the right read Preference object -var translateReadPreference = function(options) { - if(typeof options.readPreference == 'string') { - options.readPreference = new CoreReadPreference(options.readPreference); - } else if(options.readPreference instanceof ReadPreference) { - options.readPreference = new CoreReadPreference(options.readPreference.mode - , options.readPreference.tags); - } - - return options; -} - -ReplSet.prototype.parserType = function() { - return this.s.replset.parserType(); -} - -define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); - -// Connect method -ReplSet.prototype.connect = function(db, _options, callback) { - var self = this; - if('function' === typeof _options) callback = _options, _options = {}; - if(_options == null) _options = {}; - if(!('function' === typeof callback)) callback = null; - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if(event != 'error') { - self.emit(event, err); - } - } - } - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ["timeout", "error", "close"].forEach(function(e) { - self.s.replset.removeAllListeners(e); - }); - - // Set up listeners - self.s.replset.once('timeout', errorHandler('timeout')); - self.s.replset.once('error', errorHandler('error')); - self.s.replset.once('close', errorHandler('close')); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - } - } - - // Replset events relay - var replsetRelay = function(event) { - return function(t, server) { - self.emit(event, t, server.lastIsMaster(), server); - } - } - - // Relay ha - var relayHa = function(t, state) { - self.emit('ha', t, state); - - if(t == 'start') { - self.emit('ha_connect', t, state); - } else if(t == 'end') { - self.emit('ha_ismaster', t, state); - } - } - - // Set up serverConfig listeners - self.s.replset.on('joined', replsetRelay('joined')); - self.s.replset.on('left', relay('left')); - self.s.replset.on('ping', relay('ping')); - self.s.replset.on('ha', relayHa); - - self.s.replset.on('fullsetup', function(topology) { - self.emit('fullsetup', null, self); - }); - - self.s.replset.on('all', function(topology) { - self.emit('all', null, self); - }); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - - // Error handler - var connectErrorHandler = function(event) { - return function(err) { - ['timeout', 'error', 'close'].forEach(function(e) { - self.s.replset.removeListener(e, connectErrorHandler); - }); - - self.s.replset.removeListener('connect', connectErrorHandler); - // Destroy the replset - self.s.replset.destroy(); - - // Try to callback - try { - callback(err); - } catch(err) { - if(!self.s.replset.isConnected()) - process.nextTick(function() { throw err; }) - } - } - } - - // Set up listeners - self.s.replset.once('timeout', connectErrorHandler('timeout')); - self.s.replset.once('error', connectErrorHandler('error')); - self.s.replset.once('close', connectErrorHandler('close')); - self.s.replset.once('connect', connectHandler); - - // Start connection - self.s.replset.connect(_options); -} - -// Server capabilities -ReplSet.prototype.capabilities = function() { - if(this.s.sCapabilities) return this.s.sCapabilities; - if(this.s.replset.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); - this.s.sCapabilities = new ServerCapabilities(this.s.replset.lastIsMaster()); - return this.s.sCapabilities; -} - -define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); - -// Command -ReplSet.prototype.command = function(ns, cmd, options, callback) { - options = translateReadPreference(options); - this.s.replset.command(ns, cmd, options, callback); -} - -define.classMethod('command', {callback: true, promise:false}); - -// Insert -ReplSet.prototype.insert = function(ns, ops, options, callback) { - this.s.replset.insert(ns, ops, options, callback); -} - -define.classMethod('insert', {callback: true, promise:false}); - -// Update -ReplSet.prototype.update = function(ns, ops, options, callback) { - this.s.replset.update(ns, ops, options, callback); -} - -define.classMethod('update', {callback: true, promise:false}); - -// Remove -ReplSet.prototype.remove = function(ns, ops, options, callback) { - this.s.replset.remove(ns, ops, options, callback); -} - -define.classMethod('remove', {callback: true, promise:false}); - -// IsConnected -ReplSet.prototype.isConnected = function() { - return this.s.replset.isConnected(); -} - -define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); - -ReplSet.prototype.setBSONParserType = function(type) { - return this.s.replset.setBSONParserType(type); -} - -// Insert -ReplSet.prototype.cursor = function(ns, cmd, options) { - options = translateReadPreference(options); - options.disconnectHandler = this.s.store; - return this.s.replset.cursor(ns, cmd, options); -} - -define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); - -ReplSet.prototype.lastIsMaster = function() { - return this.s.replset.lastIsMaster(); -} - -ReplSet.prototype.close = function(forceClosed) { - var self = this; - this.s.replset.destroy(); - // We need to wash out all stored processes - if(forceClosed == true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } - - var events = ['timeout', 'error', 'close', 'joined', 'left']; - events.forEach(function(e) { - self.removeAllListeners(e); - }); -} - -define.classMethod('close', {callback: false, promise:false}); - -ReplSet.prototype.auth = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.replset.auth.apply(this.s.replset, args); -} - -define.classMethod('auth', {callback: true, promise:false}); - -/** - * All raw connections - * @method - * @return {array} - */ -ReplSet.prototype.connections = function() { - return this.s.replset.connections(); -} - -define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * ReplSet open event, emitted when replicaset can start processing commands. - * - * @event ReplSet#open - * @type {Replset} - */ - -/** - * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. - * - * @event ReplSet#fullsetup - * @type {Replset} - */ - -/** - * ReplSet close event - * - * @event ReplSet#close - * @type {object} - */ - -/** - * ReplSet error event, emitted if there is an error listener. - * - * @event ReplSet#error - * @type {MongoError} - */ - -/** - * ReplSet timeout event - * - * @event ReplSet#timeout - * @type {object} - */ - -/** - * ReplSet parseError event - * - * @event ReplSet#parseError - * @type {object} - */ - -module.exports = ReplSet; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/server.js b/util/demographicsImporter/node_modules/mongodb/lib/server.js deleted file mode 100644 index eff7771..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/server.js +++ /dev/null @@ -1,437 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , CServer = require('mongodb-core').Server - , Cursor = require('./cursor') - , AggregationCursor = require('./aggregation_cursor') - , CommandCursor = require('./command_cursor') - , f = require('util').format - , ServerCapabilities = require('./topology_base').ServerCapabilities - , Store = require('./topology_base').Store - , Define = require('./metadata') - , MongoError = require('mongodb-core').MongoError - , shallowClone = require('./utils').shallowClone; - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * **Server Should not be used, use MongoClient.connect** - * @example - * var Db = require('mongodb').Db, - * Server = require('mongodb').Server, - * test = require('assert'); - * // Connect using single Server - * var db = new Db('test', new Server('localhost', 27017);); - * db.open(function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - -/** - * Creates a new Server instance - * @class - * @deprecated - * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. - * @param {number} [port] The server port if IP4. - * @param {object} [options=null] Optional settings. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {object} [options.socketOptions=null] Socket options - * @param {boolean} [options.socketOptions.autoReconnect=false] Reconnect on error. - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @return {Server} a Server instance. - */ -var Server = function(host, port, options) { - options = options || {}; - if(!(this instanceof Server)) return new Server(host, port, options); - EventEmitter.call(this); - var self = this; - - // Store option defaults - var storeOptions = { - force: false - , bufferMaxEntries: -1 - } - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Detect if we have a socket connection - if(host.indexOf('\/') != -1) { - if(port != null && typeof port == 'object') { - options = port; - port = null; - } - } else if(port == null) { - throw MongoError.create({message: 'port must be specified', driver:true}); - } - - // Clone options - var clonedOptions = shallowClone(options); - clonedOptions.host = host; - clonedOptions.port = port; - - // Reconnect - var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; - var emitError = typeof options.emitError == 'boolean' ? options.emitError : true; - var poolSize = typeof options.poolSize == 'number' ? options.poolSize : 5; - - // Socket options passed down - if(options.socketOptions) { - if(options.socketOptions.connectTimeoutMS) { - this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; - clonedOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; - } - - if(options.socketOptions.socketTimeoutMS) { - clonedOptions.socketTimeout = options.socketOptions.socketTimeoutMS; - } - - if(typeof options.socketOptions.keepAlive == 'number') { - clonedOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; - clonedOptions.keepAlive = true; - } - - if(typeof options.socketOptions.noDelay == 'boolean') { - clonedOptions.noDelay = options.socketOptions.noDelay; - } - } - - // Add the cursor factory function - clonedOptions.cursorFactory = Cursor; - clonedOptions.reconnect = reconnect; - clonedOptions.emitError = emitError; - clonedOptions.size = poolSize; - - // Translate the options - if(clonedOptions.sslCA) clonedOptions.ca = clonedOptions.sslCA; - if(typeof clonedOptions.sslValidate == 'boolean') clonedOptions.rejectUnauthorized = clonedOptions.sslValidate; - if(clonedOptions.sslKey) clonedOptions.key = clonedOptions.sslKey; - if(clonedOptions.sslCert) clonedOptions.cert = clonedOptions.sslCert; - if(clonedOptions.sslPass) clonedOptions.passphrase = clonedOptions.sslPass; - - // Add the non connection store - clonedOptions.disconnectHandler = store; - - // Create an instance of a server instance from mongodb-core - var server = new CServer(clonedOptions); - // Server capabilities - var sCapabilities = null; - - // Define the internal properties - this.s = { - // Create an instance of a server instance from mongodb-core - server: server - // Server capabilities - , sCapabilities: null - // Cloned options - , clonedOptions: clonedOptions - // Reconnect - , reconnect: reconnect - // Emit error - , emitError: emitError - // Pool size - , poolSize: poolSize - // Store Options - , storeOptions: storeOptions - // Store - , store: store - // Host - , host: host - // Port - , port: port - // Options - , options: options - } - - // BSON property - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - return self.s.server.bson; - } - }); - - // Last ismaster - Object.defineProperty(this, 'isMasterDoc', { - enumerable:true, get: function() { - return self.s.server.lastIsMaster(); - } - }); - - // Last ismaster - Object.defineProperty(this, 'poolSize', { - enumerable:true, get: function() { return self.s.server.connections().length; } - }); - - Object.defineProperty(this, 'autoReconnect', { - enumerable:true, get: function() { return self.s.reconnect; } - }); - - Object.defineProperty(this, 'host', { - enumerable:true, get: function() { return self.s.host; } - }); - - Object.defineProperty(this, 'port', { - enumerable:true, get: function() { return self.s.port; } - }); -} - -inherits(Server, EventEmitter); - -var define = Server.define = new Define('Server', Server, false); - -Server.prototype.parserType = function() { - return this.s.server.parserType(); -} - -define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); - -// Connect -Server.prototype.connect = function(db, _options, callback) { - var self = this; - if('function' === typeof _options) callback = _options, _options = {}; - if(_options == null) _options = {}; - if(!('function' === typeof callback)) callback = null; - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; - - // Error handler - var connectErrorHandler = function(event) { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.s.server.removeListener(e, connectHandlers[e]); - }); - - self.s.server.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - } - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if(event != 'error') { - self.emit(event, err); - } - } - } - - // Error handler - var reconnectHandler = function(err) { - self.emit('reconnect', self); - self.s.store.execute(); - } - - // Destroy called on topology, perform cleanup - var destroyHandler = function() { - self.s.store.flush(); - } - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ["timeout", "error", "close"].forEach(function(e) { - self.s.server.removeAllListeners(e); - }); - - // Set up listeners - self.s.server.once('timeout', errorHandler('timeout')); - self.s.server.once('error', errorHandler('error')); - self.s.server.on('close', errorHandler('close')); - // Only called on destroy - self.s.server.once('destroy', destroyHandler); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch(err) { - console.log(err.stack) - process.nextTick(function() { throw err; }) - } - } - - // Set up listeners - var connectHandlers = { - timeout: connectErrorHandler('timeout'), - error: connectErrorHandler('error'), - close: connectErrorHandler('close') - }; - - // Add the event handlers - self.s.server.once('timeout', connectHandlers.timeout); - self.s.server.once('error', connectHandlers.error); - self.s.server.once('close', connectHandlers.close); - self.s.server.once('connect', connectHandler); - // Reconnect server - self.s.server.on('reconnect', reconnectHandler); - - // Start connection - self.s.server.connect(_options); -} - -// Server capabilities -Server.prototype.capabilities = function() { - if(this.s.sCapabilities) return this.s.sCapabilities; - if(this.s.server.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); - this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster()); - return this.s.sCapabilities; -} - -define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); - -// Command -Server.prototype.command = function(ns, cmd, options, callback) { - this.s.server.command(ns, cmd, options, callback); -} - -define.classMethod('command', {callback: true, promise:false}); - -// Insert -Server.prototype.insert = function(ns, ops, options, callback) { - this.s.server.insert(ns, ops, options, callback); -} - -define.classMethod('insert', {callback: true, promise:false}); - -// Update -Server.prototype.update = function(ns, ops, options, callback) { - this.s.server.update(ns, ops, options, callback); -} - -define.classMethod('update', {callback: true, promise:false}); - -// Remove -Server.prototype.remove = function(ns, ops, options, callback) { - this.s.server.remove(ns, ops, options, callback); -} - -define.classMethod('remove', {callback: true, promise:false}); - -// IsConnected -Server.prototype.isConnected = function() { - return this.s.server.isConnected(); -} - -define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); - -// Insert -Server.prototype.cursor = function(ns, cmd, options) { - options.disconnectHandler = this.s.store; - return this.s.server.cursor(ns, cmd, options); -} - -define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); - -Server.prototype.setBSONParserType = function(type) { - return this.s.server.setBSONParserType(type); -} - -Server.prototype.lastIsMaster = function() { - return this.s.server.lastIsMaster(); -} - -Server.prototype.close = function(forceClosed) { - this.s.server.destroy(); - // We need to wash out all stored processes - if(forceClosed == true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } -} - -define.classMethod('close', {callback: false, promise:false}); - -Server.prototype.auth = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.server.auth.apply(this.s.server, args); -} - -define.classMethod('auth', {callback: true, promise:false}); - -/** - * All raw connections - * @method - * @return {array} - */ -Server.prototype.connections = function() { - return this.s.server.connections(); -} - -define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); - -/** - * Server connect event - * - * @event Server#connect - * @type {object} - */ - -/** - * Server close event - * - * @event Server#close - * @type {object} - */ - -/** - * Server reconnect event - * - * @event Server#reconnect - * @type {object} - */ - -/** - * Server error event - * - * @event Server#error - * @type {MongoError} - */ - -/** - * Server timeout event - * - * @event Server#timeout - * @type {object} - */ - -/** - * Server parseError event - * - * @event Server#parseError - * @type {object} - */ - -module.exports = Server; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/topology_base.js b/util/demographicsImporter/node_modules/mongodb/lib/topology_base.js deleted file mode 100644 index 000f7ec..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/topology_base.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; - -var MongoError = require('mongodb-core').MongoError - , f = require('util').format; - -// The store of ops -var Store = function(topology, storeOptions) { - var self = this; - var storedOps = []; - storeOptions = storeOptions || {force:false, bufferMaxEntries: -1} - - // Internal state - this.s = { - storedOps: storedOps - , storeOptions: storeOptions - , topology: topology - } - - Object.defineProperty(this, 'length', { - enumerable:true, get: function() { return self.s.storedOps.length; } - }); -} - -Store.prototype.add = function(opType, ns, ops, options, callback) { - if(this.s.storeOptions.force) { - return callback(MongoError.create({message: "db closed by application", driver:true})); - } - - if(this.s.storeOptions.bufferMaxEntries == 0) { - return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { - while(this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - return; - } - - this.s.storedOps.push({t: opType, n: ns, o: ops, op: options, c: callback}) -} - -Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { - if(this.s.storeOptions.force) { - return callback(MongoError.create({message: "db closed by application", driver:true })); - } - - if(this.s.storeOptions.bufferMaxEntries == 0) { - return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { - while(this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - return; - } - - this.s.storedOps.push({t: opType, m: method, o: object, p: params, c: callback}) -} - -Store.prototype.flush = function() { - while(this.s.storedOps.length > 0) { - this.s.storedOps.shift().c(MongoError.create({message: f("no connection available for operation"), driver:true })); - } -} - -Store.prototype.execute = function() { - // Get current ops - var ops = this.s.storedOps; - // Reset the ops - this.s.storedOps = []; - - // Execute all the stored ops - while(ops.length > 0) { - var op = ops.shift(); - - if(op.t == 'cursor') { - op.o[op.m].apply(op.o, op.p); - } else { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } - } -} - -Store.prototype.all = function() { - return this.s.storedOps; -} - -// Server capabilities -var ServerCapabilities = function(ismaster) { - var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true - , get: function () { return value; } - }); - } - - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var listCollections = false; - var listIndexes = false; - var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; - - if(ismaster.minWireVersion >= 0) { - textSearch = true; - } - - if(ismaster.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if(ismaster.maxWireVersion >= 2) { - writeCommands = true; - } - - if(ismaster.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } - - // If no min or max wire version set to 0 - if(ismaster.minWireVersion == null) { - ismaster.minWireVersion = 0; - } - - if(ismaster.maxWireVersion == null) { - ismaster.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, "hasAggregationCursor", aggregationCursor); - setup_get_property(this, "hasWriteCommands", writeCommands); - setup_get_property(this, "hasTextSearch", textSearch); - setup_get_property(this, "hasAuthCommands", authCommands); - setup_get_property(this, "hasListCollectionsCommand", listCollections); - setup_get_property(this, "hasListIndexesCommand", listIndexes); - setup_get_property(this, "minWireVersion", ismaster.minWireVersion); - setup_get_property(this, "maxWireVersion", ismaster.maxWireVersion); - setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); -} - -exports.Store = Store; -exports.ServerCapabilities = ServerCapabilities; diff --git a/util/demographicsImporter/node_modules/mongodb/lib/url_parser.js b/util/demographicsImporter/node_modules/mongodb/lib/url_parser.js deleted file mode 100644 index eccc1e0..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/url_parser.js +++ /dev/null @@ -1,295 +0,0 @@ -"use strict"; - -var ReadPreference = require('./read_preference'); - -module.exports = function(url, options) { - // Ensure we have a default options object if none set - options = options || {}; - // Variables - var connection_part = ''; - var auth_part = ''; - var query_string_part = ''; - var dbName = 'admin'; - - // Must start with mongodb - if(url.indexOf("mongodb://") != 0) - throw Error("URL must be in the format mongodb://user:pass@host:port/dbname"); - // If we have a ? mark cut the query elements off - if(url.indexOf("?") != -1) { - query_string_part = url.substr(url.indexOf("?") + 1); - connection_part = url.substring("mongodb://".length, url.indexOf("?")) - } else { - connection_part = url.substring("mongodb://".length); - } - - // Check if we have auth params - if(connection_part.indexOf("@") != -1) { - auth_part = connection_part.split("@")[0]; - connection_part = connection_part.split("@")[1]; - } - - // Check if the connection string has a db - if(connection_part.indexOf(".sock") != -1) { - if(connection_part.indexOf(".sock/") != -1) { - dbName = connection_part.split(".sock/")[1]; - connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); - } - } else if(connection_part.indexOf("/") != -1) { - dbName = connection_part.split("/")[1]; - connection_part = connection_part.split("/")[0]; - } - - // Result object - var object = {}; - - // Pick apart the authentication part of the string - var authPart = auth_part || ''; - var auth = authPart.split(':', 2); - - // Decode the URI components - auth[0] = decodeURIComponent(auth[0]); - if(auth[1]){ - auth[1] = decodeURIComponent(auth[1]); - } - - // Add auth to final object if we have 2 elements - if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; - - // Variables used for temporary storage - var hostPart; - var urlOptions; - var servers; - var serverOptions = {socketOptions: {}}; - var dbOptions = {read_preference_tags: []}; - var replSetServersOptions = {socketOptions: {}}; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = {}; - - // Let's check if we are using a domain socket - if(url.match(/\.sock/)) { - // Split out the socket part - var domainSocket = url.substring( - url.indexOf("mongodb://") + "mongodb://".length - , url.lastIndexOf(".sock") + ".sock".length); - // Clean out any auth stuff if any - if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; - servers = [{domain_socket: domainSocket}]; - } else { - // Split up the db - hostPart = connection_part; - // Deduplicate servers - var deduplicatedServers = {}; - - // Parse all server results - servers = hostPart.split(',').map(function(h) { - var _host, _port, ipv6match; - //check if it matches [IPv6]:port, where the port number is optional - if ((ipv6match = /\[([^\]]+)\](?:\:(.+))?/.exec(h))) { - _host = ipv6match[1]; - _port = parseInt(ipv6match[2], 10) || 27017; - } else { - //otherwise assume it's IPv4, or plain hostname - var hostPort = h.split(':', 2); - _host = hostPort[0] || 'localhost'; - _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; - } - - // No entry returned for duplicate servr - if(deduplicatedServers[_host + "_" + _port]) return null; - deduplicatedServers[_host + "_" + _port] = 1; - - // Return the mapped object - return {host: _host, port: _port}; - }).filter(function(x) { - return x != null; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if(!opt) return; - var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; - // Options implementations - switch(name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = (value == 'true'); - dbOptions.slaveOk = (value == 'true'); - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = (value == 'true'); - break; - case 'minPoolSize': - throw new Error("minPoolSize not supported"); - case 'maxIdleTimeMS': - throw new Error("maxIdleTimeMS not supported"); - case 'waitQueueMultiple': - throw new Error("waitQueueMultiple not supported"); - case 'waitQueueTimeoutMS': - throw new Error("waitQueueTimeoutMS not supported"); - case 'uuidRepresentation': - throw new Error("uuidRepresentation not supported"); - case 'ssl': - if(value == 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - break; - } - serverOptions.ssl = (value == 'true'); - replSetServersOptions.ssl = (value == 'true'); - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = (value == 'true'); - break; - case 'fsync': - dbOptions.fsync = (value == 'true'); - break; - case 'journal': - dbOptions.j = (value == 'true'); - break; - case 'safe': - dbOptions.safe = (value == 'true'); - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = (value == 'true'); - break; - case 'readConcernLevel': - dbOptions.readConcern = {level: value}; - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - if(isNaN(dbOptions.w)) dbOptions.w = value; - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if(value == 'GSSAPI') { - // If no password provided decode only the principal - if(object.auth == null) { - var urlDecodeAuthPart = decodeURIComponent(authPart); - if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); - object.auth = {user: urlDecodeAuthPart, password: null}; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if(value == 'MONGODB-X509') { - object.auth = {user: decodeURIComponent(authPart)}; - } - - // Only support GSSAPI or MONGODB-CR for now - if(value != 'GSSAPI' - && value != 'MONGODB-X509' - && value != 'MONGODB-CR' - && value != 'DEFAULT' - && value != 'SCRAM-SHA-1' - && value != 'PLAIN') - throw new Error("only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'authMechanismProperties': - // Split up into key, value pairs - var values = value.split(','); - var o = {}; - // For each value split into key, value - values.forEach(function(x) { - var v = x.split(':'); - o[v[0]] = v[1]; - }); - - // Set all authMechanismProperties - dbOptions.authMechanismProperties = o; - // Set the service name value - if(typeof o.SERVICE_NAME == 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; - break; - case 'wtimeoutMS': - dbOptions.wtimeout = parseInt(value, 10); - break; - case 'readPreference': - if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); - dbOptions.read_preference = value; - break; - case 'readPreferenceTags': - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - var tagObject = {}; - if(value == null || value == '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - var tags = value.split(/\,/); - for(var i = 0; i < tags.length; i++) { - var parts = tags[i].trim().split(/\:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - break; - default: - break; - } - }); - - // No tags: should be null (not []) - if(dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if((dbOptions.w == -1 || dbOptions.w == 0) && ( - dbOptions.journal == true - || dbOptions.fsync == true - || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") - - // If no read preference set it to primary - if(!dbOptions.read_preference) dbOptions.read_preference = 'primary'; - - // Add servers to result - object.servers = servers; - // Returned parsed object - return object; -} diff --git a/util/demographicsImporter/node_modules/mongodb/lib/utils.js b/util/demographicsImporter/node_modules/mongodb/lib/utils.js deleted file mode 100644 index cb20e67..0000000 --- a/util/demographicsImporter/node_modules/mongodb/lib/utils.js +++ /dev/null @@ -1,234 +0,0 @@ -"use strict"; - -var MongoError = require('mongodb-core').MongoError, - f = require('util').format; - -var shallowClone = function(obj) { - var copy = {}; - for(var name in obj) copy[name] = obj[name]; - return copy; -} - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable:true, - get: function() { - return value - } - }); -} - -var formatSortValue = exports.formatSortValue = function(sortDirection) { - var value = ("" + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error("Illegal sort clause, must be of the form " - + "[['field1', '(ascending|descending)'], " - + "['field2', '(ascending|descending)']]"); - } -}; - -var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - if(sortValue == null) return null; - if (Array.isArray(sortValue)) { - if(sortValue.length === 0) { - return null; - } - - for(var i = 0; i < sortValue.length; i++) { - if(sortValue[i].constructor == String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if(sortValue != null && typeof sortValue == 'object') { - orderBy = sortValue; - } else if (typeof sortValue == 'string') { - orderBy[sortValue] = 1; - } else { - throw new Error("Illegal sort clause, must be of the form " + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); - } - - return orderBy; -}; - -var checkCollectionName = function checkCollectionName (collectionName) { - if('string' !== typeof collectionName) { - throw Error("collection name must be a String"); - } - - if(!collectionName || collectionName.indexOf('..') != -1) { - throw Error("collection names cannot be empty"); - } - - if(collectionName.indexOf('$') != -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { - throw Error("collection names must not contain '$'"); - } - - if(collectionName.match(/^\.|\.$/) != null) { - throw Error("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the colletion name - if(!!~collectionName.indexOf("\x00")) { - throw new Error("collection names cannot contain a null character"); - } -}; - -var handleCallback = function(callback, err, value1, value2) { - try { - if(callback == null) return; - if(value2) return callback(err, value1, value2); - return callback(err, value1); - } catch(err) { - process.nextTick(function() { throw err; }); - return false; - } - - return true; -} - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error; - var e = MongoError.create({message: msg, driver:true}); - - // Get all object keys - var keys = typeof error == 'object' - ? Object.keys(error) - : []; - - for(var i = 0; i < keys.length; i++) { - e[keys[i]] = error[keys[i]]; - } - - return e; -} - -/** - * @ignore - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if(typeof hint == 'string') { - finalHint = hint; - } else if(Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if(hint != null && typeof hint == 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -/** - * Create index name based on field spec - * - * @ignore - * @api private - */ -var parseIndexOptions = function(fieldOrSpec) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if('string' == typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - } else if(Array.isArray(fieldOrSpec)) { - fieldOrSpec.forEach(function(f) { - if('string' == typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if(Array.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if(isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - } else if(isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - return { - name: indexes.join("_"), keys: keys, fieldHash: fieldHash - } -} - -var isObject = exports.isObject = function (arg) { - return '[object Object]' == toString.call(arg) -} - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -var decorateCommand = function(command, options, exclude) { - for(var name in options) { - if(exclude[name] == null) command[name] = options[name]; - } - - return command; -} - -exports.shallowClone = shallowClone; -exports.getSingleProperty = getSingleProperty; -exports.checkCollectionName = checkCollectionName; -exports.toError = toError; -exports.formattedOrderClause = formattedOrderClause; -exports.parseIndexOptions = parseIndexOptions; -exports.normalizeHintField = normalizeHintField; -exports.handleCallback = handleCallback; -exports.decorateCommand = decorateCommand; -exports.isObject = isObject; -exports.debugOptions = debugOptions; diff --git a/util/demographicsImporter/node_modules/mongodb/load.js b/util/demographicsImporter/node_modules/mongodb/load.js deleted file mode 100644 index 01b570e..0000000 --- a/util/demographicsImporter/node_modules/mongodb/load.js +++ /dev/null @@ -1,32 +0,0 @@ -var MongoClient = require('./').MongoClient; - -MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { - var col = db.collection('test'); - col.ensureIndex({dt:-1}, function() { - var docs = []; - for(var i = 0; i < 100; i++) { - docs.push({a:i, dt:i, ot:i}); - } - console.log("------------------------------- 0") - - col.insertMany(docs, function() { - // Start firing finds - - for(var i = 0; i < 100; i++) { - setInterval(function() { - col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) { - console.log("-------------------------------- 1") - }); - }, 10) - } - - // while(true) { - // - // // console.log("------------------------------- 1") - // col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) { - // console.log("-------------------------------- 1") - // }); - // } - }); - }); -}); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md deleted file mode 100644 index e06b496..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md +++ /dev/null @@ -1,9 +0,0 @@ -# Master - -# 2.0.0 - -* re-sync with RSVP. Many large performance improvements and bugfixes. - -# 1.0.0 - -* first subset of RSVP diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE deleted file mode 100644 index 954ec59..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/README.md deleted file mode 100644 index ca8678e..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) - -This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js), if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). - -For API details and how to use promises, see the JavaScript Promises HTML5Rocks article. - -## Downloads - -* [es6-promise](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.js) -* [es6-promise-min](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise-min.js) - -## Node.js - -To install: - -```sh -npm install es6-promise -``` - -To use: - -```js -var Promise = require('es6-promise').Promise; -``` - -## Usage in IE<9 - -`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example. - -However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production: - -```js -promise['catch'](function(err) { - // ... -}); -``` - -Or use `.then` instead: - -```js -promise.then(undefined, function(err) { - // ... -}); -``` - -## Auto-polyfill - -To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: - -```js -require('es6-promise').polyfill(); -``` - -Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. - -## Building & Testing - -* `npm run build` to build -* `npm test` to run tests -* `npm start` to run a build watcher, and webserver to test -* `npm run test:server` for a testem test runner and watching builder diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js deleted file mode 100644 index 308f3ac..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js +++ /dev/null @@ -1,957 +0,0 @@ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 2.1.1 - */ - -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } - - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$toString = {}.toString; - var lib$es6$promise$asap$$vertxNext; - function lib$es6$promise$asap$$asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - lib$es6$promise$asap$$scheduleFlush(); - } - } - - var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function() { - nextTick(lib$es6$promise$asap$$flush); - }; - } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } - - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFullfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$default(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } - } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - var then = lib$es6$promise$$internal$$getThen(maybeThenable); - - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } - } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); - } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } - - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } - } - } else { - lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); - } - } - - lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { - return lib$es6$promise$utils$$isArray(input); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { - this._result = new Array(this.length); - }; - - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (lib$es6$promise$utils$$isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - enumerator._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, enumerator._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } - - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; - } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; - } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - var lib$es6$promise$promise$$counter = 0; - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - if (!lib$es6$promise$utils$$isFunction(resolver)) { - lib$es6$promise$promise$$needsResolver(); - } - - if (!(this instanceof lib$es6$promise$promise$$Promise)) { - lib$es6$promise$promise$$needsNew(); - } - - lib$es6$promise$$internal$$initializePromise(this, resolver); - } - } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$default(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; - } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; - } - - lib$es6$promise$polyfill$$default(); -}).call(this); - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js deleted file mode 100644 index 0552e12..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js +++ /dev/null @@ -1,9 +0,0 @@ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 2.1.1 - */ - -(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;function lib$es6$promise$asap$$asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){lib$es6$promise$asap$$scheduleFlush()}}var lib$es6$promise$asap$$default=lib$es6$promise$asap$$asap;var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){var nextTick=process.nextTick;var version=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);if(Array.isArray(version)&&version[1]==="0"&&version[2]==="10"){nextTick=setImmediate}return function(){nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i -// -// 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. - -// when used in node, this will actually load the util module we depend on -// versus loading the builtin util module as happens otherwise -// this is a bug in node module loading as far as I am concerned -var util = require('util/'); - -var pSlice = Array.prototype.slice; -var hasOwn = Object.prototype.hasOwnProperty; - -// 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 = module.exports = ok; - -// 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.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } - else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = stackStartFunction.name; - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; -} - -function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} - -function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); -} - -// 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);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = 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; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - 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 (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 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 isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(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 = objectKeys(a), - kb = objectKeys(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 expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (util.isString(expected)) { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 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*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function(err) { if (err) {throw err;}}; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; - -},{"util/":6}],3:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],4:[function(require,module,exports){ -// shim for using process in browser - -var process = module.exports = {}; - -process.nextTick = (function () { - var canSetImmediate = typeof window !== 'undefined' - && window.setImmediate; - var canMutationObserver = typeof window !== 'undefined' - && window.MutationObserver; - var canPost = typeof window !== 'undefined' - && window.postMessage && window.addEventListener - ; - - if (canSetImmediate) { - return function (f) { return window.setImmediate(f) }; - } - - var queue = []; - - if (canMutationObserver) { - var hiddenDiv = document.createElement("div"); - var observer = new MutationObserver(function () { - var queueList = queue.slice(); - queue.length = 0; - queueList.forEach(function (fn) { - fn(); - }); - }); - - observer.observe(hiddenDiv, { attributes: true }); - - return function nextTick(fn) { - if (!queue.length) { - hiddenDiv.setAttribute('yes', 'no'); - } - queue.push(fn); - }; - } - - if (canPost) { - window.addEventListener('message', function (ev) { - var source = ev.source; - if ((source === window || source === null) && ev.data === 'process-tick') { - ev.stopPropagation(); - if (queue.length > 0) { - var fn = queue.shift(); - fn(); - } - } - }, true); - - return function nextTick(fn) { - queue.push(fn); - window.postMessage('process-tick', '*'); - }; - } - - return function nextTick(fn) { - setTimeout(fn, 0); - }; -})(); - -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -// TODO(shtylman) -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; - -},{}],5:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],6:[function(require,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":5,"_process":4,"inherits":3}],7:[function(require,module,exports){ -require("./tests/2.1.2"); -require("./tests/2.1.3"); -require("./tests/2.2.1"); -require("./tests/2.2.2"); -require("./tests/2.2.3"); -require("./tests/2.2.4"); -require("./tests/2.2.5"); -require("./tests/2.2.6"); -require("./tests/2.2.7"); -require("./tests/2.3.1"); -require("./tests/2.3.2"); -require("./tests/2.3.3"); -require("./tests/2.3.4"); - -},{"./tests/2.1.2":8,"./tests/2.1.3":9,"./tests/2.2.1":10,"./tests/2.2.2":11,"./tests/2.2.3":12,"./tests/2.2.4":13,"./tests/2.2.5":14,"./tests/2.2.6":15,"./tests/2.2.7":16,"./tests/2.3.1":17,"./tests/2.3.2":18,"./tests/2.3.3":19,"./tests/2.3.4":20}],8:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; - -var adapter = global.adapter; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.1.2.1: When fulfilled, a promise: must not transition to any other state.", function () { - testFulfilled(dummy, function (promise, done) { - var onFulfilledCalled = false; - - promise.then(function onFulfilled() { - onFulfilledCalled = true; - }, function onRejected() { - assert.strictEqual(onFulfilledCalled, false); - done(); - }); - - setTimeout(done, 100); - }); - - specify("trying to fulfill then immediately reject", function (done) { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }, function onRejected() { - assert.strictEqual(onFulfilledCalled, false); - done(); - }); - - d.resolve(dummy); - d.reject(dummy); - setTimeout(done, 100); - }); - - specify("trying to fulfill then reject, delayed", function (done) { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }, function onRejected() { - assert.strictEqual(onFulfilledCalled, false); - done(); - }); - - setTimeout(function () { - d.resolve(dummy); - d.reject(dummy); - }, 50); - setTimeout(done, 100); - }); - - specify("trying to fulfill immediately then reject delayed", function (done) { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }, function onRejected() { - assert.strictEqual(onFulfilledCalled, false); - done(); - }); - - d.resolve(dummy); - setTimeout(function () { - d.reject(dummy); - }, 50); - setTimeout(done, 100); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],9:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testRejected = require("./helpers/testThreeCases").testRejected; - -var adapter = global.adapter; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.1.3.1: When rejected, a promise: must not transition to any other state.", function () { - testRejected(dummy, function (promise, done) { - var onRejectedCalled = false; - - promise.then(function onFulfilled() { - assert.strictEqual(onRejectedCalled, false); - done(); - }, function onRejected() { - onRejectedCalled = true; - }); - - setTimeout(done, 100); - }); - - specify("trying to reject then immediately fulfill", function (done) { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(function onFulfilled() { - assert.strictEqual(onRejectedCalled, false); - done(); - }, function onRejected() { - onRejectedCalled = true; - }); - - d.reject(dummy); - d.resolve(dummy); - setTimeout(done, 100); - }); - - specify("trying to reject then fulfill, delayed", function (done) { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(function onFulfilled() { - assert.strictEqual(onRejectedCalled, false); - done(); - }, function onRejected() { - onRejectedCalled = true; - }); - - setTimeout(function () { - d.reject(dummy); - d.resolve(dummy); - }, 50); - setTimeout(done, 100); - }); - - specify("trying to reject immediately then fulfill delayed", function (done) { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(function onFulfilled() { - assert.strictEqual(onRejectedCalled, false); - done(); - }, function onRejected() { - onRejectedCalled = true; - }); - - d.reject(dummy); - setTimeout(function () { - d.resolve(dummy); - }, 50); - setTimeout(done, 100); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],10:[function(require,module,exports){ -(function (global){ -"use strict"; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.2.1: Both `onFulfilled` and `onRejected` are optional arguments.", function () { - describe("2.2.1.1: If `onFulfilled` is not a function, it must be ignored.", function () { - describe("applied to a directly-rejected promise", function () { - function testNonFunction(nonFunction, stringRepresentation) { - specify("`onFulfilled` is " + stringRepresentation, function (done) { - rejected(dummy).then(nonFunction, function () { - done(); - }); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - }); - - describe("applied to a promise rejected and then chained off of", function () { - function testNonFunction(nonFunction, stringRepresentation) { - specify("`onFulfilled` is " + stringRepresentation, function (done) { - rejected(dummy).then(function () { }, undefined).then(nonFunction, function () { - done(); - }); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - }); - }); - - describe("2.2.1.2: If `onRejected` is not a function, it must be ignored.", function () { - describe("applied to a directly-fulfilled promise", function () { - function testNonFunction(nonFunction, stringRepresentation) { - specify("`onRejected` is " + stringRepresentation, function (done) { - resolved(dummy).then(function () { - done(); - }, nonFunction); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - }); - - describe("applied to a promise fulfilled and then chained off of", function () { - function testNonFunction(nonFunction, stringRepresentation) { - specify("`onFulfilled` is " + stringRepresentation, function (done) { - resolved(dummy).then(undefined, function () { }).then(function () { - done(); - }, nonFunction); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],11:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality - -describe("2.2.2: If `onFulfilled` is a function,", function () { - describe("2.2.2.1: it must be called after `promise` is fulfilled, with `promise`’s fulfillment value as its " + - "first argument.", function () { - testFulfilled(sentinel, function (promise, done) { - promise.then(function onFulfilled(value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("2.2.2.2: it must not be called before `promise` is fulfilled", function () { - specify("fulfilled after a delay", function (done) { - var d = deferred(); - var isFulfilled = false; - - d.promise.then(function onFulfilled() { - assert.strictEqual(isFulfilled, true); - done(); - }); - - setTimeout(function () { - d.resolve(dummy); - isFulfilled = true; - }, 50); - }); - - specify("never fulfilled", function (done) { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - done(); - }); - - setTimeout(function () { - assert.strictEqual(onFulfilledCalled, false); - done(); - }, 150); - }); - }); - - describe("2.2.2.3: it must not be called more than once.", function () { - specify("already-fulfilled", function (done) { - var timesCalled = 0; - - resolved(dummy).then(function onFulfilled() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - }); - - specify("trying to fulfill a pending promise more than once, immediately", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - d.resolve(dummy); - d.resolve(dummy); - }); - - specify("trying to fulfill a pending promise more than once, delayed", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - setTimeout(function () { - d.resolve(dummy); - d.resolve(dummy); - }, 50); - }); - - specify("trying to fulfill a pending promise more than once, immediately then delayed", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - d.resolve(dummy); - setTimeout(function () { - d.resolve(dummy); - }, 50); - }); - - specify("when multiple `then` calls are made, spaced apart in time", function (done) { - var d = deferred(); - var timesCalled = [0, 0, 0]; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[0], 1); - }); - - setTimeout(function () { - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[1], 1); - }); - }, 50); - - setTimeout(function () { - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[2], 1); - done(); - }); - }, 100); - - setTimeout(function () { - d.resolve(dummy); - }, 150); - }); - - specify("when `then` is interleaved with fulfillment", function (done) { - var d = deferred(); - var timesCalled = [0, 0]; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[0], 1); - }); - - d.resolve(dummy); - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[1], 1); - done(); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],12:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testRejected = require("./helpers/testThreeCases").testRejected; - -var adapter = global.adapter; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality - -describe("2.2.3: If `onRejected` is a function,", function () { - describe("2.2.3.1: it must be called after `promise` is rejected, with `promise`’s rejection reason as its " + - "first argument.", function () { - testRejected(sentinel, function (promise, done) { - promise.then(null, function onRejected(reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("2.2.3.2: it must not be called before `promise` is rejected", function () { - specify("rejected after a delay", function (done) { - var d = deferred(); - var isRejected = false; - - d.promise.then(null, function onRejected() { - assert.strictEqual(isRejected, true); - done(); - }); - - setTimeout(function () { - d.reject(dummy); - isRejected = true; - }, 50); - }); - - specify("never rejected", function (done) { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(null, function onRejected() { - onRejectedCalled = true; - done(); - }); - - setTimeout(function () { - assert.strictEqual(onRejectedCalled, false); - done(); - }, 150); - }); - }); - - describe("2.2.3.3: it must not be called more than once.", function () { - specify("already-rejected", function (done) { - var timesCalled = 0; - - rejected(dummy).then(null, function onRejected() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - }); - - specify("trying to reject a pending promise more than once, immediately", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - d.reject(dummy); - d.reject(dummy); - }); - - specify("trying to reject a pending promise more than once, delayed", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - setTimeout(function () { - d.reject(dummy); - d.reject(dummy); - }, 50); - }); - - specify("trying to reject a pending promise more than once, immediately then delayed", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - d.reject(dummy); - setTimeout(function () { - d.reject(dummy); - }, 50); - }); - - specify("when multiple `then` calls are made, spaced apart in time", function (done) { - var d = deferred(); - var timesCalled = [0, 0, 0]; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[0], 1); - }); - - setTimeout(function () { - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[1], 1); - }); - }, 50); - - setTimeout(function () { - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[2], 1); - done(); - }); - }, 100); - - setTimeout(function () { - d.reject(dummy); - }, 150); - }); - - specify("when `then` is interleaved with rejection", function (done) { - var d = deferred(); - var timesCalled = [0, 0]; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[0], 1); - }); - - d.reject(dummy); - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[1], 1); - done(); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],13:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; -var testRejected = require("./helpers/testThreeCases").testRejected; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.2.4: `onFulfilled` or `onRejected` must not be called until the execution context stack contains only " + - "platform code.", function () { - describe("`then` returns before the promise becomes fulfilled or rejected", function () { - testFulfilled(dummy, function (promise, done) { - var thenHasReturned = false; - - promise.then(function onFulfilled() { - assert.strictEqual(thenHasReturned, true); - done(); - }); - - thenHasReturned = true; - }); - testRejected(dummy, function (promise, done) { - var thenHasReturned = false; - - promise.then(null, function onRejected() { - assert.strictEqual(thenHasReturned, true); - done(); - }); - - thenHasReturned = true; - }); - }); - - describe("Clean-stack execution ordering tests (fulfillment case)", function () { - specify("when `onFulfilled` is added immediately before the promise is fulfilled", - function () { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }); - - d.resolve(dummy); - - assert.strictEqual(onFulfilledCalled, false); - }); - - specify("when `onFulfilled` is added immediately after the promise is fulfilled", - function () { - var d = deferred(); - var onFulfilledCalled = false; - - d.resolve(dummy); - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }); - - assert.strictEqual(onFulfilledCalled, false); - }); - - specify("when one `onFulfilled` is added inside another `onFulfilled`", function (done) { - var promise = resolved(); - var firstOnFulfilledFinished = false; - - promise.then(function () { - promise.then(function () { - assert.strictEqual(firstOnFulfilledFinished, true); - done(); - }); - firstOnFulfilledFinished = true; - }); - }); - - specify("when `onFulfilled` is added inside an `onRejected`", function (done) { - var promise = rejected(); - var promise2 = resolved(); - var firstOnRejectedFinished = false; - - promise.then(null, function () { - promise2.then(function () { - assert.strictEqual(firstOnRejectedFinished, true); - done(); - }); - firstOnRejectedFinished = true; - }); - }); - - specify("when the promise is fulfilled asynchronously", function (done) { - var d = deferred(); - var firstStackFinished = false; - - setTimeout(function () { - d.resolve(dummy); - firstStackFinished = true; - }, 0); - - d.promise.then(function () { - assert.strictEqual(firstStackFinished, true); - done(); - }); - }); - }); - - describe("Clean-stack execution ordering tests (rejection case)", function () { - specify("when `onRejected` is added immediately before the promise is rejected", - function () { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(null, function onRejected() { - onRejectedCalled = true; - }); - - d.reject(dummy); - - assert.strictEqual(onRejectedCalled, false); - }); - - specify("when `onRejected` is added immediately after the promise is rejected", - function () { - var d = deferred(); - var onRejectedCalled = false; - - d.reject(dummy); - - d.promise.then(null, function onRejected() { - onRejectedCalled = true; - }); - - assert.strictEqual(onRejectedCalled, false); - }); - - specify("when `onRejected` is added inside an `onFulfilled`", function (done) { - var promise = resolved(); - var promise2 = rejected(); - var firstOnFulfilledFinished = false; - - promise.then(function () { - promise2.then(null, function () { - assert.strictEqual(firstOnFulfilledFinished, true); - done(); - }); - firstOnFulfilledFinished = true; - }); - }); - - specify("when one `onRejected` is added inside another `onRejected`", function (done) { - var promise = rejected(); - var firstOnRejectedFinished = false; - - promise.then(null, function () { - promise.then(null, function () { - assert.strictEqual(firstOnRejectedFinished, true); - done(); - }); - firstOnRejectedFinished = true; - }); - }); - - specify("when the promise is rejected asynchronously", function (done) { - var d = deferred(); - var firstStackFinished = false; - - setTimeout(function () { - d.reject(dummy); - firstStackFinished = true; - }, 0); - - d.promise.then(null, function () { - assert.strictEqual(firstStackFinished, true); - done(); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],14:[function(require,module,exports){ -(function (global){ -/*jshint strict: false */ - -var assert = require("assert"); - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -function impimentsUseStrictCorrectly() { - "use strict"; - function test() { - /*jshint validthis:true */ - return !this; - } - return test(); -} -describe("2.2.5 `onFulfilled` and `onRejected` must be called as functions (i.e. with no `this` value).", function () { - if (impimentsUseStrictCorrectly()) { - describe("strict mode", function () { - specify("fulfilled", function (done) { - resolved(dummy).then(function onFulfilled() { - "use strict"; - - assert.strictEqual(this, undefined); - done(); - }); - }); - - specify("rejected", function (done) { - rejected(dummy).then(null, function onRejected() { - "use strict"; - - assert.strictEqual(this, undefined); - done(); - }); - }); - }); - } - describe("sloppy mode", function () { - specify("fulfilled", function (done) { - resolved(dummy).then(function onFulfilled() { - assert.strictEqual(this, global); - done(); - }); - }); - - specify("rejected", function (done) { - rejected(dummy).then(null, function onRejected() { - assert.strictEqual(this, global); - done(); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"assert":2}],15:[function(require,module,exports){ -"use strict"; - -var assert = require("assert"); -var sinon = require("sinon"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; -var testRejected = require("./helpers/testThreeCases").testRejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var other = { other: "other" }; // a value we don't want to be strict equal to -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality -var sentinel2 = { sentinel2: "sentinel2" }; -var sentinel3 = { sentinel3: "sentinel3" }; - -function callbackAggregator(times, ultimateCallback) { - var soFar = 0; - return function () { - if (++soFar === times) { - ultimateCallback(); - } - }; -} - -describe("2.2.6: `then` may be called multiple times on the same promise.", function () { - describe("2.2.6.1: If/when `promise` is fulfilled, all respective `onFulfilled` callbacks must execute in the " + - "order of their originating calls to `then`.", function () { - describe("multiple boring fulfillment handlers", function () { - testFulfilled(sentinel, function (promise, done) { - var handler1 = sinon.stub().returns(other); - var handler2 = sinon.stub().returns(other); - var handler3 = sinon.stub().returns(other); - - var spy = sinon.spy(); - promise.then(handler1, spy); - promise.then(handler2, spy); - promise.then(handler3, spy); - - promise.then(function (value) { - assert.strictEqual(value, sentinel); - - sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); - sinon.assert.notCalled(spy); - - done(); - }); - }); - }); - - describe("multiple fulfillment handlers, one of which throws", function () { - testFulfilled(sentinel, function (promise, done) { - var handler1 = sinon.stub().returns(other); - var handler2 = sinon.stub().throws(other); - var handler3 = sinon.stub().returns(other); - - var spy = sinon.spy(); - promise.then(handler1, spy); - promise.then(handler2, spy); - promise.then(handler3, spy); - - promise.then(function (value) { - assert.strictEqual(value, sentinel); - - sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); - sinon.assert.notCalled(spy); - - done(); - }); - }); - }); - - describe("results in multiple branching chains with their own fulfillment values", function () { - testFulfilled(dummy, function (promise, done) { - var semiDone = callbackAggregator(3, done); - - promise.then(function () { - return sentinel; - }).then(function (value) { - assert.strictEqual(value, sentinel); - semiDone(); - }); - - promise.then(function () { - throw sentinel2; - }).then(null, function (reason) { - assert.strictEqual(reason, sentinel2); - semiDone(); - }); - - promise.then(function () { - return sentinel3; - }).then(function (value) { - assert.strictEqual(value, sentinel3); - semiDone(); - }); - }); - }); - - describe("`onFulfilled` handlers are called in the original order", function () { - testFulfilled(dummy, function (promise, done) { - var handler1 = sinon.spy(function handler1() {}); - var handler2 = sinon.spy(function handler2() {}); - var handler3 = sinon.spy(function handler3() {}); - - promise.then(handler1); - promise.then(handler2); - promise.then(handler3); - - promise.then(function () { - sinon.assert.callOrder(handler1, handler2, handler3); - done(); - }); - }); - - describe("even when one handler is added inside another handler", function () { - testFulfilled(dummy, function (promise, done) { - var handler1 = sinon.spy(function handler1() {}); - var handler2 = sinon.spy(function handler2() {}); - var handler3 = sinon.spy(function handler3() {}); - - promise.then(function () { - handler1(); - promise.then(handler3); - }); - promise.then(handler2); - - promise.then(function () { - // Give implementations a bit of extra time to flush their internal queue, if necessary. - setTimeout(function () { - sinon.assert.callOrder(handler1, handler2, handler3); - done(); - }, 15); - }); - }); - }); - }); - }); - - describe("2.2.6.2: If/when `promise` is rejected, all respective `onRejected` callbacks must execute in the " + - "order of their originating calls to `then`.", function () { - describe("multiple boring rejection handlers", function () { - testRejected(sentinel, function (promise, done) { - var handler1 = sinon.stub().returns(other); - var handler2 = sinon.stub().returns(other); - var handler3 = sinon.stub().returns(other); - - var spy = sinon.spy(); - promise.then(spy, handler1); - promise.then(spy, handler2); - promise.then(spy, handler3); - - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - - sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); - sinon.assert.notCalled(spy); - - done(); - }); - }); - }); - - describe("multiple rejection handlers, one of which throws", function () { - testRejected(sentinel, function (promise, done) { - var handler1 = sinon.stub().returns(other); - var handler2 = sinon.stub().throws(other); - var handler3 = sinon.stub().returns(other); - - var spy = sinon.spy(); - promise.then(spy, handler1); - promise.then(spy, handler2); - promise.then(spy, handler3); - - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - - sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); - sinon.assert.notCalled(spy); - - done(); - }); - }); - }); - - describe("results in multiple branching chains with their own fulfillment values", function () { - testRejected(sentinel, function (promise, done) { - var semiDone = callbackAggregator(3, done); - - promise.then(null, function () { - return sentinel; - }).then(function (value) { - assert.strictEqual(value, sentinel); - semiDone(); - }); - - promise.then(null, function () { - throw sentinel2; - }).then(null, function (reason) { - assert.strictEqual(reason, sentinel2); - semiDone(); - }); - - promise.then(null, function () { - return sentinel3; - }).then(function (value) { - assert.strictEqual(value, sentinel3); - semiDone(); - }); - }); - }); - - describe("`onRejected` handlers are called in the original order", function () { - testRejected(dummy, function (promise, done) { - var handler1 = sinon.spy(function handler1() {}); - var handler2 = sinon.spy(function handler2() {}); - var handler3 = sinon.spy(function handler3() {}); - - promise.then(null, handler1); - promise.then(null, handler2); - promise.then(null, handler3); - - promise.then(null, function () { - sinon.assert.callOrder(handler1, handler2, handler3); - done(); - }); - }); - - describe("even when one handler is added inside another handler", function () { - testRejected(dummy, function (promise, done) { - var handler1 = sinon.spy(function handler1() {}); - var handler2 = sinon.spy(function handler2() {}); - var handler3 = sinon.spy(function handler3() {}); - - promise.then(null, function () { - handler1(); - promise.then(null, handler3); - }); - promise.then(null, handler2); - - promise.then(null, function () { - // Give implementations a bit of extra time to flush their internal queue, if necessary. - setTimeout(function () { - sinon.assert.callOrder(handler1, handler2, handler3); - done(); - }, 15); - }); - }); - }); - }); - }); -}); - -},{"./helpers/testThreeCases":22,"assert":2,"sinon":24}],16:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; -var testRejected = require("./helpers/testThreeCases").testRejected; -var reasons = require("./helpers/reasons"); - -var adapter = global.adapter; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality -var other = { other: "other" }; // a value we don't want to be strict equal to - -describe("2.2.7: `then` must return a promise: `promise2 = promise1.then(onFulfilled, onRejected)`", function () { - specify("is a promise", function () { - var promise1 = deferred().promise; - var promise2 = promise1.then(); - - assert(typeof promise2 === "object" || typeof promise2 === "function"); - assert.notStrictEqual(promise2, null); - assert.strictEqual(typeof promise2.then, "function"); - }); - - describe("2.2.7.1: If either `onFulfilled` or `onRejected` returns a value `x`, run the Promise Resolution " + - "Procedure `[[Resolve]](promise2, x)`", function () { - specify("see separate 3.3 tests", function () { }); - }); - - describe("2.2.7.2: If either `onFulfilled` or `onRejected` throws an exception `e`, `promise2` must be rejected " + - "with `e` as the reason.", function () { - function testReason(expectedReason, stringRepresentation) { - describe("The reason is " + stringRepresentation, function () { - testFulfilled(dummy, function (promise1, done) { - var promise2 = promise1.then(function onFulfilled() { - throw expectedReason; - }); - - promise2.then(null, function onPromise2Rejected(actualReason) { - assert.strictEqual(actualReason, expectedReason); - done(); - }); - }); - testRejected(dummy, function (promise1, done) { - var promise2 = promise1.then(null, function onRejected() { - throw expectedReason; - }); - - promise2.then(null, function onPromise2Rejected(actualReason) { - assert.strictEqual(actualReason, expectedReason); - done(); - }); - }); - }); - } - - Object.keys(reasons).forEach(function (stringRepresentation) { - testReason(reasons[stringRepresentation], stringRepresentation); - }); - }); - - describe("2.2.7.3: If `onFulfilled` is not a function and `promise1` is fulfilled, `promise2` must be fulfilled " + - "with the same value.", function () { - - function testNonFunction(nonFunction, stringRepresentation) { - describe("`onFulfilled` is " + stringRepresentation, function () { - testFulfilled(sentinel, function (promise1, done) { - var promise2 = promise1.then(nonFunction); - - promise2.then(function onPromise2Fulfilled(value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - testNonFunction([function () { return other; }], "an array containing a function"); - }); - - describe("2.2.7.4: If `onRejected` is not a function and `promise1` is rejected, `promise2` must be rejected " + - "with the same reason.", function () { - - function testNonFunction(nonFunction, stringRepresentation) { - describe("`onRejected` is " + stringRepresentation, function () { - testRejected(sentinel, function (promise1, done) { - var promise2 = promise1.then(null, nonFunction); - - promise2.then(null, function onPromise2Rejected(reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - testNonFunction([function () { return other; }], "an array containing a function"); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/reasons":21,"./helpers/testThreeCases":22,"assert":2}],17:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.3.1: If `promise` and `x` refer to the same object, reject `promise` with a `TypeError' as the reason.", - function () { - specify("via return from a fulfilled promise", function (done) { - var promise = resolved(dummy).then(function () { - return promise; - }); - - promise.then(null, function (reason) { - assert(reason instanceof TypeError); - done(); - }); - }); - - specify("via return from a rejected promise", function (done) { - var promise = rejected(dummy).then(null, function () { - return promise; - }); - - promise.then(null, function (reason) { - assert(reason instanceof TypeError); - done(); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"assert":2}],18:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality - -function testPromiseResolution(xFactory, test) { - specify("via return from a fulfilled promise", function (done) { - var promise = resolved(dummy).then(function onBasePromiseFulfilled() { - return xFactory(); - }); - - test(promise, done); - }); - - specify("via return from a rejected promise", function (done) { - var promise = rejected(dummy).then(null, function onBasePromiseRejected() { - return xFactory(); - }); - - test(promise, done); - }); -} - -describe("2.3.2: If `x` is a promise, adopt its state", function () { - describe("2.3.2.1: If `x` is pending, `promise` must remain pending until `x` is fulfilled or rejected.", - function () { - function xFactory() { - return deferred().promise; - } - - testPromiseResolution(xFactory, function (promise, done) { - var wasFulfilled = false; - var wasRejected = false; - - promise.then( - function onPromiseFulfilled() { - wasFulfilled = true; - }, - function onPromiseRejected() { - wasRejected = true; - } - ); - - setTimeout(function () { - assert.strictEqual(wasFulfilled, false); - assert.strictEqual(wasRejected, false); - done(); - }, 100); - }); - }); - - describe("2.3.2.2: If/when `x` is fulfilled, fulfill `promise` with the same value.", function () { - describe("`x` is already-fulfilled", function () { - function xFactory() { - return resolved(sentinel); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function onPromiseFulfilled(value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("`x` is eventually-fulfilled", function () { - var d = null; - - function xFactory() { - d = deferred(); - setTimeout(function () { - d.resolve(sentinel); - }, 50); - return d.promise; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function onPromiseFulfilled(value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - }); - - describe("2.3.2.3: If/when `x` is rejected, reject `promise` with the same reason.", function () { - describe("`x` is already-rejected", function () { - function xFactory() { - return rejected(sentinel); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function onPromiseRejected(reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`x` is eventually-rejected", function () { - var d = null; - - function xFactory() { - d = deferred(); - setTimeout(function () { - d.reject(sentinel); - }, 50); - return d.promise; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function onPromiseRejected(reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"assert":2}],19:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var thenables = require("./helpers/thenables"); -var reasons = require("./helpers/reasons"); - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality -var other = { other: "other" }; // a value we don't want to be strict equal to -var sentinelArray = [sentinel]; // a sentinel fulfillment value to test when we need an array - -function testPromiseResolution(xFactory, test) { - specify("via return from a fulfilled promise", function (done) { - var promise = resolved(dummy).then(function onBasePromiseFulfilled() { - return xFactory(); - }); - - test(promise, done); - }); - - specify("via return from a rejected promise", function (done) { - var promise = rejected(dummy).then(null, function onBasePromiseRejected() { - return xFactory(); - }); - - test(promise, done); - }); -} - -function testCallingResolvePromise(yFactory, stringRepresentation, test) { - describe("`y` is " + stringRepresentation, function () { - describe("`then` calls `resolvePromise` synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - resolvePromise(yFactory()); - } - }; - } - - testPromiseResolution(xFactory, test); - }); - - describe("`then` calls `resolvePromise` asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - setTimeout(function () { - resolvePromise(yFactory()); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, test); - }); - }); -} - -function testCallingRejectPromise(r, stringRepresentation, test) { - describe("`r` is " + stringRepresentation, function () { - describe("`then` calls `rejectPromise` synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(r); - } - }; - } - - testPromiseResolution(xFactory, test); - }); - - describe("`then` calls `rejectPromise` asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - rejectPromise(r); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, test); - }); - }); -} - -function testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, fulfillmentValue) { - testCallingResolvePromise(yFactory, stringRepresentation, function (promise, done) { - promise.then(function onPromiseFulfilled(value) { - assert.strictEqual(value, fulfillmentValue); - done(); - }); - }); -} - -function testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, rejectionReason) { - testCallingResolvePromise(yFactory, stringRepresentation, function (promise, done) { - promise.then(null, function onPromiseRejected(reason) { - assert.strictEqual(reason, rejectionReason); - done(); - }); - }); -} - -function testCallingRejectPromiseRejectsWith(reason, stringRepresentation) { - testCallingRejectPromise(reason, stringRepresentation, function (promise, done) { - promise.then(null, function onPromiseRejected(rejectionReason) { - assert.strictEqual(rejectionReason, reason); - done(); - }); - }); -} - -describe("2.3.3: Otherwise, if `x` is an object or function,", function () { - describe("2.3.3.1: Let `then` be `x.then`", function () { - describe("`x` is an object with null prototype", function () { - var numberOfTimesThenWasRetrieved = null; - - beforeEach(function () { - numberOfTimesThenWasRetrieved = 0; - }); - - function xFactory() { - return Object.create(null, { - then: { - get: function () { - ++numberOfTimesThenWasRetrieved; - return function thenMethodForX(onFulfilled) { - onFulfilled(); - }; - } - } - }); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - assert.strictEqual(numberOfTimesThenWasRetrieved, 1); - done(); - }); - }); - }); - - describe("`x` is an object with normal Object.prototype", function () { - var numberOfTimesThenWasRetrieved = null; - - beforeEach(function () { - numberOfTimesThenWasRetrieved = 0; - }); - - function xFactory() { - return Object.create(Object.prototype, { - then: { - get: function () { - ++numberOfTimesThenWasRetrieved; - return function thenMethodForX(onFulfilled) { - onFulfilled(); - }; - } - } - }); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - assert.strictEqual(numberOfTimesThenWasRetrieved, 1); - done(); - }); - }); - }); - - describe("`x` is a function", function () { - var numberOfTimesThenWasRetrieved = null; - - beforeEach(function () { - numberOfTimesThenWasRetrieved = 0; - }); - - function xFactory() { - function x() { } - - Object.defineProperty(x, "then", { - get: function () { - ++numberOfTimesThenWasRetrieved; - return function thenMethodForX(onFulfilled) { - onFulfilled(); - }; - } - }); - - return x; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - assert.strictEqual(numberOfTimesThenWasRetrieved, 1); - done(); - }); - }); - }); - }); - - describe("2.3.3.2: If retrieving the property `x.then` results in a thrown exception `e`, reject `promise` with " + - "`e` as the reason.", function () { - function testRejectionViaThrowingGetter(e, stringRepresentation) { - function xFactory() { - return Object.create(Object.prototype, { - then: { - get: function () { - throw e; - } - } - }); - } - - describe("`e` is " + stringRepresentation, function () { - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, e); - done(); - }); - }); - }); - } - - Object.keys(reasons).forEach(function (stringRepresentation) { - testRejectionViaThrowingGetter(reasons[stringRepresentation], stringRepresentation); - }); - }); - - describe("2.3.3.3: If `then` is a function, call it with `x` as `this`, first argument `resolvePromise`, and " + - "second argument `rejectPromise`", function () { - describe("Calls with `x` as `this` and two function arguments", function () { - function xFactory() { - var x = { - then: function (onFulfilled, onRejected) { - assert.strictEqual(this, x); - assert.strictEqual(typeof onFulfilled, "function"); - assert.strictEqual(typeof onRejected, "function"); - onFulfilled(); - } - }; - return x; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - done(); - }); - }); - }); - - describe("Uses the original value of `then`", function () { - var numberOfTimesThenWasRetrieved = null; - - beforeEach(function () { - numberOfTimesThenWasRetrieved = 0; - }); - - function xFactory() { - return Object.create(Object.prototype, { - then: { - get: function () { - if (numberOfTimesThenWasRetrieved === 0) { - return function (onFulfilled) { - onFulfilled(); - }; - } - return null; - } - } - }); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - done(); - }); - }); - }); - - describe("2.3.3.3.1: If/when `resolvePromise` is called with value `y`, run `[[Resolve]](promise, y)`", - function () { - describe("`y` is not a thenable", function () { - testCallingResolvePromiseFulfillsWith(function () { return undefined; }, "`undefined`", undefined); - testCallingResolvePromiseFulfillsWith(function () { return null; }, "`null`", null); - testCallingResolvePromiseFulfillsWith(function () { return false; }, "`false`", false); - testCallingResolvePromiseFulfillsWith(function () { return 5; }, "`5`", 5); - testCallingResolvePromiseFulfillsWith(function () { return sentinel; }, "an object", sentinel); - testCallingResolvePromiseFulfillsWith(function () { return sentinelArray; }, "an array", sentinelArray); - }); - - describe("`y` is a thenable", function () { - Object.keys(thenables.fulfilled).forEach(function (stringRepresentation) { - function yFactory() { - return thenables.fulfilled[stringRepresentation](sentinel); - } - - testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, sentinel); - }); - - Object.keys(thenables.rejected).forEach(function (stringRepresentation) { - function yFactory() { - return thenables.rejected[stringRepresentation](sentinel); - } - - testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, sentinel); - }); - }); - - describe("`y` is a thenable for a thenable", function () { - Object.keys(thenables.fulfilled).forEach(function (outerStringRepresentation) { - var outerThenableFactory = thenables.fulfilled[outerStringRepresentation]; - - Object.keys(thenables.fulfilled).forEach(function (innerStringRepresentation) { - var innerThenableFactory = thenables.fulfilled[innerStringRepresentation]; - - var stringRepresentation = outerStringRepresentation + " for " + innerStringRepresentation; - - function yFactory() { - return outerThenableFactory(innerThenableFactory(sentinel)); - } - - testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, sentinel); - }); - - Object.keys(thenables.rejected).forEach(function (innerStringRepresentation) { - var innerThenableFactory = thenables.rejected[innerStringRepresentation]; - - var stringRepresentation = outerStringRepresentation + " for " + innerStringRepresentation; - - function yFactory() { - return outerThenableFactory(innerThenableFactory(sentinel)); - } - - testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, sentinel); - }); - }); - }); - }); - - describe("2.3.3.3.2: If/when `rejectPromise` is called with reason `r`, reject `promise` with `r`", - function () { - Object.keys(reasons).forEach(function (stringRepresentation) { - testCallingRejectPromiseRejectsWith(reasons[stringRepresentation], stringRepresentation); - }); - }); - - describe("2.3.3.3.3: If both `resolvePromise` and `rejectPromise` are called, or multiple calls to the same " + - "argument are made, the first call takes precedence, and any further calls are ignored.", - function () { - describe("calling `resolvePromise` then `rejectPromise`, both synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(sentinel); - rejectPromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` synchronously then `rejectPromise` asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(sentinel); - - setTimeout(function () { - rejectPromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` then `rejectPromise`, both asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - resolvePromise(sentinel); - }, 0); - - setTimeout(function () { - rejectPromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` with an asynchronously-fulfilled promise, then calling " + - "`rejectPromise`, both synchronously", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.resolve(sentinel); - }, 50); - - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(d.promise); - rejectPromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` with an asynchronously-rejected promise, then calling " + - "`rejectPromise`, both synchronously", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.reject(sentinel); - }, 50); - - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(d.promise); - rejectPromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` then `resolvePromise`, both synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - resolvePromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` synchronously then `resolvePromise` asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - - setTimeout(function () { - resolvePromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` then `resolvePromise`, both asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - rejectPromise(sentinel); - }, 0); - - setTimeout(function () { - resolvePromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` twice synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - resolvePromise(sentinel); - resolvePromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` twice, first synchronously then asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - resolvePromise(sentinel); - - setTimeout(function () { - resolvePromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` twice, both times asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - setTimeout(function () { - resolvePromise(sentinel); - }, 0); - - setTimeout(function () { - resolvePromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` with an asynchronously-fulfilled promise, then calling it again, both " + - "times synchronously", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.resolve(sentinel); - }, 50); - - return { - then: function (resolvePromise) { - resolvePromise(d.promise); - resolvePromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` with an asynchronously-rejected promise, then calling it again, both " + - "times synchronously", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.reject(sentinel); - }, 50); - - return { - then: function (resolvePromise) { - resolvePromise(d.promise); - resolvePromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` twice synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - rejectPromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` twice, first synchronously then asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - - setTimeout(function () { - rejectPromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` twice, both times asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - rejectPromise(sentinel); - }, 0); - - setTimeout(function () { - rejectPromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("saving and abusing `resolvePromise` and `rejectPromise`", function () { - var savedResolvePromise, savedRejectPromise; - - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - savedResolvePromise = resolvePromise; - savedRejectPromise = rejectPromise; - } - }; - } - - beforeEach(function () { - savedResolvePromise = null; - savedRejectPromise = null; - }); - - testPromiseResolution(xFactory, function (promise, done) { - var timesFulfilled = 0; - var timesRejected = 0; - - promise.then( - function () { - ++timesFulfilled; - }, - function () { - ++timesRejected; - } - ); - - if (savedResolvePromise && savedRejectPromise) { - savedResolvePromise(dummy); - savedResolvePromise(dummy); - savedRejectPromise(dummy); - savedRejectPromise(dummy); - } - - setTimeout(function () { - savedResolvePromise(dummy); - savedResolvePromise(dummy); - savedRejectPromise(dummy); - savedRejectPromise(dummy); - }, 50); - - setTimeout(function () { - assert.strictEqual(timesFulfilled, 1); - assert.strictEqual(timesRejected, 0); - done(); - }, 100); - }); - }); - }); - - describe("2.3.3.3.4: If calling `then` throws an exception `e`,", function () { - describe("2.3.3.3.4.1: If `resolvePromise` or `rejectPromise` have been called, ignore it.", function () { - describe("`resolvePromise` was called with a non-thenable", function () { - function xFactory() { - return { - then: function (resolvePromise) { - resolvePromise(sentinel); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("`resolvePromise` was called with an asynchronously-fulfilled promise", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.resolve(sentinel); - }, 50); - - return { - then: function (resolvePromise) { - resolvePromise(d.promise); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("`resolvePromise` was called with an asynchronously-rejected promise", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.reject(sentinel); - }, 50); - - return { - then: function (resolvePromise) { - resolvePromise(d.promise); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`rejectPromise` was called", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`resolvePromise` then `rejectPromise` were called", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(sentinel); - rejectPromise(other); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("`rejectPromise` then `resolvePromise` were called", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - resolvePromise(other); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - }); - - describe("2.3.3.3.4.2: Otherwise, reject `promise` with `e` as the reason.", function () { - describe("straightforward case", function () { - function xFactory() { - return { - then: function () { - throw sentinel; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`resolvePromise` is called asynchronously before the `throw`", function () { - function xFactory() { - return { - then: function (resolvePromise) { - setTimeout(function () { - resolvePromise(other); - }, 0); - throw sentinel; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`rejectPromise` is called asynchronously before the `throw`", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - rejectPromise(other); - }, 0); - throw sentinel; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - }); - }); - }); - - describe("2.3.3.4: If `then` is not a function, fulfill promise with `x`", function () { - function testFulfillViaNonFunction(then, stringRepresentation) { - var x = null; - - beforeEach(function () { - x = { then: then }; - }); - - function xFactory() { - return x; - } - - describe("`then` is " + stringRepresentation, function () { - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, x); - done(); - }); - }); - }); - } - - testFulfillViaNonFunction(5, "`5`"); - testFulfillViaNonFunction({}, "an object"); - testFulfillViaNonFunction([function () { }], "an array containing a function"); - testFulfillViaNonFunction(/a-b/i, "a regular expression"); - testFulfillViaNonFunction(Object.create(Function.prototype), "an object inheriting from `Function.prototype`"); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/reasons":21,"./helpers/thenables":23,"assert":2}],20:[function(require,module,exports){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; -var testRejected = require("./helpers/testThreeCases").testRejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.3.4: If `x` is not an object or function, fulfill `promise` with `x`", function () { - function testValue(expectedValue, stringRepresentation, beforeEachHook, afterEachHook) { - describe("The value is " + stringRepresentation, function () { - if (typeof beforeEachHook === "function") { - beforeEach(beforeEachHook); - } - if (typeof afterEachHook === "function") { - afterEach(afterEachHook); - } - - testFulfilled(dummy, function (promise1, done) { - var promise2 = promise1.then(function onFulfilled() { - return expectedValue; - }); - - promise2.then(function onPromise2Fulfilled(actualValue) { - assert.strictEqual(actualValue, expectedValue); - done(); - }); - }); - testRejected(dummy, function (promise1, done) { - var promise2 = promise1.then(null, function onRejected() { - return expectedValue; - }); - - promise2.then(function onPromise2Fulfilled(actualValue) { - assert.strictEqual(actualValue, expectedValue); - done(); - }); - }); - }); - } - - testValue(undefined, "`undefined`"); - testValue(null, "`null`"); - testValue(false, "`false`"); - testValue(true, "`true`"); - testValue(0, "`0`"); - - testValue( - true, - "`true` with `Boolean.prototype` modified to have a `then` method", - function () { - Boolean.prototype.then = function () {}; - }, - function () { - delete Boolean.prototype.then; - } - ); - - testValue( - 1, - "`1` with `Number.prototype` modified to have a `then` method", - function () { - Number.prototype.then = function () {}; - }, - function () { - delete Number.prototype.then; - } - ); -}); - -},{"./helpers/testThreeCases":22,"assert":2}],21:[function(require,module,exports){ -(function (global){ -"use strict"; - -// This module exports some valid rejection reason factories, keyed by human-readable versions of their names. - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; - -var dummy = { dummy: "dummy" }; - -exports["`undefined`"] = function () { - return undefined; -}; - -exports["`null`"] = function () { - return null; -}; - -exports["`false`"] = function () { - return false; -}; - -exports["`0`"] = function () { - return 0; -}; - -exports["an error"] = function () { - return new Error(); -}; - -exports["an error without a stack"] = function () { - var error = new Error(); - delete error.stack; - - return error; -}; - -exports["a date"] = function () { - return new Date(); -}; - -exports["an object"] = function () { - return {}; -}; - -exports["an always-pending thenable"] = function () { - return { then: function () { } }; -}; - -exports["a fulfilled promise"] = function () { - return resolved(dummy); -}; - -exports["a rejected promise"] = function () { - return rejected(dummy); -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],22:[function(require,module,exports){ -(function (global){ -"use strict"; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -exports.testFulfilled = function (value, test) { - specify("already-fulfilled", function (done) { - test(resolved(value), done); - }); - - specify("immediately-fulfilled", function (done) { - var d = deferred(); - test(d.promise, done); - d.resolve(value); - }); - - specify("eventually-fulfilled", function (done) { - var d = deferred(); - test(d.promise, done); - setTimeout(function () { - d.resolve(value); - }, 50); - }); -}; - -exports.testRejected = function (reason, test) { - specify("already-rejected", function (done) { - test(rejected(reason), done); - }); - - specify("immediately-rejected", function (done) { - var d = deferred(); - test(d.promise, done); - d.reject(reason); - }); - - specify("eventually-rejected", function (done) { - var d = deferred(); - test(d.promise, done); - setTimeout(function () { - d.reject(reason); - }, 50); - }); -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],23:[function(require,module,exports){ -(function (global){ -"use strict"; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var other = { other: "other" }; // a value we don't want to be strict equal to - -exports.fulfilled = { - "a synchronously-fulfilled custom thenable": function (value) { - return { - then: function (onFulfilled) { - onFulfilled(value); - } - }; - }, - - "an asynchronously-fulfilled custom thenable": function (value) { - return { - then: function (onFulfilled) { - setTimeout(function () { - onFulfilled(value); - }, 0); - } - }; - }, - - "a synchronously-fulfilled one-time thenable": function (value) { - var numberOfTimesThenRetrieved = 0; - return Object.create(null, { - then: { - get: function () { - if (numberOfTimesThenRetrieved === 0) { - ++numberOfTimesThenRetrieved; - return function (onFulfilled) { - onFulfilled(value); - }; - } - return null; - } - } - }); - }, - - "a thenable that tries to fulfill twice": function (value) { - return { - then: function (onFulfilled) { - onFulfilled(value); - onFulfilled(other); - } - }; - }, - - "a thenable that fulfills but then throws": function (value) { - return { - then: function (onFulfilled) { - onFulfilled(value); - throw other; - } - }; - }, - - "an already-fulfilled promise": function (value) { - return resolved(value); - }, - - "an eventually-fulfilled promise": function (value) { - var d = deferred(); - setTimeout(function () { - d.resolve(value); - }, 50); - return d.promise; - } -}; - -exports.rejected = { - "a synchronously-rejected custom thenable": function (reason) { - return { - then: function (onFulfilled, onRejected) { - onRejected(reason); - } - }; - }, - - "an asynchronously-rejected custom thenable": function (reason) { - return { - then: function (onFulfilled, onRejected) { - setTimeout(function () { - onRejected(reason); - }, 0); - } - }; - }, - - "a synchronously-rejected one-time thenable": function (reason) { - var numberOfTimesThenRetrieved = 0; - return Object.create(null, { - then: { - get: function () { - if (numberOfTimesThenRetrieved === 0) { - ++numberOfTimesThenRetrieved; - return function (onFulfilled, onRejected) { - onRejected(reason); - }; - } - return null; - } - } - }); - }, - - "a thenable that immediately throws in `then`": function (reason) { - return { - then: function () { - throw reason; - } - }; - }, - - "an object with a throwing `then` accessor": function (reason) { - return Object.create(null, { - then: { - get: function () { - throw reason; - } - } - }); - }, - - "an already-rejected promise": function (reason) { - return rejected(reason); - }, - - "an eventually-rejected promise": function (reason) { - var d = deferred(); - setTimeout(function () { - d.reject(reason); - }, 50); - return d.promise; - } -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],24:[function(require,module,exports){ -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -var sinon = (function () { - var sinon; - var isNode = typeof module !== "undefined" && module.exports && typeof require === "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - sinon = module.exports = require("./sinon/util/core"); - require("./sinon/extend"); - require("./sinon/typeOf"); - require("./sinon/times_in_words"); - require("./sinon/spy"); - require("./sinon/call"); - require("./sinon/behavior"); - require("./sinon/stub"); - require("./sinon/mock"); - require("./sinon/collection"); - require("./sinon/assert"); - require("./sinon/sandbox"); - require("./sinon/test"); - require("./sinon/test_case"); - require("./sinon/match"); - require("./sinon/format"); - require("./sinon/log_error"); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - sinon = module.exports; - } else { - sinon = {}; - } - - return sinon; -}()); - -},{"./sinon/assert":25,"./sinon/behavior":26,"./sinon/call":27,"./sinon/collection":28,"./sinon/extend":29,"./sinon/format":30,"./sinon/log_error":31,"./sinon/match":32,"./sinon/mock":33,"./sinon/sandbox":34,"./sinon/spy":35,"./sinon/stub":36,"./sinon/test":37,"./sinon/test_case":38,"./sinon/times_in_words":39,"./sinon/typeOf":40,"./sinon/util/core":41}],25:[function(require,module,exports){ -(function (global){ -/** - * @depend times_in_words.js - * @depend util/core.js - * @depend match.js - * @depend format.js - */ -/** - * Assertions matching the test spy retrieval interface. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon, global) { - var slice = Array.prototype.slice; - - function makeApi(sinon) { - var assert; - - function verifyIsStub() { - var method; - - for (var i = 0, l = arguments.length; i < l; ++i) { - method = arguments[i]; - - if (!method) { - assert.fail("fake is not a spy"); - } - - if (method.proxy) { - verifyIsStub(method.proxy); - } else { - if (typeof method != "function") { - assert.fail(method + " is not a function"); - } - - if (typeof method.getCall != "function") { - assert.fail(method + " is not stubbed"); - } - } - - } - } - - function failAssertion(object, msg) { - object = object || global; - var failMethod = object.fail || assert.fail; - failMethod.call(object, msg); - } - - function mirrorPropAsAssertion(name, method, message) { - if (arguments.length == 2) { - message = method; - method = name; - } - - assert[name] = function (fake) { - verifyIsStub(fake); - - var args = slice.call(arguments, 1); - var failed = false; - - if (typeof method == "function") { - failed = !method(fake); - } else { - failed = typeof fake[method] == "function" ? - !fake[method].apply(fake, args) : !fake[method]; - } - - if (failed) { - failAssertion(this, (fake.printf || fake.proxy.printf).apply(fake, [message].concat(args))); - } else { - assert.pass(name); - } - }; - } - - function exposedName(prefix, prop) { - return !prefix || /^fail/.test(prop) ? prop : - prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1); - } - - assert = { - failException: "AssertError", - - fail: function fail(message) { - var error = new Error(message); - error.name = this.failException || assert.failException; - - throw error; - }, - - pass: function pass(assertion) {}, - - callOrder: function assertCallOrder() { - verifyIsStub.apply(null, arguments); - var expected = "", actual = ""; - - if (!sinon.calledInOrder(arguments)) { - try { - expected = [].join.call(arguments, ", "); - var calls = slice.call(arguments); - var i = calls.length; - while (i) { - if (!calls[--i].called) { - calls.splice(i, 1); - } - } - actual = sinon.orderByFirstCall(calls).join(", "); - } catch (e) { - // If this fails, we'll just fall back to the blank string - } - - failAssertion(this, "expected " + expected + " to be " + - "called in order but were called as " + actual); - } else { - assert.pass("callOrder"); - } - }, - - callCount: function assertCallCount(method, count) { - verifyIsStub(method); - - if (method.callCount != count) { - var msg = "expected %n to be called " + sinon.timesInWords(count) + - " but was called %c%C"; - failAssertion(this, method.printf(msg)); - } else { - assert.pass("callCount"); - } - }, - - expose: function expose(target, options) { - if (!target) { - throw new TypeError("target is null or undefined"); - } - - var o = options || {}; - var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix; - var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail; - - for (var method in this) { - if (method != "expose" && (includeFail || !/^(fail)/.test(method))) { - target[exposedName(prefix, method)] = this[method]; - } - } - - return target; - }, - - match: function match(actual, expectation) { - var matcher = sinon.match(expectation); - if (matcher.test(actual)) { - assert.pass("match"); - } else { - var formatted = [ - "expected value to match", - " expected = " + sinon.format(expectation), - " actual = " + sinon.format(actual) - ] - failAssertion(this, formatted.join("\n")); - } - } - }; - - mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called"); - mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; }, - "expected %n to not have been called but was called %c%C"); - mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C"); - mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C"); - mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C"); - mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t"); - mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t"); - mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new"); - mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new"); - mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C"); - mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C"); - mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C"); - mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C"); - mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C"); - mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C"); - mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C"); - mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C"); - mirrorPropAsAssertion("threw", "%n did not throw exception%C"); - mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C"); - - sinon.assert = assert; - return assert; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./match"); - require("./format"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } - -}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./format":30,"./match":32,"./util/core":41}],26:[function(require,module,exports){ -(function (process){ -/** - * @depend util/core.js - * @depend extend.js - */ -/** - * Stub behavior - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Tim Fischbach (mail@timfischbach.de) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - var slice = Array.prototype.slice; - var join = Array.prototype.join; - var useLeftMostCallback = -1; - var useRightMostCallback = -2; - - var nextTick = (function () { - if (typeof process === "object" && typeof process.nextTick === "function") { - return process.nextTick; - } else if (typeof setImmediate === "function") { - return setImmediate; - } else { - return function (callback) { - setTimeout(callback, 0); - }; - } - })(); - - function throwsException(error, message) { - if (typeof error == "string") { - this.exception = new Error(message || ""); - this.exception.name = error; - } else if (!error) { - this.exception = new Error("Error"); - } else { - this.exception = error; - } - - return this; - } - - function getCallback(behavior, args) { - var callArgAt = behavior.callArgAt; - - if (callArgAt >= 0) { - return args[callArgAt]; - } - - var argumentList; - - if (callArgAt === useLeftMostCallback) { - argumentList = args; - } - - if (callArgAt === useRightMostCallback) { - argumentList = slice.call(args).reverse(); - } - - var callArgProp = behavior.callArgProp; - - for (var i = 0, l = argumentList.length; i < l; ++i) { - if (!callArgProp && typeof argumentList[i] == "function") { - return argumentList[i]; - } - - if (callArgProp && argumentList[i] && - typeof argumentList[i][callArgProp] == "function") { - return argumentList[i][callArgProp]; - } - } - - return null; - } - - function makeApi(sinon) { - function getCallbackError(behavior, func, args) { - if (behavior.callArgAt < 0) { - var msg; - - if (behavior.callArgProp) { - msg = sinon.functionName(behavior.stub) + - " expected to yield to '" + behavior.callArgProp + - "', but no object with such a property was passed."; - } else { - msg = sinon.functionName(behavior.stub) + - " expected to yield, but no callback was passed."; - } - - if (args.length > 0) { - msg += " Received [" + join.call(args, ", ") + "]"; - } - - return msg; - } - - return "argument at index " + behavior.callArgAt + " is not a function: " + func; - } - - function callCallback(behavior, args) { - if (typeof behavior.callArgAt == "number") { - var func = getCallback(behavior, args); - - if (typeof func != "function") { - throw new TypeError(getCallbackError(behavior, func, args)); - } - - if (behavior.callbackAsync) { - nextTick(function () { - func.apply(behavior.callbackContext, behavior.callbackArguments); - }); - } else { - func.apply(behavior.callbackContext, behavior.callbackArguments); - } - } - } - - var proto = { - create: function create(stub) { - var behavior = sinon.extend({}, sinon.behavior); - delete behavior.create; - behavior.stub = stub; - - return behavior; - }, - - isPresent: function isPresent() { - return (typeof this.callArgAt == "number" || - this.exception || - typeof this.returnArgAt == "number" || - this.returnThis || - this.returnValueDefined); - }, - - invoke: function invoke(context, args) { - callCallback(this, args); - - if (this.exception) { - throw this.exception; - } else if (typeof this.returnArgAt == "number") { - return args[this.returnArgAt]; - } else if (this.returnThis) { - return context; - } - - return this.returnValue; - }, - - onCall: function onCall(index) { - return this.stub.onCall(index); - }, - - onFirstCall: function onFirstCall() { - return this.stub.onFirstCall(); - }, - - onSecondCall: function onSecondCall() { - return this.stub.onSecondCall(); - }, - - onThirdCall: function onThirdCall() { - return this.stub.onThirdCall(); - }, - - withArgs: function withArgs(/* arguments */) { - throw new Error("Defining a stub by invoking \"stub.onCall(...).withArgs(...)\" is not supported. " + - "Use \"stub.withArgs(...).onCall(...)\" to define sequential behavior for calls with certain arguments."); - }, - - callsArg: function callsArg(pos) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - - this.callArgAt = pos; - this.callbackArguments = []; - this.callbackContext = undefined; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - callsArgOn: function callsArgOn(pos, context) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - if (typeof context != "object") { - throw new TypeError("argument context is not an object"); - } - - this.callArgAt = pos; - this.callbackArguments = []; - this.callbackContext = context; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - callsArgWith: function callsArgWith(pos) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - - this.callArgAt = pos; - this.callbackArguments = slice.call(arguments, 1); - this.callbackContext = undefined; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - callsArgOnWith: function callsArgWith(pos, context) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - if (typeof context != "object") { - throw new TypeError("argument context is not an object"); - } - - this.callArgAt = pos; - this.callbackArguments = slice.call(arguments, 2); - this.callbackContext = context; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - yields: function () { - this.callArgAt = useLeftMostCallback; - this.callbackArguments = slice.call(arguments, 0); - this.callbackContext = undefined; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - yieldsRight: function () { - this.callArgAt = useRightMostCallback; - this.callbackArguments = slice.call(arguments, 0); - this.callbackContext = undefined; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - yieldsOn: function (context) { - if (typeof context != "object") { - throw new TypeError("argument context is not an object"); - } - - this.callArgAt = useLeftMostCallback; - this.callbackArguments = slice.call(arguments, 1); - this.callbackContext = context; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - yieldsTo: function (prop) { - this.callArgAt = useLeftMostCallback; - this.callbackArguments = slice.call(arguments, 1); - this.callbackContext = undefined; - this.callArgProp = prop; - this.callbackAsync = false; - - return this; - }, - - yieldsToOn: function (prop, context) { - if (typeof context != "object") { - throw new TypeError("argument context is not an object"); - } - - this.callArgAt = useLeftMostCallback; - this.callbackArguments = slice.call(arguments, 2); - this.callbackContext = context; - this.callArgProp = prop; - this.callbackAsync = false; - - return this; - }, - - throws: throwsException, - throwsException: throwsException, - - returns: function returns(value) { - this.returnValue = value; - this.returnValueDefined = true; - - return this; - }, - - returnsArg: function returnsArg(pos) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - - this.returnArgAt = pos; - - return this; - }, - - returnsThis: function returnsThis() { - this.returnThis = true; - - return this; - } - }; - - // create asynchronous versions of callsArg* and yields* methods - for (var method in proto) { - // need to avoid creating anotherasync versions of the newly added async methods - if (proto.hasOwnProperty(method) && - method.match(/^(callsArg|yields)/) && - !method.match(/Async/)) { - proto[method + "Async"] = (function (syncFnName) { - return function () { - var result = this[syncFnName].apply(this, arguments); - this.callbackAsync = true; - return result; - }; - })(method); - } - } - - sinon.behavior = proto; - return proto; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./extend"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -}).call(this,require('_process')) -},{"./extend":29,"./util/core":41,"_process":4}],27:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend match.js - * @depend format.js - */ -/** - * Spy calls - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Maximilian Antoni (mail@maxantoni.de) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - * Copyright (c) 2013 Maximilian Antoni - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - function throwYieldError(proxy, text, args) { - var msg = sinon.functionName(proxy) + text; - if (args.length) { - msg += " Received [" + slice.call(args).join(", ") + "]"; - } - throw new Error(msg); - } - - var slice = Array.prototype.slice; - - var callProto = { - calledOn: function calledOn(thisValue) { - if (sinon.match && sinon.match.isMatcher(thisValue)) { - return thisValue.test(this.thisValue); - } - return this.thisValue === thisValue; - }, - - calledWith: function calledWith() { - var l = arguments.length; - if (l > this.args.length) { - return false; - } - for (var i = 0; i < l; i += 1) { - if (!sinon.deepEqual(arguments[i], this.args[i])) { - return false; - } - } - - return true; - }, - - calledWithMatch: function calledWithMatch() { - var l = arguments.length; - if (l > this.args.length) { - return false; - } - for (var i = 0; i < l; i += 1) { - var actual = this.args[i]; - var expectation = arguments[i]; - if (!sinon.match || !sinon.match(expectation).test(actual)) { - return false; - } - } - return true; - }, - - calledWithExactly: function calledWithExactly() { - return arguments.length == this.args.length && - this.calledWith.apply(this, arguments); - }, - - notCalledWith: function notCalledWith() { - return !this.calledWith.apply(this, arguments); - }, - - notCalledWithMatch: function notCalledWithMatch() { - return !this.calledWithMatch.apply(this, arguments); - }, - - returned: function returned(value) { - return sinon.deepEqual(value, this.returnValue); - }, - - threw: function threw(error) { - if (typeof error === "undefined" || !this.exception) { - return !!this.exception; - } - - return this.exception === error || this.exception.name === error; - }, - - calledWithNew: function calledWithNew() { - return this.proxy.prototype && this.thisValue instanceof this.proxy; - }, - - calledBefore: function (other) { - return this.callId < other.callId; - }, - - calledAfter: function (other) { - return this.callId > other.callId; - }, - - callArg: function (pos) { - this.args[pos](); - }, - - callArgOn: function (pos, thisValue) { - this.args[pos].apply(thisValue); - }, - - callArgWith: function (pos) { - this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); - }, - - callArgOnWith: function (pos, thisValue) { - var args = slice.call(arguments, 2); - this.args[pos].apply(thisValue, args); - }, - - yield: function () { - this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); - }, - - yieldOn: function (thisValue) { - var args = this.args; - for (var i = 0, l = args.length; i < l; ++i) { - if (typeof args[i] === "function") { - args[i].apply(thisValue, slice.call(arguments, 1)); - return; - } - } - throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); - }, - - yieldTo: function (prop) { - this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); - }, - - yieldToOn: function (prop, thisValue) { - var args = this.args; - for (var i = 0, l = args.length; i < l; ++i) { - if (args[i] && typeof args[i][prop] === "function") { - args[i][prop].apply(thisValue, slice.call(arguments, 2)); - return; - } - } - throwYieldError(this.proxy, " cannot yield to '" + prop + - "' since no callback was passed.", args); - }, - - toString: function () { - var callStr = this.proxy.toString() + "("; - var args = []; - - for (var i = 0, l = this.args.length; i < l; ++i) { - args.push(sinon.format(this.args[i])); - } - - callStr = callStr + args.join(", ") + ")"; - - if (typeof this.returnValue != "undefined") { - callStr += " => " + sinon.format(this.returnValue); - } - - if (this.exception) { - callStr += " !" + this.exception.name; - - if (this.exception.message) { - callStr += "(" + this.exception.message + ")"; - } - } - - return callStr; - } - }; - - callProto.invokeCallback = callProto.yield; - - function createSpyCall(spy, thisValue, args, returnValue, exception, id) { - if (typeof id !== "number") { - throw new TypeError("Call id is not a number"); - } - var proxyCall = sinon.create(callProto); - proxyCall.proxy = spy; - proxyCall.thisValue = thisValue; - proxyCall.args = args; - proxyCall.returnValue = returnValue; - proxyCall.exception = exception; - proxyCall.callId = id; - - return proxyCall; - } - createSpyCall.toString = callProto.toString; // used by mocks - - sinon.spyCall = createSpyCall; - return createSpyCall; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./match"); - require("./format"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./format":30,"./match":32,"./util/core":41}],28:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend spy.js - * @depend stub.js - * @depend mock.js - */ -/** - * Collections of stubs, spies and mocks. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - var push = [].push; - var hasOwnProperty = Object.prototype.hasOwnProperty; - - function getFakes(fakeCollection) { - if (!fakeCollection.fakes) { - fakeCollection.fakes = []; - } - - return fakeCollection.fakes; - } - - function each(fakeCollection, method) { - var fakes = getFakes(fakeCollection); - - for (var i = 0, l = fakes.length; i < l; i += 1) { - if (typeof fakes[i][method] == "function") { - fakes[i][method](); - } - } - } - - function compact(fakeCollection) { - var fakes = getFakes(fakeCollection); - var i = 0; - while (i < fakes.length) { - fakes.splice(i, 1); - } - } - - function makeApi(sinon) { - var collection = { - verify: function resolve() { - each(this, "verify"); - }, - - restore: function restore() { - each(this, "restore"); - compact(this); - }, - - reset: function restore() { - each(this, "reset"); - }, - - verifyAndRestore: function verifyAndRestore() { - var exception; - - try { - this.verify(); - } catch (e) { - exception = e; - } - - this.restore(); - - if (exception) { - throw exception; - } - }, - - add: function add(fake) { - push.call(getFakes(this), fake); - return fake; - }, - - spy: function spy() { - return this.add(sinon.spy.apply(sinon, arguments)); - }, - - stub: function stub(object, property, value) { - if (property) { - var original = object[property]; - - if (typeof original != "function") { - if (!hasOwnProperty.call(object, property)) { - throw new TypeError("Cannot stub non-existent own property " + property); - } - - object[property] = value; - - return this.add({ - restore: function () { - object[property] = original; - } - }); - } - } - if (!property && !!object && typeof object == "object") { - var stubbedObj = sinon.stub.apply(sinon, arguments); - - for (var prop in stubbedObj) { - if (typeof stubbedObj[prop] === "function") { - this.add(stubbedObj[prop]); - } - } - - return stubbedObj; - } - - return this.add(sinon.stub.apply(sinon, arguments)); - }, - - mock: function mock() { - return this.add(sinon.mock.apply(sinon, arguments)); - }, - - inject: function inject(obj) { - var col = this; - - obj.spy = function () { - return col.spy.apply(col, arguments); - }; - - obj.stub = function () { - return col.stub.apply(col, arguments); - }; - - obj.mock = function () { - return col.mock.apply(col, arguments); - }; - - return obj; - } - }; - - sinon.collection = collection; - return collection; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./mock"); - require("./spy"); - require("./stub"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./mock":33,"./spy":35,"./stub":36,"./util/core":41}],29:[function(require,module,exports){ -/** - * @depend util/core.js - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - - // Adapted from https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug - var hasDontEnumBug = (function () { - var obj = { - constructor: function () { - return "0"; - }, - toString: function () { - return "1"; - }, - valueOf: function () { - return "2"; - }, - toLocaleString: function () { - return "3"; - }, - prototype: function () { - return "4"; - }, - isPrototypeOf: function () { - return "5"; - }, - propertyIsEnumerable: function () { - return "6"; - }, - hasOwnProperty: function () { - return "7"; - }, - length: function () { - return "8"; - }, - unique: function () { - return "9" - } - }; - - var result = []; - for (var prop in obj) { - result.push(obj[prop]()); - } - return result.join("") !== "0123456789"; - })(); - - /* Public: Extend target in place with all (own) properties from sources in-order. Thus, last source will - * override properties in previous sources. - * - * target - The Object to extend - * sources - Objects to copy properties from. - * - * Returns the extended target - */ - function extend(target /*, sources */) { - var sources = Array.prototype.slice.call(arguments, 1), - source, i, prop; - - for (i = 0; i < sources.length; i++) { - source = sources[i]; - - for (prop in source) { - if (source.hasOwnProperty(prop)) { - target[prop] = source[prop]; - } - } - - // Make sure we copy (own) toString method even when in JScript with DontEnum bug - // See https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug - if (hasDontEnumBug && source.hasOwnProperty("toString") && source.toString !== target.toString) { - target.toString = source.toString; - } - } - - return target; - }; - - sinon.extend = extend; - return sinon.extend; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./util/core":41}],30:[function(require,module,exports){ -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -(function (sinon, formatio) { - function makeApi(sinon) { - function valueFormatter(value) { - return "" + value; - } - - function getFormatioFormatter() { - var formatter = formatio.configure({ - quoteStrings: false, - limitChildrenCount: 250 - }); - - function format() { - return formatter.ascii.apply(formatter, arguments); - }; - - return format; - } - - function getNodeFormatter(value) { - function format(value) { - return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; - }; - - try { - var util = require("util"); - } catch (e) { - /* Node, but no util module - would be very old, but better safe than sorry */ - } - - return util ? format : valueFormatter; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function", - formatter; - - if (isNode) { - try { - formatio = require("formatio"); - } catch (e) {} - } - - if (formatio) { - formatter = getFormatioFormatter() - } else if (isNode) { - formatter = getNodeFormatter(); - } else { - formatter = valueFormatter; - } - - sinon.format = formatter; - return sinon.format; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}( - (typeof sinon == "object" && sinon || null), - (typeof formatio == "object" && formatio) -)); - -},{"./util/core":41,"formatio":48,"util":6}],31:[function(require,module,exports){ -/** - * @depend util/core.js - */ -/** - * Logs errors - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -(function (sinon) { - // cache a reference to setTimeout, so that our reference won't be stubbed out - // when using fake timers and errors will still get logged - // https://github.com/cjohansen/Sinon.JS/issues/381 - var realSetTimeout = setTimeout; - - function makeApi(sinon) { - - function log() {} - - function logError(label, err) { - var msg = label + " threw exception: "; - - sinon.log(msg + "[" + err.name + "] " + err.message); - - if (err.stack) { - sinon.log(err.stack); - } - - logError.setTimeout(function () { - err.message = msg + err.message; - throw err; - }, 0); - }; - - // wrap realSetTimeout with something we can stub in tests - logError.setTimeout = function (func, timeout) { - realSetTimeout(func, timeout); - } - - var exports = {}; - exports.log = sinon.log = log; - exports.logError = sinon.logError = logError; - - return exports; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./util/core":41}],32:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend typeOf.js - */ -/*jslint eqeqeq: false, onevar: false, plusplus: false*/ -/*global module, require, sinon*/ -/** - * Match functions - * - * @author Maximilian Antoni (mail@maxantoni.de) - * @license BSD - * - * Copyright (c) 2012 Maximilian Antoni - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - function assertType(value, type, name) { - var actual = sinon.typeOf(value); - if (actual !== type) { - throw new TypeError("Expected type of " + name + " to be " + - type + ", but was " + actual); - } - } - - var matcher = { - toString: function () { - return this.message; - } - }; - - function isMatcher(object) { - return matcher.isPrototypeOf(object); - } - - function matchObject(expectation, actual) { - if (actual === null || actual === undefined) { - return false; - } - for (var key in expectation) { - if (expectation.hasOwnProperty(key)) { - var exp = expectation[key]; - var act = actual[key]; - if (match.isMatcher(exp)) { - if (!exp.test(act)) { - return false; - } - } else if (sinon.typeOf(exp) === "object") { - if (!matchObject(exp, act)) { - return false; - } - } else if (!sinon.deepEqual(exp, act)) { - return false; - } - } - } - return true; - } - - matcher.or = function (m2) { - if (!arguments.length) { - throw new TypeError("Matcher expected"); - } else if (!isMatcher(m2)) { - m2 = match(m2); - } - var m1 = this; - var or = sinon.create(matcher); - or.test = function (actual) { - return m1.test(actual) || m2.test(actual); - }; - or.message = m1.message + ".or(" + m2.message + ")"; - return or; - }; - - matcher.and = function (m2) { - if (!arguments.length) { - throw new TypeError("Matcher expected"); - } else if (!isMatcher(m2)) { - m2 = match(m2); - } - var m1 = this; - var and = sinon.create(matcher); - and.test = function (actual) { - return m1.test(actual) && m2.test(actual); - }; - and.message = m1.message + ".and(" + m2.message + ")"; - return and; - }; - - var match = function (expectation, message) { - var m = sinon.create(matcher); - var type = sinon.typeOf(expectation); - switch (type) { - case "object": - if (typeof expectation.test === "function") { - m.test = function (actual) { - return expectation.test(actual) === true; - }; - m.message = "match(" + sinon.functionName(expectation.test) + ")"; - return m; - } - var str = []; - for (var key in expectation) { - if (expectation.hasOwnProperty(key)) { - str.push(key + ": " + expectation[key]); - } - } - m.test = function (actual) { - return matchObject(expectation, actual); - }; - m.message = "match(" + str.join(", ") + ")"; - break; - case "number": - m.test = function (actual) { - return expectation == actual; - }; - break; - case "string": - m.test = function (actual) { - if (typeof actual !== "string") { - return false; - } - return actual.indexOf(expectation) !== -1; - }; - m.message = "match(\"" + expectation + "\")"; - break; - case "regexp": - m.test = function (actual) { - if (typeof actual !== "string") { - return false; - } - return expectation.test(actual); - }; - break; - case "function": - m.test = expectation; - if (message) { - m.message = message; - } else { - m.message = "match(" + sinon.functionName(expectation) + ")"; - } - break; - default: - m.test = function (actual) { - return sinon.deepEqual(expectation, actual); - }; - } - if (!m.message) { - m.message = "match(" + expectation + ")"; - } - return m; - }; - - match.isMatcher = isMatcher; - - match.any = match(function () { - return true; - }, "any"); - - match.defined = match(function (actual) { - return actual !== null && actual !== undefined; - }, "defined"); - - match.truthy = match(function (actual) { - return !!actual; - }, "truthy"); - - match.falsy = match(function (actual) { - return !actual; - }, "falsy"); - - match.same = function (expectation) { - return match(function (actual) { - return expectation === actual; - }, "same(" + expectation + ")"); - }; - - match.typeOf = function (type) { - assertType(type, "string", "type"); - return match(function (actual) { - return sinon.typeOf(actual) === type; - }, "typeOf(\"" + type + "\")"); - }; - - match.instanceOf = function (type) { - assertType(type, "function", "type"); - return match(function (actual) { - return actual instanceof type; - }, "instanceOf(" + sinon.functionName(type) + ")"); - }; - - function createPropertyMatcher(propertyTest, messagePrefix) { - return function (property, value) { - assertType(property, "string", "property"); - var onlyProperty = arguments.length === 1; - var message = messagePrefix + "(\"" + property + "\""; - if (!onlyProperty) { - message += ", " + value; - } - message += ")"; - return match(function (actual) { - if (actual === undefined || actual === null || - !propertyTest(actual, property)) { - return false; - } - return onlyProperty || sinon.deepEqual(value, actual[property]); - }, message); - }; - } - - match.has = createPropertyMatcher(function (actual, property) { - if (typeof actual === "object") { - return property in actual; - } - return actual[property] !== undefined; - }, "has"); - - match.hasOwn = createPropertyMatcher(function (actual, property) { - return actual.hasOwnProperty(property); - }, "hasOwn"); - - match.bool = match.typeOf("boolean"); - match.number = match.typeOf("number"); - match.string = match.typeOf("string"); - match.object = match.typeOf("object"); - match.func = match.typeOf("function"); - match.array = match.typeOf("array"); - match.regexp = match.typeOf("regexp"); - match.date = match.typeOf("date"); - - sinon.match = match; - return match; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./typeOf"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./typeOf":40,"./util/core":41}],33:[function(require,module,exports){ -/** - * @depend times_in_words.js - * @depend util/core.js - * @depend call.js - * @depend extend.js - * @depend match.js - * @depend spy.js - * @depend stub.js - * @depend format.js - */ -/** - * Mock functions. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - var push = [].push; - var match = sinon.match; - - function mock(object) { - if (!object) { - return sinon.expectation.create("Anonymous mock"); - } - - return mock.create(object); - } - - function each(collection, callback) { - if (!collection) { - return; - } - - for (var i = 0, l = collection.length; i < l; i += 1) { - callback(collection[i]); - } - } - - sinon.extend(mock, { - create: function create(object) { - if (!object) { - throw new TypeError("object is null"); - } - - var mockObject = sinon.extend({}, mock); - mockObject.object = object; - delete mockObject.create; - - return mockObject; - }, - - expects: function expects(method) { - if (!method) { - throw new TypeError("method is falsy"); - } - - if (!this.expectations) { - this.expectations = {}; - this.proxies = []; - } - - if (!this.expectations[method]) { - this.expectations[method] = []; - var mockObject = this; - - sinon.wrapMethod(this.object, method, function () { - return mockObject.invokeMethod(method, this, arguments); - }); - - push.call(this.proxies, method); - } - - var expectation = sinon.expectation.create(method); - push.call(this.expectations[method], expectation); - - return expectation; - }, - - restore: function restore() { - var object = this.object; - - each(this.proxies, function (proxy) { - if (typeof object[proxy].restore == "function") { - object[proxy].restore(); - } - }); - }, - - verify: function verify() { - var expectations = this.expectations || {}; - var messages = [], met = []; - - each(this.proxies, function (proxy) { - each(expectations[proxy], function (expectation) { - if (!expectation.met()) { - push.call(messages, expectation.toString()); - } else { - push.call(met, expectation.toString()); - } - }); - }); - - this.restore(); - - if (messages.length > 0) { - sinon.expectation.fail(messages.concat(met).join("\n")); - } else if (met.length > 0) { - sinon.expectation.pass(messages.concat(met).join("\n")); - } - - return true; - }, - - invokeMethod: function invokeMethod(method, thisValue, args) { - var expectations = this.expectations && this.expectations[method]; - var length = expectations && expectations.length || 0, i; - - for (i = 0; i < length; i += 1) { - if (!expectations[i].met() && - expectations[i].allowsCall(thisValue, args)) { - return expectations[i].apply(thisValue, args); - } - } - - var messages = [], available, exhausted = 0; - - for (i = 0; i < length; i += 1) { - if (expectations[i].allowsCall(thisValue, args)) { - available = available || expectations[i]; - } else { - exhausted += 1; - } - push.call(messages, " " + expectations[i].toString()); - } - - if (exhausted === 0) { - return available.apply(thisValue, args); - } - - messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ - proxy: method, - args: args - })); - - sinon.expectation.fail(messages.join("\n")); - } - }); - - var times = sinon.timesInWords; - var slice = Array.prototype.slice; - - function callCountInWords(callCount) { - if (callCount == 0) { - return "never called"; - } else { - return "called " + times(callCount); - } - } - - function expectedCallCountInWords(expectation) { - var min = expectation.minCalls; - var max = expectation.maxCalls; - - if (typeof min == "number" && typeof max == "number") { - var str = times(min); - - if (min != max) { - str = "at least " + str + " and at most " + times(max); - } - - return str; - } - - if (typeof min == "number") { - return "at least " + times(min); - } - - return "at most " + times(max); - } - - function receivedMinCalls(expectation) { - var hasMinLimit = typeof expectation.minCalls == "number"; - return !hasMinLimit || expectation.callCount >= expectation.minCalls; - } - - function receivedMaxCalls(expectation) { - if (typeof expectation.maxCalls != "number") { - return false; - } - - return expectation.callCount == expectation.maxCalls; - } - - function verifyMatcher(possibleMatcher, arg) { - if (match && match.isMatcher(possibleMatcher)) { - return possibleMatcher.test(arg); - } else { - return true; - } - } - - sinon.expectation = { - minCalls: 1, - maxCalls: 1, - - create: function create(methodName) { - var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); - delete expectation.create; - expectation.method = methodName; - - return expectation; - }, - - invoke: function invoke(func, thisValue, args) { - this.verifyCallAllowed(thisValue, args); - - return sinon.spy.invoke.apply(this, arguments); - }, - - atLeast: function atLeast(num) { - if (typeof num != "number") { - throw new TypeError("'" + num + "' is not number"); - } - - if (!this.limitsSet) { - this.maxCalls = null; - this.limitsSet = true; - } - - this.minCalls = num; - - return this; - }, - - atMost: function atMost(num) { - if (typeof num != "number") { - throw new TypeError("'" + num + "' is not number"); - } - - if (!this.limitsSet) { - this.minCalls = null; - this.limitsSet = true; - } - - this.maxCalls = num; - - return this; - }, - - never: function never() { - return this.exactly(0); - }, - - once: function once() { - return this.exactly(1); - }, - - twice: function twice() { - return this.exactly(2); - }, - - thrice: function thrice() { - return this.exactly(3); - }, - - exactly: function exactly(num) { - if (typeof num != "number") { - throw new TypeError("'" + num + "' is not a number"); - } - - this.atLeast(num); - return this.atMost(num); - }, - - met: function met() { - return !this.failed && receivedMinCalls(this); - }, - - verifyCallAllowed: function verifyCallAllowed(thisValue, args) { - if (receivedMaxCalls(this)) { - this.failed = true; - sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); - } - - if ("expectedThis" in this && this.expectedThis !== thisValue) { - sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + - this.expectedThis); - } - - if (!("expectedArguments" in this)) { - return; - } - - if (!args) { - sinon.expectation.fail(this.method + " received no arguments, expected " + - sinon.format(this.expectedArguments)); - } - - if (args.length < this.expectedArguments.length) { - sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) + - "), expected " + sinon.format(this.expectedArguments)); - } - - if (this.expectsExactArgCount && - args.length != this.expectedArguments.length) { - sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) + - "), expected " + sinon.format(this.expectedArguments)); - } - - for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { - - if (!verifyMatcher(this.expectedArguments[i], args[i])) { - sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + - ", didn't match " + this.expectedArguments.toString()); - } - - if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { - sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + - ", expected " + sinon.format(this.expectedArguments)); - } - } - }, - - allowsCall: function allowsCall(thisValue, args) { - if (this.met() && receivedMaxCalls(this)) { - return false; - } - - if ("expectedThis" in this && this.expectedThis !== thisValue) { - return false; - } - - if (!("expectedArguments" in this)) { - return true; - } - - args = args || []; - - if (args.length < this.expectedArguments.length) { - return false; - } - - if (this.expectsExactArgCount && - args.length != this.expectedArguments.length) { - return false; - } - - for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { - if (!verifyMatcher(this.expectedArguments[i], args[i])) { - return false; - } - - if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { - return false; - } - } - - return true; - }, - - withArgs: function withArgs() { - this.expectedArguments = slice.call(arguments); - return this; - }, - - withExactArgs: function withExactArgs() { - this.withArgs.apply(this, arguments); - this.expectsExactArgCount = true; - return this; - }, - - on: function on(thisValue) { - this.expectedThis = thisValue; - return this; - }, - - toString: function () { - var args = (this.expectedArguments || []).slice(); - - if (!this.expectsExactArgCount) { - push.call(args, "[...]"); - } - - var callStr = sinon.spyCall.toString.call({ - proxy: this.method || "anonymous mock expectation", - args: args - }); - - var message = callStr.replace(", [...", "[, ...") + " " + - expectedCallCountInWords(this); - - if (this.met()) { - return "Expectation met: " + message; - } - - return "Expected " + message + " (" + - callCountInWords(this.callCount) + ")"; - }, - - verify: function verify() { - if (!this.met()) { - sinon.expectation.fail(this.toString()); - } else { - sinon.expectation.pass(this.toString()); - } - - return true; - }, - - pass: function pass(message) { - sinon.assert.pass(message); - }, - - fail: function fail(message) { - var exception = new Error(message); - exception.name = "ExpectationError"; - - throw exception; - } - }; - - sinon.mock = mock; - return mock; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./times_in_words"); - require("./call"); - require("./extend"); - require("./match"); - require("./spy"); - require("./stub"); - require("./format"); - - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./call":27,"./extend":29,"./format":30,"./match":32,"./spy":35,"./stub":36,"./times_in_words":39,"./util/core":41}],34:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend extend.js - * @depend collection.js - * @depend util/fake_timers.js - * @depend util/fake_server_with_clock.js - */ -/** - * Manages fake collections as well as fake utilities such as Sinon's - * timers and fake XHR implementation in one convenient object. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function () { - function makeApi(sinon) { - var push = [].push; - - function exposeValue(sandbox, config, key, value) { - if (!value) { - return; - } - - if (config.injectInto && !(key in config.injectInto)) { - config.injectInto[key] = value; - sandbox.injectedKeys.push(key); - } else { - push.call(sandbox.args, value); - } - } - - function prepareSandboxFromConfig(config) { - var sandbox = sinon.create(sinon.sandbox); - - if (config.useFakeServer) { - if (typeof config.useFakeServer == "object") { - sandbox.serverPrototype = config.useFakeServer; - } - - sandbox.useFakeServer(); - } - - if (config.useFakeTimers) { - if (typeof config.useFakeTimers == "object") { - sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); - } else { - sandbox.useFakeTimers(); - } - } - - return sandbox; - } - - sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { - useFakeTimers: function useFakeTimers() { - this.clock = sinon.useFakeTimers.apply(sinon, arguments); - - return this.add(this.clock); - }, - - serverPrototype: sinon.fakeServer, - - useFakeServer: function useFakeServer() { - var proto = this.serverPrototype || sinon.fakeServer; - - if (!proto || !proto.create) { - return null; - } - - this.server = proto.create(); - return this.add(this.server); - }, - - inject: function (obj) { - sinon.collection.inject.call(this, obj); - - if (this.clock) { - obj.clock = this.clock; - } - - if (this.server) { - obj.server = this.server; - obj.requests = this.server.requests; - } - - obj.match = sinon.match; - - return obj; - }, - - restore: function () { - sinon.collection.restore.apply(this, arguments); - this.restoreContext(); - }, - - restoreContext: function () { - if (this.injectedKeys) { - for (var i = 0, j = this.injectedKeys.length; i < j; i++) { - delete this.injectInto[this.injectedKeys[i]]; - } - this.injectedKeys = []; - } - }, - - create: function (config) { - if (!config) { - return sinon.create(sinon.sandbox); - } - - var sandbox = prepareSandboxFromConfig(config); - sandbox.args = sandbox.args || []; - sandbox.injectedKeys = []; - sandbox.injectInto = config.injectInto; - var prop, value, exposed = sandbox.inject({}); - - if (config.properties) { - for (var i = 0, l = config.properties.length; i < l; i++) { - prop = config.properties[i]; - value = exposed[prop] || prop == "sandbox" && sandbox; - exposeValue(sandbox, config, prop, value); - } - } else { - exposeValue(sandbox, config, "sandbox", value); - } - - return sandbox; - }, - - match: sinon.match - }); - - sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; - - return sinon.sandbox; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./extend"); - require("./util/fake_server_with_clock"); - require("./util/fake_timers"); - require("./collection"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}()); - -},{"./collection":28,"./extend":29,"./util/core":41,"./util/fake_server_with_clock":44,"./util/fake_timers":45}],35:[function(require,module,exports){ -/** - * @depend times_in_words.js - * @depend util/core.js - * @depend extend.js - * @depend call.js - * @depend format.js - */ -/** - * Spy functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - - function makeApi(sinon) { - var push = Array.prototype.push; - var slice = Array.prototype.slice; - var callId = 0; - - function spy(object, property, types) { - if (!property && typeof object == "function") { - return spy.create(object); - } - - if (!object && !property) { - return spy.create(function () { }); - } - - if (types) { - var methodDesc = sinon.getPropertyDescriptor(object, property); - for (var i = 0; i < types.length; i++) { - methodDesc[types[i]] = spy.create(methodDesc[types[i]]); - } - return sinon.wrapMethod(object, property, methodDesc); - } else { - var method = object[property]; - return sinon.wrapMethod(object, property, spy.create(method)); - } - } - - function matchingFake(fakes, args, strict) { - if (!fakes) { - return; - } - - for (var i = 0, l = fakes.length; i < l; i++) { - if (fakes[i].matches(args, strict)) { - return fakes[i]; - } - } - } - - function incrementCallCount() { - this.called = true; - this.callCount += 1; - this.notCalled = false; - this.calledOnce = this.callCount == 1; - this.calledTwice = this.callCount == 2; - this.calledThrice = this.callCount == 3; - } - - function createCallProperties() { - this.firstCall = this.getCall(0); - this.secondCall = this.getCall(1); - this.thirdCall = this.getCall(2); - this.lastCall = this.getCall(this.callCount - 1); - } - - var vars = "a,b,c,d,e,f,g,h,i,j,k,l"; - function createProxy(func, proxyLength) { - // Retain the function length: - var p; - if (proxyLength) { - eval("p = (function proxy(" + vars.substring(0, proxyLength * 2 - 1) + - ") { return p.invoke(func, this, slice.call(arguments)); });"); - } else { - p = function proxy() { - return p.invoke(func, this, slice.call(arguments)); - }; - } - return p; - } - - var uuid = 0; - - // Public API - var spyApi = { - reset: function () { - if (this.invoking) { - var err = new Error("Cannot reset Sinon function while invoking it. " + - "Move the call to .reset outside of the callback."); - err.name = "InvalidResetException"; - throw err; - } - - this.called = false; - this.notCalled = true; - this.calledOnce = false; - this.calledTwice = false; - this.calledThrice = false; - this.callCount = 0; - this.firstCall = null; - this.secondCall = null; - this.thirdCall = null; - this.lastCall = null; - this.args = []; - this.returnValues = []; - this.thisValues = []; - this.exceptions = []; - this.callIds = []; - if (this.fakes) { - for (var i = 0; i < this.fakes.length; i++) { - this.fakes[i].reset(); - } - } - - return this; - }, - - create: function create(func, spyLength) { - var name; - - if (typeof func != "function") { - func = function () { }; - } else { - name = sinon.functionName(func); - } - - if (!spyLength) { - spyLength = func.length; - } - - var proxy = createProxy(func, spyLength); - - sinon.extend(proxy, spy); - delete proxy.create; - sinon.extend(proxy, func); - - proxy.reset(); - proxy.prototype = func.prototype; - proxy.displayName = name || "spy"; - proxy.toString = sinon.functionToString; - proxy.instantiateFake = sinon.spy.create; - proxy.id = "spy#" + uuid++; - - return proxy; - }, - - invoke: function invoke(func, thisValue, args) { - var matching = matchingFake(this.fakes, args); - var exception, returnValue; - - incrementCallCount.call(this); - push.call(this.thisValues, thisValue); - push.call(this.args, args); - push.call(this.callIds, callId++); - - // Make call properties available from within the spied function: - createCallProperties.call(this); - - try { - this.invoking = true; - - if (matching) { - returnValue = matching.invoke(func, thisValue, args); - } else { - returnValue = (this.func || func).apply(thisValue, args); - } - - var thisCall = this.getCall(this.callCount - 1); - if (thisCall.calledWithNew() && typeof returnValue !== "object") { - returnValue = thisValue; - } - } catch (e) { - exception = e; - } finally { - delete this.invoking; - } - - push.call(this.exceptions, exception); - push.call(this.returnValues, returnValue); - - // Make return value and exception available in the calls: - createCallProperties.call(this); - - if (exception !== undefined) { - throw exception; - } - - return returnValue; - }, - - named: function named(name) { - this.displayName = name; - return this; - }, - - getCall: function getCall(i) { - if (i < 0 || i >= this.callCount) { - return null; - } - - return sinon.spyCall(this, this.thisValues[i], this.args[i], - this.returnValues[i], this.exceptions[i], - this.callIds[i]); - }, - - getCalls: function () { - var calls = []; - var i; - - for (i = 0; i < this.callCount; i++) { - calls.push(this.getCall(i)); - } - - return calls; - }, - - calledBefore: function calledBefore(spyFn) { - if (!this.called) { - return false; - } - - if (!spyFn.called) { - return true; - } - - return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; - }, - - calledAfter: function calledAfter(spyFn) { - if (!this.called || !spyFn.called) { - return false; - } - - return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; - }, - - withArgs: function () { - var args = slice.call(arguments); - - if (this.fakes) { - var match = matchingFake(this.fakes, args, true); - - if (match) { - return match; - } - } else { - this.fakes = []; - } - - var original = this; - var fake = this.instantiateFake(); - fake.matchingAguments = args; - fake.parent = this; - push.call(this.fakes, fake); - - fake.withArgs = function () { - return original.withArgs.apply(original, arguments); - }; - - for (var i = 0; i < this.args.length; i++) { - if (fake.matches(this.args[i])) { - incrementCallCount.call(fake); - push.call(fake.thisValues, this.thisValues[i]); - push.call(fake.args, this.args[i]); - push.call(fake.returnValues, this.returnValues[i]); - push.call(fake.exceptions, this.exceptions[i]); - push.call(fake.callIds, this.callIds[i]); - } - } - createCallProperties.call(fake); - - return fake; - }, - - matches: function (args, strict) { - var margs = this.matchingAguments; - - if (margs.length <= args.length && - sinon.deepEqual(margs, args.slice(0, margs.length))) { - return !strict || margs.length == args.length; - } - }, - - printf: function (format) { - var spy = this; - var args = slice.call(arguments, 1); - var formatter; - - return (format || "").replace(/%(.)/g, function (match, specifyer) { - formatter = spyApi.formatters[specifyer]; - - if (typeof formatter == "function") { - return formatter.call(null, spy, args); - } else if (!isNaN(parseInt(specifyer, 10))) { - return sinon.format(args[specifyer - 1]); - } - - return "%" + specifyer; - }); - } - }; - - function delegateToCalls(method, matchAny, actual, notCalled) { - spyApi[method] = function () { - if (!this.called) { - if (notCalled) { - return notCalled.apply(this, arguments); - } - return false; - } - - var currentCall; - var matches = 0; - - for (var i = 0, l = this.callCount; i < l; i += 1) { - currentCall = this.getCall(i); - - if (currentCall[actual || method].apply(currentCall, arguments)) { - matches += 1; - - if (matchAny) { - return true; - } - } - } - - return matches === this.callCount; - }; - } - - delegateToCalls("calledOn", true); - delegateToCalls("alwaysCalledOn", false, "calledOn"); - delegateToCalls("calledWith", true); - delegateToCalls("calledWithMatch", true); - delegateToCalls("alwaysCalledWith", false, "calledWith"); - delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch"); - delegateToCalls("calledWithExactly", true); - delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly"); - delegateToCalls("neverCalledWith", false, "notCalledWith", - function () { return true; }); - delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", - function () { return true; }); - delegateToCalls("threw", true); - delegateToCalls("alwaysThrew", false, "threw"); - delegateToCalls("returned", true); - delegateToCalls("alwaysReturned", false, "returned"); - delegateToCalls("calledWithNew", true); - delegateToCalls("alwaysCalledWithNew", false, "calledWithNew"); - delegateToCalls("callArg", false, "callArgWith", function () { - throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); - }); - spyApi.callArgWith = spyApi.callArg; - delegateToCalls("callArgOn", false, "callArgOnWith", function () { - throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); - }); - spyApi.callArgOnWith = spyApi.callArgOn; - delegateToCalls("yield", false, "yield", function () { - throw new Error(this.toString() + " cannot yield since it was not yet invoked."); - }); - // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. - spyApi.invokeCallback = spyApi.yield; - delegateToCalls("yieldOn", false, "yieldOn", function () { - throw new Error(this.toString() + " cannot yield since it was not yet invoked."); - }); - delegateToCalls("yieldTo", false, "yieldTo", function (property) { - throw new Error(this.toString() + " cannot yield to '" + property + - "' since it was not yet invoked."); - }); - delegateToCalls("yieldToOn", false, "yieldToOn", function (property) { - throw new Error(this.toString() + " cannot yield to '" + property + - "' since it was not yet invoked."); - }); - - spyApi.formatters = { - c: function (spy) { - return sinon.timesInWords(spy.callCount); - }, - - n: function (spy) { - return spy.toString(); - }, - - C: function (spy) { - var calls = []; - - for (var i = 0, l = spy.callCount; i < l; ++i) { - var stringifiedCall = " " + spy.getCall(i).toString(); - if (/\n/.test(calls[i - 1])) { - stringifiedCall = "\n" + stringifiedCall; - } - push.call(calls, stringifiedCall); - } - - return calls.length > 0 ? "\n" + calls.join("\n") : ""; - }, - - t: function (spy) { - var objects = []; - - for (var i = 0, l = spy.callCount; i < l; ++i) { - push.call(objects, sinon.format(spy.thisValues[i])); - } - - return objects.join(", "); - }, - - "*": function (spy, args) { - var formatted = []; - - for (var i = 0, l = args.length; i < l; ++i) { - push.call(formatted, sinon.format(args[i])); - } - - return formatted.join(", "); - } - }; - - sinon.extend(spy, spyApi); - - spy.spyCall = sinon.spyCall; - sinon.spy = spy; - - return spy; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./call"); - require("./extend"); - require("./times_in_words"); - require("./format"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./call":27,"./extend":29,"./format":30,"./times_in_words":39,"./util/core":41}],36:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend extend.js - * @depend spy.js - * @depend behavior.js - */ -/** - * Stub functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - function stub(object, property, func) { - if (!!func && typeof func != "function" && typeof func != "object") { - throw new TypeError("Custom stub should be a function or a property descriptor"); - } - - var wrapper; - - if (func) { - if (typeof func == "function") { - wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; - } else { - wrapper = func; - if (sinon.spy && sinon.spy.create) { - var types = sinon.objectKeys(wrapper); - for (var i = 0; i < types.length; i++) { - wrapper[types[i]] = sinon.spy.create(wrapper[types[i]]); - } - } - } - } else { - var stubLength = 0; - if (typeof object == "object" && typeof object[property] == "function") { - stubLength = object[property].length; - } - wrapper = stub.create(stubLength); - } - - if (!object && typeof property === "undefined") { - return sinon.stub.create(); - } - - if (typeof property === "undefined" && typeof object == "object") { - for (var prop in object) { - if (typeof object[prop] === "function") { - stub(object, prop); - } - } - - return object; - } - - return sinon.wrapMethod(object, property, wrapper); - } - - function getDefaultBehavior(stub) { - return stub.defaultBehavior || getParentBehaviour(stub) || sinon.behavior.create(stub); - } - - function getParentBehaviour(stub) { - return (stub.parent && getCurrentBehavior(stub.parent)); - } - - function getCurrentBehavior(stub) { - var behavior = stub.behaviors[stub.callCount - 1]; - return behavior && behavior.isPresent() ? behavior : getDefaultBehavior(stub); - } - - var uuid = 0; - - var proto = { - create: function create(stubLength) { - var functionStub = function () { - return getCurrentBehavior(functionStub).invoke(this, arguments); - }; - - functionStub.id = "stub#" + uuid++; - var orig = functionStub; - functionStub = sinon.spy.create(functionStub, stubLength); - functionStub.func = orig; - - sinon.extend(functionStub, stub); - functionStub.instantiateFake = sinon.stub.create; - functionStub.displayName = "stub"; - functionStub.toString = sinon.functionToString; - - functionStub.defaultBehavior = null; - functionStub.behaviors = []; - - return functionStub; - }, - - resetBehavior: function () { - var i; - - this.defaultBehavior = null; - this.behaviors = []; - - delete this.returnValue; - delete this.returnArgAt; - this.returnThis = false; - - if (this.fakes) { - for (i = 0; i < this.fakes.length; i++) { - this.fakes[i].resetBehavior(); - } - } - }, - - onCall: function onCall(index) { - if (!this.behaviors[index]) { - this.behaviors[index] = sinon.behavior.create(this); - } - - return this.behaviors[index]; - }, - - onFirstCall: function onFirstCall() { - return this.onCall(0); - }, - - onSecondCall: function onSecondCall() { - return this.onCall(1); - }, - - onThirdCall: function onThirdCall() { - return this.onCall(2); - } - }; - - for (var method in sinon.behavior) { - if (sinon.behavior.hasOwnProperty(method) && - !proto.hasOwnProperty(method) && - method != "create" && - method != "withArgs" && - method != "invoke") { - proto[method] = (function (behaviorMethod) { - return function () { - this.defaultBehavior = this.defaultBehavior || sinon.behavior.create(this); - this.defaultBehavior[behaviorMethod].apply(this.defaultBehavior, arguments); - return this; - }; - }(method)); - } - } - - sinon.extend(stub, proto); - sinon.stub = stub; - - return stub; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./behavior"); - require("./spy"); - require("./extend"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./behavior":26,"./extend":29,"./spy":35,"./util/core":41}],37:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend sandbox.js - */ -/** - * Test function, sandboxes fakes - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - var slice = Array.prototype.slice; - - function test(callback) { - var type = typeof callback; - - if (type != "function") { - throw new TypeError("sinon.test needs to wrap a test function, got " + type); - } - - function sinonSandboxedTest() { - var config = sinon.getConfig(sinon.config); - config.injectInto = config.injectIntoThis && this || config.injectInto; - var sandbox = sinon.sandbox.create(config); - var args = slice.call(arguments); - var oldDone = args.length && args[args.length - 1]; - var exception, result; - - if (typeof oldDone == "function") { - args[args.length - 1] = function sinonDone(result) { - if (result) { - sandbox.restore(); - throw exception; - } else { - sandbox.verifyAndRestore(); - } - oldDone(result); - }; - } - - try { - result = callback.apply(this, args.concat(sandbox.args)); - } catch (e) { - exception = e; - } - - if (typeof oldDone != "function") { - if (typeof exception !== "undefined") { - sandbox.restore(); - throw exception; - } else { - sandbox.verifyAndRestore(); - } - } - - return result; - } - - if (callback.length) { - return function sinonAsyncSandboxedTest(callback) { - return sinonSandboxedTest.apply(this, arguments); - }; - } - - return sinonSandboxedTest; - } - - test.config = { - injectIntoThis: true, - injectInto: null, - properties: ["spy", "stub", "mock", "clock", "server", "requests"], - useFakeTimers: true, - useFakeServer: true - }; - - sinon.test = test; - return test; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./sandbox"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (sinon) { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./sandbox":34,"./util/core":41}],38:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend test.js - */ -/** - * Test case, sandboxes all test functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - function createTest(property, setUp, tearDown) { - return function () { - if (setUp) { - setUp.apply(this, arguments); - } - - var exception, result; - - try { - result = property.apply(this, arguments); - } catch (e) { - exception = e; - } - - if (tearDown) { - tearDown.apply(this, arguments); - } - - if (exception) { - throw exception; - } - - return result; - }; - } - - function makeApi(sinon) { - function testCase(tests, prefix) { - /*jsl:ignore*/ - if (!tests || typeof tests != "object") { - throw new TypeError("sinon.testCase needs an object with test functions"); - } - /*jsl:end*/ - - prefix = prefix || "test"; - var rPrefix = new RegExp("^" + prefix); - var methods = {}, testName, property, method; - var setUp = tests.setUp; - var tearDown = tests.tearDown; - - for (testName in tests) { - if (tests.hasOwnProperty(testName)) { - property = tests[testName]; - - if (/^(setUp|tearDown)$/.test(testName)) { - continue; - } - - if (typeof property == "function" && rPrefix.test(testName)) { - method = property; - - if (setUp || tearDown) { - method = createTest(property, setUp, tearDown); - } - - methods[testName] = sinon.test(method); - } else { - methods[testName] = tests[testName]; - } - } - } - - return methods; - } - - sinon.testCase = testCase; - return testCase; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./test"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./test":37,"./util/core":41}],39:[function(require,module,exports){ -/** - * @depend util/core.js - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - - function timesInWords(count) { - switch (count) { - case 1: - return "once"; - case 2: - return "twice"; - case 3: - return "thrice"; - default: - return (count || 0) + " times"; - } - } - - sinon.timesInWords = timesInWords; - return sinon.timesInWords; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./util/core":41}],40:[function(require,module,exports){ -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -(function (sinon, formatio) { - function makeApi(sinon) { - function typeOf(value) { - if (value === null) { - return "null"; - } else if (value === undefined) { - return "undefined"; - } - var string = Object.prototype.toString.call(value); - return string.substring(8, string.length - 1).toLowerCase(); - }; - - sinon.typeOf = typeOf; - return sinon.typeOf; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}( - (typeof sinon == "object" && sinon || null), - (typeof formatio == "object" && formatio) -)); - -},{"./util/core":41}],41:[function(require,module,exports){ -/** - * @depend ../../sinon.js - */ -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - var div = typeof document != "undefined" && document.createElement("div"); - var hasOwn = Object.prototype.hasOwnProperty; - - function isDOMNode(obj) { - var success = false; - - try { - obj.appendChild(div); - success = div.parentNode == obj; - } catch (e) { - return false; - } finally { - try { - obj.removeChild(div); - } catch (e) { - // Remove failed, not much we can do about that - } - } - - return success; - } - - function isElement(obj) { - return div && obj && obj.nodeType === 1 && isDOMNode(obj); - } - - function isFunction(obj) { - return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply); - } - - function isReallyNaN(val) { - return typeof val === "number" && isNaN(val); - } - - function mirrorProperties(target, source) { - for (var prop in source) { - if (!hasOwn.call(target, prop)) { - target[prop] = source[prop]; - } - } - } - - function isRestorable(obj) { - return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon; - } - - // Cheap way to detect if we have ES5 support. - var hasES5Support = "keys" in Object; - - function makeApi(sinon) { - sinon.wrapMethod = function wrapMethod(object, property, method) { - if (!object) { - throw new TypeError("Should wrap property of object"); - } - - if (typeof method != "function" && typeof method != "object") { - throw new TypeError("Method wrapper should be a function or a property descriptor"); - } - - function checkWrappedMethod(wrappedMethod) { - if (!isFunction(wrappedMethod)) { - error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + - property + " as function"); - } else if (wrappedMethod.restore && wrappedMethod.restore.sinon) { - error = new TypeError("Attempted to wrap " + property + " which is already wrapped"); - } else if (wrappedMethod.calledBefore) { - var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; - error = new TypeError("Attempted to wrap " + property + " which is already " + verb); - } - - if (error) { - if (wrappedMethod && wrappedMethod.stackTrace) { - error.stack += "\n--------------\n" + wrappedMethod.stackTrace; - } - throw error; - } - } - - var error, wrappedMethod; - - // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem - // when using hasOwn.call on objects from other frames. - var owned = object.hasOwnProperty ? object.hasOwnProperty(property) : hasOwn.call(object, property); - - if (hasES5Support) { - var methodDesc = (typeof method == "function") ? {value: method} : method, - wrappedMethodDesc = sinon.getPropertyDescriptor(object, property), - i; - - if (!wrappedMethodDesc) { - error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + - property + " as function"); - } else if (wrappedMethodDesc.restore && wrappedMethodDesc.restore.sinon) { - error = new TypeError("Attempted to wrap " + property + " which is already wrapped"); - } - if (error) { - if (wrappedMethodDesc && wrappedMethodDesc.stackTrace) { - error.stack += "\n--------------\n" + wrappedMethodDesc.stackTrace; - } - throw error; - } - - var types = sinon.objectKeys(methodDesc); - for (i = 0; i < types.length; i++) { - wrappedMethod = wrappedMethodDesc[types[i]]; - checkWrappedMethod(wrappedMethod); - } - - mirrorProperties(methodDesc, wrappedMethodDesc); - for (i = 0; i < types.length; i++) { - mirrorProperties(methodDesc[types[i]], wrappedMethodDesc[types[i]]); - } - Object.defineProperty(object, property, methodDesc); - } else { - wrappedMethod = object[property]; - checkWrappedMethod(wrappedMethod); - object[property] = method; - method.displayName = property; - } - - method.displayName = property; - - // Set up a stack trace which can be used later to find what line of - // code the original method was created on. - method.stackTrace = (new Error("Stack Trace for original")).stack; - - method.restore = function () { - // For prototype properties try to reset by delete first. - // If this fails (ex: localStorage on mobile safari) then force a reset - // via direct assignment. - if (!owned) { - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (object[property] === method) { - object[property] = wrappedMethod; - } - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - if (!hasES5Support && object[property] === method) { - object[property] = wrappedMethod; - } - }; - - method.restore.sinon = true; - - if (!hasES5Support) { - mirrorProperties(method, wrappedMethod); - } - - return method; - }; - - sinon.create = function create(proto) { - var F = function () {}; - F.prototype = proto; - return new F(); - }; - - sinon.deepEqual = function deepEqual(a, b) { - if (sinon.match && sinon.match.isMatcher(a)) { - return a.test(b); - } - - if (typeof a != "object" || typeof b != "object") { - if (isReallyNaN(a) && isReallyNaN(b)) { - return true; - } else { - return a === b; - } - } - - if (isElement(a) || isElement(b)) { - return a === b; - } - - if (a === b) { - return true; - } - - if ((a === null && b !== null) || (a !== null && b === null)) { - return false; - } - - if (a instanceof RegExp && b instanceof RegExp) { - return (a.source === b.source) && (a.global === b.global) && - (a.ignoreCase === b.ignoreCase) && (a.multiline === b.multiline); - } - - var aString = Object.prototype.toString.call(a); - if (aString != Object.prototype.toString.call(b)) { - return false; - } - - if (aString == "[object Date]") { - return a.valueOf() === b.valueOf(); - } - - var prop, aLength = 0, bLength = 0; - - if (aString == "[object Array]" && a.length !== b.length) { - return false; - } - - for (prop in a) { - aLength += 1; - - if (!(prop in b)) { - return false; - } - - if (!deepEqual(a[prop], b[prop])) { - return false; - } - } - - for (prop in b) { - bLength += 1; - } - - return aLength == bLength; - }; - - sinon.functionName = function functionName(func) { - var name = func.displayName || func.name; - - // Use function decomposition as a last resort to get function - // name. Does not rely on function decomposition to work - if it - // doesn't debugging will be slightly less informative - // (i.e. toString will say 'spy' rather than 'myFunc'). - if (!name) { - var matches = func.toString().match(/function ([^\s\(]+)/); - name = matches && matches[1]; - } - - return name; - }; - - sinon.functionToString = function toString() { - if (this.getCall && this.callCount) { - var thisValue, prop, i = this.callCount; - - while (i--) { - thisValue = this.getCall(i).thisValue; - - for (prop in thisValue) { - if (thisValue[prop] === this) { - return prop; - } - } - } - } - - return this.displayName || "sinon fake"; - }; - - sinon.objectKeys = function objectKeys(obj) { - if (obj !== Object(obj)) { - throw new TypeError("sinon.objectKeys called on a non-object"); - } - - var keys = []; - var key; - for (key in obj) { - if (hasOwn.call(obj, key)) { - keys.push(key); - } - } - - return keys; - }; - - sinon.getPropertyDescriptor = function getPropertyDescriptor(object, property) { - var proto = object, descriptor; - while (proto && !(descriptor = Object.getOwnPropertyDescriptor(proto, property))) { - proto = Object.getPrototypeOf(proto); - } - return descriptor; - } - - sinon.getConfig = function (custom) { - var config = {}; - custom = custom || {}; - var defaults = sinon.defaultConfig; - - for (var prop in defaults) { - if (defaults.hasOwnProperty(prop)) { - config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; - } - } - - return config; - }; - - sinon.defaultConfig = { - injectIntoThis: true, - injectInto: null, - properties: ["spy", "stub", "mock", "clock", "server", "requests"], - useFakeTimers: true, - useFakeServer: true - }; - - sinon.timesInWords = function timesInWords(count) { - return count == 1 && "once" || - count == 2 && "twice" || - count == 3 && "thrice" || - (count || 0) + " times"; - }; - - sinon.calledInOrder = function (spies) { - for (var i = 1, l = spies.length; i < l; i++) { - if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) { - return false; - } - } - - return true; - }; - - sinon.orderByFirstCall = function (spies) { - return spies.sort(function (a, b) { - // uuid, won't ever be equal - var aCall = a.getCall(0); - var bCall = b.getCall(0); - var aId = aCall && aCall.callId || -1; - var bId = bCall && bCall.callId || -1; - - return aId < bId ? -1 : 1; - }); - }; - - sinon.createStubInstance = function (constructor) { - if (typeof constructor !== "function") { - throw new TypeError("The constructor should be a function."); - } - return sinon.stub(sinon.create(constructor.prototype)); - }; - - sinon.restore = function (object) { - if (object !== null && typeof object === "object") { - for (var prop in object) { - if (isRestorable(object[prop])) { - object[prop].restore(); - } - } - } else if (isRestorable(object)) { - object.restore(); - } - }; - - return sinon; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports) { - makeApi(exports); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{}],42:[function(require,module,exports){ -/** - * Minimal Event interface implementation - * - * Original implementation by Sven Fuchs: https://gist.github.com/995028 - * Modifications and tests by Christian Johansen. - * - * @author Sven Fuchs (svenfuchs@artweb-design.de) - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2011 Sven Fuchs, Christian Johansen - */ -"use strict"; - -if (typeof sinon == "undefined") { - this.sinon = {}; -} - -(function () { - var push = [].push; - - function makeApi(sinon) { - sinon.Event = function Event(type, bubbles, cancelable, target) { - this.initEvent(type, bubbles, cancelable, target); - }; - - sinon.Event.prototype = { - initEvent: function (type, bubbles, cancelable, target) { - this.type = type; - this.bubbles = bubbles; - this.cancelable = cancelable; - this.target = target; - }, - - stopPropagation: function () {}, - - preventDefault: function () { - this.defaultPrevented = true; - } - }; - - sinon.ProgressEvent = function ProgressEvent(type, progressEventRaw, target) { - this.initEvent(type, false, false, target); - this.loaded = progressEventRaw.loaded || null; - this.total = progressEventRaw.total || null; - this.lengthComputable = !!progressEventRaw.total; - }; - - sinon.ProgressEvent.prototype = new sinon.Event(); - - sinon.ProgressEvent.prototype.constructor = sinon.ProgressEvent; - - sinon.CustomEvent = function CustomEvent(type, customData, target) { - this.initEvent(type, false, false, target); - this.detail = customData.detail || null; - }; - - sinon.CustomEvent.prototype = new sinon.Event(); - - sinon.CustomEvent.prototype.constructor = sinon.CustomEvent; - - sinon.EventTarget = { - addEventListener: function addEventListener(event, listener) { - this.eventListeners = this.eventListeners || {}; - this.eventListeners[event] = this.eventListeners[event] || []; - push.call(this.eventListeners[event], listener); - }, - - removeEventListener: function removeEventListener(event, listener) { - var listeners = this.eventListeners && this.eventListeners[event] || []; - - for (var i = 0, l = listeners.length; i < l; ++i) { - if (listeners[i] == listener) { - return listeners.splice(i, 1); - } - } - }, - - dispatchEvent: function dispatchEvent(event) { - var type = event.type; - var listeners = this.eventListeners && this.eventListeners[type] || []; - - for (var i = 0; i < listeners.length; i++) { - if (typeof listeners[i] == "function") { - listeners[i].call(this, event); - } else { - listeners[i].handleEvent(event); - } - } - - return !!event.defaultPrevented; - } - }; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require) { - var sinon = require("./core"); - makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require); - } else { - makeApi(sinon); - } -}()); - -},{"./core":41}],43:[function(require,module,exports){ -/** - * @depend fake_xdomain_request.js - * @depend fake_xml_http_request.js - * @depend ../format.js - * @depend ../log_error.js - */ -/** - * The Sinon "server" mimics a web server that receives requests from - * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, - * both synchronously and asynchronously. To respond synchronuously, canned - * answers have to be provided upfront. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -if (typeof sinon == "undefined") { - var sinon = {}; -} - -(function () { - var push = [].push; - function F() {} - - function create(proto) { - F.prototype = proto; - return new F(); - } - - function responseArray(handler) { - var response = handler; - - if (Object.prototype.toString.call(handler) != "[object Array]") { - response = [200, {}, handler]; - } - - if (typeof response[2] != "string") { - throw new TypeError("Fake server response body should be string, but was " + - typeof response[2]); - } - - return response; - } - - var wloc = typeof window !== "undefined" ? window.location : {}; - var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); - - function matchOne(response, reqMethod, reqUrl) { - var rmeth = response.method; - var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); - var url = response.url; - var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); - - return matchMethod && matchUrl; - } - - function match(response, request) { - var requestUrl = request.url; - - if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { - requestUrl = requestUrl.replace(rCurrLoc, ""); - } - - if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { - if (typeof response.response == "function") { - var ru = response.url; - var args = [request].concat(ru && typeof ru.exec == "function" ? ru.exec(requestUrl).slice(1) : []); - return response.response.apply(response, args); - } - - return true; - } - - return false; - } - - function makeApi(sinon) { - sinon.fakeServer = { - create: function () { - var server = create(this); - if (!sinon.xhr.supportsCORS) { - this.xhr = sinon.useFakeXDomainRequest(); - } else { - this.xhr = sinon.useFakeXMLHttpRequest(); - } - server.requests = []; - - this.xhr.onCreate = function (xhrObj) { - server.addRequest(xhrObj); - }; - - return server; - }, - - addRequest: function addRequest(xhrObj) { - var server = this; - push.call(this.requests, xhrObj); - - xhrObj.onSend = function () { - server.handleRequest(this); - - if (server.respondImmediately) { - server.respond(); - } else if (server.autoRespond && !server.responding) { - setTimeout(function () { - server.responding = false; - server.respond(); - }, server.autoRespondAfter || 10); - - server.responding = true; - } - }; - }, - - getHTTPMethod: function getHTTPMethod(request) { - if (this.fakeHTTPMethods && /post/i.test(request.method)) { - var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); - return !!matches ? matches[1] : request.method; - } - - return request.method; - }, - - handleRequest: function handleRequest(xhr) { - if (xhr.async) { - if (!this.queue) { - this.queue = []; - } - - push.call(this.queue, xhr); - } else { - this.processRequest(xhr); - } - }, - - log: function log(response, request) { - var str; - - str = "Request:\n" + sinon.format(request) + "\n\n"; - str += "Response:\n" + sinon.format(response) + "\n\n"; - - sinon.log(str); - }, - - respondWith: function respondWith(method, url, body) { - if (arguments.length == 1 && typeof method != "function") { - this.response = responseArray(method); - return; - } - - if (!this.responses) { this.responses = []; } - - if (arguments.length == 1) { - body = method; - url = method = null; - } - - if (arguments.length == 2) { - body = url; - url = method; - method = null; - } - - push.call(this.responses, { - method: method, - url: url, - response: typeof body == "function" ? body : responseArray(body) - }); - }, - - respond: function respond() { - if (arguments.length > 0) { - this.respondWith.apply(this, arguments); - } - - var queue = this.queue || []; - var requests = queue.splice(0, queue.length); - var request; - - while (request = requests.shift()) { - this.processRequest(request); - } - }, - - processRequest: function processRequest(request) { - try { - if (request.aborted) { - return; - } - - var response = this.response || [404, {}, ""]; - - if (this.responses) { - for (var l = this.responses.length, i = l - 1; i >= 0; i--) { - if (match.call(this, this.responses[i], request)) { - response = this.responses[i].response; - break; - } - } - } - - if (request.readyState != 4) { - this.log(response, request); - - request.respond(response[0], response[1], response[2]); - } - } catch (e) { - sinon.logError("Fake server request processing", e); - } - }, - - restore: function restore() { - return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); - } - }; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./core"); - require("./fake_xdomain_request"); - require("./fake_xml_http_request"); - require("../format"); - makeApi(sinon); - module.exports = sinon; - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else { - makeApi(sinon); - } -}()); - -},{"../format":30,"./core":41,"./fake_xdomain_request":46,"./fake_xml_http_request":47}],44:[function(require,module,exports){ -/** - * @depend fake_server.js - * @depend fake_timers.js - */ -/** - * Add-on for sinon.fakeServer that automatically handles a fake timer along with - * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery - * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, - * it polls the object for completion with setInterval. Dispite the direct - * motivation, there is nothing jQuery-specific in this file, so it can be used - * in any environment where the ajax implementation depends on setInterval or - * setTimeout. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function () { - function makeApi(sinon) { - function Server() {} - Server.prototype = sinon.fakeServer; - - sinon.fakeServerWithClock = new Server(); - - sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { - if (xhr.async) { - if (typeof setTimeout.clock == "object") { - this.clock = setTimeout.clock; - } else { - this.clock = sinon.useFakeTimers(); - this.resetClock = true; - } - - if (!this.longestTimeout) { - var clockSetTimeout = this.clock.setTimeout; - var clockSetInterval = this.clock.setInterval; - var server = this; - - this.clock.setTimeout = function (fn, timeout) { - server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); - - return clockSetTimeout.apply(this, arguments); - }; - - this.clock.setInterval = function (fn, timeout) { - server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); - - return clockSetInterval.apply(this, arguments); - }; - } - } - - return sinon.fakeServer.addRequest.call(this, xhr); - }; - - sinon.fakeServerWithClock.respond = function respond() { - var returnVal = sinon.fakeServer.respond.apply(this, arguments); - - if (this.clock) { - this.clock.tick(this.longestTimeout || 0); - this.longestTimeout = 0; - - if (this.resetClock) { - this.clock.restore(); - this.resetClock = false; - } - } - - return returnVal; - }; - - sinon.fakeServerWithClock.restore = function restore() { - if (this.clock) { - this.clock.restore(); - } - - return sinon.fakeServer.restore.apply(this, arguments); - }; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require) { - var sinon = require("./core"); - require("./fake_server"); - require("./fake_timers"); - makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require); - } else { - makeApi(sinon); - } -}()); - -},{"./core":41,"./fake_server":43,"./fake_timers":45}],45:[function(require,module,exports){ -(function (global){ -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -if (typeof sinon == "undefined") { - var sinon = {}; -} - -(function (global) { - function makeApi(sinon, lol) { - var llx = typeof lolex !== "undefined" ? lolex : lol; - - sinon.useFakeTimers = function () { - var now, methods = Array.prototype.slice.call(arguments); - - if (typeof methods[0] === "string") { - now = 0; - } else { - now = methods.shift(); - } - - var clock = llx.install(now || 0, methods); - clock.restore = clock.uninstall; - return clock; - }; - - sinon.clock = { - create: function (now) { - return llx.createClock(now); - } - }; - - sinon.timers = { - setTimeout: setTimeout, - clearTimeout: clearTimeout, - setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined), - clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate : undefined), - setInterval: setInterval, - clearInterval: clearInterval, - Date: Date - }; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, epxorts, module, lolex) { - var sinon = require("./core"); - makeApi(sinon, lolex); - module.exports = sinon; - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module, require("lolex")); - } else { - makeApi(sinon); - } -}(typeof global != "undefined" && typeof global !== "function" ? global : this)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./core":41,"lolex":50}],46:[function(require,module,exports){ -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XDomainRequest object - */ -"use strict"; - -if (typeof sinon == "undefined") { - this.sinon = {}; -} - -// wrapper for global -(function (global) { - var xdr = { XDomainRequest: global.XDomainRequest }; - xdr.GlobalXDomainRequest = global.XDomainRequest; - xdr.supportsXDR = typeof xdr.GlobalXDomainRequest != "undefined"; - xdr.workingXDR = xdr.supportsXDR ? xdr.GlobalXDomainRequest : false; - - function makeApi(sinon) { - sinon.xdr = xdr; - - function FakeXDomainRequest() { - this.readyState = FakeXDomainRequest.UNSENT; - this.requestBody = null; - this.requestHeaders = {}; - this.status = 0; - this.timeout = null; - - if (typeof FakeXDomainRequest.onCreate == "function") { - FakeXDomainRequest.onCreate(this); - } - } - - function verifyState(xdr) { - if (xdr.readyState !== FakeXDomainRequest.OPENED) { - throw new Error("INVALID_STATE_ERR"); - } - - if (xdr.sendFlag) { - throw new Error("INVALID_STATE_ERR"); - } - } - - function verifyRequestSent(xdr) { - if (xdr.readyState == FakeXDomainRequest.UNSENT) { - throw new Error("Request not sent"); - } - if (xdr.readyState == FakeXDomainRequest.DONE) { - throw new Error("Request done"); - } - } - - function verifyResponseBodyType(body) { - if (typeof body != "string") { - var error = new Error("Attempted to respond to fake XDomainRequest with " + - body + ", which is not a string."); - error.name = "InvalidBodyException"; - throw error; - } - } - - sinon.extend(FakeXDomainRequest.prototype, sinon.EventTarget, { - open: function open(method, url) { - this.method = method; - this.url = url; - - this.responseText = null; - this.sendFlag = false; - - this.readyStateChange(FakeXDomainRequest.OPENED); - }, - - readyStateChange: function readyStateChange(state) { - this.readyState = state; - var eventName = ""; - switch (this.readyState) { - case FakeXDomainRequest.UNSENT: - break; - case FakeXDomainRequest.OPENED: - break; - case FakeXDomainRequest.LOADING: - if (this.sendFlag) { - //raise the progress event - eventName = "onprogress"; - } - break; - case FakeXDomainRequest.DONE: - if (this.isTimeout) { - eventName = "ontimeout" - } else if (this.errorFlag || (this.status < 200 || this.status > 299)) { - eventName = "onerror"; - } else { - eventName = "onload" - } - break; - } - - // raising event (if defined) - if (eventName) { - if (typeof this[eventName] == "function") { - try { - this[eventName](); - } catch (e) { - sinon.logError("Fake XHR " + eventName + " handler", e); - } - } - } - }, - - send: function send(data) { - verifyState(this); - - if (!/^(get|head)$/i.test(this.method)) { - this.requestBody = data; - } - this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; - - this.errorFlag = false; - this.sendFlag = true; - this.readyStateChange(FakeXDomainRequest.OPENED); - - if (typeof this.onSend == "function") { - this.onSend(this); - } - }, - - abort: function abort() { - this.aborted = true; - this.responseText = null; - this.errorFlag = true; - - if (this.readyState > sinon.FakeXDomainRequest.UNSENT && this.sendFlag) { - this.readyStateChange(sinon.FakeXDomainRequest.DONE); - this.sendFlag = false; - } - }, - - setResponseBody: function setResponseBody(body) { - verifyRequestSent(this); - verifyResponseBodyType(body); - - var chunkSize = this.chunkSize || 10; - var index = 0; - this.responseText = ""; - - do { - this.readyStateChange(FakeXDomainRequest.LOADING); - this.responseText += body.substring(index, index + chunkSize); - index += chunkSize; - } while (index < body.length); - - this.readyStateChange(FakeXDomainRequest.DONE); - }, - - respond: function respond(status, contentType, body) { - // content-type ignored, since XDomainRequest does not carry this - // we keep the same syntax for respond(...) as for FakeXMLHttpRequest to ease - // test integration across browsers - this.status = typeof status == "number" ? status : 200; - this.setResponseBody(body || ""); - }, - - simulatetimeout: function simulatetimeout() { - this.status = 0; - this.isTimeout = true; - // Access to this should actually throw an error - this.responseText = undefined; - this.readyStateChange(FakeXDomainRequest.DONE); - } - }); - - sinon.extend(FakeXDomainRequest, { - UNSENT: 0, - OPENED: 1, - LOADING: 3, - DONE: 4 - }); - - sinon.useFakeXDomainRequest = function useFakeXDomainRequest() { - sinon.FakeXDomainRequest.restore = function restore(keepOnCreate) { - if (xdr.supportsXDR) { - global.XDomainRequest = xdr.GlobalXDomainRequest; - } - - delete sinon.FakeXDomainRequest.restore; - - if (keepOnCreate !== true) { - delete sinon.FakeXDomainRequest.onCreate; - } - }; - if (xdr.supportsXDR) { - global.XDomainRequest = sinon.FakeXDomainRequest; - } - return sinon.FakeXDomainRequest; - }; - - sinon.FakeXDomainRequest = FakeXDomainRequest; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./core"); - require("../extend"); - require("./event"); - require("../log_error"); - makeApi(sinon); - module.exports = sinon; - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else { - makeApi(sinon); - } -})(this); - -},{"../extend":29,"../log_error":31,"./core":41,"./event":42}],47:[function(require,module,exports){ -(function (global){ -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var sinonXhr = { XMLHttpRequest: global.XMLHttpRequest }; - sinonXhr.GlobalXMLHttpRequest = global.XMLHttpRequest; - sinonXhr.GlobalActiveXObject = global.ActiveXObject; - sinonXhr.supportsActiveX = typeof sinonXhr.GlobalActiveXObject != "undefined"; - sinonXhr.supportsXHR = typeof sinonXhr.GlobalXMLHttpRequest != "undefined"; - sinonXhr.workingXHR = sinonXhr.supportsXHR ? sinonXhr.GlobalXMLHttpRequest : sinonXhr.supportsActiveX - ? function () { return new sinonXhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; - sinonXhr.supportsCORS = sinonXhr.supportsXHR && "withCredentials" in (new sinonXhr.GlobalXMLHttpRequest()); - - /*jsl:ignore*/ - var unsafeHeaders = { - "Accept-Charset": true, - "Accept-Encoding": true, - Connection: true, - "Content-Length": true, - Cookie: true, - Cookie2: true, - "Content-Transfer-Encoding": true, - Date: true, - Expect: true, - Host: true, - "Keep-Alive": true, - Referer: true, - TE: true, - Trailer: true, - "Transfer-Encoding": true, - Upgrade: true, - "User-Agent": true, - Via: true - }; - /*jsl:end*/ - - function FakeXMLHttpRequest() { - this.readyState = FakeXMLHttpRequest.UNSENT; - this.requestHeaders = {}; - this.requestBody = null; - this.status = 0; - this.statusText = ""; - this.upload = new UploadProgress(); - if (sinonXhr.supportsCORS) { - this.withCredentials = false; - } - - var xhr = this; - var events = ["loadstart", "load", "abort", "loadend"]; - - function addEventListener(eventName) { - xhr.addEventListener(eventName, function (event) { - var listener = xhr["on" + eventName]; - - if (listener && typeof listener == "function") { - listener.call(this, event); - } - }); - } - - for (var i = events.length - 1; i >= 0; i--) { - addEventListener(events[i]); - } - - if (typeof FakeXMLHttpRequest.onCreate == "function") { - FakeXMLHttpRequest.onCreate(this); - } - } - - // An upload object is created for each - // FakeXMLHttpRequest and allows upload - // events to be simulated using uploadProgress - // and uploadError. - function UploadProgress() { - this.eventListeners = { - progress: [], - load: [], - abort: [], - error: [] - } - } - - UploadProgress.prototype.addEventListener = function addEventListener(event, listener) { - this.eventListeners[event].push(listener); - }; - - UploadProgress.prototype.removeEventListener = function removeEventListener(event, listener) { - var listeners = this.eventListeners[event] || []; - - for (var i = 0, l = listeners.length; i < l; ++i) { - if (listeners[i] == listener) { - return listeners.splice(i, 1); - } - } - }; - - UploadProgress.prototype.dispatchEvent = function dispatchEvent(event) { - var listeners = this.eventListeners[event.type] || []; - - for (var i = 0, listener; (listener = listeners[i]) != null; i++) { - listener(event); - } - }; - - function verifyState(xhr) { - if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { - throw new Error("INVALID_STATE_ERR"); - } - - if (xhr.sendFlag) { - throw new Error("INVALID_STATE_ERR"); - } - } - - function getHeader(headers, header) { - header = header.toLowerCase(); - - for (var h in headers) { - if (h.toLowerCase() == header) { - return h; - } - } - - return null; - } - - // filtering to enable a white-list version of Sinon FakeXhr, - // where whitelisted requests are passed through to real XHR - function each(collection, callback) { - if (!collection) { - return; - } - - for (var i = 0, l = collection.length; i < l; i += 1) { - callback(collection[i]); - } - } - function some(collection, callback) { - for (var index = 0; index < collection.length; index++) { - if (callback(collection[index]) === true) { - return true; - } - } - return false; - } - // largest arity in XHR is 5 - XHR#open - var apply = function (obj, method, args) { - switch (args.length) { - case 0: return obj[method](); - case 1: return obj[method](args[0]); - case 2: return obj[method](args[0], args[1]); - case 3: return obj[method](args[0], args[1], args[2]); - case 4: return obj[method](args[0], args[1], args[2], args[3]); - case 5: return obj[method](args[0], args[1], args[2], args[3], args[4]); - } - }; - - FakeXMLHttpRequest.filters = []; - FakeXMLHttpRequest.addFilter = function addFilter(fn) { - this.filters.push(fn) - }; - var IE6Re = /MSIE 6/; - FakeXMLHttpRequest.defake = function defake(fakeXhr, xhrArgs) { - var xhr = new sinonXhr.workingXHR(); - each([ - "open", - "setRequestHeader", - "send", - "abort", - "getResponseHeader", - "getAllResponseHeaders", - "addEventListener", - "overrideMimeType", - "removeEventListener" - ], function (method) { - fakeXhr[method] = function () { - return apply(xhr, method, arguments); - }; - }); - - var copyAttrs = function (args) { - each(args, function (attr) { - try { - fakeXhr[attr] = xhr[attr] - } catch (e) { - if (!IE6Re.test(navigator.userAgent)) { - throw e; - } - } - }); - }; - - var stateChange = function stateChange() { - fakeXhr.readyState = xhr.readyState; - if (xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { - copyAttrs(["status", "statusText"]); - } - if (xhr.readyState >= FakeXMLHttpRequest.LOADING) { - copyAttrs(["responseText", "response"]); - } - if (xhr.readyState === FakeXMLHttpRequest.DONE) { - copyAttrs(["responseXML"]); - } - if (fakeXhr.onreadystatechange) { - fakeXhr.onreadystatechange.call(fakeXhr, { target: fakeXhr }); - } - }; - - if (xhr.addEventListener) { - for (var event in fakeXhr.eventListeners) { - if (fakeXhr.eventListeners.hasOwnProperty(event)) { - each(fakeXhr.eventListeners[event], function (handler) { - xhr.addEventListener(event, handler); - }); - } - } - xhr.addEventListener("readystatechange", stateChange); - } else { - xhr.onreadystatechange = stateChange; - } - apply(xhr, "open", xhrArgs); - }; - FakeXMLHttpRequest.useFilters = false; - - function verifyRequestOpened(xhr) { - if (xhr.readyState != FakeXMLHttpRequest.OPENED) { - throw new Error("INVALID_STATE_ERR - " + xhr.readyState); - } - } - - function verifyRequestSent(xhr) { - if (xhr.readyState == FakeXMLHttpRequest.DONE) { - throw new Error("Request done"); - } - } - - function verifyHeadersReceived(xhr) { - if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { - throw new Error("No headers received"); - } - } - - function verifyResponseBodyType(body) { - if (typeof body != "string") { - var error = new Error("Attempted to respond to fake XMLHttpRequest with " + - body + ", which is not a string."); - error.name = "InvalidBodyException"; - throw error; - } - } - - FakeXMLHttpRequest.parseXML = function parseXML(text) { - var xmlDoc; - - if (typeof DOMParser != "undefined") { - var parser = new DOMParser(); - xmlDoc = parser.parseFromString(text, "text/xml"); - } else { - xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); - xmlDoc.async = "false"; - xmlDoc.loadXML(text); - } - - return xmlDoc; - }; - - FakeXMLHttpRequest.statusCodes = { - 100: "Continue", - 101: "Switching Protocols", - 200: "OK", - 201: "Created", - 202: "Accepted", - 203: "Non-Authoritative Information", - 204: "No Content", - 205: "Reset Content", - 206: "Partial Content", - 207: "Multi-Status", - 300: "Multiple Choice", - 301: "Moved Permanently", - 302: "Found", - 303: "See Other", - 304: "Not Modified", - 305: "Use Proxy", - 307: "Temporary Redirect", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 409: "Conflict", - 410: "Gone", - 411: "Length Required", - 412: "Precondition Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Requested Range Not Satisfiable", - 417: "Expectation Failed", - 422: "Unprocessable Entity", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", - 505: "HTTP Version Not Supported" - }; - - function makeApi(sinon) { - sinon.xhr = sinonXhr; - - sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { - async: true, - - open: function open(method, url, async, username, password) { - this.method = method; - this.url = url; - this.async = typeof async == "boolean" ? async : true; - this.username = username; - this.password = password; - this.responseText = null; - this.responseXML = null; - this.requestHeaders = {}; - this.sendFlag = false; - - if (FakeXMLHttpRequest.useFilters === true) { - var xhrArgs = arguments; - var defake = some(FakeXMLHttpRequest.filters, function (filter) { - return filter.apply(this, xhrArgs) - }); - if (defake) { - return FakeXMLHttpRequest.defake(this, arguments); - } - } - this.readyStateChange(FakeXMLHttpRequest.OPENED); - }, - - readyStateChange: function readyStateChange(state) { - this.readyState = state; - - if (typeof this.onreadystatechange == "function") { - try { - this.onreadystatechange(); - } catch (e) { - sinon.logError("Fake XHR onreadystatechange handler", e); - } - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - break; - } - }, - - setRequestHeader: function setRequestHeader(header, value) { - verifyState(this); - - if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { - throw new Error("Refused to set unsafe header \"" + header + "\""); - } - - if (this.requestHeaders[header]) { - this.requestHeaders[header] += "," + value; - } else { - this.requestHeaders[header] = value; - } - }, - - // Helps testing - setResponseHeaders: function setResponseHeaders(headers) { - verifyRequestOpened(this); - this.responseHeaders = {}; - - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - this.responseHeaders[header] = headers[header]; - } - } - - if (this.async) { - this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); - } else { - this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; - } - }, - - // Currently treats ALL data as a DOMString (i.e. no Document) - send: function send(data) { - verifyState(this); - - if (!/^(get|head)$/i.test(this.method)) { - var contentType = getHeader(this.requestHeaders, "Content-Type"); - if (this.requestHeaders[contentType]) { - var value = this.requestHeaders[contentType].split(";"); - this.requestHeaders[contentType] = value[0] + ";charset=utf-8"; - } else if (!(data instanceof FormData)) { - this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; - } - - this.requestBody = data; - } - - this.errorFlag = false; - this.sendFlag = this.async; - this.readyStateChange(FakeXMLHttpRequest.OPENED); - - if (typeof this.onSend == "function") { - this.onSend(this); - } - - this.dispatchEvent(new sinon.Event("loadstart", false, false, this)); - }, - - abort: function abort() { - this.aborted = true; - this.responseText = null; - this.errorFlag = true; - this.requestHeaders = {}; - - if (this.readyState > FakeXMLHttpRequest.UNSENT && this.sendFlag) { - this.readyStateChange(FakeXMLHttpRequest.DONE); - this.sendFlag = false; - } - - this.readyState = FakeXMLHttpRequest.UNSENT; - - this.dispatchEvent(new sinon.Event("abort", false, false, this)); - - this.upload.dispatchEvent(new sinon.Event("abort", false, false, this)); - - if (typeof this.onerror === "function") { - this.onerror(); - } - }, - - getResponseHeader: function getResponseHeader(header) { - if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { - return null; - } - - if (/^Set-Cookie2?$/i.test(header)) { - return null; - } - - header = getHeader(this.responseHeaders, header); - - return this.responseHeaders[header] || null; - }, - - getAllResponseHeaders: function getAllResponseHeaders() { - if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { - return ""; - } - - var headers = ""; - - for (var header in this.responseHeaders) { - if (this.responseHeaders.hasOwnProperty(header) && - !/^Set-Cookie2?$/i.test(header)) { - headers += header + ": " + this.responseHeaders[header] + "\r\n"; - } - } - - return headers; - }, - - setResponseBody: function setResponseBody(body) { - verifyRequestSent(this); - verifyHeadersReceived(this); - verifyResponseBodyType(body); - - var chunkSize = this.chunkSize || 10; - var index = 0; - this.responseText = ""; - - do { - if (this.async) { - this.readyStateChange(FakeXMLHttpRequest.LOADING); - } - - this.responseText += body.substring(index, index + chunkSize); - index += chunkSize; - } while (index < body.length); - - var type = this.getResponseHeader("Content-Type"); - - if (this.responseText && - (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { - try { - this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); - } catch (e) { - // Unable to parse XML - no biggie - } - } - - this.readyStateChange(FakeXMLHttpRequest.DONE); - }, - - respond: function respond(status, headers, body) { - this.status = typeof status == "number" ? status : 200; - this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; - this.setResponseHeaders(headers || {}); - this.setResponseBody(body || ""); - }, - - uploadProgress: function uploadProgress(progressEventRaw) { - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw)); - } - }, - - downloadProgress: function downloadProgress(progressEventRaw) { - if (supportsProgress) { - this.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw)); - } - }, - - uploadError: function uploadError(error) { - if (supportsCustomEvent) { - this.upload.dispatchEvent(new sinon.CustomEvent("error", {detail: error})); - } - } - }); - - sinon.extend(FakeXMLHttpRequest, { - UNSENT: 0, - OPENED: 1, - HEADERS_RECEIVED: 2, - LOADING: 3, - DONE: 4 - }); - - sinon.useFakeXMLHttpRequest = function () { - FakeXMLHttpRequest.restore = function restore(keepOnCreate) { - if (sinonXhr.supportsXHR) { - global.XMLHttpRequest = sinonXhr.GlobalXMLHttpRequest; - } - - if (sinonXhr.supportsActiveX) { - global.ActiveXObject = sinonXhr.GlobalActiveXObject; - } - - delete FakeXMLHttpRequest.restore; - - if (keepOnCreate !== true) { - delete FakeXMLHttpRequest.onCreate; - } - }; - if (sinonXhr.supportsXHR) { - global.XMLHttpRequest = FakeXMLHttpRequest; - } - - if (sinonXhr.supportsActiveX) { - global.ActiveXObject = function ActiveXObject(objId) { - if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { - - return new FakeXMLHttpRequest(); - } - - return new sinonXhr.GlobalActiveXObject(objId); - }; - } - - return FakeXMLHttpRequest; - }; - - sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./core"); - require("../extend"); - require("./event"); - require("../log_error"); - makeApi(sinon); - module.exports = sinon; - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (typeof sinon === "undefined") { - return; - } else { - makeApi(sinon); - } - -})(typeof global !== "undefined" ? global : this); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../extend":29,"../log_error":31,"./core":41,"./event":42}],48:[function(require,module,exports){ -(function (global){ -((typeof define === "function" && define.amd && function (m) { - define("formatio", ["samsam"], m); -}) || (typeof module === "object" && function (m) { - module.exports = m(require("samsam")); -}) || function (m) { this.formatio = m(this.samsam); } -)(function (samsam) { - "use strict"; - - var formatio = { - excludeConstructors: ["Object", /^.$/], - quoteStrings: true, - limitChildrenCount: 0 - }; - - var hasOwn = Object.prototype.hasOwnProperty; - - var specialObjects = []; - if (typeof global !== "undefined") { - specialObjects.push({ object: global, value: "[object global]" }); - } - if (typeof document !== "undefined") { - specialObjects.push({ - object: document, - value: "[object HTMLDocument]" - }); - } - if (typeof window !== "undefined") { - specialObjects.push({ object: window, value: "[object Window]" }); - } - - function functionName(func) { - if (!func) { return ""; } - if (func.displayName) { return func.displayName; } - if (func.name) { return func.name; } - var matches = func.toString().match(/function\s+([^\(]+)/m); - return (matches && matches[1]) || ""; - } - - function constructorName(f, object) { - var name = functionName(object && object.constructor); - var excludes = f.excludeConstructors || - formatio.excludeConstructors || []; - - var i, l; - for (i = 0, l = excludes.length; i < l; ++i) { - if (typeof excludes[i] === "string" && excludes[i] === name) { - return ""; - } else if (excludes[i].test && excludes[i].test(name)) { - return ""; - } - } - - return name; - } - - function isCircular(object, objects) { - if (typeof object !== "object") { return false; } - var i, l; - for (i = 0, l = objects.length; i < l; ++i) { - if (objects[i] === object) { return true; } - } - return false; - } - - function ascii(f, object, processed, indent) { - if (typeof object === "string") { - var qs = f.quoteStrings; - var quote = typeof qs !== "boolean" || qs; - return processed || quote ? '"' + object + '"' : object; - } - - if (typeof object === "function" && !(object instanceof RegExp)) { - return ascii.func(object); - } - - processed = processed || []; - - if (isCircular(object, processed)) { return "[Circular]"; } - - if (Object.prototype.toString.call(object) === "[object Array]") { - return ascii.array.call(f, object, processed); - } - - if (!object) { return String((1/object) === -Infinity ? "-0" : object); } - if (samsam.isElement(object)) { return ascii.element(object); } - - if (typeof object.toString === "function" && - object.toString !== Object.prototype.toString) { - return object.toString(); - } - - var i, l; - for (i = 0, l = specialObjects.length; i < l; i++) { - if (object === specialObjects[i].object) { - return specialObjects[i].value; - } - } - - return ascii.object.call(f, object, processed, indent); - } - - ascii.func = function (func) { - return "function " + functionName(func) + "() {}"; - }; - - ascii.array = function (array, processed) { - processed = processed || []; - processed.push(array); - var pieces = []; - var i, l; - l = (this.limitChildrenCount > 0) ? - Math.min(this.limitChildrenCount, array.length) : array.length; - - for (i = 0; i < l; ++i) { - pieces.push(ascii(this, array[i], processed)); - } - - if(l < array.length) - pieces.push("[... " + (array.length - l) + " more elements]"); - - return "[" + pieces.join(", ") + "]"; - }; - - ascii.object = function (object, processed, indent) { - processed = processed || []; - processed.push(object); - indent = indent || 0; - var pieces = [], properties = samsam.keys(object).sort(); - var length = 3; - var prop, str, obj, i, k, l; - l = (this.limitChildrenCount > 0) ? - Math.min(this.limitChildrenCount, properties.length) : properties.length; - - for (i = 0; i < l; ++i) { - prop = properties[i]; - obj = object[prop]; - - if (isCircular(obj, processed)) { - str = "[Circular]"; - } else { - str = ascii(this, obj, processed, indent + 2); - } - - str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; - length += str.length; - pieces.push(str); - } - - var cons = constructorName(this, object); - var prefix = cons ? "[" + cons + "] " : ""; - var is = ""; - for (i = 0, k = indent; i < k; ++i) { is += " "; } - - if(l < properties.length) - pieces.push("[... " + (properties.length - l) + " more elements]"); - - if (length + indent > 80) { - return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + - is + "}"; - } - return prefix + "{ " + pieces.join(", ") + " }"; - }; - - ascii.element = function (element) { - var tagName = element.tagName.toLowerCase(); - var attrs = element.attributes, attr, pairs = [], attrName, i, l, val; - - for (i = 0, l = attrs.length; i < l; ++i) { - attr = attrs.item(i); - attrName = attr.nodeName.toLowerCase().replace("html:", ""); - val = attr.nodeValue; - if (attrName !== "contenteditable" || val !== "inherit") { - if (!!val) { pairs.push(attrName + "=\"" + val + "\""); } - } - } - - var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); - var content = element.innerHTML; - - if (content.length > 20) { - content = content.substr(0, 20) + "[...]"; - } - - var res = formatted + pairs.join(" ") + ">" + content + - ""; - - return res.replace(/ contentEditable="inherit"/, ""); - }; - - function Formatio(options) { - for (var opt in options) { - this[opt] = options[opt]; - } - } - - Formatio.prototype = { - functionName: functionName, - - configure: function (options) { - return new Formatio(options); - }, - - constructorName: function (object) { - return constructorName(this, object); - }, - - ascii: function (object, processed, indent) { - return ascii(this, object, processed, indent); - } - }; - - return Formatio.prototype; -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"samsam":49}],49:[function(require,module,exports){ -((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) || - (typeof module === "object" && - function (m) { module.exports = m(); }) || // Node - function (m) { this.samsam = m(); } // Browser globals -)(function () { - var o = Object.prototype; - var div = typeof document !== "undefined" && document.createElement("div"); - - function isNaN(value) { - // Unlike global isNaN, this avoids type coercion - // typeof check avoids IE host object issues, hat tip to - // lodash - var val = value; // JsLint thinks value !== value is "weird" - return typeof value === "number" && value !== val; - } - - function getClass(value) { - // Returns the internal [[Class]] by calling Object.prototype.toString - // with the provided value as this. Return value is a string, naming the - // internal class, e.g. "Array" - return o.toString.call(value).split(/[ \]]/)[1]; - } - - /** - * @name samsam.isArguments - * @param Object object - * - * Returns ``true`` if ``object`` is an ``arguments`` object, - * ``false`` otherwise. - */ - function isArguments(object) { - if (getClass(object) === 'Arguments') { return true; } - if (typeof object !== "object" || typeof object.length !== "number" || - getClass(object) === "Array") { - return false; - } - if (typeof object.callee == "function") { return true; } - try { - object[object.length] = 6; - delete object[object.length]; - } catch (e) { - return true; - } - return false; - } - - /** - * @name samsam.isElement - * @param Object object - * - * Returns ``true`` if ``object`` is a DOM element node. Unlike - * Underscore.js/lodash, this function will return ``false`` if ``object`` - * is an *element-like* object, i.e. a regular object with a ``nodeType`` - * property that holds the value ``1``. - */ - function isElement(object) { - if (!object || object.nodeType !== 1 || !div) { return false; } - try { - object.appendChild(div); - object.removeChild(div); - } catch (e) { - return false; - } - return true; - } - - /** - * @name samsam.keys - * @param Object object - * - * Return an array of own property names. - */ - function keys(object) { - var ks = [], prop; - for (prop in object) { - if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); } - } - return ks; - } - - /** - * @name samsam.isDate - * @param Object value - * - * Returns true if the object is a ``Date``, or *date-like*. Duck typing - * of date objects work by checking that the object has a ``getTime`` - * function whose return value equals the return value from the object's - * ``valueOf``. - */ - function isDate(value) { - return typeof value.getTime == "function" && - value.getTime() == value.valueOf(); - } - - /** - * @name samsam.isNegZero - * @param Object value - * - * Returns ``true`` if ``value`` is ``-0``. - */ - function isNegZero(value) { - return value === 0 && 1 / value === -Infinity; - } - - /** - * @name samsam.equal - * @param Object obj1 - * @param Object obj2 - * - * Returns ``true`` if two objects are strictly equal. Compared to - * ``===`` there are two exceptions: - * - * - NaN is considered equal to NaN - * - -0 and +0 are not considered equal - */ - function identical(obj1, obj2) { - if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) { - return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2); - } - } - - - /** - * @name samsam.deepEqual - * @param Object obj1 - * @param Object obj2 - * - * Deep equal comparison. Two values are "deep equal" if: - * - * - They are equal, according to samsam.identical - * - They are both date objects representing the same time - * - They are both arrays containing elements that are all deepEqual - * - They are objects with the same set of properties, and each property - * in ``obj1`` is deepEqual to the corresponding property in ``obj2`` - * - * Supports cyclic objects. - */ - function deepEqualCyclic(obj1, obj2) { - - // used for cyclic comparison - // contain already visited objects - var objects1 = [], - objects2 = [], - // contain pathes (position in the object structure) - // of the already visited objects - // indexes same as in objects arrays - paths1 = [], - paths2 = [], - // contains combinations of already compared objects - // in the manner: { "$1['ref']$2['ref']": true } - compared = {}; - - /** - * used to check, if the value of a property is an object - * (cyclic logic is only needed for objects) - * only needed for cyclic logic - */ - function isObject(value) { - - if (typeof value === 'object' && value !== null && - !(value instanceof Boolean) && - !(value instanceof Date) && - !(value instanceof Number) && - !(value instanceof RegExp) && - !(value instanceof String)) { - - return true; - } - - return false; - } - - /** - * returns the index of the given object in the - * given objects array, -1 if not contained - * only needed for cyclic logic - */ - function getIndex(objects, obj) { - - var i; - for (i = 0; i < objects.length; i++) { - if (objects[i] === obj) { - return i; - } - } - - return -1; - } - - // does the recursion for the deep equal check - return (function deepEqual(obj1, obj2, path1, path2) { - var type1 = typeof obj1; - var type2 = typeof obj2; - - // == null also matches undefined - if (obj1 === obj2 || - isNaN(obj1) || isNaN(obj2) || - obj1 == null || obj2 == null || - type1 !== "object" || type2 !== "object") { - - return identical(obj1, obj2); - } - - // Elements are only equal if identical(expected, actual) - if (isElement(obj1) || isElement(obj2)) { return false; } - - var isDate1 = isDate(obj1), isDate2 = isDate(obj2); - if (isDate1 || isDate2) { - if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) { - return false; - } - } - - if (obj1 instanceof RegExp && obj2 instanceof RegExp) { - if (obj1.toString() !== obj2.toString()) { return false; } - } - - var class1 = getClass(obj1); - var class2 = getClass(obj2); - var keys1 = keys(obj1); - var keys2 = keys(obj2); - - if (isArguments(obj1) || isArguments(obj2)) { - if (obj1.length !== obj2.length) { return false; } - } else { - if (type1 !== type2 || class1 !== class2 || - keys1.length !== keys2.length) { - return false; - } - } - - var key, i, l, - // following vars are used for the cyclic logic - value1, value2, - isObject1, isObject2, - index1, index2, - newPath1, newPath2; - - for (i = 0, l = keys1.length; i < l; i++) { - key = keys1[i]; - if (!o.hasOwnProperty.call(obj2, key)) { - return false; - } - - // Start of the cyclic logic - - value1 = obj1[key]; - value2 = obj2[key]; - - isObject1 = isObject(value1); - isObject2 = isObject(value2); - - // determine, if the objects were already visited - // (it's faster to check for isObject first, than to - // get -1 from getIndex for non objects) - index1 = isObject1 ? getIndex(objects1, value1) : -1; - index2 = isObject2 ? getIndex(objects2, value2) : -1; - - // determine the new pathes of the objects - // - for non cyclic objects the current path will be extended - // by current property name - // - for cyclic objects the stored path is taken - newPath1 = index1 !== -1 - ? paths1[index1] - : path1 + '[' + JSON.stringify(key) + ']'; - newPath2 = index2 !== -1 - ? paths2[index2] - : path2 + '[' + JSON.stringify(key) + ']'; - - // stop recursion if current objects are already compared - if (compared[newPath1 + newPath2]) { - return true; - } - - // remember the current objects and their pathes - if (index1 === -1 && isObject1) { - objects1.push(value1); - paths1.push(newPath1); - } - if (index2 === -1 && isObject2) { - objects2.push(value2); - paths2.push(newPath2); - } - - // remember that the current objects are already compared - if (isObject1 && isObject2) { - compared[newPath1 + newPath2] = true; - } - - // End of cyclic logic - - // neither value1 nor value2 is a cycle - // continue with next level - if (!deepEqual(value1, value2, newPath1, newPath2)) { - return false; - } - } - - return true; - - }(obj1, obj2, '$1', '$2')); - } - - var match; - - function arrayContains(array, subset) { - if (subset.length === 0) { return true; } - var i, l, j, k; - for (i = 0, l = array.length; i < l; ++i) { - if (match(array[i], subset[0])) { - for (j = 0, k = subset.length; j < k; ++j) { - if (!match(array[i + j], subset[j])) { return false; } - } - return true; - } - } - return false; - } - - /** - * @name samsam.match - * @param Object object - * @param Object matcher - * - * Compare arbitrary value ``object`` with matcher. - */ - match = function match(object, matcher) { - if (matcher && typeof matcher.test === "function") { - return matcher.test(object); - } - - if (typeof matcher === "function") { - return matcher(object) === true; - } - - if (typeof matcher === "string") { - matcher = matcher.toLowerCase(); - var notNull = typeof object === "string" || !!object; - return notNull && - (String(object)).toLowerCase().indexOf(matcher) >= 0; - } - - if (typeof matcher === "number") { - return matcher === object; - } - - if (typeof matcher === "boolean") { - return matcher === object; - } - - if (typeof(matcher) === "undefined") { - return typeof(object) === "undefined"; - } - - if (matcher === null) { - return object === null; - } - - if (getClass(object) === "Array" && getClass(matcher) === "Array") { - return arrayContains(object, matcher); - } - - if (matcher && typeof matcher === "object") { - if (matcher === object) { - return true; - } - var prop; - for (prop in matcher) { - var value = object[prop]; - if (typeof value === "undefined" && - typeof object.getAttribute === "function") { - value = object.getAttribute(prop); - } - if (matcher[prop] === null || typeof matcher[prop] === 'undefined') { - if (value !== matcher[prop]) { - return false; - } - } else if (typeof value === "undefined" || !match(value, matcher[prop])) { - return false; - } - } - return true; - } - - throw new Error("Matcher was not a string, a number, a " + - "function, a boolean or an object"); - }; - - return { - isArguments: isArguments, - isElement: isElement, - isDate: isDate, - isNegZero: isNegZero, - identical: identical, - deepEqual: deepEqualCyclic, - match: match, - keys: keys - }; -}); - -},{}],50:[function(require,module,exports){ -(function (global){ -/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ -/*global global*/ -/** - * @author Christian Johansen (christian@cjohansen.no) and contributors - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -// node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref() -// browsers, a number. -// see https://github.com/cjohansen/Sinon.JS/pull/436 -var timeoutResult = setTimeout(function() {}, 0); -var addTimerReturnsObject = typeof timeoutResult === "object"; -clearTimeout(timeoutResult); - -var NativeDate = Date; -var id = 1; - -/** - * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into - * number of milliseconds. This is used to support human-readable strings passed - * to clock.tick() - */ -function parseTime(str) { - if (!str) { - return 0; - } - - var strings = str.split(":"); - var l = strings.length, i = l; - var ms = 0, parsed; - - if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { - throw new Error("tick only understands numbers and 'h:m:s'"); - } - - while (i--) { - parsed = parseInt(strings[i], 10); - - if (parsed >= 60) { - throw new Error("Invalid time " + str); - } - - ms += parsed * Math.pow(60, (l - i - 1)); - } - - return ms * 1000; -} - -/** - * Used to grok the `now` parameter to createClock. - */ -function getEpoch(epoch) { - if (!epoch) { return 0; } - if (typeof epoch.getTime === "function") { return epoch.getTime(); } - if (typeof epoch === "number") { return epoch; } - throw new TypeError("now should be milliseconds since UNIX epoch"); -} - -function inRange(from, to, timer) { - return timer && timer.callAt >= from && timer.callAt <= to; -} - -function mirrorDateProperties(target, source) { - if (source.now) { - target.now = function now() { - return target.clock.now; - }; - } else { - delete target.now; - } - - if (source.toSource) { - target.toSource = function toSource() { - return source.toSource(); - }; - } else { - delete target.toSource; - } - - target.toString = function toString() { - return source.toString(); - }; - - target.prototype = source.prototype; - target.parse = source.parse; - target.UTC = source.UTC; - target.prototype.toUTCString = source.prototype.toUTCString; - - for (var prop in source) { - if (source.hasOwnProperty(prop)) { - target[prop] = source[prop]; - } - } - - return target; -} - -function createDate() { - function ClockDate(year, month, date, hour, minute, second, ms) { - // Defensive and verbose to avoid potential harm in passing - // explicit undefined when user does not pass argument - switch (arguments.length) { - case 0: - return new NativeDate(ClockDate.clock.now); - case 1: - return new NativeDate(year); - case 2: - return new NativeDate(year, month); - case 3: - return new NativeDate(year, month, date); - case 4: - return new NativeDate(year, month, date, hour); - case 5: - return new NativeDate(year, month, date, hour, minute); - case 6: - return new NativeDate(year, month, date, hour, minute, second); - default: - return new NativeDate(year, month, date, hour, minute, second, ms); - } - } - - return mirrorDateProperties(ClockDate, NativeDate); -} - -function addTimer(clock, timer) { - if (typeof timer.func === "undefined") { - throw new Error("Callback must be provided to timer calls"); - } - - if (!clock.timers) { - clock.timers = {}; - } - - timer.id = id++; - timer.createdAt = clock.now; - timer.callAt = clock.now + (timer.delay || 0); - - clock.timers[timer.id] = timer; - - if (addTimerReturnsObject) { - return { - id: timer.id, - ref: function() {}, - unref: function() {} - }; - } - else { - return timer.id; - } -} - -function firstTimerInRange(clock, from, to) { - var timers = clock.timers, timer = null; - - for (var id in timers) { - if (!inRange(from, to, timers[id])) { - continue; - } - - if (!timer || ~compareTimers(timer, timers[id])) { - timer = timers[id]; - } - } - - return timer; -} - -function compareTimers(a, b) { - // Sort first by absolute timing - if (a.callAt < b.callAt) { - return -1; - } - if (a.callAt > b.callAt) { - return 1; - } - - // Sort next by immediate, immediate timers take precedence - if (a.immediate && !b.immediate) { - return -1; - } - if (!a.immediate && b.immediate) { - return 1; - } - - // Sort next by creation time, earlier-created timers take precedence - if (a.createdAt < b.createdAt) { - return -1; - } - if (a.createdAt > b.createdAt) { - return 1; - } - - // Sort next by id, lower-id timers take precedence - if (a.id < b.id) { - return -1; - } - if (a.id > b.id) { - return 1; - } - - // As timer ids are unique, no fallback `0` is necessary -} - -function callTimer(clock, timer) { - if (typeof timer.interval == "number") { - clock.timers[timer.id].callAt += timer.interval; - } else { - delete clock.timers[timer.id]; - } - - try { - if (typeof timer.func == "function") { - timer.func.apply(null, timer.args); - } else { - eval(timer.func); - } - } catch (e) { - var exception = e; - } - - if (!clock.timers[timer.id]) { - if (exception) { - throw exception; - } - return; - } - - if (exception) { - throw exception; - } -} - -function uninstall(clock, target) { - var method; - - for (var i = 0, l = clock.methods.length; i < l; i++) { - method = clock.methods[i]; - - if (target[method].hadOwnProperty) { - target[method] = clock["_" + method]; - } else { - try { - delete target[method]; - } catch (e) {} - } - } - - // Prevent multiple executions which will completely remove these props - clock.methods = []; -} - -function hijackMethod(target, method, clock) { - clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method); - clock["_" + method] = target[method]; - - if (method == "Date") { - var date = mirrorDateProperties(clock[method], target[method]); - target[method] = date; - } else { - target[method] = function () { - return clock[method].apply(clock, arguments); - }; - - for (var prop in clock[method]) { - if (clock[method].hasOwnProperty(prop)) { - target[method][prop] = clock[method][prop]; - } - } - } - - target[method].clock = clock; -} - -var timers = { - setTimeout: setTimeout, - clearTimeout: clearTimeout, - setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined), - clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate: undefined), - setInterval: setInterval, - clearInterval: clearInterval, - Date: Date -}; - -var keys = Object.keys || function (obj) { - var ks = []; - for (var key in obj) { - ks.push(key); - } - return ks; -}; - -exports.timers = timers; - -var createClock = exports.createClock = function (now) { - var clock = { - now: getEpoch(now), - timeouts: {}, - Date: createDate() - }; - - clock.Date.clock = clock; - - clock.setTimeout = function setTimeout(func, timeout) { - return addTimer(clock, { - func: func, - args: Array.prototype.slice.call(arguments, 2), - delay: timeout - }); - }; - - clock.clearTimeout = function clearTimeout(timerId) { - if (!timerId) { - // null appears to be allowed in most browsers, and appears to be - // relied upon by some libraries, like Bootstrap carousel - return; - } - if (!clock.timers) { - clock.timers = []; - } - // in Node, timerId is an object with .ref()/.unref(), and - // its .id field is the actual timer id. - if (typeof timerId === "object") { - timerId = timerId.id - } - if (timerId in clock.timers) { - delete clock.timers[timerId]; - } - }; - - clock.setInterval = function setInterval(func, timeout) { - return addTimer(clock, { - func: func, - args: Array.prototype.slice.call(arguments, 2), - delay: timeout, - interval: timeout - }); - }; - - clock.clearInterval = function clearInterval(timerId) { - clock.clearTimeout(timerId); - }; - - clock.setImmediate = function setImmediate(func) { - return addTimer(clock, { - func: func, - args: Array.prototype.slice.call(arguments, 1), - immediate: true - }); - }; - - clock.clearImmediate = function clearImmediate(timerId) { - clock.clearTimeout(timerId); - }; - - clock.tick = function tick(ms) { - ms = typeof ms == "number" ? ms : parseTime(ms); - var tickFrom = clock.now, tickTo = clock.now + ms, previous = clock.now; - var timer = firstTimerInRange(clock, tickFrom, tickTo); - - var firstException; - while (timer && tickFrom <= tickTo) { - if (clock.timers[timer.id]) { - tickFrom = clock.now = timer.callAt; - try { - callTimer(clock, timer); - } catch (e) { - firstException = firstException || e; - } - } - - timer = firstTimerInRange(clock, previous, tickTo); - previous = tickFrom; - } - - clock.now = tickTo; - - if (firstException) { - throw firstException; - } - - return clock.now; - }; - - clock.reset = function reset() { - clock.timers = {}; - }; - - return clock; -}; - -exports.install = function install(target, now, toFake) { - if (typeof target === "number") { - toFake = now; - now = target; - target = null; - } - - if (!target) { - target = global; - } - - var clock = createClock(now); - - clock.uninstall = function () { - uninstall(clock, target); - }; - - clock.methods = toFake || []; - - if (clock.methods.length === 0) { - clock.methods = keys(timers); - } - - for (var i = 0, l = clock.methods.length; i < l; i++) { - hijackMethod(target, clock.methods[i], clock); - } - - return clock; -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],51:[function(require,module,exports){ -(function (process,global){ -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } - - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$toString = {}.toString; - var lib$es6$promise$asap$$vertxNext; - function lib$es6$promise$asap$$asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - lib$es6$promise$asap$$scheduleFlush(); - } - } - - var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function() { - nextTick(lib$es6$promise$asap$$flush); - }; - } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } - - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFullfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$default(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } - } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - var then = lib$es6$promise$$internal$$getThen(maybeThenable); - - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } - } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); - } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } - - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } - } - } else { - lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); - } - } - - lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { - return lib$es6$promise$utils$$isArray(input); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { - this._result = new Array(this.length); - }; - - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (lib$es6$promise$utils$$isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - enumerator._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, enumerator._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } - - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; - } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; - } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - var lib$es6$promise$promise$$counter = 0; - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - if (!lib$es6$promise$utils$$isFunction(resolver)) { - lib$es6$promise$promise$$needsResolver(); - } - - if (!(this instanceof lib$es6$promise$promise$$Promise)) { - lib$es6$promise$promise$$needsNew(); - } - - lib$es6$promise$$internal$$initializePromise(this, resolver); - } - } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$default(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; - } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; - } - - lib$es6$promise$polyfill$$default(); -}).call(this); - -//# sourceMappingURL=es6-promise.js.map -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":4}],52:[function(require,module,exports){ -(function (global){ -/*global describe, specify, it, assert */ - -if (typeof Object.getPrototypeOf !== "function") { - Object.getPrototypeOf = "".__proto__ === String.prototype - ? function (object) { - return object.__proto__; - } - : function (object) { - // May break if the constructor has been tampered with - return object.constructor.prototype; - }; -} - -function keysOf(object) { - var results = []; - - for (var key in object) { - if (object.hasOwnProperty(key)) { - results.push(key); - } - } - - return results; -} - -var g = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this; -var Promise = g.adapter.Promise; -var assert = require('assert'); - -function objectEquals(obj1, obj2) { - for (var i in obj1) { - if (obj1.hasOwnProperty(i)) { - if (!obj2.hasOwnProperty(i)) return false; - if (obj1[i] != obj2[i]) return false; - } - } - for (var i in obj2) { - if (obj2.hasOwnProperty(i)) { - if (!obj1.hasOwnProperty(i)) return false; - if (obj1[i] != obj2[i]) return false; - } - } - return true; -} - -describe("extensions", function() { - describe("Promise constructor", function() { - it('should exist and have length 1', function() { - assert(Promise); - assert.equal(Promise.length, 1); - }); - - it('should fulfill if `resolve` is called with a value', function(done) { - var promise = new Promise(function(resolve) { resolve('value'); }); - - promise.then(function(value) { - assert.equal(value, 'value'); - done(); - }); - }); - - it('should reject if `reject` is called with a reason', function(done) { - var promise = new Promise(function(resolve, reject) { reject('reason'); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'reason'); - done(); - }); - }); - - it('should be a constructor', function() { - var promise = new Promise(function() {}); - - assert.equal(Object.getPrototypeOf(promise), Promise.prototype, '[[Prototype]] equals Promise.prototype'); - assert.equal(promise.constructor, Promise, 'constructor property of instances is set correctly'); - assert.equal(Promise.prototype.constructor, Promise, 'constructor property of prototype is set correctly'); - }); - - it('should NOT work without `new`', function() { - assert.throws(function(){ - Promise(function(resolve) { resolve('value'); }); - }, TypeError) - }); - - it('should throw a `TypeError` if not given a function', function() { - assert.throws(function () { - new Promise(); - }, TypeError); - - assert.throws(function () { - new Promise({}); - }, TypeError); - - assert.throws(function () { - new Promise('boo!'); - }, TypeError); - }); - - it('should reject on resolver exception', function(done) { - new Promise(function() { - throw 'error'; - }).then(null, function(e) { - assert.equal(e, 'error'); - done(); - }); - }); - - it('should not resolve multiple times', function(done) { - var resolver, rejector, fulfilled = 0, rejected = 0; - var thenable = { - then: function(resolve, reject) { - resolver = resolve; - rejector = reject; - } - }; - - var promise = new Promise(function(resolve) { - resolve(1); - }); - - promise.then(function(value){ - return thenable; - }).then(function(value){ - fulfilled++; - }, function(reason) { - rejected++; - }); - - setTimeout(function() { - resolver(1); - resolver(1); - rejector(1); - rejector(1); - - setTimeout(function() { - assert.equal(fulfilled, 1); - assert.equal(rejected, 0); - done(); - }, 20); - }, 20); - - }); - - describe('assimilation', function() { - it('should assimilate if `resolve` is called with a fulfilled promise', function(done) { - var originalPromise = new Promise(function(resolve) { resolve('original value'); }); - var promise = new Promise(function(resolve) { resolve(originalPromise); }); - - promise.then(function(value) { - assert.equal(value, 'original value'); - done(); - }); - }); - - it('should assimilate if `resolve` is called with a rejected promise', function(done) { - var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); - var promise = new Promise(function(resolve) { resolve(originalPromise); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'original reason'); - done(); - }); - }); - - it('should assimilate if `resolve` is called with a fulfilled thenable', function(done) { - var originalThenable = { - then: function (onFulfilled) { - setTimeout(function() { onFulfilled('original value'); }, 0); - } - }; - var promise = new Promise(function(resolve) { resolve(originalThenable); }); - - promise.then(function(value) { - assert.equal(value, 'original value'); - done(); - }); - }); - - it('should assimilate if `resolve` is called with a rejected thenable', function(done) { - var originalThenable = { - then: function (onFulfilled, onRejected) { - setTimeout(function() { onRejected('original reason'); }, 0); - } - }; - var promise = new Promise(function(resolve) { resolve(originalThenable); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'original reason'); - done(); - }); - }); - - - it('should assimilate two levels deep, for fulfillment of self fulfilling promises', function(done) { - var originalPromise, promise; - originalPromise = new Promise(function(resolve) { - setTimeout(function() { - resolve(originalPromise); - }, 0) - }); - - promise = new Promise(function(resolve) { - setTimeout(function() { - resolve(originalPromise); - }, 0); - }); - - promise.then(function(value) { - assert(false); - done(); - })['catch'](function(reason) { - assert.equal(reason.message, "You cannot resolve a promise with itself"); - assert(reason instanceof TypeError); - done(); - }); - }); - - it('should assimilate two levels deep, for fulfillment', function(done) { - var originalPromise = new Promise(function(resolve) { resolve('original value'); }); - var nextPromise = new Promise(function(resolve) { resolve(originalPromise); }); - var promise = new Promise(function(resolve) { resolve(nextPromise); }); - - promise.then(function(value) { - assert.equal(value, 'original value'); - done(); - }); - }); - - it('should assimilate two levels deep, for rejection', function(done) { - var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); - var nextPromise = new Promise(function(resolve) { resolve(originalPromise); }); - var promise = new Promise(function(resolve) { resolve(nextPromise); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'original reason'); - done(); - }); - }); - - it('should assimilate three levels deep, mixing thenables and promises (fulfilled case)', function(done) { - var originalPromise = new Promise(function(resolve) { resolve('original value'); }); - var intermediateThenable = { - then: function (onFulfilled) { - setTimeout(function() { onFulfilled(originalPromise); }, 0); - } - }; - var promise = new Promise(function(resolve) { resolve(intermediateThenable); }); - - promise.then(function(value) { - assert.equal(value, 'original value'); - done(); - }); - }); - - it('should assimilate three levels deep, mixing thenables and promises (rejected case)', function(done) { - var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); - var intermediateThenable = { - then: function (onFulfilled) { - setTimeout(function() { onFulfilled(originalPromise); }, 0); - } - }; - var promise = new Promise(function(resolve) { resolve(intermediateThenable); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'original reason'); - done(); - }); - }); - }); - }); - - describe("Promise.all", function() { - testAll(function(){ - return Promise.all.apply(Promise, arguments); - }); - }); - - function testAll(all) { - it('should exist', function() { - assert(all); - }); - - it('throws when not passed an array', function(done) { - var nothing = assertRejection(all()); - var string = assertRejection(all('')); - var object = assertRejection(all({})); - - Promise.all([ - nothing, - string, - object - ]).then(function(){ done(); }); - }); - - specify('fulfilled only after all of the other promises are fulfilled', function(done) { - var firstResolved, secondResolved, firstResolver, secondResolver; - - var first = new Promise(function(resolve) { - firstResolver = resolve; - }); - first.then(function() { - firstResolved = true; - }); - - var second = new Promise(function(resolve) { - secondResolver = resolve; - }); - second.then(function() { - secondResolved = true; - }); - - setTimeout(function() { - firstResolver(true); - }, 0); - - setTimeout(function() { - secondResolver(true); - }, 0); - - all([first, second]).then(function() { - assert(firstResolved); - assert(secondResolved); - done(); - }); - }); - - specify('rejected as soon as a promise is rejected', function(done) { - var firstResolver, secondResolver; - - var first = new Promise(function(resolve, reject) { - firstResolver = { resolve: resolve, reject: reject }; - }); - - var second = new Promise(function(resolve, reject) { - secondResolver = { resolve: resolve, reject: reject }; - }); - - setTimeout(function() { - firstResolver.reject({}); - }, 0); - - var firstWasRejected, secondCompleted; - - first['catch'](function(){ - firstWasRejected = true; - }); - - second.then(function(){ - secondCompleted = true; - }, function() { - secondCompleted = true; - }); - - all([first, second]).then(function() { - assert(false); - }, function() { - assert(firstWasRejected); - assert(!secondCompleted); - done(); - }); - }); - - specify('passes the resolved values of each promise to the callback in the correct order', function(done) { - var firstResolver, secondResolver, thirdResolver; - - var first = new Promise(function(resolve, reject) { - firstResolver = { resolve: resolve, reject: reject }; - }); - - var second = new Promise(function(resolve, reject) { - secondResolver = { resolve: resolve, reject: reject }; - }); - - var third = new Promise(function(resolve, reject) { - thirdResolver = { resolve: resolve, reject: reject }; - }); - - thirdResolver.resolve(3); - firstResolver.resolve(1); - secondResolver.resolve(2); - - all([first, second, third]).then(function(results) { - assert(results.length === 3); - assert(results[0] === 1); - assert(results[1] === 2); - assert(results[2] === 3); - done(); - }); - }); - - specify('resolves an empty array passed to all()', function(done) { - all([]).then(function(results) { - assert(results.length === 0); - done(); - }); - }); - - specify('works with null', function(done) { - all([null]).then(function(results) { - assert.equal(results[0], null); - done(); - }); - }); - - specify('works with a mix of promises and thenables and non-promises', function(done) { - var promise = new Promise(function(resolve) { resolve(1); }); - var syncThenable = { then: function (onFulfilled) { onFulfilled(2); } }; - var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } }; - var nonPromise = 4; - - all([promise, syncThenable, asyncThenable, nonPromise]).then(function(results) { - assert(objectEquals(results, [1, 2, 3, 4])); - done(); - })['catch'](done); - }); - } - - describe("reject", function(){ - specify("it should exist", function(){ - assert(Promise.reject); - }); - - describe('it rejects', function(){ - var reason = 'the reason', - promise = Promise.reject(reason); - - promise.then(function(){ - assert(false, 'should not fulfill'); - }, function(actualReason){ - assert.equal(reason, actualReason); - }); - }); - }); - - function assertRejection(promise) { - return promise.then(function(){ - assert(false, 'expected rejection, but got fulfillment'); - }, function(reason){ - assert(reason instanceof Error); - }); - } - - describe('race', function() { - it("should exist", function() { - assert(Promise.race); - }); - - it("throws when not passed an array", function(done) { - var nothing = assertRejection(Promise.race()); - var string = assertRejection(Promise.race('')); - var object = assertRejection(Promise.race({})); - - Promise.all([ - nothing, - string, - object - ]).then(function(){ done(); }); - }); - - specify('fulfilled after one of the other promises are fulfilled', function(done) { - var firstResolved, secondResolved, firstResolver, secondResolver; - - var first = new Promise(function(resolve) { - firstResolver = resolve; - }); - first.then(function() { - firstResolved = true; - }); - - var second = new Promise(function(resolve) { - secondResolver = resolve; - }); - second.then(function() { - secondResolved = true; - }); - - setTimeout(function() { - firstResolver(true); - }, 100); - - setTimeout(function() { - secondResolver(true); - }, 0); - - Promise.race([first, second]).then(function() { - assert(secondResolved); - assert.equal(firstResolved, undefined); - done(); - }); - }); - - specify('the race begins on nextTurn and prioritized by array entry', function(done) { - var firstResolver, secondResolver, nonPromise = 5; - - var first = new Promise(function(resolve, reject) { - resolve(true); - }); - - var second = new Promise(function(resolve, reject) { - resolve(false); - }); - - Promise.race([first, second, nonPromise]).then(function(value) { - assert.equal(value, true); - done(); - }); - }); - - specify('rejected as soon as a promise is rejected', function(done) { - var firstResolver, secondResolver; - - var first = new Promise(function(resolve, reject) { - firstResolver = { resolve: resolve, reject: reject }; - }); - - var second = new Promise(function(resolve, reject) { - secondResolver = { resolve: resolve, reject: reject }; - }); - - setTimeout(function() { - firstResolver.reject({}); - }, 0); - - var firstWasRejected, secondCompleted; - - first['catch'](function(){ - firstWasRejected = true; - }); - - second.then(function(){ - secondCompleted = true; - }, function() { - secondCompleted = true; - }); - - Promise.race([first, second]).then(function() { - assert(false); - }, function() { - assert(firstWasRejected); - assert(!secondCompleted); - done(); - }); - }); - - specify('resolves an empty array to forever pending Promise', function(done) { - var foreverPendingPromise = Promise.race([]), - wasSettled = false; - - foreverPendingPromise.then(function() { - wasSettled = true; - }, function() { - wasSettled = true; - }); - - setTimeout(function() { - assert(!wasSettled); - done(); - }, 100); - }); - - specify('works with a mix of promises and thenables', function(done) { - var promise = new Promise(function(resolve) { setTimeout(function() { resolve(1); }, 10); }), - syncThenable = { then: function (onFulfilled) { onFulfilled(2); } }; - - Promise.race([promise, syncThenable]).then(function(result) { - assert(result, 2); - done(); - }); - }); - - specify('works with a mix of thenables and non-promises', function (done) { - var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } }, - nonPromise = 4; - - Promise.race([asyncThenable, nonPromise]).then(function(result) { - assert(result, 4); - done(); - }); - }); - }); - - describe("resolve", function(){ - specify("it should exist", function(){ - assert(Promise.resolve); - }); - - describe("1. If x is a promise, adopt its state ", function(){ - specify("1.1 If x is pending, promise must remain pending until x is fulfilled or rejected.", function(done){ - var expectedValue, resolver, thenable, wrapped; - - expectedValue = 'the value'; - thenable = { - then: function(resolve, reject){ - resolver = resolve; - } - }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(function(value){ - assert(value === expectedValue); - done(); - }); - - setTimeout(function(){ - resolver(expectedValue); - }, 10); - }); - - specify("1.2 If/when x is fulfilled, fulfill promise with the same value.", function(done){ - var expectedValue, thenable, wrapped; - - expectedValue = 'the value'; - thenable = { - then: function(resolve, reject){ - resolve(expectedValue); - } - }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(function(value){ - assert(value === expectedValue); - done(); - }) - }); - - specify("1.3 If/when x is rejected, reject promise with the same reason.", function(done){ - var expectedError, thenable, wrapped; - - expectedError = new Error(); - thenable = { - then: function(resolve, reject){ - reject(expectedError); - } - }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(null, function(error){ - assert(error === expectedError); - done(); - }); - }); - }); - - describe("2. Otherwise, if x is an object or function,", function(){ - specify("2.1 Let then x.then", function(done){ - var accessCount, resolver, wrapped, thenable; - - accessCount = 0; - thenable = { }; - - // we likely don't need to test this, if the browser doesn't support it - if (typeof Object.defineProperty !== "function") { done(); return; } - - Object.defineProperty(thenable, 'then', { - get: function(){ - accessCount++; - - if (accessCount > 1) { - throw new Error(); - } - - return function(){ }; - } - }); - - assert(accessCount === 0); - - wrapped = Promise.resolve(thenable); - - assert(accessCount === 1); - - done(); - }); - - specify("2.2 If retrieving the property x.then results in a thrown exception e, reject promise with e as the reason.", function(done){ - var wrapped, thenable, expectedError; - - expectedError = new Error(); - thenable = { }; - - // we likely don't need to test this, if the browser doesn't support it - if (typeof Object.defineProperty !== "function") { done(); return; } - - Object.defineProperty(thenable, 'then', { - get: function(){ - throw expectedError; - } - }); - - wrapped = Promise.resolve(thenable); - - wrapped.then(null, function(error){ - assert(error === expectedError, 'incorrect exception was thrown'); - done(); - }); - }); - - describe('2.3. If then is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise, where', function(){ - specify('2.3.1 If/when resolvePromise is called with a value y, run Resolve(promise, y)', function(done){ - var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis; - - thenable = { - then: function(resolve, reject){ - calledThis = this; - resolver = resolve; - rejector = reject; - } - }; - - expectedSuccess = 'success'; - wrapped = Promise.resolve(thenable); - - wrapped.then(function(success){ - assert(calledThis === thenable, 'this must be the thenable'); - assert(success === expectedSuccess, 'rejected promise with x'); - done(); - }); - - setTimeout(function() { - resolver(expectedSuccess); - }, 20); - }); - - specify('2.3.2 If/when rejectPromise is called with a reason r, reject promise with r.', function(done){ - var expectedError, resolver, rejector, thenable, wrapped, calledThis; - - thenable = { - then: function(resolve, reject){ - calledThis = this; - resolver = resolve; - rejector = reject; - } - }; - - expectedError = new Error(); - - wrapped = Promise.resolve(thenable); - - wrapped.then(null, function(error){ - assert(error === expectedError, 'rejected promise with x'); - done(); - }); - - setTimeout(function() { - rejector(expectedError); - }, 20); - }); - - specify("2.3.3 If both resolvePromise and rejectPromise are called, or multiple calls to the same argument are made, the first call takes precedence, and any further calls are ignored", function(done){ - var expectedError, expectedSuccess, resolver, rejector, thenable, wrapped, calledThis, - calledRejected, calledResolved; - - calledRejected = 0; - calledResolved = 0; - - thenable = { - then: function(resolve, reject){ - calledThis = this; - resolver = resolve; - rejector = reject; - } - }; - - expectedError = new Error(); - - wrapped = Promise.resolve(thenable); - - wrapped.then(function(){ - calledResolved++; - }, function(error){ - calledRejected++; - assert(calledResolved === 0, 'never resolved'); - assert(calledRejected === 1, 'rejected only once'); - assert(error === expectedError, 'rejected promise with x'); - }); - - setTimeout(function() { - rejector(expectedError); - rejector(expectedError); - - rejector('foo'); - - resolver('bar'); - resolver('baz'); - }, 20); - - setTimeout(function(){ - assert(calledRejected === 1, 'only rejected once'); - assert(calledResolved === 0, 'never resolved'); - done(); - }, 50); - }); - - describe("2.3.4 If calling then throws an exception e", function(){ - specify("2.3.4.1 If resolvePromise or rejectPromise have been called, ignore it.", function(done){ - var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis, - calledRejected, calledResolved; - - expectedSuccess = 'success'; - - thenable = { - then: function(resolve, reject){ - resolve(expectedSuccess); - throw expectedError; - } - }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(function(success){ - assert(success === expectedSuccess, 'resolved not errored'); - done(); - }); - }); - - specify("2.3.4.2 Otherwise, reject promise with e as the reason.", function(done) { - var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount; - - expectedError = new Error(); - callCount = 0; - - thenable = { then: function() { throw expectedError; } }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(null, function(error){ - callCount++; - assert(expectedError === error, 'expected the correct error to be rejected'); - done(); - }); - - assert(callCount === 0, 'expected async, was sync'); - }); - }); - }); - - specify("2.4 If then is not a function, fulfill promise with x", function(done){ - var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount; - - thenable = { then: 3 }; - callCount = 0; - wrapped = Promise.resolve(thenable); - - wrapped.then(function(success){ - callCount++; - assert(thenable === success, 'fulfilled promise with x'); - done(); - }); - - assert(callCount === 0, 'expected async, was sync'); - }); - }); - - describe("3. If x is not an object or function, ", function(){ - specify("fulfill promise with x.", function(done){ - var thenable, callCount, wrapped; - - thenable = null; - callCount = 0; - wrapped = Promise.resolve(thenable); - - wrapped.then(function(success){ - callCount++; - assert(success === thenable, 'fulfilled promise with x'); - done(); - }, function(a){ - assert(false, 'should not also reject'); - }); - - assert(callCount === 0, 'expected async, was sync'); - }); - }); - }); - - if (typeof Worker !== 'undefined') { - describe('web worker', function () { - it('should work', function (done) { - this.timeout(2000); - var worker = new Worker('worker.js'); - worker.addEventListener('error', function(reason) { - done(new Error("Test failed:" + reason)); - }); - worker.addEventListener('message', function (e) { - worker.terminate(); - assert.equal(e.data, 'pong'); - done(); - }); - worker.postMessage('ping'); - }); - }); - } -}); - -// thanks to @wizardwerdna for the test case -> https://github.com/tildeio/rsvp.js/issues/66 -// Only run these tests in node (phantomjs cannot handle them) -if (typeof module !== 'undefined' && module.exports) { - - describe("using reduce to sum integers using promises", function(){ - it("should build the promise pipeline without error", function(){ - var array, iters, pZero, i; - - array = []; - iters = 1000; - - for (i=1; i<=iters; i++) { - array.push(i); - } - - pZero = Promise.resolve(0); - - array.reduce(function(promise, nextVal) { - return promise.then(function(currentVal) { - return Promise.resolve(currentVal + nextVal); - }); - }, pZero); - }); - - it("should get correct answer without blowing the nextTick stack", function(done){ - var pZero, array, iters, result, i; - - pZero = Promise.resolve(0); - - array = []; - iters = 1000; - - for (i=1; i<=iters; i++) { - array.push(i); - } - - result = array.reduce(function(promise, nextVal) { - return promise.then(function(currentVal) { - return Promise.resolve(currentVal + nextVal); - }); - }, pZero); - - result.then(function(value){ - assert.equal(value, (iters*(iters+1)/2)); - done(); - }); - }); - }); -} - -// Kudos to @Octane at https://github.com/getify/native-promise-only/issues/5 for this, and @getify for pinging me. -describe("Thenables should not be able to run code during assimilation", function () { - specify("resolving to a thenable", function () { - var thenCalled = false; - var thenable = { - then: function () { - thenCalled = true; - } - }; - - Promise.resolve(thenable); - assert.strictEqual(thenCalled, false); - }); - - specify("resolving to an evil promise", function () { - var thenCalled = false; - var evilPromise = Promise.resolve(); - evilPromise.then = function () { - thenCalled = true; - }; - - Promise.resolve(evilPromise); - assert.strictEqual(thenCalled, false); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"assert":2}],53:[function(require,module,exports){ -(function (global){ -var assert = require('assert'); -var g = typeof window !== 'undefined' ? - window : typeof global !== 'undefined' ? global : this; - -var Promise = g.ES6Promise || require('./es6-promise').Promise; - -function defer() { - var deferred = {}; - - deferred.promise = new Promise(function(resolve, reject) { - deferred.resolve = resolve; - deferred.reject = reject; - }); - - return deferred; -} -var resolve = Promise.resolve; -var reject = Promise.reject; - - -module.exports = g.adapter = { - resolved: function(a) { return Promise.resolve(a); }, - rejected: function(a) { return Promise.reject(a); }, - deferred: defer, - Promise: Promise -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./es6-promise":51,"assert":2}]},{},[1]); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js deleted file mode 100644 index 5b096d6..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js +++ /dev/null @@ -1,950 +0,0 @@ -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } - - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$toString = {}.toString; - var lib$es6$promise$asap$$vertxNext; - function lib$es6$promise$asap$$asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - lib$es6$promise$asap$$scheduleFlush(); - } - } - - var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function() { - nextTick(lib$es6$promise$asap$$flush); - }; - } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } - - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFullfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$default(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } - } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - var then = lib$es6$promise$$internal$$getThen(maybeThenable); - - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } - } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); - } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } - - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } - } - } else { - lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); - } - } - - lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { - return lib$es6$promise$utils$$isArray(input); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { - this._result = new Array(this.length); - }; - - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (lib$es6$promise$utils$$isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - enumerator._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, enumerator._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } - - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; - } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; - } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - var lib$es6$promise$promise$$counter = 0; - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - if (!lib$es6$promise$utils$$isFunction(resolver)) { - lib$es6$promise$promise$$needsResolver(); - } - - if (!(this instanceof lib$es6$promise$promise$$Promise)) { - lib$es6$promise$promise$$needsNew(); - } - - lib$es6$promise$$internal$$initializePromise(this, resolver); - } - } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$default(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; - } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; - } - - lib$es6$promise$polyfill$$default(); -}).call(this); - -//# sourceMappingURL=es6-promise.js.map \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js deleted file mode 100644 index 34a1f52..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;function lib$es6$promise$asap$$asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){lib$es6$promise$asap$$scheduleFlush()}}var lib$es6$promise$asap$$default=lib$es6$promise$asap$$asap;var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){var nextTick=process.nextTick;var version=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);if(Array.isArray(version)&&version[1]==="0"&&version[2]==="10"){nextTick=setImmediate}return function(){nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i - - - rsvp.js Tests - - - -
      - - - - - - - - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js deleted file mode 100644 index 4817c9e..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js +++ /dev/null @@ -1,902 +0,0 @@ -/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ -;(function () { - // Detect the `define` function exposed by asynchronous module loaders. The - // strict `define` check is necessary for compatibility with `r.js`. - var isLoader = typeof define === "function" && define.amd; - - // A set of types used to distinguish objects from primitives. - var objectTypes = { - "function": true, - "object": true - }; - - // Detect the `exports` object exposed by CommonJS implementations. - var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; - - // Use the `global` object exposed by Node (including Browserify via - // `insert-module-globals`), Narwhal, and Ringo as the default context, - // and the `window` object in browsers. Rhino exports a `global` function - // instead. - var root = objectTypes[typeof window] && window || this, - freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; - - if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { - root = freeGlobal; - } - - // Public: Initializes JSON 3 using the given `context` object, attaching the - // `stringify` and `parse` functions to the specified `exports` object. - function runInContext(context, exports) { - context || (context = root["Object"]()); - exports || (exports = root["Object"]()); - - // Native constructor aliases. - var Number = context["Number"] || root["Number"], - String = context["String"] || root["String"], - Object = context["Object"] || root["Object"], - Date = context["Date"] || root["Date"], - SyntaxError = context["SyntaxError"] || root["SyntaxError"], - TypeError = context["TypeError"] || root["TypeError"], - Math = context["Math"] || root["Math"], - nativeJSON = context["JSON"] || root["JSON"]; - - // Delegate to the native `stringify` and `parse` implementations. - if (typeof nativeJSON == "object" && nativeJSON) { - exports.stringify = nativeJSON.stringify; - exports.parse = nativeJSON.parse; - } - - // Convenience aliases. - var objectProto = Object.prototype, - getClass = objectProto.toString, - isProperty, forEach, undef; - - // Test the `Date#getUTC*` methods. Based on work by @Yaffle. - var isExtended = new Date(-3509827334573292); - try { - // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical - // results for certain dates in Opera >= 10.53. - isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && - // Safari < 2.0.2 stores the internal millisecond time value correctly, - // but clips the values returned by the date methods to the range of - // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]). - isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; - } catch (exception) {} - - // Internal: Determines whether the native `JSON.stringify` and `parse` - // implementations are spec-compliant. Based on work by Ken Snyder. - function has(name) { - if (has[name] !== undef) { - // Return cached feature test result. - return has[name]; - } - var isSupported; - if (name == "bug-string-char-index") { - // IE <= 7 doesn't support accessing string characters using square - // bracket notation. IE 8 only supports this for primitives. - isSupported = "a"[0] != "a"; - } else if (name == "json") { - // Indicates whether both `JSON.stringify` and `JSON.parse` are - // supported. - isSupported = has("json-stringify") && has("json-parse"); - } else { - var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; - // Test `JSON.stringify`. - if (name == "json-stringify") { - var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; - if (stringifySupported) { - // A test function object with a custom `toJSON` method. - (value = function () { - return 1; - }).toJSON = value; - try { - stringifySupported = - // Firefox 3.1b1 and b2 serialize string, number, and boolean - // primitives as object literals. - stringify(0) === "0" && - // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object - // literals. - stringify(new Number()) === "0" && - stringify(new String()) == '""' && - // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or - // does not define a canonical JSON representation (this applies to - // objects with `toJSON` properties as well, *unless* they are nested - // within an object or array). - stringify(getClass) === undef && - // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and - // FF 3.1b3 pass this test. - stringify(undef) === undef && - // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, - // respectively, if the value is omitted entirely. - stringify() === undef && - // FF 3.1b1, 2 throw an error if the given value is not a number, - // string, array, object, Boolean, or `null` literal. This applies to - // objects with custom `toJSON` methods as well, unless they are nested - // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` - // methods entirely. - stringify(value) === "1" && - stringify([value]) == "[1]" && - // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of - // `"[null]"`. - stringify([undef]) == "[null]" && - // YUI 3.0.0b1 fails to serialize `null` literals. - stringify(null) == "null" && - // FF 3.1b1, 2 halts serialization if an array contains a function: - // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 - // elides non-JSON values from objects and arrays, unless they - // define custom `toJSON` methods. - stringify([undef, getClass, null]) == "[null,null,null]" && - // Simple serialization test. FF 3.1b1 uses Unicode escape sequences - // where character escape codes are expected (e.g., `\b` => `\u0008`). - stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && - // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. - stringify(null, value) === "1" && - stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && - // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly - // serialize extended years. - stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && - // The milliseconds are optional in ES 5, but required in 5.1. - stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && - // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative - // four-digit years instead of six-digit years. Credits: @Yaffle. - stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && - // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond - // values less than 1000. Credits: @Yaffle. - stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; - } catch (exception) { - stringifySupported = false; - } - } - isSupported = stringifySupported; - } - // Test `JSON.parse`. - if (name == "json-parse") { - var parse = exports.parse; - if (typeof parse == "function") { - try { - // FF 3.1b1, b2 will throw an exception if a bare literal is provided. - // Conforming implementations should also coerce the initial argument to - // a string prior to parsing. - if (parse("0") === 0 && !parse(false)) { - // Simple parsing test. - value = parse(serialized); - var parseSupported = value["a"].length == 5 && value["a"][0] === 1; - if (parseSupported) { - try { - // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. - parseSupported = !parse('"\t"'); - } catch (exception) {} - if (parseSupported) { - try { - // FF 4.0 and 4.0.1 allow leading `+` signs and leading - // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow - // certain octal literals. - parseSupported = parse("01") !== 1; - } catch (exception) {} - } - if (parseSupported) { - try { - // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal - // points. These environments, along with FF 3.1b1 and 2, - // also allow trailing commas in JSON objects and arrays. - parseSupported = parse("1.") !== 1; - } catch (exception) {} - } - } - } - } catch (exception) { - parseSupported = false; - } - } - isSupported = parseSupported; - } - } - return has[name] = !!isSupported; - } - - if (!has("json")) { - // Common `[[Class]]` name aliases. - var functionClass = "[object Function]", - dateClass = "[object Date]", - numberClass = "[object Number]", - stringClass = "[object String]", - arrayClass = "[object Array]", - booleanClass = "[object Boolean]"; - - // Detect incomplete support for accessing string characters by index. - var charIndexBuggy = has("bug-string-char-index"); - - // Define additional utility methods if the `Date` methods are buggy. - if (!isExtended) { - var floor = Math.floor; - // A mapping between the months of the year and the number of days between - // January 1st and the first of the respective month. - var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; - // Internal: Calculates the number of days between the Unix epoch and the - // first day of the given month. - var getDay = function (year, month) { - return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); - }; - } - - // Internal: Determines if a property is a direct property of the given - // object. Delegates to the native `Object#hasOwnProperty` method. - if (!(isProperty = objectProto.hasOwnProperty)) { - isProperty = function (property) { - var members = {}, constructor; - if ((members.__proto__ = null, members.__proto__ = { - // The *proto* property cannot be set multiple times in recent - // versions of Firefox and SeaMonkey. - "toString": 1 - }, members).toString != getClass) { - // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but - // supports the mutable *proto* property. - isProperty = function (property) { - // Capture and break the object's prototype chain (see section 8.6.2 - // of the ES 5.1 spec). The parenthesized expression prevents an - // unsafe transformation by the Closure Compiler. - var original = this.__proto__, result = property in (this.__proto__ = null, this); - // Restore the original prototype chain. - this.__proto__ = original; - return result; - }; - } else { - // Capture a reference to the top-level `Object` constructor. - constructor = members.constructor; - // Use the `constructor` property to simulate `Object#hasOwnProperty` in - // other environments. - isProperty = function (property) { - var parent = (this.constructor || constructor).prototype; - return property in this && !(property in parent && this[property] === parent[property]); - }; - } - members = null; - return isProperty.call(this, property); - }; - } - - // Internal: Normalizes the `for...in` iteration algorithm across - // environments. Each enumerated key is yielded to a `callback` function. - forEach = function (object, callback) { - var size = 0, Properties, members, property; - - // Tests for bugs in the current environment's `for...in` algorithm. The - // `valueOf` property inherits the non-enumerable flag from - // `Object.prototype` in older versions of IE, Netscape, and Mozilla. - (Properties = function () { - this.valueOf = 0; - }).prototype.valueOf = 0; - - // Iterate over a new instance of the `Properties` class. - members = new Properties(); - for (property in members) { - // Ignore all properties inherited from `Object.prototype`. - if (isProperty.call(members, property)) { - size++; - } - } - Properties = members = null; - - // Normalize the iteration algorithm. - if (!size) { - // A list of non-enumerable properties inherited from `Object.prototype`. - members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; - // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable - // properties. - forEach = function (object, callback) { - var isFunction = getClass.call(object) == functionClass, property, length; - var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; - for (property in object) { - // Gecko <= 1.0 enumerates the `prototype` property of functions under - // certain conditions; IE does not. - if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { - callback(property); - } - } - // Manually invoke the callback for each non-enumerable property. - for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); - }; - } else if (size == 2) { - // Safari <= 2.0.4 enumerates shadowed properties twice. - forEach = function (object, callback) { - // Create a set of iterated properties. - var members = {}, isFunction = getClass.call(object) == functionClass, property; - for (property in object) { - // Store each property name to prevent double enumeration. The - // `prototype` property of functions is not enumerated due to cross- - // environment inconsistencies. - if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { - callback(property); - } - } - }; - } else { - // No bugs detected; use the standard `for...in` algorithm. - forEach = function (object, callback) { - var isFunction = getClass.call(object) == functionClass, property, isConstructor; - for (property in object) { - if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { - callback(property); - } - } - // Manually invoke the callback for the `constructor` property due to - // cross-environment inconsistencies. - if (isConstructor || isProperty.call(object, (property = "constructor"))) { - callback(property); - } - }; - } - return forEach(object, callback); - }; - - // Public: Serializes a JavaScript `value` as a JSON string. The optional - // `filter` argument may specify either a function that alters how object and - // array members are serialized, or an array of strings and numbers that - // indicates which properties should be serialized. The optional `width` - // argument may be either a string or number that specifies the indentation - // level of the output. - if (!has("json-stringify")) { - // Internal: A map of control characters and their escaped equivalents. - var Escapes = { - 92: "\\\\", - 34: '\\"', - 8: "\\b", - 12: "\\f", - 10: "\\n", - 13: "\\r", - 9: "\\t" - }; - - // Internal: Converts `value` into a zero-padded string such that its - // length is at least equal to `width`. The `width` must be <= 6. - var leadingZeroes = "000000"; - var toPaddedString = function (width, value) { - // The `|| 0` expression is necessary to work around a bug in - // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. - return (leadingZeroes + (value || 0)).slice(-width); - }; - - // Internal: Double-quotes a string `value`, replacing all ASCII control - // characters (characters with code unit values between 0 and 31) with - // their escaped equivalents. This is an implementation of the - // `Quote(value)` operation defined in ES 5.1 section 15.12.3. - var unicodePrefix = "\\u00"; - var quote = function (value) { - var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; - var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); - for (; index < length; index++) { - var charCode = value.charCodeAt(index); - // If the character is a control character, append its Unicode or - // shorthand escape sequence; otherwise, append the character as-is. - switch (charCode) { - case 8: case 9: case 10: case 12: case 13: case 34: case 92: - result += Escapes[charCode]; - break; - default: - if (charCode < 32) { - result += unicodePrefix + toPaddedString(2, charCode.toString(16)); - break; - } - result += useCharIndex ? symbols[index] : value.charAt(index); - } - } - return result + '"'; - }; - - // Internal: Recursively serializes an object. Implements the - // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. - var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { - var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; - try { - // Necessary for host object support. - value = object[property]; - } catch (exception) {} - if (typeof value == "object" && value) { - className = getClass.call(value); - if (className == dateClass && !isProperty.call(value, "toJSON")) { - if (value > -1 / 0 && value < 1 / 0) { - // Dates are serialized according to the `Date#toJSON` method - // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 - // for the ISO 8601 date time string format. - if (getDay) { - // Manually compute the year, month, date, hours, minutes, - // seconds, and milliseconds if the `getUTC*` methods are - // buggy. Adapted from @Yaffle's `date-shim` project. - date = floor(value / 864e5); - for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); - for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); - date = 1 + date - getDay(year, month); - // The `time` value specifies the time within the day (see ES - // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used - // to compute `A modulo B`, as the `%` operator does not - // correspond to the `modulo` operation for negative numbers. - time = (value % 864e5 + 864e5) % 864e5; - // The hours, minutes, seconds, and milliseconds are obtained by - // decomposing the time within the day. See section 15.9.1.10. - hours = floor(time / 36e5) % 24; - minutes = floor(time / 6e4) % 60; - seconds = floor(time / 1e3) % 60; - milliseconds = time % 1e3; - } else { - year = value.getUTCFullYear(); - month = value.getUTCMonth(); - date = value.getUTCDate(); - hours = value.getUTCHours(); - minutes = value.getUTCMinutes(); - seconds = value.getUTCSeconds(); - milliseconds = value.getUTCMilliseconds(); - } - // Serialize extended years correctly. - value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + - "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + - // Months, dates, hours, minutes, and seconds should have two - // digits; milliseconds should have three. - "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + - // Milliseconds are optional in ES 5.0, but required in 5.1. - "." + toPaddedString(3, milliseconds) + "Z"; - } else { - value = null; - } - } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { - // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the - // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3 - // ignores all `toJSON` methods on these objects unless they are - // defined directly on an instance. - value = value.toJSON(property); - } - } - if (callback) { - // If a replacement function was provided, call it to obtain the value - // for serialization. - value = callback.call(object, property, value); - } - if (value === null) { - return "null"; - } - className = getClass.call(value); - if (className == booleanClass) { - // Booleans are represented literally. - return "" + value; - } else if (className == numberClass) { - // JSON numbers must be finite. `Infinity` and `NaN` are serialized as - // `"null"`. - return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; - } else if (className == stringClass) { - // Strings are double-quoted and escaped. - return quote("" + value); - } - // Recursively serialize objects and arrays. - if (typeof value == "object") { - // Check for cyclic structures. This is a linear search; performance - // is inversely proportional to the number of unique nested objects. - for (length = stack.length; length--;) { - if (stack[length] === value) { - // Cyclic structures cannot be serialized by `JSON.stringify`. - throw TypeError(); - } - } - // Add the object to the stack of traversed objects. - stack.push(value); - results = []; - // Save the current indentation level and indent one additional level. - prefix = indentation; - indentation += whitespace; - if (className == arrayClass) { - // Recursively serialize array elements. - for (index = 0, length = value.length; index < length; index++) { - element = serialize(index, value, callback, properties, whitespace, indentation, stack); - results.push(element === undef ? "null" : element); - } - result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; - } else { - // Recursively serialize object members. Members are selected from - // either a user-specified list of property names, or the object - // itself. - forEach(properties || value, function (property) { - var element = serialize(property, value, callback, properties, whitespace, indentation, stack); - if (element !== undef) { - // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} - // is not the empty string, let `member` {quote(property) + ":"} - // be the concatenation of `member` and the `space` character." - // The "`space` character" refers to the literal space - // character, not the `space` {width} argument provided to - // `JSON.stringify`. - results.push(quote(property) + ":" + (whitespace ? " " : "") + element); - } - }); - result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; - } - // Remove the object from the traversed object stack. - stack.pop(); - return result; - } - }; - - // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. - exports.stringify = function (source, filter, width) { - var whitespace, callback, properties, className; - if (objectTypes[typeof filter] && filter) { - if ((className = getClass.call(filter)) == functionClass) { - callback = filter; - } else if (className == arrayClass) { - // Convert the property names array into a makeshift set. - properties = {}; - for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); - } - } - if (width) { - if ((className = getClass.call(width)) == numberClass) { - // Convert the `width` to an integer and create a string containing - // `width` number of space characters. - if ((width -= width % 1) > 0) { - for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); - } - } else if (className == stringClass) { - whitespace = width.length <= 10 ? width : width.slice(0, 10); - } - } - // Opera <= 7.54u2 discards the values associated with empty string keys - // (`""`) only if they are used directly within an object member list - // (e.g., `!("" in { "": 1})`). - return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); - }; - } - - // Public: Parses a JSON source string. - if (!has("json-parse")) { - var fromCharCode = String.fromCharCode; - - // Internal: A map of escaped control characters and their unescaped - // equivalents. - var Unescapes = { - 92: "\\", - 34: '"', - 47: "/", - 98: "\b", - 116: "\t", - 110: "\n", - 102: "\f", - 114: "\r" - }; - - // Internal: Stores the parser state. - var Index, Source; - - // Internal: Resets the parser state and throws a `SyntaxError`. - var abort = function () { - Index = Source = null; - throw SyntaxError(); - }; - - // Internal: Returns the next token, or `"$"` if the parser has reached - // the end of the source string. A token may be a string, number, `null` - // literal, or Boolean literal. - var lex = function () { - var source = Source, length = source.length, value, begin, position, isSigned, charCode; - while (Index < length) { - charCode = source.charCodeAt(Index); - switch (charCode) { - case 9: case 10: case 13: case 32: - // Skip whitespace tokens, including tabs, carriage returns, line - // feeds, and space characters. - Index++; - break; - case 123: case 125: case 91: case 93: case 58: case 44: - // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at - // the current position. - value = charIndexBuggy ? source.charAt(Index) : source[Index]; - Index++; - return value; - case 34: - // `"` delimits a JSON string; advance to the next character and - // begin parsing the string. String tokens are prefixed with the - // sentinel `@` character to distinguish them from punctuators and - // end-of-string tokens. - for (value = "@", Index++; Index < length;) { - charCode = source.charCodeAt(Index); - if (charCode < 32) { - // Unescaped ASCII control characters (those with a code unit - // less than the space character) are not permitted. - abort(); - } else if (charCode == 92) { - // A reverse solidus (`\`) marks the beginning of an escaped - // control character (including `"`, `\`, and `/`) or Unicode - // escape sequence. - charCode = source.charCodeAt(++Index); - switch (charCode) { - case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: - // Revive escaped control characters. - value += Unescapes[charCode]; - Index++; - break; - case 117: - // `\u` marks the beginning of a Unicode escape sequence. - // Advance to the first character and validate the - // four-digit code point. - begin = ++Index; - for (position = Index + 4; Index < position; Index++) { - charCode = source.charCodeAt(Index); - // A valid sequence comprises four hexdigits (case- - // insensitive) that form a single hexadecimal value. - if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { - // Invalid Unicode escape sequence. - abort(); - } - } - // Revive the escaped character. - value += fromCharCode("0x" + source.slice(begin, Index)); - break; - default: - // Invalid escape sequence. - abort(); - } - } else { - if (charCode == 34) { - // An unescaped double-quote character marks the end of the - // string. - break; - } - charCode = source.charCodeAt(Index); - begin = Index; - // Optimize for the common case where a string is valid. - while (charCode >= 32 && charCode != 92 && charCode != 34) { - charCode = source.charCodeAt(++Index); - } - // Append the string as-is. - value += source.slice(begin, Index); - } - } - if (source.charCodeAt(Index) == 34) { - // Advance to the next character and return the revived string. - Index++; - return value; - } - // Unterminated string. - abort(); - default: - // Parse numbers and literals. - begin = Index; - // Advance past the negative sign, if one is specified. - if (charCode == 45) { - isSigned = true; - charCode = source.charCodeAt(++Index); - } - // Parse an integer or floating-point value. - if (charCode >= 48 && charCode <= 57) { - // Leading zeroes are interpreted as octal literals. - if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { - // Illegal octal literal. - abort(); - } - isSigned = false; - // Parse the integer component. - for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); - // Floats cannot contain a leading decimal point; however, this - // case is already accounted for by the parser. - if (source.charCodeAt(Index) == 46) { - position = ++Index; - // Parse the decimal component. - for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); - if (position == Index) { - // Illegal trailing decimal. - abort(); - } - Index = position; - } - // Parse exponents. The `e` denoting the exponent is - // case-insensitive. - charCode = source.charCodeAt(Index); - if (charCode == 101 || charCode == 69) { - charCode = source.charCodeAt(++Index); - // Skip past the sign following the exponent, if one is - // specified. - if (charCode == 43 || charCode == 45) { - Index++; - } - // Parse the exponential component. - for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); - if (position == Index) { - // Illegal empty exponent. - abort(); - } - Index = position; - } - // Coerce the parsed value to a JavaScript number. - return +source.slice(begin, Index); - } - // A negative sign may only precede numbers. - if (isSigned) { - abort(); - } - // `true`, `false`, and `null` literals. - if (source.slice(Index, Index + 4) == "true") { - Index += 4; - return true; - } else if (source.slice(Index, Index + 5) == "false") { - Index += 5; - return false; - } else if (source.slice(Index, Index + 4) == "null") { - Index += 4; - return null; - } - // Unrecognized token. - abort(); - } - } - // Return the sentinel `$` character if the parser has reached the end - // of the source string. - return "$"; - }; - - // Internal: Parses a JSON `value` token. - var get = function (value) { - var results, hasMembers; - if (value == "$") { - // Unexpected end of input. - abort(); - } - if (typeof value == "string") { - if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { - // Remove the sentinel `@` character. - return value.slice(1); - } - // Parse object and array literals. - if (value == "[") { - // Parses a JSON array, returning a new JavaScript array. - results = []; - for (;; hasMembers || (hasMembers = true)) { - value = lex(); - // A closing square bracket marks the end of the array literal. - if (value == "]") { - break; - } - // If the array literal contains elements, the current token - // should be a comma separating the previous element from the - // next. - if (hasMembers) { - if (value == ",") { - value = lex(); - if (value == "]") { - // Unexpected trailing `,` in array literal. - abort(); - } - } else { - // A `,` must separate each array element. - abort(); - } - } - // Elisions and leading commas are not permitted. - if (value == ",") { - abort(); - } - results.push(get(value)); - } - return results; - } else if (value == "{") { - // Parses a JSON object, returning a new JavaScript object. - results = {}; - for (;; hasMembers || (hasMembers = true)) { - value = lex(); - // A closing curly brace marks the end of the object literal. - if (value == "}") { - break; - } - // If the object literal contains members, the current token - // should be a comma separator. - if (hasMembers) { - if (value == ",") { - value = lex(); - if (value == "}") { - // Unexpected trailing `,` in object literal. - abort(); - } - } else { - // A `,` must separate each object member. - abort(); - } - } - // Leading commas are not permitted, object property names must be - // double-quoted strings, and a `:` must separate each property - // name and value. - if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { - abort(); - } - results[value.slice(1)] = get(lex()); - } - return results; - } - // Unexpected token encountered. - abort(); - } - return value; - }; - - // Internal: Updates a traversed object member. - var update = function (source, property, callback) { - var element = walk(source, property, callback); - if (element === undef) { - delete source[property]; - } else { - source[property] = element; - } - }; - - // Internal: Recursively traverses a parsed JSON object, invoking the - // `callback` function for each value. This is an implementation of the - // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. - var walk = function (source, property, callback) { - var value = source[property], length; - if (typeof value == "object" && value) { - // `forEach` can't be used to traverse an array in Opera <= 8.54 - // because its `Object#hasOwnProperty` implementation returns `false` - // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). - if (getClass.call(value) == arrayClass) { - for (length = value.length; length--;) { - update(value, length, callback); - } - } else { - forEach(value, function (property) { - update(value, property, callback); - }); - } - } - return callback.call(source, property, value); - }; - - // Public: `JSON.parse`. See ES 5.1 section 15.12.2. - exports.parse = function (source, callback) { - var result, value; - Index = 0; - Source = "" + source; - result = get(lex()); - // If a JSON string contains multiple tokens, it is invalid. - if (lex() != "$") { - abort(); - } - // Reset the parser state. - Index = Source = null; - return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; - }; - } - } - - exports["runInContext"] = runInContext; - return exports; - } - - if (freeExports && !isLoader) { - // Export for CommonJS environments. - runInContext(root, freeExports); - } else { - // Export for web browsers and JavaScript engines. - var nativeJSON = root.JSON, - previousJSON = root["JSON3"], - isRestored = false; - - var JSON3 = runInContext(root, (root["JSON3"] = { - // Public: Restores the original value of the global `JSON` object and - // returns a reference to the `JSON3` object. - "noConflict": function () { - if (!isRestored) { - isRestored = true; - root.JSON = nativeJSON; - root["JSON3"] = previousJSON; - nativeJSON = previousJSON = null; - } - return JSON3; - } - })); - - root.JSON = { - "parse": JSON3.parse, - "stringify": JSON3.stringify - }; - } - - // Export for asynchronous module loaders. - if (isLoader) { - define(function () { - return JSON3; - }); - } -}).call(this); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css deleted file mode 100644 index 42b9798..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css +++ /dev/null @@ -1,270 +0,0 @@ -@charset "utf-8"; - -body { - margin:0; -} - -#mocha { - font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; - margin: 60px 50px; -} - -#mocha ul, -#mocha li { - margin: 0; - padding: 0; -} - -#mocha ul { - list-style: none; -} - -#mocha h1, -#mocha h2 { - margin: 0; -} - -#mocha h1 { - margin-top: 15px; - font-size: 1em; - font-weight: 200; -} - -#mocha h1 a { - text-decoration: none; - color: inherit; -} - -#mocha h1 a:hover { - text-decoration: underline; -} - -#mocha .suite .suite h1 { - margin-top: 0; - font-size: .8em; -} - -#mocha .hidden { - display: none; -} - -#mocha h2 { - font-size: 12px; - font-weight: normal; - cursor: pointer; -} - -#mocha .suite { - margin-left: 15px; -} - -#mocha .test { - margin-left: 15px; - overflow: hidden; -} - -#mocha .test.pending:hover h2::after { - content: '(pending)'; - font-family: arial, sans-serif; -} - -#mocha .test.pass.medium .duration { - background: #c09853; -} - -#mocha .test.pass.slow .duration { - background: #b94a48; -} - -#mocha .test.pass::before { - content: '✓'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; - color: #00d6b2; -} - -#mocha .test.pass .duration { - font-size: 9px; - margin-left: 5px; - padding: 2px 5px; - color: #fff; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - -ms-border-radius: 5px; - -o-border-radius: 5px; - border-radius: 5px; -} - -#mocha .test.pass.fast .duration { - display: none; -} - -#mocha .test.pending { - color: #0b97c4; -} - -#mocha .test.pending::before { - content: '◦'; - color: #0b97c4; -} - -#mocha .test.fail { - color: #c00; -} - -#mocha .test.fail pre { - color: black; -} - -#mocha .test.fail::before { - content: '✖'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; - color: #c00; -} - -#mocha .test pre.error { - color: #c00; - max-height: 300px; - overflow: auto; -} - -/** - * (1): approximate for browsers not supporting calc - * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border) - * ^^ seriously - */ -#mocha .test pre { - display: block; - float: left; - clear: left; - font: 12px/1.5 monaco, monospace; - margin: 5px; - padding: 15px; - border: 1px solid #eee; - max-width: 85%; /*(1)*/ - max-width: calc(100% - 42px); /*(2)*/ - word-wrap: break-word; - border-bottom-color: #ddd; - -webkit-border-radius: 3px; - -webkit-box-shadow: 0 1px 3px #eee; - -moz-border-radius: 3px; - -moz-box-shadow: 0 1px 3px #eee; - border-radius: 3px; -} - -#mocha .test h2 { - position: relative; -} - -#mocha .test a.replay { - position: absolute; - top: 3px; - right: 0; - text-decoration: none; - vertical-align: middle; - display: block; - width: 15px; - height: 15px; - line-height: 15px; - text-align: center; - background: #eee; - font-size: 15px; - -moz-border-radius: 15px; - border-radius: 15px; - -webkit-transition: opacity 200ms; - -moz-transition: opacity 200ms; - transition: opacity 200ms; - opacity: 0.3; - color: #888; -} - -#mocha .test:hover a.replay { - opacity: 1; -} - -#mocha-report.pass .test.fail { - display: none; -} - -#mocha-report.fail .test.pass { - display: none; -} - -#mocha-report.pending .test.pass, -#mocha-report.pending .test.fail { - display: none; -} -#mocha-report.pending .test.pass.pending { - display: block; -} - -#mocha-error { - color: #c00; - font-size: 1.5em; - font-weight: 100; - letter-spacing: 1px; -} - -#mocha-stats { - position: fixed; - top: 15px; - right: 10px; - font-size: 12px; - margin: 0; - color: #888; - z-index: 1; -} - -#mocha-stats .progress { - float: right; - padding-top: 0; -} - -#mocha-stats em { - color: black; -} - -#mocha-stats a { - text-decoration: none; - color: inherit; -} - -#mocha-stats a:hover { - border-bottom: 1px solid #eee; -} - -#mocha-stats li { - display: inline-block; - margin: 0 5px; - list-style: none; - padding-top: 11px; -} - -#mocha-stats canvas { - width: 40px; - height: 40px; -} - -#mocha code .comment { color: #ddd; } -#mocha code .init { color: #2f6fad; } -#mocha code .string { color: #5890ad; } -#mocha code .keyword { color: #8a6343; } -#mocha code .number { color: #2f6fad; } - -@media screen and (max-device-width: 480px) { - #mocha { - margin: 60px 0px; - } - - #mocha #stats { - position: absolute; - } -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js deleted file mode 100644 index e8bee79..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js +++ /dev/null @@ -1,6095 +0,0 @@ -;(function(){ - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p.charAt(0)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("browser/debug.js", function(module, exports, require){ - -module.exports = function(type){ - return function(){ - } -}; - -}); // module: browser/debug.js - -require.register("browser/diff.js", function(module, exports, require){ -/* See LICENSE file for terms of use */ - -/* - * Text diff implementation. - * - * This library supports the following APIS: - * JsDiff.diffChars: Character by character diff - * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace - * JsDiff.diffLines: Line based diff - * - * JsDiff.diffCss: Diff targeted at CSS content - * - * These methods are based on the implementation proposed in - * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 - */ -var JsDiff = (function() { - /*jshint maxparams: 5*/ - function clonePath(path) { - return { newPos: path.newPos, components: path.components.slice(0) }; - } - function removeEmpty(array) { - var ret = []; - for (var i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } - } - return ret; - } - function escapeHTML(s) { - var n = s; - n = n.replace(/&/g, '&'); - n = n.replace(//g, '>'); - n = n.replace(/"/g, '"'); - - return n; - } - - var Diff = function(ignoreWhitespace) { - this.ignoreWhitespace = ignoreWhitespace; - }; - Diff.prototype = { - diff: function(oldString, newString) { - // Handle the identity case (this is due to unrolling editLength == 0 - if (newString === oldString) { - return [{ value: newString }]; - } - if (!newString) { - return [{ value: oldString, removed: true }]; - } - if (!oldString) { - return [{ value: newString, added: true }]; - } - - newString = this.tokenize(newString); - oldString = this.tokenize(oldString); - - var newLen = newString.length, oldLen = oldString.length; - var maxEditLength = newLen + oldLen; - var bestPath = [{ newPos: -1, components: [] }]; - - // Seed editLength = 0 - var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); - if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { - return bestPath[0].components; - } - - for (var editLength = 1; editLength <= maxEditLength; editLength++) { - for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { - var basePath; - var addPath = bestPath[diagonalPath-1], - removePath = bestPath[diagonalPath+1]; - oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; - if (addPath) { - // No one else is going to attempt to use this value, clear it - bestPath[diagonalPath-1] = undefined; - } - - var canAdd = addPath && addPath.newPos+1 < newLen; - var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; - if (!canAdd && !canRemove) { - bestPath[diagonalPath] = undefined; - continue; - } - - // Select the diagonal that we want to branch from. We select the prior - // path whose position in the new string is the farthest from the origin - // and does not pass the bounds of the diff graph - if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { - basePath = clonePath(removePath); - this.pushComponent(basePath.components, oldString[oldPos], undefined, true); - } else { - basePath = clonePath(addPath); - basePath.newPos++; - this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); - } - - var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); - - if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { - return basePath.components; - } else { - bestPath[diagonalPath] = basePath; - } - } - } - }, - - pushComponent: function(components, value, added, removed) { - var last = components[components.length-1]; - if (last && last.added === added && last.removed === removed) { - // We need to clone here as the component clone operation is just - // as shallow array clone - components[components.length-1] = - {value: this.join(last.value, value), added: added, removed: removed }; - } else { - components.push({value: value, added: added, removed: removed }); - } - }, - extractCommon: function(basePath, newString, oldString, diagonalPath) { - var newLen = newString.length, - oldLen = oldString.length, - newPos = basePath.newPos, - oldPos = newPos - diagonalPath; - while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { - newPos++; - oldPos++; - - this.pushComponent(basePath.components, newString[newPos], undefined, undefined); - } - basePath.newPos = newPos; - return oldPos; - }, - - equals: function(left, right) { - var reWhitespace = /\S/; - if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { - return true; - } else { - return left === right; - } - }, - join: function(left, right) { - return left + right; - }, - tokenize: function(value) { - return value; - } - }; - - var CharDiff = new Diff(); - - var WordDiff = new Diff(true); - var WordWithSpaceDiff = new Diff(); - WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { - return removeEmpty(value.split(/(\s+|\b)/)); - }; - - var CssDiff = new Diff(true); - CssDiff.tokenize = function(value) { - return removeEmpty(value.split(/([{}:;,]|\s+)/)); - }; - - var LineDiff = new Diff(); - LineDiff.tokenize = function(value) { - var retLines = [], - lines = value.split(/^/m); - - for(var i = 0; i < lines.length; i++) { - var line = lines[i], - lastLine = lines[i - 1]; - - // Merge lines that may contain windows new lines - if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') { - retLines[retLines.length - 1] += '\n'; - } else if (line) { - retLines.push(line); - } - } - - return retLines; - }; - - return { - Diff: Diff, - - diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, - diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, - diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, - diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, - - diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, - - createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { - var ret = []; - - ret.push('Index: ' + fileName); - ret.push('==================================================================='); - ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); - ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); - - var diff = LineDiff.diff(oldStr, newStr); - if (!diff[diff.length-1].value) { - diff.pop(); // Remove trailing newline add - } - diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier - - function contextLines(lines) { - return lines.map(function(entry) { return ' ' + entry; }); - } - function eofNL(curRange, i, current) { - var last = diff[diff.length-2], - isLast = i === diff.length-2, - isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); - - // Figure out if this is the last line for the given file and missing NL - if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { - curRange.push('\\ No newline at end of file'); - } - } - - var oldRangeStart = 0, newRangeStart = 0, curRange = [], - oldLine = 1, newLine = 1; - for (var i = 0; i < diff.length; i++) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - current.lines = lines; - - if (current.added || current.removed) { - if (!oldRangeStart) { - var prev = diff[i-1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - - if (prev) { - curRange = contextLines(prev.lines.slice(-4)); - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } - curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); - eofNL(curRange, i, current); - - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= 8 && i < diff.length-2) { - // Overlapping - curRange.push.apply(curRange, contextLines(lines)); - } else { - // end the range and output - var contextSize = Math.min(lines.length, 4); - ret.push( - '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) - + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) - + ' @@'); - ret.push.apply(ret, curRange); - ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); - if (lines.length <= 4) { - eofNL(ret, i, current); - } - - oldRangeStart = 0; newRangeStart = 0; curRange = []; - } - } - oldLine += lines.length; - newLine += lines.length; - } - } - - return ret.join('\n') + '\n'; - }, - - applyPatch: function(oldStr, uniDiff) { - var diffstr = uniDiff.split('\n'); - var diff = []; - var remEOFNL = false, - addEOFNL = false; - - for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { - if(diffstr[i][0] === '@') { - var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); - diff.unshift({ - start:meh[3], - oldlength:meh[2], - oldlines:[], - newlength:meh[4], - newlines:[] - }); - } else if(diffstr[i][0] === '+') { - diff[0].newlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === '-') { - diff[0].oldlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === ' ') { - diff[0].newlines.push(diffstr[i].substr(1)); - diff[0].oldlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === '\\') { - if (diffstr[i-1][0] === '+') { - remEOFNL = true; - } else if(diffstr[i-1][0] === '-') { - addEOFNL = true; - } - } - } - - var str = oldStr.split('\n'); - for (var i = diff.length - 1; i >= 0; i--) { - var d = diff[i]; - for (var j = 0; j < d.oldlength; j++) { - if(str[d.start-1+j] !== d.oldlines[j]) { - return false; - } - } - Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); - } - - if (remEOFNL) { - while (!str[str.length-1]) { - str.pop(); - } - } else if (addEOFNL) { - str.push(''); - } - return str.join('\n'); - }, - - convertChangesToXML: function(changes){ - var ret = []; - for ( var i = 0; i < changes.length; i++) { - var change = changes[i]; - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); - } - - ret.push(escapeHTML(change.value)); - - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); - } - } - return ret.join(''); - }, - - // See: http://code.google.com/p/google-diff-match-patch/wiki/API - convertChangesToDMP: function(changes){ - var ret = [], change; - for ( var i = 0; i < changes.length; i++) { - change = changes[i]; - ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); - } - return ret; - } - }; -})(); - -if (typeof module !== 'undefined') { - module.exports = JsDiff; -} - -}); // module: browser/diff.js - -require.register("browser/escape-string-regexp.js", function(module, exports, require){ -'use strict'; - -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - -module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - return str.replace(matchOperatorsRe, '\\$&'); -}; - -}); // module: browser/escape-string-regexp.js - -require.register("browser/events.js", function(module, exports, require){ - -/** - * Module exports. - */ - -exports.EventEmitter = EventEmitter; - -/** - * Check if `obj` is an array. - */ - -function isArray(obj) { - return '[object Array]' == {}.toString.call(obj); -} - -/** - * Event emitter constructor. - * - * @api public - */ - -function EventEmitter(){}; - -/** - * Adds a listener. - * - * @api public - */ - -EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } - - return this; -}; - -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -/** - * Adds a volatile listener. - * - * @api public - */ - -EventEmitter.prototype.once = function (name, fn) { - var self = this; - - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; - - on.listener = fn; - this.on(name, on); - - return this; -}; - -/** - * Removes a listener. - * - * @api public - */ - -EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; - - if (isArray(list)) { - var pos = -1; - - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } - - if (pos < 0) { - return this; - } - - list.splice(pos, 1); - - if (!list.length) { - delete this.$events[name]; - } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } - - return this; -}; - -/** - * Removes all listeners for an event. - * - * @api public - */ - -EventEmitter.prototype.removeAllListeners = function (name) { - if (name === undefined) { - this.$events = {}; - return this; - } - - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } - - return this; -}; - -/** - * Gets all listeners for a certain event. - * - * @api public - */ - -EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = []; - } - - if (!isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } - - return this.$events[name]; -}; - -/** - * Emits an event. - * - * @api public - */ - -EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } - - var handler = this.$events[name]; - - if (!handler) { - return false; - } - - var args = [].slice.call(arguments, 1); - - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (isArray(handler)) { - var listeners = handler.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } - - return true; -}; -}); // module: browser/events.js - -require.register("browser/fs.js", function(module, exports, require){ - -}); // module: browser/fs.js - -require.register("browser/glob.js", function(module, exports, require){ - -}); // module: browser/glob.js - -require.register("browser/path.js", function(module, exports, require){ - -}); // module: browser/path.js - -require.register("browser/progress.js", function(module, exports, require){ -/** - * Expose `Progress`. - */ - -module.exports = Progress; - -/** - * Initialize a new `Progress` indicator. - */ - -function Progress() { - this.percent = 0; - this.size(0); - this.fontSize(11); - this.font('helvetica, arial, sans-serif'); -} - -/** - * Set progress size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.size = function(n){ - this._size = n; - return this; -}; - -/** - * Set text to `str`. - * - * @param {String} str - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.text = function(str){ - this._text = str; - return this; -}; - -/** - * Set font size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.fontSize = function(n){ - this._fontSize = n; - return this; -}; - -/** - * Set font `family`. - * - * @param {String} family - * @return {Progress} for chaining - */ - -Progress.prototype.font = function(family){ - this._font = family; - return this; -}; - -/** - * Update percentage to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - */ - -Progress.prototype.update = function(n){ - this.percent = n; - return this; -}; - -/** - * Draw on `ctx`. - * - * @param {CanvasRenderingContext2d} ctx - * @return {Progress} for chaining - */ - -Progress.prototype.draw = function(ctx){ - try { - var percent = Math.min(this.percent, 100) - , size = this._size - , half = size / 2 - , x = half - , y = half - , rad = half - 1 - , fontSize = this._fontSize; - - ctx.font = fontSize + 'px ' + this._font; - - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); - - // outer circle - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); - - // inner circle - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); - - // text - var text = this._text || (percent | 0) + '%' - , w = ctx.measureText(text).width; - - ctx.fillText( - text - , x - w / 2 + 1 - , y + fontSize / 2 - 1); - } catch (ex) {} //don't fail if we can't render progress - return this; -}; - -}); // module: browser/progress.js - -require.register("browser/tty.js", function(module, exports, require){ - -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - if ('innerHeight' in global) { - return [global.innerHeight, global.innerWidth]; - } else { - // In a Web Worker, the DOM Window is not available. - return [640, 480]; - } -}; - -}); // module: browser/tty.js - -require.register("context.js", function(module, exports, require){ - -/** - * Expose `Context`. - */ - -module.exports = Context; - -/** - * Initialize a new `Context`. - * - * @api private - */ - -function Context(){} - -/** - * Set or get the context `Runnable` to `runnable`. - * - * @param {Runnable} runnable - * @return {Context} - * @api private - */ - -Context.prototype.runnable = function(runnable){ - if (0 == arguments.length) return this._runnable; - this.test = this._runnable = runnable; - return this; -}; - -/** - * Set test timeout `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.timeout = function(ms){ - if (arguments.length === 0) return this.runnable().timeout(); - this.runnable().timeout(ms); - return this; -}; - -/** - * Set test timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Context} self - * @api private - */ - -Context.prototype.enableTimeouts = function (enabled) { - this.runnable().enableTimeouts(enabled); - return this; -}; - - -/** - * Set test slowness threshold `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.slow = function(ms){ - this.runnable().slow(ms); - return this; -}; - -/** - * Inspect the context void of `._runnable`. - * - * @return {String} - * @api private - */ - -Context.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_runnable' == key) return; - if ('test' == key) return; - return val; - }, 2); -}; - -}); // module: context.js - -require.register("hook.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Hook`. - */ - -module.exports = Hook; - -/** - * Initialize a new `Hook` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Hook(title, fn) { - Runnable.call(this, title, fn); - this.type = 'hook'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Hook.prototype = new F; -Hook.prototype.constructor = Hook; - - -/** - * Get or set the test `err`. - * - * @param {Error} err - * @return {Error} - * @api public - */ - -Hook.prototype.error = function(err){ - if (0 == arguments.length) { - var err = this._error; - this._error = null; - return err; - } - - this._error = err; -}; - -}); // module: hook.js - -require.register("interfaces/bdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , utils = require('../utils') - , escapeRe = require('browser/escape-string-regexp'); - -/** - * BDD-style interface: - * - * describe('Array', function(){ - * describe('#indexOf()', function(){ - * it('should return -1 when not present', function(){ - * - * }); - * - * it('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before running tests. - */ - - context.before = function(name, fn){ - suites[0].beforeAll(name, fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(name, fn){ - suites[0].afterAll(name, fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(name, fn){ - suites[0].beforeEach(name, fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(name, fn){ - suites[0].afterEach(name, fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = context.context = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending describe. - */ - - context.xdescribe = - context.xcontext = - context.describe.skip = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive suite. - */ - - context.describe.only = function(title, fn){ - var suite = context.describe(title, fn); - mocha.grep(suite.fullTitle()); - return suite; - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.it = context.specify = function(title, fn){ - var suite = suites[0]; - if (suite.pending) fn = null; - var test = new Test(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.it.only = function(title, fn){ - var test = context.it(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - return test; - }; - - /** - * Pending test case. - */ - - context.xit = - context.xspecify = - context.it.skip = function(title){ - context.it(title); - }; - }); -}; - -}); // module: interfaces/bdd.js - -require.register("interfaces/exports.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function(){ - * - * }, - * - * 'should return the correct index when the value is present': function(){ - * - * } - * } - * }; - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj, file) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - var test = new Test(key, fn); - test.file = file; - suites[0].addTest(test); - } - } else { - suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); - } - } - } -}; - -}); // module: interfaces/exports.js - -require.register("interfaces/index.js", function(module, exports, require){ - -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.qunit = require('./qunit'); -exports.exports = require('./exports'); - -}); // module: interfaces/index.js - -require.register("interfaces/qunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , escapeRe = require('browser/escape-string-regexp') - , utils = require('../utils'); - -/** - * QUnit-style interface: - * - * suite('Array'); - * - * test('#length', function(){ - * var arr = [1,2,3]; - * ok(arr.length == 3); - * }); - * - * test('#indexOf()', function(){ - * var arr = [1,2,3]; - * ok(arr.indexOf(1) == 0); - * ok(arr.indexOf(2) == 1); - * ok(arr.indexOf(3) == 2); - * }); - * - * suite('String'); - * - * test('#length', function(){ - * ok('foo'.length == 3); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before running tests. - */ - - context.before = function(name, fn){ - suites[0].beforeAll(name, fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(name, fn){ - suites[0].afterAll(name, fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(name, fn){ - suites[0].beforeEach(name, fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(name, fn){ - suites[0].afterEach(name, fn); - }; - - /** - * Describe a "suite" with the given `title`. - */ - - context.suite = function(title){ - if (suites.length > 1) suites.shift(); - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - return suite; - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var test = new Test(title, fn); - test.file = file; - suites[0].addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; - - /** - * Pending test case. - */ - - context.test.skip = function(title){ - context.test(title); - }; - }); -}; - -}); // module: interfaces/qunit.js - -require.register("interfaces/tdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , escapeRe = require('browser/escape-string-regexp') - , utils = require('../utils'); - -/** - * TDD-style interface: - * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * suiteSetup(function(){ - * - * }); - * - * test('should return -1 when not present', function(){ - * - * }); - * - * test('should return the index when present', function(){ - * - * }); - * - * suiteTeardown(function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before each test case. - */ - - context.setup = function(name, fn){ - suites[0].beforeEach(name, fn); - }; - - /** - * Execute after each test case. - */ - - context.teardown = function(name, fn){ - suites[0].afterEach(name, fn); - }; - - /** - * Execute before the suite. - */ - - context.suiteSetup = function(name, fn){ - suites[0].beforeAll(name, fn); - }; - - /** - * Execute after the suite. - */ - - context.suiteTeardown = function(name, fn){ - suites[0].afterAll(name, fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending suite. - */ - context.suite.skip = function(title, fn) { - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var suite = suites[0]; - if (suite.pending) fn = null; - var test = new Test(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; - - /** - * Pending test case. - */ - - context.test.skip = function(title){ - context.test(title); - }; - }); -}; - -}); // module: interfaces/tdd.js - -require.register("mocha.js", function(module, exports, require){ -/*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var path = require('browser/path') - , escapeRe = require('browser/escape-string-regexp') - , utils = require('./utils'); - -/** - * Expose `Mocha`. - */ - -exports = module.exports = Mocha; - -/** - * To require local UIs and reporters when running in node. - */ - -if (typeof process !== 'undefined' && typeof process.cwd === 'function') { - var join = path.join - , cwd = process.cwd(); - module.paths.push(cwd, join(cwd, 'node_modules')); -} - -/** - * Expose internals. - */ - -exports.utils = utils; -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Context = require('./context'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); - -/** - * Return image `name` path. - * - * @param {String} name - * @return {String} - * @api private - */ - -function image(name) { - return __dirname + '/../images/' + name + '.png'; -} - -/** - * Setup mocha with `options`. - * - * Options: - * - * - `ui` name "bdd", "tdd", "exports" etc - * - `reporter` reporter instance, defaults to `mocha.reporters.spec` - * - `globals` array of accepted globals - * - `timeout` timeout in milliseconds - * - `bail` bail on the first test failure - * - `slow` milliseconds to wait before considering a test slow - * - `ignoreLeaks` ignore global leaks - * - `grep` string or regexp to filter tests with - * - * @param {Object} options - * @api public - */ - -function Mocha(options) { - options = options || {}; - this.files = []; - this.options = options; - this.grep(options.grep); - this.suite = new exports.Suite('', new exports.Context); - this.ui(options.ui); - this.bail(options.bail); - this.reporter(options.reporter); - if (null != options.timeout) this.timeout(options.timeout); - this.useColors(options.useColors) - if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts); - if (options.slow) this.slow(options.slow); - - this.suite.on('pre-require', function (context) { - exports.afterEach = context.afterEach || context.teardown; - exports.after = context.after || context.suiteTeardown; - exports.beforeEach = context.beforeEach || context.setup; - exports.before = context.before || context.suiteSetup; - exports.describe = context.describe || context.suite; - exports.it = context.it || context.test; - exports.setup = context.setup || context.beforeEach; - exports.suiteSetup = context.suiteSetup || context.before; - exports.suiteTeardown = context.suiteTeardown || context.after; - exports.suite = context.suite || context.describe; - exports.teardown = context.teardown || context.afterEach; - exports.test = context.test || context.it; - }); -} - -/** - * Enable or disable bailing on the first failure. - * - * @param {Boolean} [bail] - * @api public - */ - -Mocha.prototype.bail = function(bail){ - if (0 == arguments.length) bail = true; - this.suite.bail(bail); - return this; -}; - -/** - * Add test `file`. - * - * @param {String} file - * @api public - */ - -Mocha.prototype.addFile = function(file){ - this.files.push(file); - return this; -}; - -/** - * Set reporter to `reporter`, defaults to "spec". - * - * @param {String|Function} reporter name or constructor - * @api public - */ - -Mocha.prototype.reporter = function(reporter){ - if ('function' == typeof reporter) { - this._reporter = reporter; - } else { - reporter = reporter || 'spec'; - var _reporter; - try { _reporter = require('./reporters/' + reporter); } catch (err) {}; - if (!_reporter) try { _reporter = require(reporter); } catch (err) {}; - if (!_reporter && reporter === 'teamcity') - console.warn('The Teamcity reporter was moved to a package named ' + - 'mocha-teamcity-reporter ' + - '(https://npmjs.org/package/mocha-teamcity-reporter).'); - if (!_reporter) throw new Error('invalid reporter "' + reporter + '"'); - this._reporter = _reporter; - } - return this; -}; - -/** - * Set test UI `name`, defaults to "bdd". - * - * @param {String} bdd - * @api public - */ - -Mocha.prototype.ui = function(name){ - name = name || 'bdd'; - this._ui = exports.interfaces[name]; - if (!this._ui) try { this._ui = require(name); } catch (err) {}; - if (!this._ui) throw new Error('invalid interface "' + name + '"'); - this._ui = this._ui(this.suite); - return this; -}; - -/** - * Load registered files. - * - * @api private - */ - -Mocha.prototype.loadFiles = function(fn){ - var self = this; - var suite = this.suite; - var pending = this.files.length; - this.files.forEach(function(file){ - file = path.resolve(file); - suite.emit('pre-require', global, file, self); - suite.emit('require', require(file), file, self); - suite.emit('post-require', global, file, self); - --pending || (fn && fn()); - }); -}; - -/** - * Enable growl support. - * - * @api private - */ - -Mocha.prototype._growl = function(runner, reporter) { - var notify = require('growl'); - - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + runner.total + ' tests failed'; - notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: image('ok') - }); - } - }); -}; - -/** - * Add regexp to grep, if `re` is a string it is escaped. - * - * @param {RegExp|String} re - * @return {Mocha} - * @api public - */ - -Mocha.prototype.grep = function(re){ - this.options.grep = 'string' == typeof re - ? new RegExp(escapeRe(re)) - : re; - return this; -}; - -/** - * Invert `.grep()` matches. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.invert = function(){ - this.options.invert = true; - return this; -}; - -/** - * Ignore global leaks. - * - * @param {Boolean} ignore - * @return {Mocha} - * @api public - */ - -Mocha.prototype.ignoreLeaks = function(ignore){ - this.options.ignoreLeaks = !!ignore; - return this; -}; - -/** - * Enable global leak checking. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.checkLeaks = function(){ - this.options.ignoreLeaks = false; - return this; -}; - -/** - * Enable growl support. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.growl = function(){ - this.options.growl = true; - return this; -}; - -/** - * Ignore `globals` array or string. - * - * @param {Array|String} globals - * @return {Mocha} - * @api public - */ - -Mocha.prototype.globals = function(globals){ - this.options.globals = (this.options.globals || []).concat(globals); - return this; -}; - -/** - * Emit color output. - * - * @param {Boolean} colors - * @return {Mocha} - * @api public - */ - -Mocha.prototype.useColors = function(colors){ - this.options.useColors = arguments.length && colors != undefined - ? colors - : true; - return this; -}; - -/** - * Use inline diffs rather than +/-. - * - * @param {Boolean} inlineDiffs - * @return {Mocha} - * @api public - */ - -Mocha.prototype.useInlineDiffs = function(inlineDiffs) { - this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined - ? inlineDiffs - : false; - return this; -}; - -/** - * Set the timeout in milliseconds. - * - * @param {Number} timeout - * @return {Mocha} - * @api public - */ - -Mocha.prototype.timeout = function(timeout){ - this.suite.timeout(timeout); - return this; -}; - -/** - * Set slowness threshold in milliseconds. - * - * @param {Number} slow - * @return {Mocha} - * @api public - */ - -Mocha.prototype.slow = function(slow){ - this.suite.slow(slow); - return this; -}; - -/** - * Enable timeouts. - * - * @param {Boolean} enabled - * @return {Mocha} - * @api public - */ - -Mocha.prototype.enableTimeouts = function(enabled) { - this.suite.enableTimeouts(arguments.length && enabled !== undefined - ? enabled - : true); - return this -}; - -/** - * Makes all tests async (accepting a callback) - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.asyncOnly = function(){ - this.options.asyncOnly = true; - return this; -}; - -/** - * Disable syntax highlighting (in browser). - * @returns {Mocha} - * @api public - */ -Mocha.prototype.noHighlighting = function() { - this.options.noHighlighting = true; - return this; -}; - -/** - * Run tests and invoke `fn()` when complete. - * - * @param {Function} fn - * @return {Runner} - * @api public - */ - -Mocha.prototype.run = function(fn){ - if (this.files.length) this.loadFiles(); - var suite = this.suite; - var options = this.options; - options.files = this.files; - var runner = new exports.Runner(suite); - var reporter = new this._reporter(runner, options); - runner.ignoreLeaks = false !== options.ignoreLeaks; - runner.asyncOnly = options.asyncOnly; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - exports.reporters.Base.useColors = options.useColors; - exports.reporters.Base.inlineDiffs = options.useInlineDiffs; - return runner.run(fn); -}; - -}); // module: mocha.js - -require.register("ms.js", function(module, exports, require){ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} options - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options){ - options = options || {}; - if ('string' == typeof val) return parse(val); - return options['long'] ? longFormat(val) : shortFormat(val); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!match) return; - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 's': - return n * s; - case 'ms': - return n; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function shortFormat(ms) { - if (ms >= d) return Math.round(ms / d) + 'd'; - if (ms >= h) return Math.round(ms / h) + 'h'; - if (ms >= m) return Math.round(ms / m) + 'm'; - if (ms >= s) return Math.round(ms / s) + 's'; - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function longFormat(ms) { - return plural(ms, d, 'day') - || plural(ms, h, 'hour') - || plural(ms, m, 'minute') - || plural(ms, s, 'second') - || ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) return; - if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; - return Math.ceil(ms / n) + ' ' + name + 's'; -} - -}); // module: ms.js - -require.register("reporters/base.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var tty = require('browser/tty') - , diff = require('browser/diff') - , ms = require('../ms') - , utils = require('../utils'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Check if both stdio streams are associated with a tty. - */ - -var isatty = tty.isatty(1) && tty.isatty(2); - -/** - * Expose `Base`. - */ - -exports = module.exports = Base; - -/** - * Enable coloring by default. - */ - -exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined); - -/** - * Inline diffs instead of +/- - */ - -exports.inlineDiffs = false; - -/** - * Default color map. - */ - -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': 0 - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 - , 'diff gutter': 90 - , 'diff added': 42 - , 'diff removed': 41 -}; - -/** - * Default symbol map. - */ - -exports.symbols = { - ok: '✓', - err: '✖', - dot: '․' -}; - -// With node.js on Windows: use symbols available in terminal default fonts -if ('win32' == process.platform) { - exports.symbols.ok = '\u221A'; - exports.symbols.err = '\u00D7'; - exports.symbols.dot = '.'; -} - -/** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @param {String} type - * @param {String} str - * @return {String} - * @api private - */ - -var color = exports.color = function(type, str) { - if (!exports.useColors) return str; - return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; -}; - -/** - * Expose term window size, with some - * defaults for when stderr is not a tty. - */ - -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; - -/** - * Expose some basic cursor interactions - * that are common among reporters. - */ - -exports.cursor = { - hide: function(){ - isatty && process.stdout.write('\u001b[?25l'); - }, - - show: function(){ - isatty && process.stdout.write('\u001b[?25h'); - }, - - deleteLine: function(){ - isatty && process.stdout.write('\u001b[2K'); - }, - - beginningOfLine: function(){ - isatty && process.stdout.write('\u001b[0G'); - }, - - CR: function(){ - if (isatty) { - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); - } else { - process.stdout.write('\r'); - } - } -}; - -/** - * Outut the given `failures` as a list. - * - * @param {Array} failures - * @api public - */ - -exports.list = function(failures){ - console.error(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var err = test.err - , message = err.message || '' - , stack = err.stack || message - , index = stack.indexOf(message) + message.length - , msg = stack.slice(0, index) - , actual = err.actual - , expected = err.expected - , escape = true; - - // uncaught - if (err.uncaught) { - msg = 'Uncaught ' + msg; - } - - // explicitly show diff - if (err.showDiff && sameType(actual, expected)) { - escape = false; - err.actual = actual = utils.stringify(actual); - err.expected = expected = utils.stringify(expected); - } - - // actual / expected diff - if (err.showDiff && 'string' == typeof actual && 'string' == typeof expected) { - fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); - var match = message.match(/^([^:]+): expected/); - msg = '\n ' + color('error message', match ? match[1] : msg); - - if (exports.inlineDiffs) { - msg += inlineDiff(err, escape); - } else { - msg += unifiedDiff(err, escape); - } - } - - // indent stack trace without msg - stack = stack.slice(index ? index + 1 : index) - .replace(/^/gm, ' '); - - console.error(fmt, (i + 1), test.fullTitle(), msg, stack); - }); -}; - -/** - * Initialize a new `Base` reporter. - * - * All other reporters generally - * inherit from this reporter, providing - * stats such as test duration, number - * of tests passed / failed etc. - * - * @param {Runner} runner - * @api public - */ - -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } - , failures = this.failures = []; - - if (!runner) return; - this.runner = runner; - - runner.stats = stats; - - runner.on('start', function(){ - stats.start = new Date; - }); - - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - suite.root || stats.suites++; - }); - - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); - - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; - - var medium = test.slow() / 2; - test.speed = test.duration > test.slow() - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; - - stats.passes++; - }); - - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); - - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); - - runner.on('pending', function(){ - stats.pending++; - }); -} - -/** - * Output common epilogue used by many of - * the bundled reporters. - * - * @api public - */ - -Base.prototype.epilogue = function(){ - var stats = this.stats; - var tests; - var fmt; - - console.log(); - - // passes - fmt = color('bright pass', ' ') - + color('green', ' %d passing') - + color('light', ' (%s)'); - - console.log(fmt, - stats.passes || 0, - ms(stats.duration)); - - // pending - if (stats.pending) { - fmt = color('pending', ' ') - + color('pending', ' %d pending'); - - console.log(fmt, stats.pending); - } - - // failures - if (stats.failures) { - fmt = color('fail', ' %d failing'); - - console.error(fmt, - stats.failures); - - Base.list(this.failures); - console.error(); - } - - console.log(); -}; - -/** - * Pad the given `str` to `len`. - * - * @param {String} str - * @param {String} len - * @return {String} - * @api private - */ - -function pad(str, len) { - str = String(str); - return Array(len - str.length + 1).join(' ') + str; -} - - -/** - * Returns an inline diff between 2 strings with coloured ANSI output - * - * @param {Error} Error with actual/expected - * @return {String} Diff - * @api private - */ - -function inlineDiff(err, escape) { - var msg = errorDiff(err, 'WordsWithSpace', escape); - - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } - - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; - - // indent - msg = msg.replace(/^/gm, ' '); - return msg; -} - -/** - * Returns a unified diff between 2 strings - * - * @param {Error} Error with actual/expected - * @return {String} Diff - * @api private - */ - -function unifiedDiff(err, escape) { - var indent = ' '; - function cleanUp(line) { - if (escape) { - line = escapeInvisibles(line); - } - if (line[0] === '+') return indent + colorLines('diff added', line); - if (line[0] === '-') return indent + colorLines('diff removed', line); - if (line.match(/\@\@/)) return null; - if (line.match(/\\ No newline/)) return null; - else return indent + line; - } - function notBlank(line) { - return line != null; - } - msg = diff.createPatch('string', err.actual, err.expected); - var lines = msg.split('\n').splice(4); - return '\n ' - + colorLines('diff added', '+ expected') + ' ' - + colorLines('diff removed', '- actual') - + '\n\n' - + lines.map(cleanUp).filter(notBlank).join('\n'); -} - -/** - * Return a character diff for `err`. - * - * @param {Error} err - * @return {String} - * @api private - */ - -function errorDiff(err, type, escape) { - var actual = escape ? escapeInvisibles(err.actual) : err.actual; - var expected = escape ? escapeInvisibles(err.expected) : err.expected; - return diff['diff' + type](actual, expected).map(function(str){ - if (str.added) return colorLines('diff added', str.value); - if (str.removed) return colorLines('diff removed', str.value); - return str.value; - }).join(''); -} - -/** - * Returns a string with all invisible characters in plain text - * - * @param {String} line - * @return {String} - * @api private - */ -function escapeInvisibles(line) { - return line.replace(/\t/g, '') - .replace(/\r/g, '') - .replace(/\n/g, '\n'); -} - -/** - * Color lines for `str`, using the color `name`. - * - * @param {String} name - * @param {String} str - * @return {String} - * @api private - */ - -function colorLines(name, str) { - return str.split('\n').map(function(str){ - return color(name, str); - }).join('\n'); -} - -/** - * Check that a / b have the same type. - * - * @param {Object} a - * @param {Object} b - * @return {Boolean} - * @api private - */ - -function sameType(a, b) { - a = Object.prototype.toString.call(a); - b = Object.prototype.toString.call(b); - return a == b; -} - -}); // module: reporters/base.js - -require.register("reporters/doc.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = Doc; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Doc(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
      ', indent()); - ++indents; - console.log('%s

      %s

      ', indent(), utils.escape(suite.title)); - console.log('%s
      ', indent()); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - console.log('%s
      ', indent()); - --indents; - console.log('%s
      ', indent()); - --indents; - }); - - runner.on('pass', function(test){ - console.log('%s
      %s
      ', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
      %s
      ', indent(), code); - }); - - runner.on('fail', function(test, err){ - console.log('%s
      %s
      ', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
      %s
      ', indent(), code); - console.log('%s
      %s
      ', indent(), utils.escape(err)); - }); -} - -}); // module: reporters/doc.js - -require.register("reporters/dot.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = Dot; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Dot(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , n = -1; - - runner.on('start', function(){ - process.stdout.write('\n '); - }); - - runner.on('pending', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('pending', Base.symbols.dot)); - }); - - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', Base.symbols.dot)); - } else { - process.stdout.write(color(test.speed, Base.symbols.dot)); - } - }); - - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', Base.symbols.dot)); - }); - - runner.on('end', function(){ - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Dot.prototype = new F; -Dot.prototype.constructor = Dot; - - -}); // module: reporters/dot.js - -require.register("reporters/html-cov.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var JSONCov = require('./json-cov') - , fs = require('browser/fs'); - -/** - * Expose `HTMLCov`. - */ - -exports = module.exports = HTMLCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTMLCov(runner) { - var jade = require('jade') - , file = __dirname + '/templates/coverage.jade' - , str = fs.readFileSync(file, 'utf8') - , fn = jade.compile(str, { filename: file }) - , self = this; - - JSONCov.call(this, runner, false); - - runner.on('end', function(){ - process.stdout.write(fn({ - cov: self.cov - , coverageClass: coverageClass - })); - }); -} - -/** - * Return coverage class for `n`. - * - * @return {String} - * @api private - */ - -function coverageClass(n) { - if (n >= 75) return 'high'; - if (n >= 50) return 'medium'; - if (n >= 25) return 'low'; - return 'terrible'; -} -}); // module: reporters/html-cov.js - -require.register("reporters/html.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , Progress = require('../browser/progress') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `HTML`. - */ - -exports = module.exports = HTML; - -/** - * Stats template. - */ - -var statsTemplate = ''; - -/** - * Initialize a new `HTML` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTML(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , stat = fragment(statsTemplate) - , items = stat.getElementsByTagName('li') - , passes = items[1].getElementsByTagName('em')[0] - , passesLink = items[1].getElementsByTagName('a')[0] - , failures = items[2].getElementsByTagName('em')[0] - , failuresLink = items[2].getElementsByTagName('a')[0] - , duration = items[3].getElementsByTagName('em')[0] - , canvas = stat.getElementsByTagName('canvas')[0] - , report = fragment('
        ') - , stack = [report] - , progress - , ctx - , root = document.getElementById('mocha'); - - if (canvas.getContext) { - var ratio = window.devicePixelRatio || 1; - canvas.style.width = canvas.width; - canvas.style.height = canvas.height; - canvas.width *= ratio; - canvas.height *= ratio; - ctx = canvas.getContext('2d'); - ctx.scale(ratio, ratio); - progress = new Progress; - } - - if (!root) return error('#mocha div missing, add it to your document'); - - // pass toggle - on(passesLink, 'click', function(){ - unhide(); - var name = /pass/.test(report.className) ? '' : ' pass'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test pass'); - }); - - // failure toggle - on(failuresLink, 'click', function(){ - unhide(); - var name = /fail/.test(report.className) ? '' : ' fail'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test fail'); - }); - - root.appendChild(stat); - root.appendChild(report); - - if (progress) progress.size(40); - - runner.on('suite', function(suite){ - if (suite.root) return; - - // suite - var url = self.suiteURL(suite); - var el = fragment('
      • %s

      • ', url, escape(suite.title)); - - // container - stack[0].appendChild(el); - stack.unshift(document.createElement('ul')); - el.appendChild(stack[0]); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - stack.shift(); - }); - - runner.on('fail', function(test, err){ - if ('hook' == test.type) runner.emit('test end', test); - }); - - runner.on('test end', function(test){ - // TODO: add to stats - var percent = stats.tests / this.total * 100 | 0; - if (progress) progress.update(percent).draw(ctx); - - // update stats - var ms = new Date - stats.start; - text(passes, stats.passes); - text(failures, stats.failures); - text(duration, (ms / 1000).toFixed(2)); - - // test - if ('passed' == test.state) { - var url = self.testURL(test); - var el = fragment('
      • %e%ems

      • ', test.speed, test.title, test.duration, url); - } else if (test.pending) { - var el = fragment('
      • %e

      • ', test.title); - } else { - var el = fragment('
      • %e

      • ', test.title, encodeURIComponent(test.fullTitle())); - var str = test.err.stack || test.err.toString(); - - // FF / Opera do not add the message - if (!~str.indexOf(test.err.message)) { - str = test.err.message + '\n' + str; - } - - // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - if ('[object Error]' == str) str = test.err.message; - - // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { - str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; - } - - el.appendChild(fragment('
        %e
        ', str)); - } - - // toggle code - // TODO: defer - if (!test.pending) { - var h2 = el.getElementsByTagName('h2')[0]; - - on(h2, 'click', function(){ - pre.style.display = 'none' == pre.style.display - ? 'block' - : 'none'; - }); - - var pre = fragment('
        %e
        ', utils.clean(test.fn.toString())); - el.appendChild(pre); - pre.style.display = 'none'; - } - - // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. - if (stack[0]) stack[0].appendChild(el); - }); -} - -/** - * Provide suite URL - * - * @param {Object} [suite] - */ - -HTML.prototype.suiteURL = function(suite){ - return '?grep=' + encodeURIComponent(suite.fullTitle()); -}; - -/** - * Provide test URL - * - * @param {Object} [test] - */ - -HTML.prototype.testURL = function(test){ - return '?grep=' + encodeURIComponent(test.fullTitle()); -}; - -/** - * Display error `msg`. - */ - -function error(msg) { - document.body.appendChild(fragment('
        %s
        ', msg)); -} - -/** - * Return a DOM fragment from `html`. - */ - -function fragment(html) { - var args = arguments - , div = document.createElement('div') - , i = 1; - - div.innerHTML = html.replace(/%([se])/g, function(_, type){ - switch (type) { - case 's': return String(args[i++]); - case 'e': return escape(args[i++]); - } - }); - - return div.firstChild; -} - -/** - * Check for suites that do not have elements - * with `classname`, and hide them. - */ - -function hideSuitesWithout(classname) { - var suites = document.getElementsByClassName('suite'); - for (var i = 0; i < suites.length; i++) { - var els = suites[i].getElementsByClassName(classname); - if (0 == els.length) suites[i].className += ' hidden'; - } -} - -/** - * Unhide .hidden suites. - */ - -function unhide() { - var els = document.getElementsByClassName('suite hidden'); - for (var i = 0; i < els.length; ++i) { - els[i].className = els[i].className.replace('suite hidden', 'suite'); - } -} - -/** - * Set `el` text to `str`. - */ - -function text(el, str) { - if (el.textContent) { - el.textContent = str; - } else { - el.innerText = str; - } -} - -/** - * Listen on `event` with callback `fn`. - */ - -function on(el, event, fn) { - if (el.addEventListener) { - el.addEventListener(event, fn, false); - } else { - el.attachEvent('on' + event, fn); - } -} - -}); // module: reporters/html.js - -require.register("reporters/index.js", function(module, exports, require){ - -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Min = require('./min'); -exports.Spec = require('./spec'); -exports.Nyan = require('./nyan'); -exports.XUnit = require('./xunit'); -exports.Markdown = require('./markdown'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONCov = require('./json-cov'); -exports.HTMLCov = require('./html-cov'); -exports.JSONStream = require('./json-stream'); - -}); // module: reporters/index.js - -require.register("reporters/json-cov.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `JSONCov`. - */ - -exports = module.exports = JSONCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @param {Boolean} output - * @api public - */ - -function JSONCov(runner, output) { - var self = this - , output = 1 == arguments.length ? true : output; - - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var cov = global._$jscoverage || {}; - var result = self.cov = map(cov); - result.stats = self.stats; - result.tests = tests.map(clean); - result.failures = failures.map(clean); - result.passes = passes.map(clean); - if (!output) return; - process.stdout.write(JSON.stringify(result, null, 2 )); - }); -} - -/** - * Map jscoverage data to a JSON structure - * suitable for reporting. - * - * @param {Object} cov - * @return {Object} - * @api private - */ - -function map(cov) { - var ret = { - instrumentation: 'node-jscoverage' - , sloc: 0 - , hits: 0 - , misses: 0 - , coverage: 0 - , files: [] - }; - - for (var filename in cov) { - var data = coverage(filename, cov[filename]); - ret.files.push(data); - ret.hits += data.hits; - ret.misses += data.misses; - ret.sloc += data.sloc; - } - - ret.files.sort(function(a, b) { - return a.filename.localeCompare(b.filename); - }); - - if (ret.sloc > 0) { - ret.coverage = (ret.hits / ret.sloc) * 100; - } - - return ret; -} - -/** - * Map jscoverage data for a single source file - * to a JSON structure suitable for reporting. - * - * @param {String} filename name of the source file - * @param {Object} data jscoverage coverage data - * @return {Object} - * @api private - */ - -function coverage(filename, data) { - var ret = { - filename: filename, - coverage: 0, - hits: 0, - misses: 0, - sloc: 0, - source: {} - }; - - data.source.forEach(function(line, num){ - num++; - - if (data[num] === 0) { - ret.misses++; - ret.sloc++; - } else if (data[num] !== undefined) { - ret.hits++; - ret.sloc++; - } - - ret.source[num] = { - source: line - , coverage: data[num] === undefined - ? '' - : data[num] - }; - }); - - ret.coverage = ret.hits / ret.sloc * 100; - - return ret; -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} - -}); // module: reporters/json-cov.js - -require.register("reporters/json-stream.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total; - - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); - - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); - - runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); - }); - - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats])); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json-stream.js - -require.register("reporters/json.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `JSON`. - */ - -exports = module.exports = JSONReporter; - -/** - * Initialize a new `JSON` reporter. - * - * @param {Runner} runner - * @api public - */ - -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); - - var tests = [] - , pending = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('pending', function(test){ - pending.push(test); - }); - - runner.on('end', function(){ - var obj = { - stats: self.stats, - tests: tests.map(clean), - pending: pending.map(clean), - failures: failures.map(clean), - passes: passes.map(clean) - }; - - runner.testResults = obj; - - process.stdout.write(JSON.stringify(obj, null, 2)); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title, - fullTitle: test.fullTitle(), - duration: test.duration, - err: errorJSON(test.err || {}) - } -} - -/** - * Transform `error` into a JSON object. - * @param {Error} err - * @return {Object} - */ - -function errorJSON(err) { - var res = {}; - Object.getOwnPropertyNames(err).forEach(function(key) { - res[key] = err[key]; - }, err); - return res; -} - -}); // module: reporters/json.js - -require.register("reporters/landing.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Landing`. - */ - -exports = module.exports = Landing; - -/** - * Airplane color. - */ - -Base.colors.plane = 0; - -/** - * Airplane crash color. - */ - -Base.colors['plane crash'] = 31; - -/** - * Runway color. - */ - -Base.colors.runway = 90; - -/** - * Initialize a new `Landing` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Landing(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on('start', function(){ - stream.write('\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if ('failed' == test.state) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\u001b[4F\n\n'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\u001b[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Landing.prototype = new F; -Landing.prototype.constructor = Landing; - -}); // module: reporters/landing.js - -require.register("reporters/list.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 0; - - runner.on('start', function(){ - console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); - - runner.on('pass', function(test){ - var fmt = color('checkmark', ' '+Base.symbols.dot) - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - cursor.CR(); - console.log(fmt, test.fullTitle(), test.duration); - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -List.prototype = new F; -List.prototype.constructor = List; - - -}); // module: reporters/list.js - -require.register("reporters/markdown.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Markdown`. - */ - -exports = module.exports = Markdown; - -/** - * Initialize a new `Markdown` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Markdown(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , level = 0 - , buf = ''; - - function title(str) { - return Array(level).join('#') + ' ' + str; - } - - function indent() { - return Array(level).join(' '); - } - - function mapTOC(suite, obj) { - var ret = obj; - obj = obj[suite.title] = obj[suite.title] || { suite: suite }; - suite.suites.forEach(function(suite){ - mapTOC(suite, obj); - }); - return ret; - } - - function stringifyTOC(obj, level) { - ++level; - var buf = ''; - var link; - for (var key in obj) { - if ('suite' == key) continue; - if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; - if (key) buf += Array(level).join(' ') + link; - buf += stringifyTOC(obj[key], level); - } - --level; - return buf; - } - - function generateTOC(suite) { - var obj = mapTOC(suite, {}); - return stringifyTOC(obj, 0); - } - - generateTOC(runner.suite); - - runner.on('suite', function(suite){ - ++level; - var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; - buf += title(suite.title) + '\n'; - }); - - runner.on('suite end', function(suite){ - --level; - }); - - runner.on('pass', function(test){ - var code = utils.clean(test.fn.toString()); - buf += test.title + '.\n'; - buf += '\n```js\n'; - buf += code + '\n'; - buf += '```\n\n'; - }); - - runner.on('end', function(){ - process.stdout.write('# TOC\n'); - process.stdout.write(generateTOC(runner.suite)); - process.stdout.write(buf); - }); -} -}); // module: reporters/markdown.js - -require.register("reporters/min.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Min`. - */ - -exports = module.exports = Min; - -/** - * Initialize a new `Min` minimal test reporter (best used with --watch). - * - * @param {Runner} runner - * @api public - */ - -function Min(runner) { - Base.call(this, runner); - - runner.on('start', function(){ - // clear screen - process.stdout.write('\u001b[2J'); - // set cursor position - process.stdout.write('\u001b[1;3H'); - }); - - runner.on('end', this.epilogue.bind(this)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Min.prototype = new F; -Min.prototype.constructor = Min; - - -}); // module: reporters/min.js - -require.register("reporters/nyan.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = NyanCat; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function NyanCat(runner) { - Base.call(this, runner); - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , rainbowColors = this.rainbowColors = self.generateColors() - , colorIndex = this.colorIndex = 0 - , numerOfLines = this.numberOfLines = 4 - , trajectories = this.trajectories = [[], [], [], []] - , nyanCatWidth = this.nyanCatWidth = 11 - , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) - , scoreboardWidth = this.scoreboardWidth = 5 - , tick = this.tick = 0 - , n = 0; - - runner.on('start', function(){ - Base.cursor.hide(); - self.draw(); - }); - - runner.on('pending', function(test){ - self.draw(); - }); - - runner.on('pass', function(test){ - self.draw(); - }); - - runner.on('fail', function(test, err){ - self.draw(); - }); - - runner.on('end', function(){ - Base.cursor.show(); - for (var i = 0; i < self.numberOfLines; i++) write('\n'); - self.epilogue(); - }); -} - -/** - * Draw the nyan cat - * - * @api private - */ - -NyanCat.prototype.draw = function(){ - this.appendRainbow(); - this.drawScoreboard(); - this.drawRainbow(); - this.drawNyanCat(); - this.tick = !this.tick; -}; - -/** - * Draw the "scoreboard" showing the number - * of passes, failures and pending tests. - * - * @api private - */ - -NyanCat.prototype.drawScoreboard = function(){ - var stats = this.stats; - var colors = Base.colors; - - function draw(color, n) { - write(' '); - write('\u001b[' + color + 'm' + n + '\u001b[0m'); - write('\n'); - } - - draw(colors.green, stats.passes); - draw(colors.fail, stats.failures); - draw(colors.pending, stats.pending); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Append the rainbow. - * - * @api private - */ - -NyanCat.prototype.appendRainbow = function(){ - var segment = this.tick ? '_' : '-'; - var rainbowified = this.rainbowify(segment); - - for (var index = 0; index < this.numberOfLines; index++) { - var trajectory = this.trajectories[index]; - if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); - trajectory.push(rainbowified); - } -}; - -/** - * Draw the rainbow. - * - * @api private - */ - -NyanCat.prototype.drawRainbow = function(){ - var self = this; - - this.trajectories.forEach(function(line, index) { - write('\u001b[' + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); - }); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw the nyan cat - * - * @api private - */ - -NyanCat.prototype.drawNyanCat = function() { - var self = this; - var startWidth = this.scoreboardWidth + this.trajectories[0].length; - var color = '\u001b[' + startWidth + 'C'; - var padding = ''; - - write(color); - write('_,------,'); - write('\n'); - - write(color); - padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - - write(color); - padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - write(tail + '|' + padding + this.face() + ' '); - write('\n'); - - write(color); - padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw nyan cat face. - * - * @return {String} - * @api private - */ - -NyanCat.prototype.face = function() { - var stats = this.stats; - if (stats.failures) { - return '( x .x)'; - } else if (stats.pending) { - return '( o .o)'; - } else if(stats.passes) { - return '( ^ .^)'; - } else { - return '( - .-)'; - } -}; - -/** - * Move cursor up `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorUp = function(n) { - write('\u001b[' + n + 'A'); -}; - -/** - * Move cursor down `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorDown = function(n) { - write('\u001b[' + n + 'B'); -}; - -/** - * Generate rainbow colors. - * - * @return {Array} - * @api private - */ - -NyanCat.prototype.generateColors = function(){ - var colors = []; - - for (var i = 0; i < (6 * 7); i++) { - var pi3 = Math.floor(Math.PI / 3); - var n = (i * (1.0 / 6)); - var r = Math.floor(3 * Math.sin(n) + 3); - var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); - var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); - colors.push(36 * r + 6 * g + b + 16); - } - - return colors; -}; - -/** - * Apply rainbow to the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -NyanCat.prototype.rainbowify = function(str){ - var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; - this.colorIndex += 1; - return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; -}; - -/** - * Stdout helper. - */ - -function write(string) { - process.stdout.write(string); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -NyanCat.prototype = new F; -NyanCat.prototype.constructor = NyanCat; - - -}); // module: reporters/nyan.js - -require.register("reporters/progress.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Progress`. - */ - -exports = module.exports = Progress; - -/** - * General progress bar color. - */ - -Base.colors.progress = 90; - -/** - * Initialize a new `Progress` bar test reporter. - * - * @param {Runner} runner - * @param {Object} options - * @api public - */ - -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max - , lastN = -1; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || Base.symbols.dot; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - complete++; - var incomplete = total - complete - , percent = complete / total - , n = width * percent | 0 - , i = width - n; - - if (lastN === n && !options.verbose) { - // Don't re-render the line if it hasn't changed - return; - } - lastN = n; - - cursor.CR(); - process.stdout.write('\u001b[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Progress.prototype = new F; -Progress.prototype.constructor = Progress; - - -}); // module: reporters/progress.js - -require.register("reporters/spec.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Spec`. - */ - -exports = module.exports = Spec; - -/** - * Initialize a new `Spec` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Spec(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , indents = 0 - , n = 0; - - function indent() { - return Array(indents).join(' ') - } - - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s '); - cursor.CR(); - console.log(fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s ') - + color(test.speed, '(%dms)'); - cursor.CR(); - console.log(fmt, test.title, test.duration); - } - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Spec.prototype = new F; -Spec.prototype.constructor = Spec; - - -}); // module: reporters/spec.js - -require.register("reporters/tap.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `TAP`. - */ - -exports = module.exports = TAP; - -/** - * Initialize a new `TAP` reporter. - * - * @param {Runner} runner - * @api public - */ - -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 1 - , passes = 0 - , failures = 0; - - runner.on('start', function(){ - var total = runner.grepTotal(runner.suite); - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pending', function(test){ - console.log('ok %d %s # SKIP -', n, title(test)); - }); - - runner.on('pass', function(test){ - passes++; - console.log('ok %d %s', n, title(test)); - }); - - runner.on('fail', function(test, err){ - failures++; - console.log('not ok %d %s', n, title(test)); - if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - console.log('# tests ' + (passes + failures)); - console.log('# pass ' + passes); - console.log('# fail ' + failures); - }); -} - -/** - * Return a TAP-safe title of `test` - * - * @param {Object} test - * @return {String} - * @api private - */ - -function title(test) { - return test.fullTitle().replace(/#/g, ''); -} - -}); // module: reporters/tap.js - -require.register("reporters/xunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `XUnit`. - */ - -exports = module.exports = XUnit; - -/** - * Initialize a new `XUnit` reporter. - * - * @param {Runner} runner - * @api public - */ - -function XUnit(runner) { - Base.call(this, runner); - var stats = this.stats - , tests = [] - , self = this; - - runner.on('pending', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - tests.push(test); - }); - - runner.on('fail', function(test){ - tests.push(test); - }); - - runner.on('end', function(){ - console.log(tag('testsuite', { - name: 'Mocha Tests' - , tests: stats.tests - , failures: stats.failures - , errors: stats.failures - , skipped: stats.tests - stats.failures - stats.passes - , timestamp: (new Date).toUTCString() - , time: (stats.duration / 1000) || 0 - }, false)); - - tests.forEach(test); - console.log(''); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -XUnit.prototype = new F; -XUnit.prototype.constructor = XUnit; - - -/** - * Output tag for the given `test.` - */ - -function test(test) { - var attrs = { - classname: test.parent.fullTitle() - , name: test.title - , time: (test.duration / 1000) || 0 - }; - - if ('failed' == test.state) { - var err = test.err; - console.log(tag('testcase', attrs, false, tag('failure', {}, false, cdata(escape(err.message) + "\n" + err.stack)))); - } else if (test.pending) { - console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - console.log(tag('testcase', attrs, true) ); - } -} - -/** - * HTML tag helper. - */ - -function tag(name, attrs, close, content) { - var end = close ? '/>' : '>' - , pairs = [] - , tag; - - for (var key in attrs) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } - - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - if (content) tag += content + ''; -} - -}); // module: reporters/xunit.js - -require.register("runnable.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runnable') - , milliseconds = require('./ms'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Object#toString(). - */ - -var toString = Object.prototype.toString; - -/** - * Expose `Runnable`. - */ - -module.exports = Runnable; - -/** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this._timeout = 2000; - this._slow = 75; - this._enableTimeouts = true; - this.timedOut = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runnable.prototype = new F; -Runnable.prototype.constructor = Runnable; - - -/** - * Set & get timeout `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if (ms === 0) this._enableTimeouts = false; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = ms; - if (this.timer) this.resetTimeout(); - return this; -}; - -/** - * Set & get slow `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._slow = ms; - return this; -}; - -/** - * Set and & get timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Runnable|Boolean} enabled or self - * @api private - */ - -Runnable.prototype.enableTimeouts = function(enabled){ - if (arguments.length === 0) return this._enableTimeouts; - debug('enableTimeouts %s', enabled); - this._enableTimeouts = enabled; - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; - -/** - * Clear the timeout. - * - * @api private - */ - -Runnable.prototype.clearTimeout = function(){ - clearTimeout(this.timer); -}; - -/** - * Inspect the runnable void of private properties. - * - * @return {String} - * @api private - */ - -Runnable.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_' == key[0]) return; - if ('parent' == key) return '#'; - if ('ctx' == key) return '#'; - return val; - }, 2); -}; - -/** - * Reset the timeout. - * - * @api private - */ - -Runnable.prototype.resetTimeout = function(){ - var self = this; - var ms = this.timeout() || 1e9; - - if (!this._enableTimeouts) return; - this.clearTimeout(); - this.timer = setTimeout(function(){ - if (!self._enableTimeouts) return; - self.callback(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); -}; - -/** - * Whitelist these globals for this test run - * - * @api private - */ -Runnable.prototype.globals = function(arr){ - var self = this; - this._allowedGlobals = arr; -}; - -/** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runnable.prototype.run = function(fn){ - var self = this - , start = new Date - , ctx = this.ctx - , finished - , emitted; - - // Some times the ctx exists but it is not runnable - if (ctx && ctx.runnable) ctx.runnable(this); - - // called multiple times - function multiple(err) { - if (emitted) return; - emitted = true; - self.emit('error', err || new Error('done() called multiple times')); - } - - // finished - function done(err) { - var ms = self.timeout(); - if (self.timedOut) return; - if (finished) return multiple(err); - self.clearTimeout(); - self.duration = new Date - start; - finished = true; - if (!err && self.duration > ms && self._enableTimeouts) err = new Error('timeout of ' + ms + 'ms exceeded'); - fn(err); - } - - // for .resetTimeout() - this.callback = done; - - // explicit async with `done` argument - if (this.async) { - this.resetTimeout(); - - try { - this.fn.call(ctx, function(err){ - if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); - if (null != err) { - if (Object.prototype.toString.call(err) === '[object Object]') { - return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err))); - } else { - return done(new Error('done() invoked with non-Error: ' + err)); - } - } - done(); - }); - } catch (err) { - done(err); - } - return; - } - - if (this.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()`')); - } - - // sync or promise-returning - try { - if (this.pending) { - done(); - } else { - callFn(this.fn); - } - } catch (err) { - done(err); - } - - function callFn(fn) { - var result = fn.call(ctx); - if (result && typeof result.then === 'function') { - self.resetTimeout(); - result - .then(function() { - done() - }, - function(reason) { - done(reason || new Error('Promise rejected with no or falsy reason')) - }); - } else { - done(); - } - } -}; - -}); // module: runnable.js - -require.register("runner.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runner') - , Test = require('./test') - , utils = require('./utils') - , filter = utils.filter - , keys = utils.keys; - -/** - * Non-enumerable globals. - */ - -var globals = [ - 'setTimeout', - 'clearTimeout', - 'setInterval', - 'clearInterval', - 'XMLHttpRequest', - 'Date' -]; - -/** - * Expose `Runner`. - */ - -module.exports = Runner; - -/** - * Initialize a `Runner` for the given `suite`. - * - * Events: - * - * - `start` execution started - * - `end` execution complete - * - `suite` (suite) test suite execution started - * - `suite end` (suite) all tests (and sub-suites) have finished - * - `test` (test) test execution started - * - `test end` (test) test completed - * - `hook` (hook) hook execution started - * - `hook end` (hook) hook complete - * - `pass` (test) test passed - * - `fail` (test, err) test failed - * - `pending` (test) test pending - * - * @api public - */ - -function Runner(suite) { - var self = this; - this._globals = []; - this._abort = false; - this.suite = suite; - this.total = suite.total(); - this.failures = 0; - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); - this.globals(this.globalProps().concat(extraGlobals())); -} - -/** - * Wrapper for setImmediate, process.nextTick, or browser polyfill. - * - * @param {Function} fn - * @api private - */ - -Runner.immediately = global.setImmediate || process.nextTick; - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runner.prototype = new F; -Runner.prototype.constructor = Runner; - - -/** - * Run tests with full titles matching `re`. Updates runner.total - * with number of tests matched. - * - * @param {RegExp} re - * @param {Boolean} invert - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.grep = function(re, invert){ - debug('grep %s', re); - this._grep = re; - this._invert = invert; - this.total = this.grepTotal(this.suite); - return this; -}; - -/** - * Returns the number of tests matching the grep search for the - * given suite. - * - * @param {Suite} suite - * @return {Number} - * @api public - */ - -Runner.prototype.grepTotal = function(suite) { - var self = this; - var total = 0; - - suite.eachTest(function(test){ - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (match) total++; - }); - - return total; -}; - -/** - * Return a list of global properties. - * - * @return {Array} - * @api private - */ - -Runner.prototype.globalProps = function() { - var props = utils.keys(global); - - // non-enumerables - for (var i = 0; i < globals.length; ++i) { - if (~utils.indexOf(props, globals[i])) continue; - props.push(globals[i]); - } - - return props; -}; - -/** - * Allow the given `arr` of globals. - * - * @param {Array} arr - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.globals = function(arr){ - if (0 == arguments.length) return this._globals; - debug('globals %j', arr); - this._globals = this._globals.concat(arr); - return this; -}; - -/** - * Check for global variable leaks. - * - * @api private - */ - -Runner.prototype.checkGlobals = function(test){ - if (this.ignoreLeaks) return; - var ok = this._globals; - - var globals = this.globalProps(); - var leaks; - - if (test) { - ok = ok.concat(test._allowedGlobals || []); - } - - if(this.prevGlobalsLength == globals.length) return; - this.prevGlobalsLength = globals.length; - - leaks = filterLeaks(ok, globals); - this._globals = this._globals.concat(leaks); - - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; - -/** - * Fail the given `test`. - * - * @param {Test} test - * @param {Error} err - * @api private - */ - -Runner.prototype.fail = function(test, err){ - ++this.failures; - test.state = 'failed'; - - if ('string' == typeof err) { - err = new Error('the string "' + err + '" was thrown, throw an Error :)'); - } - - this.emit('fail', test, err); -}; - -/** - * Fail the given `hook` with `err`. - * - * Hook failures work in the following pattern: - * - If bail, then exit - * - Failed `before` hook skips all tests in a suite and subsuites, - * but jumps to corresponding `after` hook - * - Failed `before each` hook skips remaining tests in a - * suite and jumps to corresponding `after each` hook, - * which is run only once - * - Failed `after` hook does not alter - * execution order - * - Failed `after each` hook skips remaining tests in a - * suite and subsuites, but executes other `after each` - * hooks - * - * @param {Hook} hook - * @param {Error} err - * @api private - */ - -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - if (this.suite.bail()) { - this.emit('end'); - } -}; - -/** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @param {String} name - * @param {Function} function - * @api private - */ - -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , self = this - , timer; - - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - if (self.failures && suite.bail()) return fn(); - self.currentRunnable = hook; - - hook.ctx.currentTest = self.test; - - self.emit('hook', hook); - - hook.on('error', function(err){ - self.failHook(hook, err); - }); - - hook.run(function(err){ - hook.removeAllListeners('error'); - var testError = hook.error(); - if (testError) self.fail(self.test, testError); - if (err) { - self.failHook(hook, err); - - // stop executing hooks, notify callee of hook err - return fn(err); - } - self.emit('hook end', hook); - delete hook.ctx.currentTest; - next(++i); - }); - } - - Runner.immediately(function(){ - next(0); - }); -}; - -/** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err, errSuite)`. - * - * @param {String} name - * @param {Array} suites - * @param {Function} fn - * @api private - */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function(err){ - if (err) { - var errSuite = self.suite; - self.suite = orig; - return fn(err, errSuite); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); -}; - -/** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; - -/** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; - -/** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @api private - */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; - -/** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; - - if (this.asyncOnly) test.asyncOnly = true; - - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; - -/** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests.slice() - , test; - - - function hookErr(err, errSuite, after) { - // before/after Each hook for errSuite failed: - var orig = self.suite; - - // for failed 'after each' hook start from errSuite parent, - // otherwise start from errSuite itself - self.suite = after ? errSuite.parent : errSuite; - - if (self.suite) { - // call hookUp afterEach - self.hookUp('afterEach', function(err2, errSuite2) { - self.suite = orig; - // some hooks may fail even now - if (err2) return hookErr(err2, errSuite2, true); - // report error suite - fn(errSuite); - }); - } else { - // there is no need calling other 'after each' hooks - self.suite = orig; - fn(errSuite); - } - } - - function next(err, errSuite) { - // if we bail after first err - if (self.failures && suite._bail) return fn(); - - if (self._abort) return fn(); - - if (err) return hookErr(err, errSuite, true); - - // next test - test = tests.shift(); - - // all done - if (!test) return fn(); - - // grep - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (!match) return next(); - - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(err, errSuite){ - - if (err) return hookErr(err, errSuite, false); - - self.currentRunnable = self.test; - self.runTest(function(err){ - test = self.test; - - if (err) { - self.fail(test, err); - self.emit('test end', test); - return self.hookUp('afterEach', next); - } - - test.state = 'passed'; - self.emit('pass', test); - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } - - this.next = next; - next(); -}; - -/** - * Run the given `suite` and invoke the - * callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runSuite = function(suite, fn){ - var total = this.grepTotal(suite) - , self = this - , i = 0; - - debug('run suite %s', suite.fullTitle()); - - if (!total) return fn(); - - this.emit('suite', this.suite = suite); - - function next(errSuite) { - if (errSuite) { - // current suite failed on a hook from errSuite - if (errSuite == suite) { - // if errSuite is current suite - // continue to the next sibling suite - return done(); - } else { - // errSuite is among the parents of current suite - // stop execution of errSuite and all sub-suites - return done(errSuite); - } - } - - if (self._abort) return done(); - - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } - - function done(errSuite) { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(errSuite); - }); - } - - this.hook('beforeAll', function(err){ - if (err) return done(); - self.runTests(suite, next); - }); -}; - -/** - * Handle uncaught exceptions. - * - * @param {Error} err - * @api private - */ - -Runner.prototype.uncaught = function(err){ - if (err) { - debug('uncaught exception %s', err !== function () { - return this; - }.call(err) ? err : ( err.message || err )); - } else { - debug('uncaught undefined exception'); - err = new Error('Caught undefined error, did you throw without specifying what?'); - } - err.uncaught = true; - - var runnable = this.currentRunnable; - if (!runnable) return; - - var wasAlreadyDone = runnable.state; - this.fail(runnable, err); - - runnable.clearTimeout(); - - if (wasAlreadyDone) return; - - // recover from test - if ('test' == runnable.type) { - this.emit('test end', runnable); - this.hookUp('afterEach', this.next); - return; - } - - // bail on hooks - this.emit('end'); -}; - -/** - * Run the root suite and invoke `fn(failures)` - * on completion. - * - * @param {Function} fn - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.run = function(fn){ - var self = this - , fn = fn || function(){}; - - function uncaught(err){ - self.uncaught(err); - } - - debug('start'); - - // callback - this.on('end', function(){ - debug('end'); - process.removeListener('uncaughtException', uncaught); - fn(self.failures); - }); - - // run suites - this.emit('start'); - this.runSuite(this.suite, function(){ - debug('finished running'); - self.emit('end'); - }); - - // uncaught exception - process.on('uncaughtException', uncaught); - - return this; -}; - -/** - * Cleanly abort execution - * - * @return {Runner} for chaining - * @api public - */ -Runner.prototype.abort = function(){ - debug('aborting'); - this._abort = true; -}; - -/** - * Filter leaks with the given globals flagged as `ok`. - * - * @param {Array} ok - * @param {Array} globals - * @return {Array} - * @api private - */ - -function filterLeaks(ok, globals) { - return filter(globals, function(key){ - // Firefox and Chrome exposes iframes as index inside the window object - if (/^d+/.test(key)) return false; - - // in firefox - // if runner runs in an iframe, this iframe's window.getInterface method not init at first - // it is assigned in some seconds - if (global.navigator && /^getInterface/.test(key)) return false; - - // an iframe could be approached by window[iframeIndex] - // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak - if (global.navigator && /^\d+/.test(key)) return false; - - // Opera and IE expose global variables for HTML element IDs (issue #243) - if (/^mocha-/.test(key)) return false; - - var matched = filter(ok, function(ok){ - if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); - return key == ok; - }); - return matched.length == 0 && (!global.navigator || 'onerror' !== key); - }); -} - -/** - * Array of globals dependent on the environment. - * - * @return {Array} - * @api private - */ - - function extraGlobals() { - if (typeof(process) === 'object' && - typeof(process.version) === 'string') { - - var nodeVersion = process.version.split('.').reduce(function(a, v) { - return a << 8 | v; - }); - - // 'errno' was renamed to process._errno in v0.9.11. - - if (nodeVersion < 0x00090B) { - return ['errno']; - } - } - - return []; - } - -}); // module: runner.js - -require.register("suite.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:suite') - , milliseconds = require('./ms') - , utils = require('./utils') - , Hook = require('./hook'); - -/** - * Expose `Suite`. - */ - -exports = module.exports = Suite; - -/** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. - * - * @param {Suite} parent - * @param {String} title - * @return {Suite} - * @api public - */ - -exports.create = function(parent, title){ - var suite = new Suite(title, parent.ctx); - suite.parent = parent; - if (parent.pending) suite.pending = true; - title = suite.fullTitle(); - parent.addSuite(suite); - return suite; -}; - -/** - * Initialize a new `Suite` with the given - * `title` and `ctx`. - * - * @param {String} title - * @param {Context} ctx - * @api private - */ - -function Suite(title, parentContext) { - this.title = title; - var context = function() {}; - context.prototype = parentContext; - this.ctx = new context(); - this.suites = []; - this.tests = []; - this.pending = false; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this._timeout = 2000; - this._enableTimeouts = true; - this._slow = 75; - this._bail = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Suite.prototype = new F; -Suite.prototype.constructor = Suite; - - -/** - * Return a clone of this `Suite`. - * - * @return {Suite} - * @api private - */ - -Suite.prototype.clone = function(){ - var suite = new Suite(this.title); - debug('clone'); - suite.ctx = this.ctx; - suite.timeout(this.timeout()); - suite.enableTimeouts(this.enableTimeouts()); - suite.slow(this.slow()); - suite.bail(this.bail()); - return suite; -}; - -/** - * Set timeout `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if (ms === 0) this._enableTimeouts = false; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = parseInt(ms, 10); - return this; -}; - -/** - * Set timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Suite|Boolean} self or enabled - * @api private - */ - -Suite.prototype.enableTimeouts = function(enabled){ - if (arguments.length === 0) return this._enableTimeouts; - debug('enableTimeouts %s', enabled); - this._enableTimeouts = enabled; - return this; -}; - -/** - * Set slow `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('slow %d', ms); - this._slow = ms; - return this; -}; - -/** - * Sets whether to bail after first error. - * - * @parma {Boolean} bail - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.bail = function(bail){ - if (0 == arguments.length) return this._bail; - debug('bail %s', bail); - this._bail = bail; - return this; -}; - -/** - * Run `fn(test[, done])` before running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` before each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** - * Add a test `suite`. - * - * @param {Suite} suite - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - suite.timeout(this.timeout()); - suite.enableTimeouts(this.enableTimeouts()); - suite.slow(this.slow()); - suite.bail(this.bail()); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; - -/** - * Add a `test` to this suite. - * - * @param {Test} test - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addTest = function(test){ - test.parent = this; - test.timeout(this.timeout()); - test.enableTimeouts(this.enableTimeouts()); - test.slow(this.slow()); - test.ctx = this.ctx; - this.tests.push(test); - this.emit('test', test); - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; - -/** - * Return the total number of tests. - * - * @return {Number} - * @api public - */ - -Suite.prototype.total = function(){ - return utils.reduce(this.suites, function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; - -/** - * Iterates through each suite recursively to find - * all tests. Applies a function in the format - * `fn(test)`. - * - * @param {Function} fn - * @return {Suite} - * @api private - */ - -Suite.prototype.eachTest = function(fn){ - utils.forEach(this.tests, fn); - utils.forEach(this.suites, function(suite){ - suite.eachTest(fn); - }); - return this; -}; - -}); // module: suite.js - -require.register("test.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Test`. - */ - -module.exports = Test; - -/** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; - this.type = 'test'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Test.prototype = new F; -Test.prototype.constructor = Test; - - -}); // module: test.js - -require.register("utils.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var fs = require('browser/fs') - , path = require('browser/path') - , basename = path.basename - , exists = fs.existsSync || path.existsSync - , glob = require('browser/glob') - , join = path.join - , debug = require('browser/debug')('mocha:watch'); - -/** - * Ignored directories. - */ - -var ignore = ['node_modules', '.git']; - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; - -/** - * Array#forEach (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.forEach = function(arr, fn, scope){ - for (var i = 0, l = arr.length; i < l; i++) - fn.call(scope, arr[i], i); -}; - -/** - * Array#map (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.map = function(arr, fn, scope){ - var result = []; - for (var i = 0, l = arr.length; i < l; i++) - result.push(fn.call(scope, arr[i], i)); - return result; -}; - -/** - * Array#indexOf (<=IE8) - * - * @parma {Array} arr - * @param {Object} obj to find index of - * @param {Number} start - * @api private - */ - -exports.indexOf = function(arr, obj, start){ - for (var i = start || 0, l = arr.length; i < l; i++) { - if (arr[i] === obj) - return i; - } - return -1; -}; - -/** - * Array#reduce (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} initial value - * @api private - */ - -exports.reduce = function(arr, fn, val){ - var rval = val; - - for (var i = 0, l = arr.length; i < l; i++) { - rval = fn(rval, arr[i], i, arr); - } - - return rval; -}; - -/** - * Array#filter (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @api private - */ - -exports.filter = function(arr, fn){ - var ret = []; - - for (var i = 0, l = arr.length; i < l; i++) { - var val = arr[i]; - if (fn(val, i, arr)) ret.push(val); - } - - return ret; -}; - -/** - * Object.keys (<=IE8) - * - * @param {Object} obj - * @return {Array} keys - * @api private - */ - -exports.keys = Object.keys || function(obj) { - var keys = [] - , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 - - for (var key in obj) { - if (has.call(obj, key)) { - keys.push(key); - } - } - - return keys; -}; - -/** - * Watch the given `files` for changes - * and invoke `fn(file)` on modification. - * - * @param {Array} files - * @param {Function} fn - * @api private - */ - -exports.watch = function(files, fn){ - var options = { interval: 100 }; - files.forEach(function(file){ - debug('file %s', file); - fs.watchFile(file, options, function(curr, prev){ - if (prev.mtime < curr.mtime) fn(file); - }); - }); -}; - -/** - * Ignored files. - */ - -function ignored(path){ - return !~ignore.indexOf(path); -} - -/** - * Lookup files in the given `dir`. - * - * @return {Array} - * @api private - */ - -exports.files = function(dir, ext, ret){ - ret = ret || []; - ext = ext || ['js']; - - var re = new RegExp('\\.(' + ext.join('|') + ')$'); - - fs.readdirSync(dir) - .filter(ignored) - .forEach(function(path){ - path = join(dir, path); - if (fs.statSync(path).isDirectory()) { - exports.files(path, ext, ret); - } else if (path.match(re)) { - ret.push(path); - } - }); - - return ret; -}; - -/** - * Compute a slug from the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.slug = function(str){ - return str - .toLowerCase() - .replace(/ +/g, '-') - .replace(/[^-\w]/g, ''); -}; - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -exports.clean = function(str) { - str = str - .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '') - .replace(/^function *\(.*\) *{|\(.*\) *=> *{?/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , tabs = str.match(/^\n?(\t*)/)[1].length - , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm'); - - str = str.replace(re, ''); - - return exports.trim(str); -}; - -/** - * Trim the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.trim = function(str){ - return str.replace(/^\s+|\s+$/g, ''); -}; - -/** - * Parse the given `qs`. - * - * @param {String} qs - * @return {Object} - * @api private - */ - -exports.parseQuery = function(qs){ - return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); - - obj[key] = decodeURIComponent(val); - return obj; - }, {}); -}; - -/** - * Highlight the given string of `js`. - * - * @param {String} js - * @return {String} - * @api private - */ - -function highlight(js) { - return js - .replace(//g, '>') - .replace(/\/\/(.*)/gm, '//$1') - .replace(/('.*?')/gm, '$1') - .replace(/(\d+\.\d+)/gm, '$1') - .replace(/(\d+)/gm, '$1') - .replace(/\bnew[ \t]+(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') -} - -/** - * Highlight the contents of tag `name`. - * - * @param {String} name - * @api private - */ - -exports.highlightTags = function(name) { - var code = document.getElementById('mocha').getElementsByTagName(name); - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } -}; - - -/** - * Stringify `obj`. - * - * @param {Object} obj - * @return {String} - * @api private - */ - -exports.stringify = function(obj) { - if (obj instanceof RegExp) return obj.toString(); - return JSON.stringify(exports.canonicalize(obj), null, 2).replace(/,(\n|$)/g, '$1'); -}; - -/** - * Return a new object that has the keys in sorted order. - * @param {Object} obj - * @param {Array} [stack] - * @return {Object} - * @api private - */ - -exports.canonicalize = function(obj, stack) { - stack = stack || []; - - if (exports.indexOf(stack, obj) !== -1) return '[Circular]'; - - var canonicalizedObj; - - if ({}.toString.call(obj) === '[object Array]') { - stack.push(obj); - canonicalizedObj = exports.map(obj, function (item) { - return exports.canonicalize(item, stack); - }); - stack.pop(); - } else if (typeof obj === 'object' && obj !== null) { - stack.push(obj); - canonicalizedObj = {}; - exports.forEach(exports.keys(obj).sort(), function (key) { - canonicalizedObj[key] = exports.canonicalize(obj[key], stack); - }); - stack.pop(); - } else { - canonicalizedObj = obj; - } - - return canonicalizedObj; - }; - -/** - * Lookup file names at the given `path`. - */ -exports.lookupFiles = function lookupFiles(path, extensions, recursive) { - var files = []; - var re = new RegExp('\\.(' + extensions.join('|') + ')$'); - - if (!exists(path)) { - if (exists(path + '.js')) { - path += '.js'; - } else { - files = glob.sync(path); - if (!files.length) throw new Error("cannot resolve path (or pattern) '" + path + "'"); - return files; - } - } - - try { - var stat = fs.statSync(path); - if (stat.isFile()) return path; - } - catch (ignored) { - return; - } - - fs.readdirSync(path).forEach(function(file){ - file = join(path, file); - try { - var stat = fs.statSync(file); - if (stat.isDirectory()) { - if (recursive) { - files = files.concat(lookupFiles(file, extensions, recursive)); - } - return; - } - } - catch (ignored) { - return; - } - if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') return; - files.push(file); - }); - - return files; -}; - -}); // module: utils.js -// The global object is "self" in Web Workers. -var global = (function() { return this; })(); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date; -var setTimeout = global.setTimeout; -var setInterval = global.setInterval; -var clearTimeout = global.clearTimeout; -var clearInterval = global.clearInterval; - -/** - * Node shims. - * - * These are meant only to allow - * mocha.js to run untouched, not - * to allow running node code in - * the browser. - */ - -var process = {}; -process.exit = function(status){}; -process.stdout = {}; - -var uncaughtExceptionHandlers = []; - -var originalOnerrorHandler = global.onerror; - -/** - * Remove uncaughtException listener. - * Revert to original onerror handler if previously defined. - */ - -process.removeListener = function(e, fn){ - if ('uncaughtException' == e) { - if (originalOnerrorHandler) { - global.onerror = originalOnerrorHandler; - } else { - global.onerror = function() {}; - } - var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn); - if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); } - } -}; - -/** - * Implements uncaughtException listener. - */ - -process.on = function(e, fn){ - if ('uncaughtException' == e) { - global.onerror = function(err, url, line){ - fn(new Error(err + ' (' + url + ':' + line + ')')); - return true; - }; - uncaughtExceptionHandlers.push(fn); - } -}; - -/** - * Expose mocha. - */ - -var Mocha = global.Mocha = require('mocha'), - mocha = global.mocha = new Mocha({ reporter: 'html' }); - -// The BDD UI is registered by default, but no UI will be functional in the -// browser without an explicit call to the overridden `mocha.ui` (see below). -// Ensure that this default UI does not expose its methods to the global scope. -mocha.suite.removeAllListeners('pre-require'); - -var immediateQueue = [] - , immediateTimeout; - -function timeslice() { - var immediateStart = new Date().getTime(); - while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { - immediateQueue.shift()(); - } - if (immediateQueue.length) { - immediateTimeout = setTimeout(timeslice, 0); - } else { - immediateTimeout = null; - } -} - -/** - * High-performance override of Runner.immediately. - */ - -Mocha.Runner.immediately = function(callback) { - immediateQueue.push(callback); - if (!immediateTimeout) { - immediateTimeout = setTimeout(timeslice, 0); - } -}; - -/** - * Function to allow assertion libraries to throw errors directly into mocha. - * This is useful when running tests in a browser because window.onerror will - * only receive the 'message' attribute of the Error. - */ -mocha.throwError = function(err) { - Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) { - fn(err); - }); - throw err; -}; - -/** - * Override ui to ensure that the ui functions are initialized. - * Normally this would happen in Mocha.prototype.loadFiles. - */ - -mocha.ui = function(ui){ - Mocha.prototype.ui.call(this, ui); - this.suite.emit('pre-require', global, null, this); - return this; -}; - -/** - * Setup mocha with the given setting options. - */ - -mocha.setup = function(opts){ - if ('string' == typeof opts) opts = { ui: opts }; - for (var opt in opts) this[opt](opts[opt]); - return this; -}; - -/** - * Run mocha, returning the Runner. - */ - -mocha.run = function(fn){ - var options = mocha.options; - mocha.globals('location'); - - var query = Mocha.utils.parseQuery(global.location.search || ''); - if (query.grep) mocha.grep(query.grep); - if (query.invert) mocha.invert(); - - return Mocha.prototype.run.call(mocha, function(err){ - // The DOM Document is not available in Web Workers. - var document = global.document; - if (document && document.getElementById('mocha') && options.noHighlighting !== true) { - Mocha.utils.highlightTags('code'); - } - if (fn) fn(err); - }); -}; - -/** - * Expose the process shim. - */ - -Mocha.process = process; -})(); \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js deleted file mode 100644 index 7ad9f8a..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js +++ /dev/null @@ -1,16 +0,0 @@ -importScripts('es6-promise.js'); -new ES6Promise.Promise(function(resolve, reject) { - self.onmessage = function (e) { - if (e.data === 'ping') { - resolve('pong'); - } else { - reject(new Error('wrong message')); - } - }; -}).then(function (result) { - self.postMessage(result); -}, function (err){ - setTimeout(function () { - throw err; - }); -}); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js deleted file mode 100644 index 5984f70..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js +++ /dev/null @@ -1,18 +0,0 @@ -import Promise from './es6-promise/promise'; -import polyfill from './es6-promise/polyfill'; - -var ES6Promise = { - 'Promise': Promise, - 'polyfill': polyfill -}; - -/* global define:true module:true window: true */ -if (typeof define === 'function' && define['amd']) { - define(function() { return ES6Promise; }); -} else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = ES6Promise; -} else if (typeof this !== 'undefined') { - this['ES6Promise'] = ES6Promise; -} - -polyfill(); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js deleted file mode 100644 index daee2c3..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js +++ /dev/null @@ -1,250 +0,0 @@ -import { - objectOrFunction, - isFunction -} from './utils'; - -import asap from './asap'; - -function noop() {} - -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; - -var GET_THEN_ERROR = new ErrorObject(); - -function selfFullfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} - -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} - -function getThen(promise) { - try { - return promise.then; - } catch(error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } -} - -function tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } -} - -function handleForeignThenable(promise, thenable, then) { - asap(function(promise) { - var sealed = false; - var error = tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - resolve(promise, value); - } else { - fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - reject(promise, error); - } - }, promise); -} - -function handleOwnThenable(promise, thenable) { - if (thenable._state === FULFILLED) { - fulfill(promise, thenable._result); - } else if (thenable._state === REJECTED) { - reject(promise, thenable._result); - } else { - subscribe(thenable, undefined, function(value) { - resolve(promise, value); - }, function(reason) { - reject(promise, reason); - }); - } -} - -function handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - handleOwnThenable(promise, maybeThenable); - } else { - var then = getThen(maybeThenable); - - if (then === GET_THEN_ERROR) { - reject(promise, GET_THEN_ERROR.error); - } else if (then === undefined) { - fulfill(promise, maybeThenable); - } else if (isFunction(then)) { - handleForeignThenable(promise, maybeThenable, then); - } else { - fulfill(promise, maybeThenable); - } - } -} - -function resolve(promise, value) { - if (promise === value) { - reject(promise, selfFullfillment()); - } else if (objectOrFunction(value)) { - handleMaybeThenable(promise, value); - } else { - fulfill(promise, value); - } -} - -function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - publish(promise); -} - -function fulfill(promise, value) { - if (promise._state !== PENDING) { return; } - - promise._result = value; - promise._state = FULFILLED; - - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} - -function reject(promise, reason) { - if (promise._state !== PENDING) { return; } - promise._state = REJECTED; - promise._result = reason; - - asap(publishRejection, promise); -} - -function subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + FULFILLED] = onFulfillment; - subscribers[length + REJECTED] = onRejection; - - if (length === 0 && parent._state) { - asap(publish, parent); - } -} - -function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; -} - -function ErrorObject() { - this.error = null; -} - -var TRY_CATCH_ERROR = new ErrorObject(); - -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } -} - -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = tryCatch(callback, detail); - - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - reject(promise, cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== PENDING) { - // noop - } else if (hasCallback && succeeded) { - resolve(promise, value); - } else if (failed) { - reject(promise, error); - } else if (settled === FULFILLED) { - fulfill(promise, value); - } else if (settled === REJECTED) { - reject(promise, value); - } -} - -function initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - resolve(promise, value); - }, function rejectPromise(reason) { - reject(promise, reason); - }); - } catch(e) { - reject(promise, e); - } -} - -export { - noop, - resolve, - reject, - fulfill, - subscribe, - publish, - publishRejection, - initializePromise, - invokeCallback, - FULFILLED, - REJECTED, - PENDING -}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js deleted file mode 100644 index 4f7dcee..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js +++ /dev/null @@ -1,111 +0,0 @@ -var len = 0; -var toString = {}.toString; -var vertxNext; -export default function asap(callback, arg) { - queue[len] = callback; - queue[len + 1] = arg; - len += 2; - if (len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - scheduleFlush(); - } -} - -var browserWindow = (typeof window !== 'undefined') ? window : undefined; -var browserGlobal = browserWindow || {}; -var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; -var isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - -// test for web worker but not in IE10 -var isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - -// node -function useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function() { - nextTick(flush); - }; -} - -// vertx -function useVertxTimer() { - return function() { - vertxNext(flush); - }; -} - -function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; -} - -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - channel.port2.postMessage(0); - }; -} - -function useSetTimeout() { - return function() { - setTimeout(flush, 1); - }; -} - -var queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i+=2) { - var callback = queue[i]; - var arg = queue[i+1]; - - callback(arg); - - queue[i] = undefined; - queue[i+1] = undefined; - } - - len = 0; -} - -function attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch(e) { - return useSetTimeout(); - } -} - -var scheduleFlush; -// Decide what async method to use to triggering processing of queued callbacks: -if (isNode) { - scheduleFlush = useNextTick(); -} else if (BrowserMutationObserver) { - scheduleFlush = useMutationObserver(); -} else if (isWorker) { - scheduleFlush = useMessageChannel(); -} else if (browserWindow === undefined && typeof require === 'function') { - scheduleFlush = attemptVertex(); -} else { - scheduleFlush = useSetTimeout(); -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js deleted file mode 100644 index 03fdf8c..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js +++ /dev/null @@ -1,113 +0,0 @@ -import { - isArray, - isMaybeThenable -} from './utils'; - -import { - noop, - reject, - fulfill, - subscribe, - FULFILLED, - REJECTED, - PENDING -} from './-internal'; - -function Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - fulfill(enumerator.promise, enumerator._result); - } - } - } else { - reject(enumerator.promise, enumerator._validationError()); - } -} - -Enumerator.prototype._validateInput = function(input) { - return isArray(input); -}; - -Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); -}; - -Enumerator.prototype._init = function() { - this._result = new Array(this.length); -}; - -export default Enumerator; - -Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } -}; - -Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } -}; - -Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === PENDING) { - enumerator._remaining--; - - if (state === REJECTED) { - reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - fulfill(promise, enumerator._result); - } -}; - -Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - subscribe(promise, undefined, function(value) { - enumerator._settledAt(FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(REJECTED, i, reason); - }); -}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js deleted file mode 100644 index 6696dfc..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js +++ /dev/null @@ -1,26 +0,0 @@ -/*global self*/ -import Promise from './promise'; - -export default function polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = Promise; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js deleted file mode 100644 index 78fe2ca..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js +++ /dev/null @@ -1,408 +0,0 @@ -import { - isFunction -} from './utils'; - -import { - noop, - subscribe, - initializePromise, - invokeCallback, - FULFILLED, - REJECTED -} from './-internal'; - -import asap from './asap'; - -import all from './promise/all'; -import race from './promise/race'; -import Resolve from './promise/resolve'; -import Reject from './promise/reject'; - -var counter = 0; - -function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); -} - -function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); -} - -export default Promise; -/** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor -*/ -function Promise(resolver) { - this._id = counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (noop !== resolver) { - if (!isFunction(resolver)) { - needsResolver(); - } - - if (!(this instanceof Promise)) { - needsNew(); - } - - initializePromise(this, resolver); - } -} - -Promise.all = all; -Promise.race = race; -Promise.resolve = Resolve; -Promise.reject = Reject; - -Promise.prototype = { - constructor: Promise, - -/** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} -*/ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - asap(function(){ - invokeCallback(state, child, callback, result); - }); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - -/** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} -*/ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } -}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js deleted file mode 100644 index 03033f0..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js +++ /dev/null @@ -1,52 +0,0 @@ -import Enumerator from '../enumerator'; - -/** - `Promise.all` accepts an array of promises, and returns a new promise which - is fulfilled with an array of fulfillment values for the passed promises, or - rejected with the reason of the first passed promise to be rejected. It casts all - elements of the passed iterable to promises as it runs this algorithm. - - Example: - - ```javascript - var promise1 = resolve(1); - var promise2 = resolve(2); - var promise3 = resolve(3); - var promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` - - If any of the `promises` given to `all` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - Example: - - ```javascript - var promise1 = resolve(1); - var promise2 = reject(new Error("2")); - var promise3 = reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` - - @method all - @static - @param {Array} entries array of promises - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all `promises` have been - fulfilled, or rejected if any of them become rejected. - @static -*/ -export default function all(entries) { - return new Enumerator(this, entries).promise; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js deleted file mode 100644 index 0d7ff13..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js +++ /dev/null @@ -1,104 +0,0 @@ -import { - isArray -} from "../utils"; - -import { - noop, - resolve, - reject, - subscribe, - PENDING -} from '../-internal'; - -/** - `Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. - - Example: - - ```javascript - var promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - var promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 2'); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // result === 'promise 2' because it was resolved before promise1 - // was resolved. - }); - ``` - - `Promise.race` is deterministic in that only the state of the first - settled promise matters. For example, even if other promises given to the - `promises` array argument are resolved, but the first settled promise has - become rejected before the other promises became fulfilled, the returned - promise will become rejected: - - ```javascript - var promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - var promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // Code here never runs - }, function(reason){ - // reason.message === 'promise 2' because promise 2 became rejected before - // promise 1 became fulfilled - }); - ``` - - An example real-world use case is implementing timeouts: - - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` - - @method race - @static - @param {Array} promises array of promises to observe - Useful for tooling. - @return {Promise} a promise which settles in the same way as the first passed - promise to settle. -*/ -export default function race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(noop); - - if (!isArray(entries)) { - reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - resolve(promise, value); - } - - function onRejection(reason) { - reject(promise, reason); - } - - for (var i = 0; promise._state === PENDING && i < length; i++) { - subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js deleted file mode 100644 index 63b86cb..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js +++ /dev/null @@ -1,46 +0,0 @@ -import { - noop, - reject as _reject -} from '../-internal'; - -/** - `Promise.reject` returns a promise rejected with the passed `reason`. - It is shorthand for the following: - - ```javascript - var promise = new Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = Promise.reject(new Error('WHOOPS')); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - @method reject - @static - @param {Any} reason value that the returned promise will be rejected with. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. -*/ -export default function reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(noop); - _reject(promise, reason); - return promise; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js deleted file mode 100644 index 201a545..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js +++ /dev/null @@ -1,48 +0,0 @@ -import { - noop, - resolve as _resolve -} from '../-internal'; - -/** - `Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: - - ```javascript - var promise = new Promise(function(resolve, reject){ - resolve(1); - }); - - promise.then(function(value){ - // value === 1 - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = Promise.resolve(1); - - promise.then(function(value){ - // value === 1 - }); - ``` - - @method resolve - @static - @param {Any} value value that the returned promise will be resolved with - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` -*/ -export default function resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(noop); - _resolve(promise, object); - return promise; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js deleted file mode 100644 index 31ec6f9..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js +++ /dev/null @@ -1,22 +0,0 @@ -export function objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); -} - -export function isFunction(x) { - return typeof x === 'function'; -} - -export function isMaybeThenable(x) { - return typeof x === 'object' && x !== null; -} - -var _isArray; -if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; -} else { - _isArray = Array.isArray; -} - -export var isArray = _isArray; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/package.json deleted file mode 100644 index 6fc9a80..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/es6-promise/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "name": "es6-promise", - "namespace": "es6-promise", - "version": "2.1.1", - "description": "A lightweight library that provides tools for organizing asynchronous code", - "main": "dist/es6-promise.js", - "directories": { - "lib": "lib" - }, - "files": [ - "dist", - "lib" - ], - "devDependencies": { - "bower": "^1.3.9", - "brfs": "0.0.8", - "broccoli-es3-safe-recast": "0.0.8", - "broccoli-es6-module-transpiler": "^0.5.0", - "broccoli-jshint": "^0.5.1", - "broccoli-merge-trees": "^0.1.4", - "broccoli-replace": "^0.2.0", - "broccoli-stew": "0.0.6", - "broccoli-uglify-js": "^0.1.3", - "broccoli-watchify": "^0.2.0", - "ember-cli": "^0.2.2", - "ember-publisher": "0.0.7", - "git-repo-version": "0.0.2", - "json3": "^3.3.2", - "minimatch": "^2.0.1", - "mocha": "^1.20.1", - "promises-aplus-tests-phantom": "^2.1.0-revise", - "release-it": "0.0.10" - }, - "scripts": { - "build": "ember build", - "start": "ember s", - "test": "ember test", - "test:server": "ember test --server", - "test:node": "ember build && mocha ./dist/test/browserify", - "lint": "jshint lib", - "prepublish": "ember build --environment production", - "dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive" - }, - "repository": { - "type": "git", - "url": "git://github.com/jakearchibald/ES6-Promises.git" - }, - "bugs": { - "url": "https://github.com/jakearchibald/ES6-Promises/issues" - }, - "browser": { - "vertx": false - }, - "keywords": [ - "promises", - "futures" - ], - "author": { - "name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors", - "url": "Conversion to ES6 API by Jake Archibald" - }, - "license": "MIT", - "spm": { - "main": "dist/es6-promise.js" - }, - "gitHead": "02cf697c50856f0cd3785f425a2cf819af0e521c", - "homepage": "https://github.com/jakearchibald/ES6-Promises", - "_id": "es6-promise@2.1.1", - "_shasum": "03e8f3c7297928e5478d6ab1d0643251507bdedd", - "_from": "es6-promise@2.1.1", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.1", - "_npmUser": { - "name": "jaffathecake", - "email": "jaffathecake@gmail.com" - }, - "maintainers": [ - { - "name": "jaffathecake", - "email": "jaffathecake@gmail.com" - } - ], - "dist": { - "shasum": "03e8f3c7297928e5478d6ab1d0643251507bdedd", - "tarball": "http://registry.npmjs.org/es6-promise/-/es6-promise-2.1.1.tgz" - }, - "_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-2.1.1.tgz" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md deleted file mode 100644 index a21da87..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md +++ /dev/null @@ -1,246 +0,0 @@ -1.2.14 09-28-2015 ------------------ -- NODE-547 only emit error if there are any listeners. -- Fixed APM issue with issuing readConcern. - -1.2.13 09-18-2015 ------------------ -- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. - -1.2.12 09-08-2015 ------------------ -- NODE-541 Added initial support for readConcern. - -1.2.11 08-31-2015 ------------------ -- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. -- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. -- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). - -1.2.10 08-14-2015 ------------------ -- Added missing Mongos.prototype.parserType function. - -1.2.9 08-05-2015 ----------------- -- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -- NODE-518 connectTimeoutMS is doubled in 2.0.39. - -1.2.8 07-24-2015 ------------------ -- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. - -1.2.7 07-16-2015 ------------------ -- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. - -1.2.6 07-14-2015 ------------------ -- NODE-505 Query fails to find records that have a 'result' property with an array value. - -1.2.5 07-14-2015 ------------------ -- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. - -1.2.4 07-07-2015 ------------------ -- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. - -1.2.3 06-26-2015 ------------------ -- Minor bug fixes. - -1.2.2 06-22-2015 ------------------ -- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). - -1.2.1 06-17-2015 ------------------ -- Ensure serializeFunctions passed down correctly to wire protocol. - -1.2.0 06-17-2015 ------------------ -- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. -- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. -- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -1.1.33 05-31-2015 ------------------ -- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. - -1.1.32 05-20-2015 ------------------ -- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) - -1.1.31 05-19-2015 ------------------ -- Minor fixes for issues with re-authentication of mongos. - -1.1.30 05-18-2015 ------------------ -- Correctly emit 'all' event when primary + all secondaries have connected. - -1.1.29 05-17-2015 ------------------ -- NODE-464 Only use a single socket against arbiters and hidden servers. -- Ensure we filter out hidden servers from any server queries. - -1.1.28 05-12-2015 ------------------ -- Fixed buffer compare for electionId for < node 12.0.2 - -1.1.27 05-12-2015 ------------------ -- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. - -1.1.26 05-06-2015 ------------------ -- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. -- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. - -1.1.25 04-24-2015 ------------------ -- Handle lack of callback in crud operations when returning error on application closed. - -1.1.24 04-22-2015 ------------------ -- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. - -1.1.23 04-15-2015 ------------------ -- Standardizing mongoErrors and its API (Issue #14) -- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) -- remove mkdirp and rimraf dependencies (Issue #12) -- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) -- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) -- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) - -1.1.22 04-10-2015 ------------------ -- Minor refactorings in cursor code to make extending the cursor simpler. -- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. - -1.1.21 03-26-2015 ------------------ -- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. - -1.1.20 03-24-2015 ------------------ -- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. - -1.1.19 03-21-2015 ------------------ -- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. - -1.1.18 03-17-2015 ------------------ -- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. - -1.1.17 03-16-2015 ------------------ -- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. - -1.1.16 03-06-2015 ------------------ -- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. - -1.1.15 03-04-2015 ------------------ -- Removed check for type in replset pickserver function. - -1.1.14 02-26-2015 ------------------ -- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads - -1.1.13 02-24-2015 ------------------ -- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) - -1.1.12 02-16-2015 ------------------ -- Fixed cursor transforms for buffered document reads from cursor. - -1.1.11 02-02-2015 ------------------ -- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -1.1.10 31-01-2015 ------------------ -- Added tranforms.doc option to cursor to allow for pr. document transformations. - -1.1.9 21-01-2015 ----------------- -- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. -- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. -- Don't treat findOne() as a command cursor. -- Refactored out state changes into methods to simplify read the next method. - -1.1.8 09-12-2015 ----------------- -- Stripped out Object.defineProperty for performance reasons -- Applied more performance optimizations. -- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit - -1.1.7 18-12-2014 ----------------- -- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. - -1.1.6 18-12-2014 ----------------- -- Server manager fixed to support 2.2.X servers for travis test matrix. - -1.1.5 17-12-2014 ----------------- -- Fall back to errmsg when creating MongoError for command errors - -1.1.4 17-12-2014 ----------------- -- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. -- Fixed variable leak in scram. -- Fixed server manager to deal better with killing processes. -- Bumped bson to 0.2.16. - -1.1.3 01-12-2014 ----------------- -- Fixed error handling issue with nonce generation in mongocr. -- Fixed issues with restarting servers when using ssl. -- Using strict for all classes. -- Cleaned up any escaping global variables. - -1.1.2 20-11-2014 ----------------- -- Correctly encoding UTF8 collection names on wire protocol messages. -- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. - -1.1.1 14-11-2014 ----------------- -- Refactored code to use prototype instead of privileged methods. -- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. -- Several deopt optimizations for v8 to improve performance and reduce GC pauses. - -1.0.5 29-10-2014 ----------------- -- Fixed issue with wrong namespace being created for command cursors. - -1.0.4 24-10-2014 ----------------- -- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. - -1.0.3 21-10-2014 ----------------- -- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. - -1.0.2 07-10-2014 ----------------- -- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. -- fixed issue with replset_state logging. - -1.0.1 07-10-2014 ----------------- -- Dependency issue solved - -1.0.0 07-10-2014 ----------------- -- Initial release of mongodb-core diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE deleted file mode 100644 index ad410e1..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile deleted file mode 100644 index 36e1202..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -NODE = node -NPM = npm -JSDOC = jsdoc -name = all - -generate_docs: - # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md - hugo -s docs/reference -d ../../public - $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api - cp -R ./public/api/scripts ./public/. - cp -R ./public/api/styles ./public/. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/README.md deleted file mode 100644 index 1c9e4c8..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/README.md +++ /dev/null @@ -1,225 +0,0 @@ -# Description - -The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. - -## MongoDB Node.JS Core Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native/ | -| apidoc | http://mongodb.github.io/node-mongodb-native/ | -| source | https://github.com/christkv/mongodb-core | -| mongodb | http://www.mongodb.org/ | - -### Blogs of Engineers involved in the driver -- Christian Kvalheim [@christkv](https://twitter.com/christkv) - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a -case in our issue management tool, JIRA: - -- Create an account and login . -- Navigate to the NODE project . -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Questions and Bug Reports - - * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native - * jira: http://jira.mongodb.org/ - -### Change Log - -http://jira.mongodb.org/browse/NODE - -# QuickStart - -The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. - -## Create the package.json file - -Let's create a directory where our application will live. In our case we will put this under our projects directory. - -``` -mkdir myproject -cd myproject -``` - -Create a **package.json** using your favorite text editor and fill it in. - -```json -{ - "name": "myproject", - "version": "1.0.0", - "description": "My first project", - "main": "index.js", - "repository": { - "type": "git", - "url": "git://github.com/christkv/myfirstproject.git" - }, - "dependencies": { - "mongodb-core": "~1.0" - }, - "author": "Christian Kvalheim", - "license": "Apache 2.0", - "bugs": { - "url": "https://github.com/christkv/myfirstproject/issues" - }, - "homepage": "https://github.com/christkv/myfirstproject" -} -``` - -Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. - -``` -npm install -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -Booting up a MongoDB Server ---------------------------- -Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). - -``` -mongod --dbpath=/data --port 27017 -``` - -You should see the **mongod** process start up and print some status information. - -## Connecting to MongoDB - -Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. - -First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. - -```js -var Server = require('mongodb-core').Server - , assert = require('assert'); - -// Set up server connection -var server = new Server({ - host: 'localhost' - , port: 27017 - , reconnect: true - , reconnectInterval: 50 -}); - -// Add event listeners -server.on('connect', function(_server) { - console.log('connected'); - test.done(); -}); - -server.on('close', function() { - console.log('closed'); -}); - -server.on('reconnect', function() { - console.log('reconnect'); -}); - -// Start connection -server.connect(); -``` - -To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. - -```js -var Server = require('mongodb-core').Server - , assert = require('assert'); - -// Set up server connection -var server = new Server({ - host: 'localhost' - , port: 27017 - , reconnect: true - , reconnectInterval: 50 -}); - -// Add event listeners -server.on('connect', function(_server) { - console.log('connected'); - - // Execute the ismaster command - _server.command('system.$cmd', {ismaster: true}, function(err, result) { - - // Perform a document insert - _server.insert('myproject.inserts1', [{a:1}, {a:2}], { - writeConcern: {w:1}, ordered:true - }, function(err, results) { - assert.equal(null, err); - assert.equal(2, results.result.n); - - // Perform a document update - _server.update('myproject.inserts1', [{ - q: {a: 1}, u: {'$set': {b:1}} - }], { - writeConcern: {w:1}, ordered:true - }, function(err, results) { - assert.equal(null, err); - assert.equal(1, results.result.n); - - // Remove a document - _server.remove('myproject.inserts1', [{ - q: {a: 1}, limit: 1 - }], { - writeConcern: {w:1}, ordered:true - }, function(err, results) { - assert.equal(null, err); - assert.equal(1, results.result.n); - - // Get a document - var cursor = _server.cursor('integration_tests.inserts_example4', { - find: 'integration_tests.example4' - , query: {a:1} - }); - - // Get the first document - cursor.next(function(err, doc) { - assert.equal(null, err); - assert.equal(2, doc.a); - - // Execute the ismaster command - _server.command("system.$cmd" - , {ismaster: true}, function(err, result) { - assert.equal(null, err) - _server.destroy(); - }); - }); - }); - }); - - test.done(); - }); -}); - -server.on('close', function() { - console.log('closed'); -}); - -server.on('reconnect', function() { - console.log('reconnect'); -}); - -// Start connection -server.connect(); -``` - -The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. - -* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. -* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. -* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. -* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. -* `command`, Executes a command against MongoDB and returns the result. -* `auth`, Authenticates the current topology using a supported authentication scheme. - -The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. - -## Next steps - -The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md deleted file mode 100644 index fe03ea0..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md +++ /dev/null @@ -1,18 +0,0 @@ -Testing setup -============= - -Single Server -------------- -mongod --dbpath=./db - -Replicaset ----------- -mongo --nodb -var x = new ReplSetTest({"useHostName":"false", "nodes" : {node0 : {}, node1 : {}, node2 : {}}}) -x.startSet(); -var config = x.getReplSetConfig() -x.initiate(config); - -Mongos ------- -var s = new ShardingTest( "auth1", 1 , 0 , 2 , {rs: true, noChunkSize : true}); \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json deleted file mode 100644 index c5eca92..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], - "source": { - "include": [ - "test/tests/functional/operation_example_tests.js", - "lib/topologies/mongos.js", - "lib/topologies/command_result.js", - "lib/topologies/read_preference.js", - "lib/topologies/replset.js", - "lib/topologies/server.js", - "lib/topologies/session.js", - "lib/topologies/replset_state.js", - "lib/connection/logger.js", - "lib/connection/connection.js", - "lib/cursor.js", - "lib/error.js", - "node_modules/bson/lib/bson/binary.js", - "node_modules/bson/lib/bson/code.js", - "node_modules/bson/lib/bson/db_ref.js", - "node_modules/bson/lib/bson/double.js", - "node_modules/bson/lib/bson/long.js", - "node_modules/bson/lib/bson/objectid.js", - "node_modules/bson/lib/bson/symbol.js", - "node_modules/bson/lib/bson/timestamp.js", - "node_modules/bson/lib/bson/max_key.js", - "node_modules/bson/lib/bson/min_key.js" - ] - }, - "templates": { - "cleverLinks": true, - "monospaceLinks": true, - "default": { - "outputSourceFiles" : true - }, - "applicationName": "Node.js MongoDB Driver API", - "disqus": true, - "googleAnalytics": "UA-29229787-1", - "openGraph": { - "title": "", - "type": "website", - "image": "", - "site_name": "", - "url": "" - }, - "meta": { - "title": "", - "description": "", - "keyword": "" - }, - "linenums": true - }, - "markdown": { - "parser": "gfm", - "hardwrap": true, - "tags": ["examples"] - }, - "examples": { - "indent": 4 - } -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/index.js deleted file mode 100644 index 8f10860..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/index.js +++ /dev/null @@ -1,18 +0,0 @@ -module.exports = { - MongoError: require('./lib/error') - , Server: require('./lib/topologies/server') - , ReplSet: require('./lib/topologies/replset') - , Mongos: require('./lib/topologies/mongos') - , Logger: require('./lib/connection/logger') - , Cursor: require('./lib/cursor') - , ReadPreference: require('./lib/topologies/read_preference') - , BSON: require('bson') - // Raw operations - , Query: require('./lib/connection/commands').Query - // Auth mechanisms - , MongoCR: require('./lib/auth/mongocr') - , X509: require('./lib/auth/x509') - , Plain: require('./lib/auth/plain') - , GSSAPI: require('./lib/auth/gssapi') - , ScramSHA1: require('./lib/auth/scram') -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js deleted file mode 100644 index c442b9b..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js +++ /dev/null @@ -1,244 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , MongoError = require('../error'); - -var AuthSession = function(db, username, password, options) { - this.db = db; - this.username = username; - this.password = password; - this.options = options; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; - -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -/** - * Creates a new GSSAPI authentication mechanism - * @class - * @return {GSSAPI} A cursor instance - */ -var GSSAPI = function() { - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -GSSAPI.prototype.auth = function(server, pool, db, username, password, options, callback) { - var self = this; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Start Auth process for a connection - GSSAPIInitialize(db, username, password, db, gssapiServiceName, server, connection, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password, options)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - // Get the connection - execute(connections.shift()); - } -} - -// -// Initialize step -var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, server, connection, callback) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); - - // Perform initialization - mongo_auth_process.init(username, password, function(err, context) { - if(err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if(err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback) { - // Build the sasl start command - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: payload - , autoAuthorize: 1 - }; - - // Execute first sasl step - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - // Execute mongodb transition - mongo_auth_process.transition(r.result.payload, function(err, payload) { - if(err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); - }); - }); -} - -var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { - // Build final command - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - mongo_auth_process.transition(null, function(err, payload) { - if(err) return callback(err, null); - callback(null, r); - }); - }); -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -GSSAPI.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = GSSAPI; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js deleted file mode 100644 index d0e9f59..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js +++ /dev/null @@ -1,160 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new MongoCR authentication mechanism - * @class - * @return {MongoCR} A cursor instance - */ -var MongoCR = function() { - this.authStore = []; -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -MongoCR.prototype.auth = function(server, pool, db, username, password, callback) { - var self = this; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var executeMongoCR = function(connection) { - // Let's start the process - server.command(f("%s.$cmd", db) - , { getnonce: 1 } - , { connection: connection }, function(err, r) { - var nonce = null; - var key = null; - - // Adjust the number of connections left - // Get nonce - if(err == null) { - nonce = r.result.nonce; - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password); - key = md5.digest('hex'); - } - - // Execute command - server.command(f("%s.$cmd", db) - , { authenticate: 1, user: username, nonce: nonce, key:key} - , { connection: connection }, function(err, r) { - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - }); - } - - // Get the connection - executeMongoCR(connections.shift()); - } -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -MongoCR.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = MongoCR; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js deleted file mode 100644 index 31ce872..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js +++ /dev/null @@ -1,150 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , Binary = require('bson').Binary - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new Plain authentication mechanism - * @class - * @return {Plain} A cursor instance - */ -var Plain = function() { - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -Plain.prototype.auth = function(server, pool, db, username, password, callback) { - var self = this; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Create payload - var payload = new Binary(f("\x00%s\x00%s", username, password)); - - // Let's start the sasl process - var command = { - saslStart: 1 - , mechanism: 'PLAIN' - , payload: payload - , autoAuthorize: 1 - }; - - // Let's start the process - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - // Get the connection - execute(connections.shift()); - } -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -Plain.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = Plain; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js deleted file mode 100644 index fe96637..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js +++ /dev/null @@ -1,317 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , Binary = require('bson').Binary - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new ScramSHA1 authentication mechanism - * @class - * @return {ScramSHA1} A cursor instance - */ -var ScramSHA1 = function() { - this.authStore = []; -} - -var parsePayload = function(payload) { - var dict = {}; - var parts = payload.split(','); - - for(var i = 0; i < parts.length; i++) { - var valueParts = parts[i].split('='); - dict[valueParts[0]] = valueParts[1]; - } - - return dict; -} - -var passwordDigest = function(username, password) { - if(typeof username != 'string') throw new MongoError("username must be a string"); - if(typeof password != 'string') throw new MongoError("password must be a string"); - if(password.length == 0) throw new MongoError("password cannot be empty"); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - return md5.digest('hex'); -} - -// XOR two buffers -var xor = function(a, b) { - if (!Buffer.isBuffer(a)) a = new Buffer(a) - if (!Buffer.isBuffer(b)) b = new Buffer(b) - var res = [] - if (a.length > b.length) { - for (var i = 0; i < b.length; i++) { - res.push(a[i] ^ b[i]) - } - } else { - for (var i = 0; i < a.length; i++) { - res.push(a[i] ^ b[i]) - } - } - return new Buffer(res); -} - -// Create a final digest -var hi = function(data, salt, iterations) { - // Create digest - var digest = function(msg) { - var hmac = crypto.createHmac('sha1', data); - hmac.update(msg); - return new Buffer(hmac.digest('base64'), 'base64'); - } - - // Create variables - salt = Buffer.concat([salt, new Buffer('\x00\x00\x00\x01')]) - var ui = digest(salt); - var u1 = ui; - - for(var i = 0; i < iterations - 1; i++) { - u1 = digest(u1); - ui = xor(ui, u1); - } - - return ui; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -ScramSHA1.prototype.auth = function(server, pool, db, username, password, callback) { - var self = this; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var executeScram = function(connection) { - // Clean up the user - username = username.replace('=', "=3D").replace(',', '=2C'); - - // Create a random nonce - var nonce = crypto.randomBytes(24).toString('base64'); - // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' - var firstBare = f("n=%s,r=%s", username, nonce); - - // Build command structure - var cmd = { - saslStart: 1 - , mechanism: 'SCRAM-SHA-1' - , payload: new Binary(f("n,,%s", firstBare)) - , autoAuthorize: 1 - } - - // Handle the error - var handleError = function(err, r) { - if(err) { - numberOfValidConnections = numberOfValidConnections - 1; - errorObject = err; return false; - } else if(r.result['$err']) { - errorObject = r.result; return false; - } else if(r.result['errmsg']) { - errorObject = r.result; return false; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - return true - } - - // Finish up - var finish = function(_count, _numberOfValidConnections) { - if(_count == 0 && _numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - return callback(null, true); - } else if(_count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); - return callback(errorObject, false); - } - } - - var handleEnd = function(_err, _r) { - // Handle any error - handleError(_err, _r) - // Adjust the number of connections - count = count - 1; - // Execute the finish - finish(count, numberOfValidConnections); - } - - // Execute start sasl command - server.command(f("%s.$cmd", db) - , cmd, { connection: connection }, function(err, r) { - - // Do we have an error, handle it - if(handleError(err, r) == false) { - count = count - 1; - - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - return callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); - return callback(errorObject, false); - } - - return; - } - - // Get the dictionary - var dict = parsePayload(r.result.payload.value()) - - // Unpack dictionary - var iterations = parseInt(dict.i, 10); - var salt = dict.s; - var rnonce = dict.r; - - // Set up start of proof - var withoutProof = f("c=biws,r=%s", rnonce); - var passwordDig = passwordDigest(username, password); - var saltedPassword = hi(passwordDig - , new Buffer(salt, 'base64') - , iterations); - - // Create the client key - var hmac = crypto.createHmac('sha1', saltedPassword); - hmac.update(new Buffer("Client Key")); - var clientKey = new Buffer(hmac.digest('base64'), 'base64'); - - // Create the stored key - var hash = crypto.createHash('sha1'); - hash.update(clientKey); - var storedKey = new Buffer(hash.digest('base64'), 'base64'); - - // Create the authentication message - var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(','); - - // Create client signature - var hmac = crypto.createHmac('sha1', storedKey); - hmac.update(new Buffer(authMsg)); - var clientSig = new Buffer(hmac.digest('base64'), 'base64'); - - // Create client proof - var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64')); - - // Create client final - var clientFinal = [withoutProof, clientProof].join(','); - - // Generate server key - var hmac = crypto.createHmac('sha1', saltedPassword); - hmac.update(new Buffer('Server Key')) - var serverKey = new Buffer(hmac.digest('base64'), 'base64'); - - // Generate server signature - var hmac = crypto.createHmac('sha1', serverKey); - hmac.update(new Buffer(authMsg)) - var serverSig = new Buffer(hmac.digest('base64'), 'base64'); - - // - // Create continue message - var cmd = { - saslContinue: 1 - , conversationId: r.result.conversationId - , payload: new Binary(new Buffer(clientFinal)) - } - - // - // Execute sasl continue - server.command(f("%s.$cmd", db) - , cmd, { connection: connection }, function(err, r) { - if(r && r.result.done == false) { - var cmd = { - saslContinue: 1 - , conversationId: r.result.conversationId - , payload: new Buffer(0) - } - - server.command(f("%s.$cmd", db) - , cmd, { connection: connection }, function(err, r) { - handleEnd(err, r); - }); - } else { - handleEnd(err, r); - } - }); - }); - } - - // Get the connection - executeScram(connections.shift()); - } -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -ScramSHA1.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - - -module.exports = ScramSHA1; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js deleted file mode 100644 index 177ede5..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js +++ /dev/null @@ -1,234 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , MongoError = require('../error'); - -var AuthSession = function(db, username, password, options) { - this.db = db; - this.username = username; - this.password = password; - this.options = options; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; - -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -/** - * Creates a new SSPI authentication mechanism - * @class - * @return {SSPI} A cursor instance - */ -var SSPI = function() { - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -SSPI.prototype.auth = function(server, pool, db, username, password, options, callback) { - var self = this; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Start Auth process for a connection - SSIPAuthenticate(username, password, gssapiServiceName, server, connection, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r && typeof r == 'object' && r.result['$err']) { - errorObject = r.result; - } else if(r && typeof r == 'object' && r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password, options)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - // Get the connection - execute(connections.shift()); - } -} - -var SSIPAuthenticate = function(username, password, gssapiServiceName, server, connection, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: '' - , autoAuthorize: 1 - }; - - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); - - // Execute first sasl step - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - mongo_auth_process.init(username, password, function(err) { - if(err) return callback(err); - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - if(doc.done) return callback(null, true); - callback(new Error("Authentication failed"), false); - }); - }); - }); - }); - }); - }); - }); - }); -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -SSPI.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = SSPI; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js deleted file mode 100644 index 641990e..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js +++ /dev/null @@ -1,145 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new X509 authentication mechanism - * @class - * @return {X509} A cursor instance - */ -var X509 = function() { - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -X509.prototype.auth = function(server, pool, db, username, password, callback) { - var self = this; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Let's start the sasl process - var command = { - authenticate: 1 - , mechanism: 'MONGODB-X509' - , user: username - }; - - // Let's start the process - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - // Get the connection - execute(connections.shift()); - } -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -X509.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = X509; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js deleted file mode 100644 index 05023b4..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js +++ /dev/null @@ -1,519 +0,0 @@ -"use strict"; - -var f = require('util').format - , Long = require('bson').Long - , setProperty = require('./utils').setProperty - , getProperty = require('./utils').getProperty - , getSingleProperty = require('./utils').getSingleProperty; - -// Incrementing request id -var _requestId = 0; - -// Wire command operation ids -var OP_QUERY = 2004; -var OP_GETMORE = 2005; -var OP_KILL_CURSORS = 2007; - -// Query flags -var OPTS_NONE = 0; -var OPTS_TAILABLE_CURSOR = 2; -var OPTS_SLAVE = 4; -var OPTS_OPLOG_REPLAY = 8; -var OPTS_NO_CURSOR_TIMEOUT = 16; -var OPTS_AWAIT_DATA = 32; -var OPTS_EXHAUST = 64; -var OPTS_PARTIAL = 128; - -// Response flags -var CURSOR_NOT_FOUND = 0; -var QUERY_FAILURE = 2; -var SHARD_CONFIG_STALE = 4; -var AWAIT_CAPABLE = 8; - -/************************************************************** - * QUERY - **************************************************************/ -var Query = function(bson, ns, query, options) { - var self = this; - // Basic options needed to be passed in - if(ns == null) throw new Error("ns must be specified for query"); - if(query == null) throw new Error("query must be specified for query"); - - // Validate that we are not passing 0x00 in the colletion name - if(!!~ns.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Basic options - this.bson = bson; - this.ns = ns; - this.query = query; - - // Ensure empty options - this.options = options || {}; - - // Additional options - this.numberToSkip = options.numberToSkip || 0; - this.numberToReturn = options.numberToReturn || 0; - this.returnFieldSelector = options.returnFieldSelector || null; - this.requestId = _requestId++; - - // Serialization option - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; - this.batchSize = self.numberToReturn; - - // Flags - this.tailable = false; - this.slaveOk = false; - this.oplogReply = false; - this.noCursorTimeout = false; - this.awaitData = false; - this.exhaust = false; - this.partial = false; -} - -// -// Assign a new request Id -Query.prototype.incRequestId = function() { - this.requestId = _requestId++; -} - -// -// Assign a new request Id -Query.nextRequestId = function() { - return _requestId + 1; -} - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -Query.prototype.toBin = function() { - var self = this; - var buffers = []; - var projection = null; - - // Set up the flags - var flags = 0; - if(this.tailable) flags |= OPTS_TAILABLE_CURSOR; - if(this.slaveOk) flags |= OPTS_SLAVE; - if(this.oplogReply) flags |= OPTS_OPLOG_REPLAY; - if(this.noCursorTimeout) flags |= OPTS_NO_CURSOR_TIMEOUT; - if(this.awaitData) flags |= OPTS_AWAIT_DATA; - if(this.exhaust) flags |= OPTS_EXHAUST; - if(this.partial) flags |= OPTS_PARTIAL; - - // If batchSize is different to self.numberToReturn - if(self.batchSize != self.numberToReturn) self.numberToReturn = self.batchSize; - - // Allocate write protocol header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // Flags - + Buffer.byteLength(self.ns) + 1 // namespace - + 4 // numberToSkip - + 4 // numberToReturn - ); - - // Add header to buffers - buffers.push(header); - - // Serialize the query - var query = self.bson.serialize(this.query - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - - // Add query document - buffers.push(query); - - if(self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { - // Serialize the projection document - projection = self.bson.serialize(this.returnFieldSelector, this.checkKeys, true, this.serializeFunctions, this.ignoreUndefined); - // Add projection document - buffers.push(projection); - } - - // Total message size - var totalLength = header.length + query.length + (projection ? projection.length : 0); - - // Set up the index - var index = 4; - - // Write total document length - header[3] = (totalLength >> 24) & 0xff; - header[2] = (totalLength >> 16) & 0xff; - header[1] = (totalLength >> 8) & 0xff; - header[0] = (totalLength) & 0xff; - - // Write header information requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // Write header information responseTo - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Write header information OP_QUERY - header[index + 3] = (OP_QUERY >> 24) & 0xff; - header[index + 2] = (OP_QUERY >> 16) & 0xff; - header[index + 1] = (OP_QUERY >> 8) & 0xff; - header[index] = (OP_QUERY) & 0xff; - index = index + 4; - - // Write header information flags - header[index + 3] = (flags >> 24) & 0xff; - header[index + 2] = (flags >> 16) & 0xff; - header[index + 1] = (flags >> 8) & 0xff; - header[index] = (flags) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write header information flags numberToSkip - header[index + 3] = (this.numberToSkip >> 24) & 0xff; - header[index + 2] = (this.numberToSkip >> 16) & 0xff; - header[index + 1] = (this.numberToSkip >> 8) & 0xff; - header[index] = (this.numberToSkip) & 0xff; - index = index + 4; - - // Write header information flags numberToReturn - header[index + 3] = (this.numberToReturn >> 24) & 0xff; - header[index + 2] = (this.numberToReturn >> 16) & 0xff; - header[index + 1] = (this.numberToReturn >> 8) & 0xff; - header[index] = (this.numberToReturn) & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -} - -Query.getRequestId = function() { - return ++_requestId; -} - -/************************************************************** - * GETMORE - **************************************************************/ -var GetMore = function(bson, ns, cursorId, opts) { - opts = opts || {}; - this.numberToReturn = opts.numberToReturn || 0; - this.requestId = _requestId++; - this.bson = bson; - this.ns = ns; - this.cursorId = cursorId; -} - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -GetMore.prototype.toBin = function() { - var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); - // Create command buffer - var index = 0; - // Allocate buffer - var _buffer = new Buffer(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = (length) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = (this.requestId) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_GETMORE); - _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; - _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; - _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; - _buffer[index] = (OP_GETMORE) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // Write collection name - index = index + _buffer.write(this.ns, index, 'utf8') + 1; - _buffer[index - 1] = 0; - - // Write batch size - // index = write32bit(index, _buffer, numberToReturn); - _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; - _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; - _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; - _buffer[index] = (this.numberToReturn) & 0xff; - index = index + 4; - - // Write cursor id - // index = write32bit(index, _buffer, cursorId.getLowBits()); - _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; - _buffer[index] = (this.cursorId.getLowBits()) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorId.getHighBits()); - _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; - _buffer[index] = (this.cursorId.getHighBits()) & 0xff; - index = index + 4; - - // Return buffer - return _buffer; -} - -/************************************************************** - * KILLCURSOR - **************************************************************/ -var KillCursor = function(bson, cursorIds) { - this.requestId = _requestId++; - this.cursorIds = cursorIds; -} - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -KillCursor.prototype.toBin = function() { - var length = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); - - // Create command buffer - var index = 0; - var _buffer = new Buffer(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = (length) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = (this.requestId) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_KILL_CURSORS); - _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; - _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; - _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; - _buffer[index] = (OP_KILL_CURSORS) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // Write batch size - // index = write32bit(index, _buffer, this.cursorIds.length); - _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; - _buffer[index] = (this.cursorIds.length) & 0xff; - index = index + 4; - - // Write all the cursor ids into the array - for(var i = 0; i < this.cursorIds.length; i++) { - // Write cursor id - // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); - _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; - _buffer[index] = (this.cursorIds[i].getLowBits()) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); - _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; - _buffer[index] = (this.cursorIds[i].getHighBits()) & 0xff; - index = index + 4; - } - - // Return buffer - return _buffer; -} - -var Response = function(bson, data, opts) { - opts = opts || {promoteLongs: true}; - this.parsed = false; - - // - // Parse Header - // - this.index = 0; - this.raw = data; - this.data = data; - this.bson = bson; - this.opts = opts; - - // Read the message length - this.length = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Fetch the request id for this reply - this.requestId = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Fetch the id of the request that triggered the response - this.responseTo = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Skip op-code field - this.index = this.index + 4; - - // Unpack flags - this.responseFlags = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Unpack the cursor - var lowBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - var highBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - // Create long object - this.cursorId = new Long(lowBits, highBits); - - // Unpack the starting from - this.startingFrom = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Unpack the number of objects returned - this.numberReturned = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Preallocate document array - this.documents = new Array(this.numberReturned); - - // Flag values - this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) != 0; - this.queryFailure = (this.responseFlags & QUERY_FAILURE) != 0; - this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) != 0; - this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) != 0; - this.promoteLongs = typeof opts.promoteLongs == 'boolean' ? opts.promoteLongs : true; -} - -Response.prototype.isParsed = function() { - return this.parsed; -} - -// Validation buffers -var firstBatch = new Buffer('firstBatch', 'utf8'); -var nextBatch = new Buffer('nextBatch', 'utf8'); -var cursorId = new Buffer('id', 'utf8').toString('hex'); - -var documentBuffers = { - firstBatch: firstBatch.toString('hex'), - nextBatch: nextBatch.toString('hex') -}; - -Response.prototype.parse = function(options) { - // Don't parse again if not needed - if(this.parsed) return; - options = options || {}; - - // Allow the return of raw documents instead of parsing - var raw = options.raw || false; - var documentsReturnedIn = options.documentsReturnedIn || null; - - // - // Single document and documentsReturnedIn set - // - if(this.numberReturned == 1 && documentsReturnedIn != null && raw) { - // Calculate the bson size - var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; - // Slice out the buffer containing the command result document - var document = this.data.slice(this.index, this.index + bsonSize); - // Set up field we wish to keep as raw - var fieldsAsRaw = {} - fieldsAsRaw[documentsReturnedIn] = true; - // Set up the options - var _options = {promoteLongs: this.opts.promoteLongs, fieldsAsRaw: fieldsAsRaw}; - - // Deserialize but keep the array of documents in non-parsed form - var doc = this.bson.deserialize(document, _options); - - // Get the documents - this.documents = doc.cursor[documentsReturnedIn]; - this.numberReturned = this.documents.length; - // Ensure we have a Long valie cursor id - this.cursorId = typeof doc.cursor.id == 'number' - ? Long.fromNumber(doc.cursor.id) - : doc.cursor.id; - - // Adjust the index - this.index = this.index + bsonSize; - - // Set as parsed - this.parsed = true - return; - } - - // - // Parse Body - // - for(var i = 0; i < this.numberReturned; i++) { - var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; - // Parse options - var _options = {promoteLongs: this.opts.promoteLongs}; - - // If we have raw results specified slice the return document - if(raw) { - this.documents[i] = this.data.slice(this.index, this.index + bsonSize); - } else { - this.documents[i] = this.bson.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); - } - - // Adjust the index - this.index = this.index + bsonSize; - } - - // Set parsed - this.parsed = true; -} - -module.exports = { - Query: Query - , GetMore: GetMore - , Response: Response - , KillCursor: KillCursor -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js deleted file mode 100644 index 217e58a..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js +++ /dev/null @@ -1,462 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , EventEmitter = require('events').EventEmitter - , net = require('net') - , tls = require('tls') - , f = require('util').format - , getSingleProperty = require('./utils').getSingleProperty - , debugOptions = require('./utils').debugOptions - , Response = require('./commands').Response - , MongoError = require('../error') - , Logger = require('./logger'); - -var _id = 0; -var debugFields = ['host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay' - , 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert' - , 'rejectUnauthorized', 'promoteLongs']; - -/** - * Creates a new Connection instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @fires Connection#connect - * @fires Connection#close - * @fires Connection#error - * @fires Connection#timeout - * @fires Connection#parseError - * @return {Connection} A cursor instance - */ -var Connection = function(options) { - // Add event listener - EventEmitter.call(this); - // Set empty if no options passed - this.options = options || {}; - // Identification information - this.id = _id++; - // Logger instance - this.logger = Logger('Connection', options); - // No bson parser passed in - if(!options.bson) throw new Error("must pass in valid bson parser"); - // Get bson parser - this.bson = options.bson; - // Grouping tag used for debugging purposes - this.tag = options.tag; - // Message handler - this.messageHandler = options.messageHandler; - - // Max BSON message size - this.maxBsonMessageSize = options.maxBsonMessageSize || (1024 * 1024 * 16 * 4); - // Debug information - if(this.logger.isDebug()) this.logger.debug(f('creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)))); - - // Default options - this.port = options.port || 27017; - this.host = options.host || 'localhost'; - this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; - this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0; - this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; - this.connectionTimeout = options.connectionTimeout || 0; - this.socketTimeout = options.socketTimeout || 0; - - // If connection was destroyed - this.destroyed = false; - - // Check if we have a domain socket - this.domainSocket = this.host.indexOf('\/') != -1; - - // Serialize commands using function - this.singleBufferSerializtion = typeof options.singleBufferSerializtion == 'boolean' ? options.singleBufferSerializtion : true; - this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; - - // SSL options - this.ca = options.ca || null; - this.cert = options.cert || null; - this.key = options.key || null; - this.passphrase = options.passphrase || null; - this.ssl = typeof options.ssl == 'boolean' ? options.ssl : false; - this.rejectUnauthorized = typeof options.rejectUnauthorized == 'boolean' ? options.rejectUnauthorized : true - - // If ssl not enabled - if(!this.ssl) this.rejectUnauthorized = false; - - // Response options - this.responseOptions = { - promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true - } - - // Flushing - this.flushing = false; - this.queue = []; - - // Internal state - this.connection = null; - this.writeStream = null; -} - -inherits(Connection, EventEmitter); - -// -// Connection handlers -var errorHandler = function(self) { - return function(err) { - // Debug information - if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err))); - // Emit the error - if(self.listeners('error').length > 0) self.emit("error", MongoError.create(err), self); - } -} - -var timeoutHandler = function(self) { - return function() { - // Debug information - if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); - // Emit timeout error - self.emit("timeout" - , MongoError.create(f("connection %s to %s:%s timed out", self.id, self.host, self.port)) - , self); - } -} - -var closeHandler = function(self) { - return function(hadError) { - // Debug information - if(self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); - // Emit close event - if(!hadError) { - self.emit("close" - , MongoError.create(f("connection %s to %s:%s closed", self.id, self.host, self.port)) - , self); - } - } -} - -var dataHandler = function(self) { - return function(data) { - // Parse until we are done with the data - while(data.length > 0) { - // If we still have bytes to read on the current message - if(self.bytesRead > 0 && self.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; - // Check if the current chunk contains the rest of the message - if(remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(self.buffer, self.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - self.bytesRead = self.bytesRead + data.length; - - // Reset state of buffer - data = new Buffer(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - try { - var emitBuffer = self.buffer; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Emit the buffer - self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); - } catch(err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if(self.stubBuffer != null && self.stubBuffer.length > 0) { - // If we have enough bytes to determine the message size let's do it - if(self.stubBuffer.length + data.length > 4) { - // Prepad the data - var newData = new Buffer(self.stubBuffer.length + data.length); - self.stubBuffer.copy(newData, 0); - data.copy(newData, self.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - - } else { - - // Add the the bytes to the stub buffer - var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); - // Copy existing stub buffer - self.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, self.stubBuffer.length); - // Exit parsing loop - data = new Buffer(0); - } - } else { - if(data.length > 4) { - // Retrieve the message size - // var sizeOfMessage = data.readUInt32LE(0); - var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; - // If we have a negative sizeOfMessage emit error and return - if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { - var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ - sizeOfMessage: sizeOfMessage, - bytesRead: self.bytesRead, - stubBuffer: self.stubBuffer}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage > data.length) { - self.buffer = new Buffer(sizeOfMessage); - // Copy all the data into the buffer - data.copy(self.buffer, 0); - // Update bytes read - self.bytesRead = data.length; - // Update sizeOfMessage - self.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage == data.length) { - try { - var emitBuffer = data; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - // Emit the message - self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { - var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:0, - buffer:null, - stubBuffer:null}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - - // Clear out the state of the parser - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - } else { - var emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); - } - } else { - // Create a buffer that contains the space for the non-complete message - self.stubBuffer = new Buffer(data.length) - // Copy the data to the stub buffer - data.copy(self.stubBuffer, 0); - // Exit parsing loop - data = new Buffer(0); - } - } - } - } - } -} - -/** - * Connect - * @method - */ -Connection.prototype.connect = function(_options) { - var self = this; - _options = _options || {}; - // Check if we are overriding the promoteLongs - if(typeof _options.promoteLongs == 'boolean') { - self.responseOptions.promoteLongs = _options.promoteLongs; - } - - // Create new connection instance - self.connection = self.domainSocket - ? net.createConnection(self.host) - : net.createConnection(self.port, self.host); - - // Set the options for the connection - self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); - self.connection.setTimeout(self.connectionTimeout); - self.connection.setNoDelay(self.noDelay); - - // If we have ssl enabled - if(self.ssl) { - var sslOptions = { - socket: self.connection - , rejectUnauthorized: self.rejectUnauthorized - } - - if(self.ca) sslOptions.ca = self.ca; - if(self.cert) sslOptions.cert = self.cert; - if(self.key) sslOptions.key = self.key; - if(self.passphrase) sslOptions.passphrase = self.passphrase; - - // Attempt SSL connection - self.connection = tls.connect(self.port, self.host, sslOptions, function() { - // Error on auth or skip - if(self.connection.authorizationError && self.rejectUnauthorized) { - return self.emit("error", self.connection.authorizationError, self, {ssl:true}); - } - - // Set socket timeout instead of connection timeout - self.connection.setTimeout(self.socketTimeout); - // We are done emit connect - self.emit('connect', self); - }); - self.connection.setTimeout(self.connectionTimeout); - } else { - self.connection.on('connect', function() { - // Set socket timeout instead of connection timeout - self.connection.setTimeout(self.socketTimeout); - // Emit connect event - self.emit('connect', self); - }); - } - - // Add handlers for events - self.connection.once('error', errorHandler(self)); - self.connection.once('timeout', timeoutHandler(self)); - self.connection.once('close', closeHandler(self)); - self.connection.on('data', dataHandler(self)); -} - -/** - * Destroy connection - * @method - */ -Connection.prototype.destroy = function() { - if(this.connection) this.connection.destroy(); - this.destroyed = true; -} - -/** - * Write to connection - * @method - * @param {Command} command Command to write out need to implement toBin and toBinUnified - */ -Connection.prototype.write = function(buffer) { - // Debug log - if(this.logger.isDebug()) this.logger.debug(f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port)); - // Write out the command - if(!Array.isArray(buffer)) return this.connection.write(buffer, 'binary'); - // Iterate over all buffers and write them in order to the socket - for(var i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); -} - -/** - * Return id of connection as a string - * @method - * @return {string} - */ -Connection.prototype.toString = function() { - return "" + this.id; -} - -/** - * Return json object of connection - * @method - * @return {object} - */ -Connection.prototype.toJSON = function() { - return {id: this.id, host: this.host, port: this.port}; -} - -/** - * Is the connection connected - * @method - * @return {boolean} - */ -Connection.prototype.isConnected = function() { - if(this.destroyed) return false; - return !this.connection.destroyed && this.connection.writable; -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Connection#connect - * @type {Connection} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Connection#close - * @type {Connection} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Connection#error - * @type {Connection} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Connection#timeout - * @type {Connection} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Connection#parseError - * @type {Connection} - */ - -module.exports = Connection; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js deleted file mode 100644 index 69c6f93..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js +++ /dev/null @@ -1,196 +0,0 @@ -"use strict"; - -var f = require('util').format - , MongoError = require('../error'); - -// Filters for classes -var classFilters = {}; -var filteredClasses = {}; -var level = null; -// Save the process id -var pid = process.pid; -// current logger -var currentLogger = null; - -/** - * Creates a new Logger instance - * @class - * @param {string} className The Class name associated with the logging instance - * @param {object} [options=null] Optional settings. - * @param {Function} [options.logger=null] Custom logger function; - * @param {string} [options.loggerLevel=error] Override default global log level. - * @return {Logger} a Logger instance. - */ -var Logger = function(className, options) { - if(!(this instanceof Logger)) return new Logger(className, options); - options = options || {}; - - // Current reference - var self = this; - this.className = className; - - // Current logger - if(currentLogger == null && options.logger) { - currentLogger = options.logger; - } else if(currentLogger == null) { - currentLogger = console.log; - } - - // Set level of logging, default is error - if(level == null) { - level = options.loggerLevel || 'error'; - } - - // Add all class names - if(filteredClasses[this.className] == null) classFilters[this.className] = true; -} - -/** - * Log a message at the debug level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.debug = function(message, object) { - if(this.isDebug() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); - var state = { - type: 'debug', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -} - -/** - * Log a message at the info level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.info = function(message, object) { - if(this.isInfo() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); - var state = { - type: 'info', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -}, - -/** - * Log a message at the error level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.error = function(message, object) { - if(this.isError() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); - var state = { - type: 'error', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -}, - -/** - * Is the logger set at info level - * @method - * @return {boolean} - */ -Logger.prototype.isInfo = function() { - return level == 'info' || level == 'debug'; -}, - -/** - * Is the logger set at error level - * @method - * @return {boolean} - */ -Logger.prototype.isError = function() { - return level == 'error' || level == 'info' || level == 'debug'; -}, - -/** - * Is the logger set at debug level - * @method - * @return {boolean} - */ -Logger.prototype.isDebug = function() { - return level == 'debug'; -} - -/** - * Resets the logger to default settings, error and no filtered classes - * @method - * @return {null} - */ -Logger.reset = function() { - level = 'error'; - filteredClasses = {}; -} - -/** - * Get the current logger function - * @method - * @return {function} - */ -Logger.currentLogger = function() { - return currentLogger; -} - -/** - * Set the current logger function - * @method - * @param {function} logger Logger function. - * @return {null} - */ -Logger.setCurrentLogger = function(logger) { - if(typeof logger != 'function') throw new MongoError("current logger must be a function"); - currentLogger = logger; -} - -/** - * Set what classes to log. - * @method - * @param {string} type The type of filter (currently only class) - * @param {string[]} values The filters to apply - * @return {null} - */ -Logger.filter = function(type, values) { - if(type == 'class' && Array.isArray(values)) { - filteredClasses = {}; - - values.forEach(function(x) { - filteredClasses[x] = true; - }); - } -} - -/** - * Set the current log level - * @method - * @param {string} level Set current log level (debug, info, error) - * @return {null} - */ -Logger.setLevel = function(_level) { - if(_level != 'info' && _level != 'error' && _level != 'debug') throw new Error(f("%s is an illegal logging level", _level)); - level = _level; -} - -module.exports = Logger; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js deleted file mode 100644 index dd13707..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js +++ /dev/null @@ -1,275 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , EventEmitter = require('events').EventEmitter - , Connection = require('./connection') - , Query = require('./commands').Query - , Logger = require('./logger') - , f = require('util').format; - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -var _id = 0; - -/** - * Creates a new Pool instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passPhrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @fires Pool#connect - * @fires Pool#close - * @fires Pool#error - * @fires Pool#timeout - * @fires Pool#parseError - * @return {Pool} A cursor instance - */ -var Pool = function(options) { - var self = this; - // Add event listener - EventEmitter.call(this); - // Set empty if no options passed - this.options = options || {}; - this.size = typeof options.size == 'number' ? options.size : 5; - // Message handler - this.messageHandler = options.messageHandler; - // No bson parser passed in - if(!options.bson) throw new Error("must pass in valid bson parser"); - // Contains all connections - this.connections = []; - this.state = DISCONNECTED; - // Round robin index - this.index = 0; - this.dead = false; - // Logger instance - this.logger = Logger('Pool', options); - // Pool id - this.id = _id++; - // Grouping tag used for debugging purposes - this.tag = options.tag; -} - -inherits(Pool, EventEmitter); - -var errorHandler = function(self) { - return function(err, connection) { - if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); - if(!self.dead) { - self.state = DISCONNECTED; - self.dead = true; - self.destroy(); - self.emit('error', err, self); - } - } -} - -var timeoutHandler = function(self) { - return function(err, connection) { - if(self.logger.isDebug()) self.logger.debug(f('pool [%s] timed out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); - if(!self.dead) { - self.state = DISCONNECTED; - self.dead = true; - self.destroy(); - self.emit('timeout', err, self); - } - } -} - -var closeHandler = function(self) { - return function(err, connection) { - if(self.logger.isDebug()) self.logger.debug(f('pool [%s] closed [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); - if(!self.dead) { - self.state = DISCONNECTED; - self.dead = true; - self.destroy(); - self.emit('close', err, self); - } - } -} - -var parseErrorHandler = function(self) { - return function(err, connection) { - if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); - if(!self.dead) { - self.state = DISCONNECTED; - self.dead = true; - self.destroy(); - self.emit('parseError', err, self); - } - } -} - -var connectHandler = function(self) { - return function(connection) { - self.connections.push(connection); - // We have connected to all servers - if(self.connections.length == self.size) { - self.state = CONNECTED; - // Done connecting - self.emit("connect", self); - } - } -} - -/** - * Destroy pool - * @method - */ -Pool.prototype.destroy = function() { - this.state = DESTROYED; - // Set dead - this.dead = true; - // Destroy all the connections - this.connections.forEach(function(c) { - // Destroy all event emitters - ["close", "message", "error", "timeout", "parseError", "connect"].forEach(function(e) { - c.removeAllListeners(e); - }); - - // Destroy the connection - c.destroy(); - }); -} - -var execute = null; - -try { - execute = setImmediate; -} catch(err) { - execute = process.nextTick; -} - -/** - * Connect pool - * @method - */ -Pool.prototype.connect = function(_options) { - var self = this; - // Set to connecting - this.state = CONNECTING - // No dead - this.dead = false; - - // Ensure we allow for a little time to setup connections - var wait = 1; - - // Connect all sockets - for(var i = 0; i < this.size; i++) { - setTimeout(function() { - execute(function() { - self.options.messageHandler = self.messageHandler; - var connection = new Connection(self.options); - - // Add all handlers - connection.once('close', closeHandler(self)); - connection.once('error', errorHandler(self)); - connection.once('timeout', timeoutHandler(self)); - connection.once('parseError', parseErrorHandler(self)); - connection.on('connect', connectHandler(self)); - - // Start connection - connection.connect(_options); - }); - }, wait); - - // wait for 1 miliseconds before attempting to connect, spacing out connections - wait = wait + 1; - } -} - -/** - * Get a pool connection (round-robin) - * @method - * @return {Connection} - */ -Pool.prototype.get = function() { - // if(this.dead) return null; - var connection = this.connections[this.index++]; - this.index = this.index % this.connections.length; - return connection; -} - -/** - * Get all pool connections - * @method - * @return {array} - */ -Pool.prototype.getAll = function() { - return this.connections.slice(0); -} - -/** - * Is the pool connected - * @method - * @return {boolean} - */ -Pool.prototype.isConnected = function() { - for(var i = 0; i < this.connections.length; i++) { - if(!this.connections[i].isConnected()) return false; - } - - return this.state == CONNECTED; -} - -/** - * Was the pool destroyed - * @method - * @return {boolean} - */ -Pool.prototype.isDestroyed = function() { - return this.state == DESTROYED; -} - - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Pool#connect - * @type {Pool} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Pool#close - * @type {Pool} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Pool#error - * @type {Pool} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Pool#timeout - * @type {Pool} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Pool#parseError - * @type {Pool} - */ - -module.exports = Pool; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js deleted file mode 100644 index 7f0b89d..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; - -// Set property function -var setProperty = function(obj, prop, flag, values) { - Object.defineProperty(obj, prop.name, { - enumerable:true, - set: function(value) { - if(typeof value != 'boolean') throw new Error(f("%s required a boolean", prop.name)); - // Flip the bit to 1 - if(value == true) values.flags |= flag; - // Flip the bit to 0 if it's set, otherwise ignore - if(value == false && (values.flags & flag) == flag) values.flags ^= flag; - prop.value = value; - } - , get: function() { return prop.value; } - }); -} - -// Set property function -var getProperty = function(obj, propName, fieldName, values, func) { - Object.defineProperty(obj, propName, { - enumerable:true, - get: function() { - // Not parsed yet, parse it - if(values[fieldName] == null && obj.isParsed && !obj.isParsed()) { - obj.parse(); - } - - // Do we have a post processing function - if(typeof func == 'function') return func(values[fieldName]); - // Return raw value - return values[fieldName]; - } - }); -} - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable:true, - get: function() { - return value - } - }); -} - -// Shallow copy -var copy = function(fObj, tObj) { - tObj = tObj || {}; - for(var name in fObj) tObj[name] = fObj[name]; - return tObj; -} - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) return callback; - return domain.bind(callback); -} - -exports.setProperty = setProperty; -exports.getProperty = getProperty; -exports.getSingleProperty = getSingleProperty; -exports.copy = copy; -exports.bindToCurrentDomain = bindToCurrentDomain; -exports.debugOptions = debugOptions; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js deleted file mode 100644 index ab82818..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js +++ /dev/null @@ -1,756 +0,0 @@ -"use strict"; - -var Long = require('bson').Long - , Logger = require('./connection/logger') - , MongoError = require('./error') - , f = require('util').format; - -/** - * This is a cursor results callback - * - * @callback resultCallback - * @param {error} error An error object. Set to null if no error present - * @param {object} document - */ - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. - * - * **CURSORS Cannot directly be instantiated** - * @example - * var Server = require('mongodb-core').Server - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new Server({host: 'localhost', port: 27017}); - * // Wait for the connection event - * server.on('connect', function(server) { - * assert.equal(null, err); - * - * // Execute the write - * var cursor = _server.cursor('integration_tests.inserts_example4', { - * find: 'integration_tests.example4' - * , query: {a:1} - * }, { - * readPreference: new ReadPreference('secondary'); - * }); - * - * // Get the first document - * cursor.next(function(err, doc) { - * assert.equal(null, err); - * server.destroy(); - * }); - * }); - * - * // Start connecting - * server.connect(); - */ - -/** - * Creates a new Cursor, not to be used directly - * @class - * @param {object} bson An instance of the BSON parser - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|Long} cmd The selector (can be a command or a cursorId) - * @param {object} [options=null] Optional settings. - * @param {object} [options.batchSize=1000] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {object} [options.transforms=null] Transform methods for the cursor results - * @param {function} [options.transforms.query] Transform the value returned from the initial query - * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next - * @param {object} topology The server topology instance. - * @param {object} topologyOptions The server topology options. - * @return {Cursor} A cursor instance - * @property {number} cursorBatchSize The current cursorBatchSize for the cursor - * @property {number} cursorLimit The current cursorLimit for the cursor - * @property {number} cursorSkip The current cursorSkip for the cursor - */ -var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { - options = options || {}; - // Cursor reference - var self = this; - // Initial query - var query = null; - - // Cursor connection - this.connection = null; - // Cursor server - this.server = null; - - // Do we have a not connected handler - this.disconnectHandler = options.disconnectHandler; - - // Set local values - this.bson = bson; - this.ns = ns; - this.cmd = cmd; - this.options = options; - this.topology = topology; - - // All internal state - this.cursorState = { - cursorId: null - , cmd: cmd - , documents: options.documents || [] - , cursorIndex: 0 - , dead: false - , killed: false - , init: false - , notified: false - , limit: options.limit || cmd.limit || 0 - , skip: options.skip || cmd.skip || 0 - , batchSize: options.batchSize || cmd.batchSize || 1000 - , currentLimit: 0 - // Result field name if not a cursor (contains the array of results) - , transforms: options.transforms - } - - // Callback controller - this.callbacks = null; - - // Logger - this.logger = Logger('Cursor', options); - - // - // Did we pass in a cursor id - if(typeof cmd == 'number') { - this.cursorState.cursorId = Long.fromNumber(cmd); - } else if(cmd instanceof Long) { - this.cursorState.cursorId = cmd; - } -} - -Cursor.prototype.setCursorBatchSize = function(value) { - this.cursorState.batchSize = value; -} - -Cursor.prototype.cursorBatchSize = function() { - return this.cursorState.batchSize; -} - -Cursor.prototype.setCursorLimit = function(value) { - this.cursorState.limit = value; -} - -Cursor.prototype.cursorLimit = function() { - return this.cursorState.limit; -} - -Cursor.prototype.setCursorSkip = function(value) { - this.cursorState.skip = value; -} - -Cursor.prototype.cursorSkip = function() { - return this.cursorState.skip; -} - -// // -// // Execute getMore command -// var execGetMore = function(self, callback) { -// } - -// -// Execute the first query -var execInitialQuery = function(self, query, cmd, options, cursorState, connection, logger, callbacks, callback) { - if(logger.isDebug()) { - logger.debug(f("issue initial query [%s] with flags [%s]" - , JSON.stringify(cmd) - , JSON.stringify(query))); - } - - var queryCallback = function(err, result) { - if(err) return callback(err); - - if(result.queryFailure) { - return callback(MongoError.create(result.documents[0]), null); - } - - // Check if we have a command cursor - if(Array.isArray(result.documents) && result.documents.length == 1 - && (!cmd.find || (cmd.find && cmd.virtual == false)) - && (result.documents[0].cursor != 'string' - || result.documents[0]['$err'] - || result.documents[0]['errmsg'] - || Array.isArray(result.documents[0].result)) - ) { - - // We have a an error document return the error - if(result.documents[0]['$err'] - || result.documents[0]['errmsg']) { - return callback(MongoError.create(result.documents[0]), null); - } - - // We have a cursor document - if(result.documents[0].cursor != null - && typeof result.documents[0].cursor != 'string') { - var id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if(result.documents[0].cursor.ns) { - self.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; - // If we have a firstBatch set it - if(Array.isArray(result.documents[0].cursor.firstBatch)) { - cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); - } - - // Return after processing command cursor - return callback(null, null); - } - - if(Array.isArray(result.documents[0].result)) { - cursorState.documents = result.documents[0].result; - cursorState.cursorId = Long.ZERO; - return callback(null, null); - } - } - - // Otherwise fall back to regular find path - cursorState.cursorId = result.cursorId; - cursorState.documents = result.documents; - - // Transform the results with passed in transformation method if provided - if(cursorState.transforms && typeof cursorState.transforms.query == 'function') { - cursorState.documents = cursorState.transforms.query(result); - } - - // Return callback - callback(null, null); - } - - // If we have a raw query decorate the function - if(options.raw || cmd.raw) { - queryCallback.raw = options.raw || cmd.raw; - } - - // Do we have documentsReturnedIn set on the query - if(typeof query.documentsReturnedIn == 'string') { - queryCallback.documentsReturnedIn = query.documentsReturnedIn; - } - - // Set up callback - callbacks.register(query.requestId, queryCallback); - - // Write the initial command out - connection.write(query.toBin()); -} - -// -// Handle callback (including any exceptions thrown) -var handleCallback = function(callback, err, result) { - try { - callback(err, result); - } catch(err) { - process.nextTick(function() { - throw err; - }); - } -} - - -// Internal methods -Cursor.prototype._find = function(callback) { - var self = this; - // execInitialQuery(self, self.query, self.cmd, self.options, self.cursorState, self.connection, self.logger, self.callbacks, function(err, r) { - if(self.logger.isDebug()) { - self.logger.debug(f("issue initial query [%s] with flags [%s]" - , JSON.stringify(self.cmd) - , JSON.stringify(self.query))); - } - - var queryCallback = function(err, result) { - if(err) return callback(err); - - if(result.queryFailure) { - return callback(MongoError.create(result.documents[0]), null); - } - - // Check if we have a command cursor - if(Array.isArray(result.documents) && result.documents.length == 1 - && (!self.cmd.find || (self.cmd.find && self.cmd.virtual == false)) - && (result.documents[0].cursor != 'string' - || result.documents[0]['$err'] - || result.documents[0]['errmsg'] - || Array.isArray(result.documents[0].result)) - ) { - - // We have a an error document return the error - if(result.documents[0]['$err'] - || result.documents[0]['errmsg']) { - return callback(MongoError.create(result.documents[0]), null); - } - - // We have a cursor document - if(result.documents[0].cursor != null - && typeof result.documents[0].cursor != 'string') { - var id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if(result.documents[0].cursor.ns) { - self.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - self.cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; - // If we have a firstBatch set it - if(Array.isArray(result.documents[0].cursor.firstBatch)) { - self.cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); - } - - // Return after processing command cursor - return callback(null, null); - } - - if(Array.isArray(result.documents[0].result)) { - self.cursorState.documents = result.documents[0].result; - self.cursorState.cursorId = Long.ZERO; - return callback(null, null); - } - } - - // Otherwise fall back to regular find path - self.cursorState.cursorId = result.cursorId; - self.cursorState.documents = result.documents; - - // Transform the results with passed in transformation method if provided - if(self.cursorState.transforms && typeof self.cursorState.transforms.query == 'function') { - self.cursorState.documents = self.cursorState.transforms.query(result); - } - - // Return callback - callback(null, null); - } - // console.log("------------------------- 2") - - // If we have a raw query decorate the function - if(self.options.raw || self.cmd.raw) { - queryCallback.raw = self.options.raw || self.cmd.raw; - } - // console.log("------------------------- 3") - - // Do we have documentsReturnedIn set on the query - if(typeof self.query.documentsReturnedIn == 'string') { - queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; - } - // console.log("------------------------- 4") - - // Set up callback - self.callbacks.register(self.query.requestId, queryCallback); - - // Write the initial command out - self.connection.write(self.query.toBin()); -// console.log("------------------------- 5") -} - -Cursor.prototype._getmore = function(callback) { - if(this.logger.isDebug()) this.logger.debug(f("schedule getMore call for query [%s]", JSON.stringify(this.query))) - // Determine if it's a raw query - var raw = this.options.raw || this.cmd.raw; - // We have a wire protocol handler - this.server.wireProtocolHandler.getMore(this.bson, this.ns, this.cursorState, this.cursorState.batchSize, raw, this.connection, this.callbacks, this.options, callback); -} - -Cursor.prototype._killcursor = function(callback) { - // Set cursor to dead - this.cursorState.dead = true; - this.cursorState.killed = true; - // Remove documents - this.cursorState.documents = []; - - // If no cursor id just return - if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) { - if(callback) callback(null, null); - return; - } - - // Execute command - this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState.cursorId, this.connection, this.callbacks, callback); -} - -/** - * Clone the cursor - * @method - * @return {Cursor} - */ -Cursor.prototype.clone = function() { - return this.topology.cursor(this.ns, this.cmd, this.options); -} - -/** - * Checks if the cursor is dead - * @method - * @return {boolean} A boolean signifying if the cursor is dead or not - */ -Cursor.prototype.isDead = function() { - return this.cursorState.dead == true; -} - -/** - * Checks if the cursor was killed by the application - * @method - * @return {boolean} A boolean signifying if the cursor was killed by the application - */ -Cursor.prototype.isKilled = function() { - return this.cursorState.killed == true; -} - -/** - * Checks if the cursor notified it's caller about it's death - * @method - * @return {boolean} A boolean signifying if the cursor notified the callback - */ -Cursor.prototype.isNotified = function() { - return this.cursorState.notified == true; -} - -/** - * Returns current buffered documents length - * @method - * @return {number} The number of items in the buffered documents - */ -Cursor.prototype.bufferedCount = function() { - return this.cursorState.documents.length - this.cursorState.cursorIndex; -} - -/** - * Returns current buffered documents - * @method - * @return {Array} An array of buffered documents - */ -Cursor.prototype.readBufferedDocuments = function(number) { - var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; - var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; - var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length); - - // Transform the doc with passed in transformation method if provided - if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') { - // Transform all the elements - for(var i = 0; i < elements.length; i++) { - elements[i] = this.cursorState.transforms.doc(elements[i]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if(this.cursorState.limit > 0 && (this.cursorState.currentLimit + elements.length) > this.cursorState.limit) { - elements = elements.slice(0, (this.cursorState.limit - this.cursorState.currentLimit)); - this.kill(); - } - - // Adjust current limit - this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; - this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; - - // Return elements - return elements; -} - -/** - * Kill the cursor - * @method - * @param {resultCallback} callback A callback function - */ -Cursor.prototype.kill = function(callback) { - this._killcursor(callback); -} - -/** - * Resets the cursor - * @method - * @return {null} - */ -Cursor.prototype.rewind = function() { - if(this.cursorState.init) { - if(!this.cursorState.dead) { - this.kill(); - } - - this.cursorState.currentLimit = 0; - this.cursorState.init = false; - this.cursorState.dead = false; - this.cursorState.killed = false; - this.cursorState.notified = false; - this.cursorState.documents = []; - this.cursorState.cursorId = null; - this.cursorState.cursorIndex = 0; - } -} - -/** - * Validate if the connection is dead and return error - */ -var isConnectionDead = function(self, callback) { - if(self.connection - && !self.connection.isConnected()) { - self.cursorState.notified = true; - self.cursorState.killed = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - callback(MongoError.create(f('connection to host %s:%s was destroyed', self.connection.host, self.connection.port))) - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead but was not explicitly killed by user - */ -var isCursorDeadButNotkilled = function(self, callback) { - // Cursor is dead but not marked killed, return null - if(self.cursorState.dead && !self.cursorState.killed) { - self.cursorState.notified = true; - self.cursorState.killed = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead and was killed by user - */ -var isCursorDeadAndKilled = function(self, callback) { - if(self.cursorState.dead && self.cursorState.killed) { - handleCallback(callback, MongoError.create("cursor is dead")); - return true; - } - - return false; -} - -/** - * Validate if the cursor was killed by the user - */ -var isCursorKilled = function(self, callback) { - if(self.cursorState.killed) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); - return true; - } - - return false; -} - -/** - * Mark cursor as being dead and notified - */ -var setCursorDeadAndNotified = function(self, callback) { - self.cursorState.dead = true; - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); -} - -/** - * Mark cursor as being notified - */ -var setCursorNotified = function(self, callback) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); -} - -var nextFunction = function(self, callback) { - // We have notified about it - if(self.cursorState.notified) { - return callback(new Error('cursor is exhausted')); - } - - // Cursor is killed return null - if(isCursorKilled(self, callback)) return; - - // Cursor is dead but not marked killed, return null - if(isCursorDeadButNotkilled(self, callback)) return; - - // We have a dead and killed cursor, attempting to call next should error - if(isCursorDeadAndKilled(self, callback)) return; - - // We have just started the cursor - if(!self.cursorState.init) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.topology.isConnected(self.options) && self.disconnectHandler != null) { - return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); - } - - try { - // Get a server - self.server = self.topology.getServer(self.options); - // Get a connection - self.connection = self.server.getConnection(); - // Get the callbacks - self.callbacks = self.server.getCallbacks(); - } catch(err) { - return callback(err); - } - - // Set as init - self.cursorState.init = true; - - try { - // Get the right wire protocol command - self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options); - } catch(err) { - return callback(err); - } - } - - // Process exhaust messages - var processExhaustMessages = function(err, result) { - if(err) { - self.cursorState.dead = true; - self.callbacks.unregister(self.query.requestId); - return callback(err); - } - - // Concatenate all the documents - self.cursorState.documents = self.cursorState.documents.concat(result.documents); - - // If we have no documents left - if(Long.ZERO.equals(result.cursorId)) { - self.cursorState.cursorId = Long.ZERO; - self.callbacks.unregister(self.query.requestId); - return nextFunction(self, callback); - } - - // Set up next listener - self.callbacks.register(result.requestId, processExhaustMessages) - - // Initial result - if(self.cursorState.cursorId == null) { - self.cursorState.cursorId = result.cursorId; - nextFunction(self, callback); - } - } - - // If we have exhaust - if(self.cmd.exhaust && self.cursorState.cursorId == null) { - // Handle all the exhaust responses - self.callbacks.register(self.query.requestId, processExhaustMessages); - // Write the initial command out - return self.connection.write(self.query.toBin()); - } else if(self.cmd.exhaust && self.cursorState.cursorIndex < self.cursorState.documents.length) { - return handleCallback(callback, null, self.cursorState.documents[self.cursorState.cursorIndex++]); - } else if(self.cmd.exhaust && Long.ZERO.equals(self.cursorState.cursorId)) { - self.callbacks.unregister(self.query.requestId); - return setCursorNotified(self, callback); - } else if(self.cmd.exhaust) { - return setTimeout(function() { - if(Long.ZERO.equals(self.cursorState.cursorId)) return; - nextFunction(self, callback); - }, 1); - } - - // If we don't have a cursorId execute the first query - if(self.cursorState.cursorId == null) { - // Check if connection is dead and return if not possible to - // execute the query against the db - if(isConnectionDead(self, callback)) return; - - // Check if topology is destroyed - if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); - - // query, cmd, options, cursorState, callback - self._find(function(err, r) { - if(err) return handleCallback(callback, err, null); - if(self.cursorState.documents.length == 0 && !self.cmd.tailable && !self.cmd.awaitData) { - return setCursorNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } else if(self.cursorState.cursorIndex == self.cursorState.documents.length - && !Long.ZERO.equals(self.cursorState.cursorId)) { - // Ensure an empty cursor state - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - // Check if topology is destroyed - if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); - - // Check if connection is dead and return if not possible to - // execute a getmore on this connection - if(isConnectionDead(self, callback)) return; - - // Execute the next get more - self._getmore(function(err, doc) { - if(err) return handleCallback(callback, err); - if(self.cursorState.documents.length == 0 - && Long.ZERO.equals(self.cursorState.cursorId)) { - self.cursorState.dead = true; - } - - // Tailable cursor getMore result, notify owner about it - // No attempt is made here to retry, this is left to the user of the - // core module to handle to keep core simple - if(self.cursorState.documents.length == 0 && self.cmd.tailable) { - return handleCallback(callback, MongoError.create({ - message: "No more documents in tailed cursor" - , tailable: self.cmd.tailable - , awaitData: self.cmd.awaitData - })); - } - - if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - return setCursorDeadAndNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if(self.cursorState.documents.length == self.cursorState.cursorIndex - && self.cmd.tailable) { - return handleCallback(callback, MongoError.create({ - message: "No more documents in tailed cursor" - , tailable: self.cmd.tailable - , awaitData: self.cmd.awaitData - })); - } else if(self.cursorState.documents.length == self.cursorState.cursorIndex - && Long.ZERO.equals(self.cursorState.cursorId)) { - setCursorDeadAndNotified(self, callback); - } else { - if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } - - // Increment the current cursor limit - self.cursorState.currentLimit += 1; - - // Get the document - var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; - - // Transform the doc with passed in transformation method if provided - if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') { - doc = self.cursorState.transforms.doc(doc); - } - - // Return the document - handleCallback(callback, null, doc); - } -} - -/** - * Retrieve the next document from the cursor - * @method - * @param {resultCallback} callback A callback function - */ -Cursor.prototype.next = function(callback) { - nextFunction(this, callback); -} - -module.exports = Cursor; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js deleted file mode 100644 index 4e17ef3..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; - -/** - * Creates a new MongoError - * @class - * @augments Error - * @param {string} message The error message - * @return {MongoError} A MongoError instance - */ -function MongoError(message) { - this.name = 'MongoError'; - this.message = message; - Error.captureStackTrace(this, MongoError); -} - -/** - * Creates a new MongoError object - * @method - * @param {object} options The error options - * @return {MongoError} A MongoError instance - */ -MongoError.create = function(options) { - var err = null; - - if(options instanceof Error) { - err = new MongoError(options.message); - err.stack = options.stack; - } else if(typeof options == 'string') { - err = new MongoError(options); - } else { - err = new MongoError(options.message || options.errmsg || options.$err || "n/a"); - // Other options - for(var name in options) { - err[name] = options[name]; - } - } - - return err; -} - -// Extend JavaScript error -MongoError.prototype = new Error; - -module.exports = MongoError; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js deleted file mode 100644 index dcceda4..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js +++ /dev/null @@ -1,59 +0,0 @@ -var fs = require('fs'); - -/* Note: because this plugin uses process.on('uncaughtException'), only one - * of these can exist at any given time. This plugin and anything else that - * uses process.on('uncaughtException') will conflict. */ -exports.attachToRunner = function(runner, outputFile) { - var smokeOutput = { results : [] }; - var runningTests = {}; - - var integraPlugin = { - beforeTest: function(test, callback) { - test.startTime = Date.now(); - runningTests[test.name] = test; - callback(); - }, - afterTest: function(test, callback) { - smokeOutput.results.push({ - status: test.status, - start: test.startTime, - end: Date.now(), - test_file: test.name, - exit_code: 0, - url: "" - }); - delete runningTests[test.name]; - callback(); - }, - beforeExit: function(obj, callback) { - fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { - callback(); - }); - } - }; - - // In case of exception, make sure we write file - process.on('uncaughtException', function(err) { - // Mark all currently running tests as failed - for (var testName in runningTests) { - smokeOutput.results.push({ - status: "fail", - start: runningTests[testName].startTime, - end: Date.now(), - test_file: testName, - exit_code: 0, - url: "" - }); - } - - // write file - fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); - - // Standard NodeJS uncaught exception handler - console.error(err.stack); - process.exit(1); - }); - - runner.plugin(integraPlugin); - return integraPlugin; -}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js deleted file mode 100644 index ff7bf1b..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; - -var setProperty = require('../connection/utils').setProperty - , getProperty = require('../connection/utils').getProperty - , getSingleProperty = require('../connection/utils').getSingleProperty; - -/** - * Creates a new CommandResult instance - * @class - * @param {object} result CommandResult object - * @param {Connection} connection A connection instance associated with this result - * @return {CommandResult} A cursor instance - */ -var CommandResult = function(result, connection) { - this.result = result; - this.connection = connection; -} - -/** - * Convert CommandResult to JSON - * @method - * @return {object} - */ -CommandResult.prototype.toJSON = function() { - return this.result; -} - -/** - * Convert CommandResult to String representation - * @method - * @return {string} - */ -CommandResult.prototype.toString = function() { - return JSON.stringify(this.toJSON()); -} - -module.exports = CommandResult; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js deleted file mode 100644 index c54514a..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js +++ /dev/null @@ -1,1000 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , b = require('bson') - , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain - , EventEmitter = require('events').EventEmitter - , BasicCursor = require('../cursor') - , BSON = require('bson').native().BSON - , BasicCursor = require('../cursor') - , Server = require('./server') - , Logger = require('../connection/logger') - , ReadPreference = require('./read_preference') - , Session = require('./session') - , MongoError = require('../error'); - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * @example - * var Mongos = require('mongodb-core').Mongos - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new Mongos([{host: 'localhost', port: 30000}]); - * // Wait for the connection event - * server.on('connect', function(server) { - * server.destroy(); - * }); - * - * // Start connecting - * server.connect(); - */ - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -// All bson types -var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; -// BSON parser -var bsonInstance = null; - -// Instance id -var mongosId = 0; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for(var name in options) { - opts[name] = options[name]; - } - return opts; -} - -var State = function(readPreferenceStrategies) { - // Internal state - this.s = { - connectedServers: [] - , disconnectedServers: [] - , readPreferenceStrategies: readPreferenceStrategies - } -} - -// -// A Mongos connected -State.prototype.connected = function(server) { - // Locate in disconnected servers and remove - this.s.disconnectedServers = this.s.disconnectedServers.filter(function(s) { - return !s.equals(server); - }); - - var found = false; - // Check if the server exists - this.s.connectedServers.forEach(function(s) { - if(s.equals(server)) found = true; - }); - - // Add to disconnected list if it does not already exist - if(!found) this.s.connectedServers.push(server); -} - -// -// A Mongos disconnected -State.prototype.disconnected = function(server) { - // Locate in disconnected servers and remove - this.s.connectedServers = this.s.connectedServers.filter(function(s) { - return !s.equals(server); - }); - - var found = false; - // Check if the server exists - this.s.disconnectedServers.forEach(function(s) { - if(s.equals(server)) found = true; - }); - - // Add to disconnected list if it does not already exist - if(!found) this.s.disconnectedServers.push(server); -} - -// -// Return the list of disconnected servers -State.prototype.disconnectedServers = function() { - return this.s.disconnectedServers.slice(0); -} - -// -// Get connectedServers -State.prototype.connectedServers = function() { - return this.s.connectedServers.slice(0) -} - -// -// Get all servers -State.prototype.getAll = function() { - return this.s.connectedServers.slice(0).concat(this.s.disconnectedServers); -} - -// -// Get all connections -State.prototype.getAllConnections = function() { - var connections = []; - this.s.connectedServers.forEach(function(e) { - connections = connections.concat(e.connections()); - }); - return connections; -} - -// -// Destroy the state -State.prototype.destroy = function() { - // Destroy any connected servers - while(this.s.connectedServers.length > 0) { - var server = this.s.connectedServers.shift(); - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Server destroy - server.destroy(); - // Add to list of disconnected servers - this.s.disconnectedServers.push(server); - } -} - -// -// Are we connected -State.prototype.isConnected = function() { - return this.s.connectedServers.length > 0; -} - -// -// Pick a server -State.prototype.pickServer = function(readPreference) { - readPreference = readPreference || ReadPreference.primary; - - // Do we have a custom readPreference strategy, use it - if(this.s.readPreferenceStrategies != null && this.s.readPreferenceStrategies[readPreference] != null) { - return this.s.readPreferenceStrategies[readPreference].pickServer(connectedServers, readPreference); - } - - // No valid connections - if(this.s.connectedServers.length == 0) throw new MongoError("no mongos proxy available"); - // Pick first one - return this.s.connectedServers[0]; -} - -/** - * Creates a new Mongos instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {number} [options.reconnectTries=30] Reconnect retries for HA if no servers available - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @return {Mongos} A cursor instance - * @fires Mongos#connect - * @fires Mongos#joined - * @fires Mongos#left - */ -var Mongos = function(seedlist, options) { - var self = this; - options = options || {}; - - // Add event listener - EventEmitter.call(this); - - // Validate seedlist - if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); - // Validate list - if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); - // Validate entries - seedlist.forEach(function(e) { - if(typeof e.host != 'string' || typeof e.port != 'number') - throw new MongoError("seedlist entry must contain a host and port"); - }); - - // BSON Parser, ensure we have a single instance - bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; - // Pick the right bson parser - var bson = options.bson ? options.bson : bsonInstance; - // Add bson parser to options - options.bson = bson; - - // The Mongos state - this.s = { - // Seed list for sharding passed in - seedlist: seedlist - // Passed in options - , options: options - // Logger - , logger: Logger('Mongos', options) - // Reconnect tries - , reconnectTries: options.reconnectTries || 30 - // Ha interval - , haInterval: options.haInterval || 5000 - // Have omitted fullsetup - , fullsetup: false - // Cursor factory - , Cursor: options.cursorFactory || BasicCursor - // Current credentials used for auth - , credentials: [] - // BSON Parser - , bsonInstance: bsonInstance - , bson: bson - // Default state - , state: DISCONNECTED - // Swallow or emit errors - , emitError: typeof options.emitError == 'boolean' ? options.emitError : false - // Contains any alternate strategies for picking - , readPreferenceStrategies: {} - // Auth providers - , authProviders: {} - // Unique instance id - , id: mongosId++ - // Authentication in progress - , authInProgress: false - // Servers added while auth in progress - , authInProgressServers: [] - // Current retries left - , retriesLeft: options.reconnectTries || 30 - // Do we have a not connected handler - , disconnectHandler: options.disconnectHandler - } - - // Set up the connection timeout for the options - options.connectionTimeout = options.connectionTimeout || 1000; - - // Create a new state for the mongos - this.s.mongosState = new State(this.s.readPreferenceStrategies); - - // BSON property (find a server and pass it along) - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - var servers = self.s.mongosState.getAll(); - return servers.length > 0 ? servers[0].bson : null; - } - }); - - Object.defineProperty(this, 'id', { - enumerable:true, get: function() { return self.s.id; } - }); - - Object.defineProperty(this, 'type', { - enumerable:true, get: function() { return 'mongos'; } - }); - - Object.defineProperty(this, 'haInterval', { - enumerable:true, get: function() { return self.s.haInterval; } - }); - - Object.defineProperty(this, 'state', { - enumerable:true, get: function() { return self.s.mongosState; } - }); -} - -inherits(Mongos, EventEmitter); - -/** - * Name of BSON parser currently used - * @method - * @return {string} - */ -Mongos.prototype.parserType = function() { - if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) - return 'c++'; - return 'js'; -} - -/** - * Execute a command - * @method - * @param {string} type Type of BSON parser to use (c++ or js) - */ -Mongos.prototype.setBSONParserType = function(type) { - var nBSON = null; - - if(type == 'c++') { - nBSON = require('bson').native().BSON; - } else if(type == 'js') { - nBSON = require('bson').pure().BSON; - } else { - throw new MongoError(f("% parser not supported", type)); - } - - this.s.options.bson = new nBSON(bsonTypes); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Mongos.prototype.lastIsMaster = function() { - var connectedServers = this.s.mongosState.connectedServers(); - if(connectedServers.length > 0) return connectedServers[0].lastIsMaster(); - return null; -} - -/** - * Initiate server connect - * @method - */ -Mongos.prototype.connect = function(_options) { - var self = this; - // Start replicaset inquiry process - setTimeout(mongosInquirer(self, self.s), self.s.haInterval); - // Additional options - if(_options) for(var name in _options) self.s.options[name] = _options[name]; - // For all entries in the seedlist build a server instance - self.s.seedlist.forEach(function(e) { - // Clone options - var opts = cloneOptions(self.s.options); - // Add host and port - opts.host = e.host; - opts.port = e.port; - opts.reconnect = false; - opts.readPreferenceStrategies = self.s.readPreferenceStrategies; - // Share the auth store - opts.authProviders = self.s.authProviders; - // Don't emit errors - opts.emitError = true; - // Create a new Server - self.s.mongosState.disconnected(new Server(opts)); - }); - - // Get the disconnected servers - var servers = self.s.mongosState.disconnectedServers(); - - // Attempt to connect to all the servers - while(servers.length > 0) { - // Get the server - var server = servers.shift(); - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { - server.removeAllListeners(e); - }); - - // Set up the event handlers - server.once('error', errorHandlerTemp(self, self.s, server)); - server.once('close', errorHandlerTemp(self, self.s, server)); - server.once('timeout', errorHandlerTemp(self, self.s, server)); - server.once('parseError', errorHandlerTemp(self, self.s, server)); - server.once('connect', connectHandler(self, self.s, 'connect')); - - if(self.s.logger.isInfo()) self.s.logger.info(f('connecting to server %s', server.name)); - // Attempt to connect - server.connect(); - } -} - -/** - * Destroy the server connection - * @method - */ -Mongos.prototype.destroy = function(emitClose) { - this.s.state = DESTROYED; - // Emit close - if(emitClose && self.listeners('close').length > 0) self.emit('close', self); - // Destroy the state - this.s.mongosState.destroy(); -} - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Mongos.prototype.isConnected = function() { - return this.s.mongosState.isConnected(); -} - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Mongos.prototype.isDestroyed = function() { - return this.s.state == DESTROYED; -} - -// -// Operations -// - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.insert = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - executeWriteOperation(this.s, 'insert', ns, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.update = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - executeWriteOperation(this.s, 'update', ns, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.remove = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - executeWriteOperation(this.s, 'remove', ns, ops, options, callback); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.command = function(ns, cmd, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - var server = null; - // Ensure we have no options - options = options || {}; - - // We need to execute the command on all servers - if(options.onAll) { - var servers = self.s.mongosState.getAll(); - var count = servers.length; - var cmdErr = null; - - for(var i = 0; i < servers.length; i++) { - servers[i].command(ns, cmd, options, function(err, r) { - count = count - 1; - // Finished executing command - if(count == 0) { - // Was it a logout command clear any credentials - if(cmd.logout) clearCredentials(state, ns); - // Return the error - callback(err, r); - } - }); - } - - return; - } - - - try { - // Get a primary - server = self.s.mongosState.pickServer(options.writeConcern ? ReadPreference.primary : options.readPreference); - } catch(err) { - return callback(err); - } - - // No server returned we had an error - if(server == null) return callback(new MongoError("no mongos found")); - server.command(ns, cmd, options, function(err, r) { - // Was it a logout command clear any credentials - if(cmd.logout) clearCredentials(self.s, ns); - callback(err, r); - }); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.cursor = function(ns, cmd, cursorOptions) { - cursorOptions = cursorOptions || {}; - var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; - return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.auth = function(mechanism, db) { - var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - var callback = args.pop(); - - // If we don't have the mechanism fail - if(this.s.authProviders[mechanism] == null && mechanism != 'default') - throw new MongoError(f("auth provider %s does not exist", mechanism)); - - // Authenticate against all the servers - var servers = this.s.mongosState.connectedServers().slice(0); - var count = servers.length; - // Correct authentication - var authenticated = true; - var authErr = null; - // Set auth in progress - this.s.authInProgress = true; - - // Authenticate against all servers - while(servers.length > 0) { - var server = servers.shift(); - // Arguments without a callback - var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); - // Create arguments - var finalArguments = argsWithoutCallback.concat([function(err, r) { - count = count - 1; - if(err) authErr = err; - if(!r) authenticated = false; - - // We are done - if(count == 0) { - // We have more servers that are not authenticated, let's authenticate - if(self.s.authInProgressServers.length > 0) { - self.s.authInProgressServers = []; - return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); - } - - // Auth is done - self.s.authInProgress = false; - // Add successful credentials - if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); - // Return the auth error - if(authErr) return callback(authErr, false); - // Successfully authenticated session - callback(null, new Session({}, self)); - } - }]); - - // Execute the auth - server.auth.apply(server, finalArguments); - } -} - -// -// Plugin methods -// - -/** - * Add custom read preference strategy - * @method - * @param {string} name Name of the read preference strategy - * @param {object} strategy Strategy object instance - */ -Mongos.prototype.addReadPreferenceStrategy = function(name, strategy) { - if(this.s.readPreferenceStrategies == null) this.s.readPreferenceStrategies = {}; - this.s.readPreferenceStrategies[name] = strategy; -} - -/** - * Add custom authentication mechanism - * @method - * @param {string} name Name of the authentication mechanism - * @param {object} provider Authentication object instance - */ -Mongos.prototype.addAuthProvider = function(name, provider) { - this.s.authProviders[name] = provider; -} - -/** - * Get connection - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Connection} - */ -Mongos.prototype.getConnection = function(options) { - // Ensure we have no options - options = options || {}; - // Pick the right server based on readPreference - var server = this.s.mongosState.pickServer(options.readPreference); - if(server == null) return null; - // Return connection - return server.getConnection(); -} - -/** - * Get server - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Server} - */ -Mongos.prototype.getServer = function(options) { - // Ensure we have no options - options = options || {}; - // Pick the right server based on readPreference - return this.s.mongosState.pickServer(options.readPreference); -} - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Mongos.prototype.connections = function() { - return this.s.mongosState.getAllConnections(); -} - -// -// Inquires about state changes -// -var mongosInquirer = function(self, state) { - return function() { - if(state.state == DESTROYED) return - if(state.state == CONNECTED) state.retriesLeft = state.reconnectTries; - - // If we have a disconnected site - if(state.state == DISCONNECTED && state.retriesLeft == 0) { - self.destroy(); - return self.emit('error', new MongoError(f('failed to reconnect after %s', state.reconnectTries))); - } else if(state == DISCONNECTED) { - state.retriesLeft = state.retriesLeft - 1; - } - - // If we have a primary and a disconnect handler, execute - // buffered operations - if(state.mongosState.isConnected() && state.disconnectHandler) { - state.disconnectHandler.execute(); - } - - // Log the information - if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess running')); - - // Let's query any disconnected proxies - var disconnectedServers = state.mongosState.disconnectedServers(); - if(disconnectedServers.length == 0) return setTimeout(mongosInquirer(self, state), state.haInterval); - - // Count of connections waiting to be connected - var connectionCount = disconnectedServers.length; - if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess found %d disconnected proxies', connectionCount)); - - // Let's attempt to reconnect - while(disconnectedServers.length > 0) { - var server = disconnectedServers.shift(); - if(state.logger.isDebug()) state.logger.debug(f('attempting to connect to server %s', server.name)); - - // Remove any listeners - ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { - server.removeAllListeners(e); - }); - - // Set up the event handlers - server.once('error', errorHandlerTemp(self, state, server)); - server.once('close', errorHandlerTemp(self, state, server)); - server.once('timeout', errorHandlerTemp(self, state, server)); - server.once('connect', connectHandler(self, state, 'ha')); - // Start connect - server.connect(); - } - - // Let's keep monitoring but wait for possible timeout to happen - return setTimeout(mongosInquirer(self, state), state.options.connectionTimeout + state.haInterval); - } -} - -// -// Error handler for initial connect -var errorHandlerTemp = function(self, state, server) { - return function(err, server) { - // Log the information - if(state.logger.isInfo()) state.logger.info(f('server %s disconnected with error %s', server.name, JSON.stringify(err))); - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Signal disconnect of server - state.mongosState.disconnected(server); - } -} - -// -// Handlers -var errorHandler = function(self, state) { - return function(err, server) { - if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', server.name, JSON.stringify(err))); - state.mongosState.disconnected(server); - // No more servers left emit close - if(state.mongosState.connectedServers().length == 0) { - state.state = DISCONNECTED; - } - - // Signal server left - self.emit('left', 'mongos', server); - if(state.emitError) self.emit('error', err, server); - } -} - -var timeoutHandler = function(self, state) { - return function(err, server) { - if(state.logger.isInfo()) state.logger.info(f('server %s timed out', server.name)); - state.mongosState.disconnected(server); - - // No more servers emit close event if no entries left - if(state.mongosState.connectedServers().length == 0) { - state.state = DISCONNECTED; - } - - // Signal server left - self.emit('left', 'mongos', server); - } -} - -var closeHandler = function(self, state) { - return function(err, server) { - if(state.logger.isInfo()) state.logger.info(f('server %s closed', server.name)); - state.mongosState.disconnected(server); - - // No more servers left emit close - if(state.mongosState.connectedServers().length == 0) { - state.state = DISCONNECTED; - } - - // Signal server left - self.emit('left', 'mongos', server); - } -} - -// Connect handler -var connectHandler = function(self, state, e) { - return function(server) { - if(state.logger.isInfo()) state.logger.info(f('connected to %s', server.name)); - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { - server.removeAllListeners(e); - }); - - // finish processing the server - var processNewServer = function(_server) { - // Add the server handling code - if(_server.isConnected()) { - _server.once('error', errorHandler(self, state)); - _server.once('close', closeHandler(self, state)); - _server.once('timeout', timeoutHandler(self, state)); - _server.once('parseError', timeoutHandler(self, state)); - } - - // Emit joined event - self.emit('joined', 'mongos', _server); - - // Add to list connected servers - state.mongosState.connected(_server); - - // Do we have a reconnect event - if('ha' == e && state.mongosState.connectedServers().length == 1) { - self.emit('reconnect', _server); - } - - // Full setup - if(state.mongosState.disconnectedServers().length == 0 && - state.mongosState.connectedServers().length > 0 && - !state.fullsetup) { - state.fullsetup = true; - self.emit('fullsetup'); - } - - // all connected - if(state.mongosState.disconnectedServers().length == 0 && - state.mongosState.connectedServers().length == state.seedlist.length && - !state.all) { - state.all = true; - self.emit('all'); - } - - // Set connected - if(state.state == DISCONNECTED) { - state.state = CONNECTED; - self.emit('connect', self); - } - } - - // Is there an authentication process ongoing - if(state.authInProgress) { - state.authInProgressServers.push(server); - } - - // No credentials just process server - if(state.credentials.length == 0) return processNewServer(server); - - // Do we have credentials, let's apply them all - var count = state.credentials.length; - // Apply the credentials - for(var i = 0; i < state.credentials.length; i++) { - server.auth.apply(server, state.credentials[i].concat([function(err, r) { - count = count - 1; - if(count == 0) processNewServer(server); - }])); - } - } -} - -// -// Add server to the list if it does not exist -var addToListIfNotExist = function(list, server) { - var found = false; - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Check if the server already exists - for(var i = 0; i < list.length; i++) { - if(list[i].equals(server)) found = true; - } - - if(!found) { - list.push(server); - } -} - -// Add the new credential for a db, removing the old -// credential from the cache -var addCredentials = function(state, db, argsWithoutCallback) { - // Remove any credentials for the db - clearCredentials(state, db + ".dummy"); - // Add new credentials to list - state.credentials.push(argsWithoutCallback); -} - -// Clear out credentials for a namespace -var clearCredentials = function(state, ns) { - var db = ns.split('.')[0]; - var filteredCredentials = []; - - // Filter out all credentials for the db the user is logging out off - for(var i = 0; i < state.credentials.length; i++) { - if(state.credentials[i][1] != db) filteredCredentials.push(state.credentials[i]); - } - - // Set new list of credentials - state.credentials = filteredCredentials; -} - -var processReadPreference = function(cmd, options) { - options = options || {} - // No read preference specified - if(options.readPreference == null) return cmd; -} - -// -// Execute write operation -var executeWriteOperation = function(state, op, ns, ops, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - var server = null; - // Ensure we have no options - options = options || {}; - try { - // Get a primary - server = state.mongosState.pickServer(); - } catch(err) { - return callback(err); - } - - // No server returned we had an error - if(server == null) return callback(new MongoError("no mongos found")); - // Execute the command - server[op](ns, ops, options, callback); -} - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * A server member left the mongos list - * - * @event Mongos#left - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos list - * - * @event Mongos#joined - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that joined - */ - -module.exports = Mongos; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js deleted file mode 100644 index 913ca1b..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js +++ /dev/null @@ -1,106 +0,0 @@ -"use strict"; - -var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; - -/** - * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * - * @example - * var ReplSet = require('mongodb-core').ReplSet - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); - * // Wait for the connection event - * server.on('connect', function(server) { - * var cursor = server.cursor('db.test' - * , {find: 'db.test', query: {}} - * , {readPreference: new ReadPreference('secondary')}); - * cursor.next(function(err, doc) { - * server.destroy(); - * }); - * }); - * - * // Start connecting - * server.connect(); - */ - -/** - * Creates a new Pool instance - * @class - * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @param {object} tags The tags object - * @param {object} [options] Additional read preference options - * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @property {object} tags The tags object - * @property {object} options Additional read preference options - * @return {ReadPreference} - */ -var ReadPreference = function(preference, tags, options) { - this.preference = preference; - this.tags = tags; - this.options = options; -} - -/** - * This needs slaveOk bit set - * @method - * @return {boolean} - */ -ReadPreference.prototype.slaveOk = function() { - return needSlaveOk.indexOf(this.preference) != -1; -} - -/** - * Are the two read preference equal - * @method - * @return {boolean} - */ -ReadPreference.prototype.equals = function(readPreference) { - return readPreference.preference == this.preference; -} - -/** - * Return JSON representation - * @method - * @return {Object} - */ -ReadPreference.prototype.toJSON = function() { - var readPreference = {mode: this.preference}; - if(Array.isArray(this.tags)) readPreference.tags = this.tags; - return readPreference; -} - -/** - * Primary read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.primary = new ReadPreference('primary'); -/** - * Primary Preferred read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); -/** - * Secondary read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.secondary = new ReadPreference('secondary'); -/** - * Secondary Preferred read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); -/** - * Nearest read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.nearest = new ReadPreference('nearest'); - -module.exports = ReadPreference; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js deleted file mode 100644 index 011c8fe..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js +++ /dev/null @@ -1,1333 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , b = require('bson') - , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain - , debugOptions = require('../connection/utils').debugOptions - , EventEmitter = require('events').EventEmitter - , Server = require('./server') - , ReadPreference = require('./read_preference') - , MongoError = require('../error') - , Ping = require('./strategies/ping') - , Session = require('./session') - , BasicCursor = require('../cursor') - , BSON = require('bson').native().BSON - , State = require('./replset_state') - , Logger = require('../connection/logger'); - -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connecctions. - * - * @example - * var ReplSet = require('mongodb-core').ReplSet - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); - * // Wait for the connection event - * server.on('connect', function(server) { - * server.destroy(); - * }); - * - * // Start connecting - * server.connect(); - */ - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -// -// ReplSet instance id -var replSetId = 1; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for(var name in options) { - opts[name] = options[name]; - } - return opts; -} - -// All bson types -var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; -// BSON parser -var bsonInstance = null; - -/** - * Creates a new Replset instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {boolean} options.setName The Replicaset set name - * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) - * @return {ReplSet} A cursor instance - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - */ -var ReplSet = function(seedlist, options) { - var self = this; - options = options || {}; - - // Validate seedlist - if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); - // Validate list - if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); - // Validate entries - seedlist.forEach(function(e) { - if(typeof e.host != 'string' || typeof e.port != 'number') - throw new MongoError("seedlist entry must contain a host and port"); - }); - - // Add event listener - EventEmitter.call(this); - - // Set the bson instance - bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; - - // Internal state hash for the object - this.s = { - options: options - // Logger instance - , logger: Logger('ReplSet', options) - // Uniquely identify the replicaset instance - , id: replSetId++ - // Index - , index: 0 - // Ha Index - , haId: 0 - // Current credentials used for auth - , credentials: [] - // Factory overrides - , Cursor: options.cursorFactory || BasicCursor - // BSON Parser, ensure we have a single instance - , bsonInstance: bsonInstance - // Pick the right bson parser - , bson: options.bson ? options.bson : bsonInstance - // Special replicaset options - , secondaryOnlyConnectionAllowed: typeof options.secondaryOnlyConnectionAllowed == 'boolean' - ? options.secondaryOnlyConnectionAllowed : false - , haInterval: options.haInterval || 10000 - // Are we running in debug mode - , debug: typeof options.debug == 'boolean' ? options.debug : false - // The replicaset name - , setName: options.setName - // Swallow or emit errors - , emitError: typeof options.emitError == 'boolean' ? options.emitError : false - // Grouping tag used for debugging purposes - , tag: options.tag - // Do we have a not connected handler - , disconnectHandler: options.disconnectHandler - // Currently connecting servers - , connectingServers: {} - // Contains any alternate strategies for picking - , readPreferenceStrategies: {} - // Auth providers - , authProviders: {} - // All the servers - , disconnectedServers: [] - // Initial connection servers - , initialConnectionServers: [] - // High availability process running - , highAvailabilityProcessRunning: false - // Full setup - , fullsetup: false - // All servers accounted for (used for testing) - , all: false - // Seedlist - , seedlist: seedlist - // Authentication in progress - , authInProgress: false - // Servers added while auth in progress - , authInProgressServers: [] - // Minimum heartbeat frequency used if we detect a server close - , minHeartbeatFrequencyMS: 500 - } - - // Add bson parser to options - options.bson = this.s.bson; - // Set up the connection timeout for the options - options.connectionTimeout = options.connectionTimeout || 10000; - - // Replicaset state - var replState = new State(this, { - id: this.s.id, setName: this.s.setName - , connectingServers: this.s.connectingServers - , secondaryOnlyConnectionAllowed: this.s.secondaryOnlyConnectionAllowed - }); - - // Add Replicaset state to our internal state - this.s.replState = replState; - - // BSON property (find a server and pass it along) - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - var servers = self.s.replState.getAll(); - return servers.length > 0 ? servers[0].bson : null; - } - }); - - Object.defineProperty(this, 'id', { - enumerable:true, get: function() { return self.s.id; } - }); - - Object.defineProperty(this, 'haInterval', { - enumerable:true, get: function() { return self.s.haInterval; } - }); - - Object.defineProperty(this, 'state', { - enumerable:true, get: function() { return self.s.replState; } - }); - - // - // Debug options - if(self.s.debug) { - // Add access to the read Preference Strategies - Object.defineProperty(this, 'readPreferenceStrategies', { - enumerable: true, get: function() { return self.s.readPreferenceStrategies; } - }); - } - - Object.defineProperty(this, 'type', { - enumerable:true, get: function() { return 'replset'; } - }); - - // Add the ping strategy for nearest - this.addReadPreferenceStrategy('nearest', new Ping(options)); -} - -inherits(ReplSet, EventEmitter); - -// -// Plugin methods -// - -/** - * Add custom read preference strategy - * @method - * @param {string} name Name of the read preference strategy - * @param {object} strategy Strategy object instance - */ -ReplSet.prototype.addReadPreferenceStrategy = function(name, func) { - this.s.readPreferenceStrategies[name] = func; -} - -/** - * Add custom authentication mechanism - * @method - * @param {string} name Name of the authentication mechanism - * @param {object} provider Authentication object instance - */ -ReplSet.prototype.addAuthProvider = function(name, provider) { - if(this.s.authProviders == null) this.s.authProviders = {}; - this.s.authProviders[name] = provider; -} - -/** - * Name of BSON parser currently used - * @method - * @return {string} - */ -ReplSet.prototype.parserType = function() { - if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) - return 'c++'; - return 'js'; -} - -/** - * Execute a command - * @method - * @param {string} type Type of BSON parser to use (c++ or js) - */ -ReplSet.prototype.setBSONParserType = function(type) { - var nBSON = null; - - if(type == 'c++') { - nBSON = require('bson').native().BSON; - } else if(type == 'js') { - nBSON = require('bson').pure().BSON; - } else { - throw new MongoError(f("% parser not supported", type)); - } - - this.s.options.bson = new nBSON(bsonTypes); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -ReplSet.prototype.lastIsMaster = function() { - return this.s.replState.lastIsMaster(); -} - -/** - * Get connection - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Connection} - */ -ReplSet.prototype.getConnection = function(options) { - // Ensure we have no options - options = options || {}; - // Pick the right server based on readPreference - var server = pickServer(this, this.s, options.readPreference); - if(server == null) return null; - // Return connection - return server.getConnection(); -} - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -ReplSet.prototype.connections = function() { - return this.s.replState.getAllConnections(); -} - -/** - * Get server - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Server} - */ -ReplSet.prototype.getServer = function(options) { - // Ensure we have no options - options = options || {}; - // Pick the right server based on readPreference - return pickServer(this, this.s, options.readPreference); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { - cursorOptions = cursorOptions || {}; - var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; - return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); -} - -// -// Execute write operation -var executeWriteOperation = function(self, op, ns, ops, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - var server = null; - // Ensure we have no options - options = options || {}; - // Get a primary - try { - server = pickServer(self, self.s, ReadPreference.primary); - if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); - } catch(err) { - return callback(err); - } - - // No server returned we had an error - if(server == null) return callback(new MongoError("no server found")); - - // Handler - var handler = function(err, r) { - // We have a no master error, immediately refresh the view of the replicaset - if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); - // Return the result - callback(err, r); - } - - // Add operationId if existing - if(callback.operationId) handler.operationId = callback.operationId; - // Execute the command - server[op](ns, ops, options, handler); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.command = function(ns, cmd, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - var server = null; - var self = this; - // Ensure we have no options - options = options || {}; - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected(options) && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // We need to execute the command on all servers - if(options.onAll) { - var servers = this.s.replState.getAll(); - var count = servers.length; - var cmdErr = null; - - for(var i = 0; i < servers.length; i++) { - servers[i].command(ns, cmd, options, function(err, r) { - count = count - 1; - // Finished executing command - if(count == 0) { - // Was it a logout command clear any credentials - if(cmd.logout) clearCredentials(self.s, ns); - // We have a no master error, immediately refresh the view of the replicaset - if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); - // Return the error - callback(err, r); - } - }); - } - - return; - } - - // Pick the right server based on readPreference - try { - server = pickServer(self, self.s, options.writeConcern ? ReadPreference.primary : options.readPreference); - if(self.s.debug) self.emit('pickedServer', options.writeConcern ? ReadPreference.primary : options.readPreference, server); - } catch(err) { - return callback(err); - } - - // No server returned we had an error - if(server == null) return callback(new MongoError("no server found")); - // Execute the command - server.command(ns, cmd, options, function(err, r) { - // Was it a logout command clear any credentials - if(cmd.logout) clearCredentials(self.s, ns); - // We have a no master error, immediately refresh the view of the replicaset - if(notMasterError(r) || notMasterError(err)) { - replicasetInquirer(self, self.s, true)(); - } - // Return the error - callback(err, r); - }); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.remove = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - executeWriteOperation(this, 'remove', ns, ops, options, callback); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.insert = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - executeWriteOperation(this, 'insert', ns, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.update = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - executeWriteOperation(this, 'update', ns, ops, options, callback); -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.auth = function(mechanism, db) { - var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - var callback = args.pop(); - - // If we don't have the mechanism fail - if(this.s.authProviders[mechanism] == null && mechanism != 'default') - throw new MongoError(f("auth provider %s does not exist", mechanism)); - - // Authenticate against all the servers - var servers = this.s.replState.getAll().slice(0); - var count = servers.length; - // Correct authentication - var authenticated = true; - var authErr = null; - // Set auth in progress - this.s.authInProgress = true; - - // Authenticate against all servers - while(servers.length > 0) { - var server = servers.shift(); - - // Arguments without a callback - var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); - // Create arguments - var finalArguments = argsWithoutCallback.concat([function(err, r) { - count = count - 1; - if(err) authErr = err; - if(!r) authenticated = false; - - // We are done - if(count == 0) { - // We have more servers that are not authenticated, let's authenticate - if(self.s.authInProgressServers.length > 0) { - self.s.authInProgressServers = []; - return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); - } - - // Auth is done - self.s.authInProgress = false; - // Add successful credentials - if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); - // Return the auth error - if(authErr) return callback(authErr, false); - // Successfully authenticated session - callback(null, new Session({}, self)); - } - }]); - - // Execute the auth - server.auth.apply(server, finalArguments); - } -} - -ReplSet.prototype.state = function() { - return this.s.replState.state; -} - -/** - * Ensure single socket connections to arbiters and hidden servers - * @method - */ -var handleIsmaster = function(self) { - return function(ismaster, _server) { - if(ismaster.arbiterOnly) { - _server.s.options.size = 1; - } else if(ismaster.hidden) { - _server.s.options.size = 1; - } - } -} - -/** - * Initiate server connect - * @method - */ -ReplSet.prototype.connect = function(_options) { - var self = this; - // Start replicaset inquiry process - setTimeout(replicasetInquirer(this, this.s, false), this.s.haInterval); - // Additional options - if(_options) for(var name in _options) this.s.options[name] = _options[name]; - - // Set the state as connecting - this.s.replState.state = CONNECTING; - - // No fullsetup reached - this.s.fullsetup = false; - - // For all entries in the seedlist build a server instance - this.s.seedlist.forEach(function(e) { - // Clone options - var opts = cloneOptions(self.s.options); - // Add host and port - opts.host = e.host; - opts.port = e.port; - opts.reconnect = false; - opts.readPreferenceStrategies = self.s.readPreferenceStrategies; - opts.emitError = true; - if(self.s.tag) opts.tag = self.s.tag; - // Share the auth store - opts.authProviders = self.s.authProviders; - // Create a new Server - var server = new Server(opts); - // Handle the ismaster - server.on('ismaster', handleIsmaster(self)); - // Add to list of disconnected servers - self.s.disconnectedServers.push(server); - // Add to list of inflight Connections - self.s.initialConnectionServers.push(server); - }); - - // Attempt to connect to all the servers - while(this.s.disconnectedServers.length > 0) { - // Get the server - var server = this.s.disconnectedServers.shift(); - - // Set up the event handlers - server.once('error', errorHandlerTemp(this, this.s, 'error')); - server.once('close', errorHandlerTemp(this, this.s, 'close')); - server.once('timeout', errorHandlerTemp(this, this.s, 'timeout')); - server.once('connect', connectHandler(this, this.s)); - - // Attempt to connect - server.connect(); - } -} - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - // If we specified a read preference check if we are connected to something - // than can satisfy this - if(options.readPreference - && options.readPreference.equals(ReadPreference.secondary)) - return this.s.replState.isSecondaryConnected(); - - if(options.readPreference - && options.readPreference.equals(ReadPreference.primary)) - return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); - - if(this.s.secondaryOnlyConnectionAllowed - && this.s.replState.isSecondaryConnected()) return true; - return this.s.replState.isPrimaryConnected(); -} - -/** - * Figure out if the replicaset instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -ReplSet.prototype.isDestroyed = function() { - return this.s.replState.state == DESTROYED; -} - -/** - * Destroy the server connection - * @method - */ -ReplSet.prototype.destroy = function(emitClose) { - var self = this; - if(this.s.logger.isInfo()) this.s.logger.info(f('[%s] destroyed', this.s.id)); - this.s.replState.state = DESTROYED; - - // Emit close - if(emitClose && self.listeners('close').length > 0) self.emit('close', self); - - // Destroy state - this.s.replState.destroy(); - - // Clear out any listeners - var events = ['timeout', 'error', 'close', 'joined', 'left']; - events.forEach(function(e) { - self.removeAllListeners(e); - }); -} - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -// -// Inquires about state changes -// - -// Add the new credential for a db, removing the old -// credential from the cache -var addCredentials = function(s, db, argsWithoutCallback) { - // Remove any credentials for the db - clearCredentials(s, db + ".dummy"); - // Add new credentials to list - s.credentials.push(argsWithoutCallback); -} - -// Clear out credentials for a namespace -var clearCredentials = function(s, ns) { - var db = ns.split('.')[0]; - var filteredCredentials = []; - - // Filter out all credentials for the db the user is logging out off - for(var i = 0; i < s.credentials.length; i++) { - if(s.credentials[i][1] != db) filteredCredentials.push(s.credentials[i]); - } - - // Set new list of credentials - s.credentials = filteredCredentials; -} - -// -// Filter serves by tags -var filterByTags = function(readPreference, servers) { - if(readPreference.tags == null) return servers; - var filteredServers = []; - var tags = readPreference.tags; - - // Iterate over all the servers - for(var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - // Did we find the a matching server - var found = true; - // Check if the server is valid - for(var name in tags) { - if(serverTag[name] != tags[name]) found = false; - } - - // Add to candidate list - if(found) filteredServers.push(servers[i]); - } - - // Returned filtered servers - return filteredServers; -} - -// -// Pick a server based on readPreference -var pickServer = function(self, s, readPreference) { - // If no read Preference set to primary by default - readPreference = readPreference || ReadPreference.primary; - - // Do we have a custom readPreference strategy, use it - if(s.readPreferenceStrategies != null && s.readPreferenceStrategies[readPreference.preference] != null) { - if(s.readPreferenceStrategies[readPreference.preference] == null) throw new MongoError(f("cannot locate read preference handler for %s", readPreference.preference)); - var server = s.readPreferenceStrategies[readPreference.preference].pickServer(s.replState, readPreference); - if(s.debug) self.emit('pickedServer', readPreference, server); - return server; - } - - // Filter out any hidden secondaries - var secondaries = s.replState.secondaries.filter(function(server) { - if(server.lastIsMaster().hidden) return false; - return true; - }); - - // Check if we can satisfy and of the basic read Preferences - if(readPreference.equals(ReadPreference.secondary) - && secondaries.length == 0) - throw new MongoError("no secondary server available"); - - if(readPreference.equals(ReadPreference.secondaryPreferred) - && secondaries.length == 0 - && s.replState.primary == null) - throw new MongoError("no secondary or primary server available"); - - if(readPreference.equals(ReadPreference.primary) - && s.replState.primary == null) - throw new MongoError("no primary server available"); - - // Secondary - if(readPreference.equals(ReadPreference.secondary)) { - s.index = (s.index + 1) % secondaries.length; - return secondaries[s.index]; - } - - // Secondary preferred - if(readPreference.equals(ReadPreference.secondaryPreferred)) { - if(secondaries.length > 0) { - // Apply tags if present - var servers = filterByTags(readPreference, secondaries); - // If have a matching server pick one otherwise fall through to primary - if(servers.length > 0) { - s.index = (s.index + 1) % servers.length; - return servers[s.index]; - } - } - - return s.replState.primary; - } - - // Primary preferred - if(readPreference.equals(ReadPreference.primaryPreferred)) { - if(s.replState.primary) return s.replState.primary; - - if(secondaries.length > 0) { - // Apply tags if present - var servers = filterByTags(readPreference, secondaries); - // If have a matching server pick one otherwise fall through to primary - if(servers.length > 0) { - s.index = (s.index + 1) % servers.length; - return servers[s.index]; - } - - // Throw error a we have not valid secondary or primary servers - throw new MongoError("no secondary or primary server available"); - } - } - - // Return the primary - return s.replState.primary; -} - -var replicasetInquirer = function(self, state, norepeat) { - return function() { - if(state.replState.state == DESTROYED) return - // Process already running don't rerun - if(state.highAvailabilityProcessRunning) return; - // Started processes - state.highAvailabilityProcessRunning = true; - if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring process running %s', state.id, JSON.stringify(state.replState))); - - // Unique HA id to identify the current look running - var localHaId = state.haId++; - - // Clean out any failed connection attempts - state.connectingServers = {}; - - // Controls if we are doing a single inquiry or repeating - norepeat = typeof norepeat == 'boolean' ? norepeat : false; - - // If we have a primary and a disconnect handler, execute - // buffered operations - if(state.replState.isPrimaryConnected() && state.replState.isSecondaryConnected() && state.disconnectHandler) { - state.disconnectHandler.execute(); - } - - // Emit replicasetInquirer - self.emit('ha', 'start', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - - // Let's process all the disconnected servers - while(state.disconnectedServers.length > 0) { - // Get the first disconnected server - var server = state.disconnectedServers.shift(); - if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring attempting to connect to %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); - // Set up the event handlers - server.once('error', errorHandlerTemp(self, state, 'error')); - server.once('close', errorHandlerTemp(self, state, 'close')); - server.once('timeout', errorHandlerTemp(self, state, 'timeout')); - server.once('connect', connectHandler(self, state)); - // Attempt to connect - server.connect(); - } - - // Cleanup state (removed disconnected servers) - state.replState.clean(); - - // We need to query all servers - var servers = state.replState.getAll(); - var serversLeft = servers.length; - - // If no servers and we are not destroyed keep pinging - if(servers.length == 0 && state.replState.state == CONNECTED) { - // Emit ha process end - self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - // Ended highAvailabilityProcessRunning - state.highAvailabilityProcessRunning = false; - // Restart ha process - if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); - return; - } - - // - // ismaster for Master server - var primaryIsMaster = null; - - // Kill the server connection if it hangs - var timeoutServer = function(_server) { - return setTimeout(function() { - if(_server.isConnected()) { - _server.connections()[0].connection.destroy(); - } - }, self.s.options.connectionTimeout); - } - - // - // Inspect a specific servers ismaster - var inspectServer = function(server) { - if(state.replState.state == DESTROYED) return; - // Did we get a server - if(server && server.isConnected()) { - // Get the timeout id - var timeoutId = timeoutServer(server); - // Execute ismaster - server.command('system.$cmd', {ismaster:true}, function(err, r) { - // Clear out the timeoutServer - clearTimeout(timeoutId); - // If the state was destroyed - if(state.replState.state == DESTROYED) return; - // Count down the number of servers left - serversLeft = serversLeft - 1; - // If we have an error but still outstanding server request return - if(err && serversLeft > 0) return; - // We had an error and have no more servers to inspect, schedule a new check - if(err && serversLeft == 0) { - self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - // Ended highAvailabilityProcessRunnfing - state.highAvailabilityProcessRunning = false; - // Return the replicasetInquirer - if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); - return; - } - - // Let all the read Preferences do things to the servers - var rPreferencesCount = Object.keys(state.readPreferenceStrategies).length; - - // Handle the primary - var ismaster = r.result; - if(state.logger.isDebug()) state.logger.debug(f('[%s] monitoring process ismaster %s', state.id, JSON.stringify(ismaster))); - - // Update the replicaset state - state.replState.update(ismaster, server); - - // Add any new servers - if(err == null && ismaster.ismaster && Array.isArray(ismaster.hosts)) { - // Hosts to process - var hosts = ismaster.hosts; - // Add arbiters to list of hosts if we have any - if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); - if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); - // Process all the hsots - processHosts(self, state, hosts); - } - - // No read Preferences strategies - if(rPreferencesCount == 0) { - // Don't schedule a new inquiry - if(serversLeft > 0) return; - // Emit ha process end - self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - // Ended highAvailabilityProcessRunning - state.highAvailabilityProcessRunning = false; - // Let's keep monitoring - if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); - return; - } - - // No servers left to query, execute read preference strategies - if(serversLeft == 0) { - // Go over all the read preferences - for(var name in state.readPreferenceStrategies) { - state.readPreferenceStrategies[name].ha(self, state.replState, function() { - rPreferencesCount = rPreferencesCount - 1; - - if(rPreferencesCount == 0) { - // Add any new servers in primary ismaster - if(err == null - && ismaster.ismaster - && Array.isArray(ismaster.hosts)) { - processHosts(self, state, ismaster.hosts); - } - - // Emit ha process end - self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - // Ended highAvailabilityProcessRunning - state.highAvailabilityProcessRunning = false; - // Let's keep monitoring - if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); - return; - } - }); - } - } - }); - } - } - - // Call ismaster on all servers - for(var i = 0; i < servers.length; i++) { - inspectServer(servers[i]); - } - - // If no more initial servers and new scheduled servers to connect - if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { - state.fullsetup = true; - self.emit('fullsetup', self); - } - - // If all servers are accounted for and we have not sent the all event - if(state.replState.primary != null && self.lastIsMaster() - && Array.isArray(self.lastIsMaster().hosts) && !state.all) { - var length = 1 + state.replState.secondaries.length; - // If we have all secondaries + primary - if(length == self.lastIsMaster().hosts.length + 1) { - state.all = true; - self.emit('all', self); - } - } - } -} - -// Error handler for initial connect -var errorHandlerTemp = function(self, state, event) { - return function(err, server) { - // Log the information - if(state.logger.isInfo()) state.logger.info(f('[%s] server %s disconnected', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); - // Filter out any connection servers - state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { - return server.name != _server.name; - }); - - // Connection is destroyed, ignore - if(state.replState.state == DESTROYED) return; - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Push to list of disconnected servers - addToListIfNotExist(state.disconnectedServers, server); - - // End connection operation if we have no legal replicaset state - if(state.initialConnectionServers == 0 && state.replState.state == CONNECTING) { - if((state.secondaryOnlyConnectionAllowed && !state.replState.isSecondaryConnected() && !state.replState.isPrimaryConnected()) - || (!state.secondaryOnlyConnectionAllowed && !state.replState.isPrimaryConnected())) { - if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); - - if(self.listeners('error').length > 0) - return self.emit('error', new MongoError('no valid seed servers in list')); - } - } - - // If the number of disconnected servers is equal to - // the number of seed servers we cannot connect - if(state.disconnectedServers.length == state.seedlist.length && state.replState.state == CONNECTING) { - if(state.emitError && self.listeners('error').length > 0) { - if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); - - if(self.listeners('error').length > 0) - self.emit('error', new MongoError('no valid seed servers in list')); - } - } - } -} - -// Connect handler -var connectHandler = function(self, state) { - return function(server) { - if(state.logger.isInfo()) state.logger.info(f('[%s] connected to %s', state.id, server.name)); - // Destroyed connection - if(state.replState.state == DESTROYED) { - server.destroy(false, false); - return; - } - - // Filter out any connection servers - state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { - return server.name != _server.name; - }); - - // Process the new server - var processNewServer = function() { - // Discover any additional servers - var ismaster = server.lastIsMaster(); - - var events = ['error', 'close', 'timeout', 'connect', 'message']; - // Remove any non used handlers - events.forEach(function(e) { - server.removeAllListeners(e); - }) - - // Clean up - delete state.connectingServers[server.name]; - // Update the replicaset state, destroy if not added - if(!state.replState.update(ismaster, server)) { - return server.destroy(); - } - - // Add the server handling code - if(server.isConnected()) { - server.on('error', errorHandler(self, state)); - server.on('close', closeHandler(self, state)); - server.on('timeout', timeoutHandler(self, state)); - } - - // Hosts to process - var hosts = ismaster.hosts; - // Add arbiters to list of hosts if we have any - if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); - if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); - - // Add any new servers - processHosts(self, state, hosts); - - // If have the server instance already destroy it - if(state.initialConnectionServers.length == 0 && Object.keys(state.connectingServers).length == 0 - && !state.replState.isPrimaryConnected() && !state.secondaryOnlyConnectionAllowed && state.replState.state == CONNECTING) { - if(state.logger.isInfo()) state.logger.info(f('[%s] no primary found in replicaset', state.id)); - self.emit('error', new MongoError("no primary found in replicaset")); - return self.destroy(); - } - - // If no more initial servers and new scheduled servers to connect - if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { - state.fullsetup = true; - self.emit('fullsetup', self); - } - } - - // Save up new members to be authenticated against - if(self.s.authInProgress) { - self.s.authInProgressServers.push(server); - } - - // No credentials just process server - if(state.credentials.length == 0) return processNewServer(); - // Do we have credentials, let's apply them all - var count = state.credentials.length; - // Apply the credentials - for(var i = 0; i < state.credentials.length; i++) { - server.auth.apply(server, state.credentials[i].concat([function(err, r) { - count = count - 1; - if(count == 0) processNewServer(); - }])); - } - } -} - -// -// Detect if we need to add new servers -var processHosts = function(self, state, hosts) { - if(state.replState.state == DESTROYED) return; - if(Array.isArray(hosts)) { - // Check any hosts exposed by ismaster - for(var i = 0; i < hosts.length; i++) { - // If not found we need to create a new connection - if(!state.replState.contains(hosts[i])) { - if(state.connectingServers[hosts[i]] == null && !inInitialConnectingServers(self, state, hosts[i])) { - if(state.logger.isInfo()) state.logger.info(f('[%s] scheduled server %s for connection', state.id, hosts[i])); - // Make sure we know what is trying to connect - state.connectingServers[hosts[i]] = hosts[i]; - // Connect the server - connectToServer(self, state, hosts[i].split(':')[0], parseInt(hosts[i].split(':')[1], 10)); - } - } - } - } -} - -var inInitialConnectingServers = function(self, state, address) { - for(var i = 0; i < state.initialConnectionServers.length; i++) { - if(state.initialConnectionServers[i].name == address) return true; - } - return false; -} - -// Connect to a new server -var connectToServer = function(self, state, host, port) { - var opts = cloneOptions(state.options); - opts.host = host; - opts.port = port; - opts.reconnect = false; - opts.readPreferenceStrategies = state.readPreferenceStrategies; - if(state.tag) opts.tag = state.tag; - // Share the auth store - opts.authProviders = state.authProviders; - opts.emitError = true; - // Create a new server instance - var server = new Server(opts); - // Handle the ismaster - server.on('ismaster', handleIsmaster(self)); - // Set up the event handlers - server.once('error', errorHandlerTemp(self, state, 'error')); - server.once('close', errorHandlerTemp(self, state, 'close')); - server.once('timeout', errorHandlerTemp(self, state, 'timeout')); - server.once('connect', connectHandler(self, state)); - // Attempt to connect - server.connect(); -} - -// -// Add server to the list if it does not exist -var addToListIfNotExist = function(list, server) { - var found = false; - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Check if the server already exists - for(var i = 0; i < list.length; i++) { - if(list[i].equals(server)) found = true; - } - - if(!found) { - list.push(server); - } - - return found; -} - -var errorHandler = function(self, state) { - return function(err, server) { - if(state.replState.state == DESTROYED) return; - if(state.logger.isInfo()) state.logger.info(f('[%s] server %s errored out with %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name, JSON.stringify(err))); - var found = addToListIfNotExist(state.disconnectedServers, server); - if(!found) self.emit('left', state.replState.remove(server), server); - if(found && state.emitError && self.listeners('error').length > 0) self.emit('error', err, server); - - // Fire off a detection of missing server using minHeartbeatFrequencyMS - setTimeout(function() { - replicasetInquirer(self, self.s, true)(); - }, self.s.minHeartbeatFrequencyMS); - } -} - -var timeoutHandler = function(self, state) { - return function(err, server) { - if(state.replState.state == DESTROYED) return; - if(state.logger.isInfo()) state.logger.info(f('[%s] server %s timed out', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); - var found = addToListIfNotExist(state.disconnectedServers, server); - if(!found) self.emit('left', state.replState.remove(server), server); - - // Fire off a detection of missing server using minHeartbeatFrequencyMS - setTimeout(function() { - replicasetInquirer(self, self.s, true)(); - }, self.s.minHeartbeatFrequencyMS); - } -} - -var closeHandler = function(self, state) { - return function(err, server) { - if(state.replState.state == DESTROYED) return; - if(state.logger.isInfo()) state.logger.info(f('[%s] server %s closed', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); - var found = addToListIfNotExist(state.disconnectedServers, server); - if(!found) self.emit('left', state.replState.remove(server), server); - - // Fire off a detection of missing server using minHeartbeatFrequencyMS - setTimeout(function() { - replicasetInquirer(self, self.s, true)(); - }, self.s.minHeartbeatFrequencyMS); - } -} - -// -// Validate if a non-master or recovering error -var notMasterError = function(r) { - // Get result of any - var result = r && r.result ? r.result : r; - - // Explore if we have a not master error - if(result && (result.err == 'not master' - || result.errmsg == 'not master' || (result['$err'] && result['$err'].indexOf('not master or secondary') != -1) - || (result['$err'] && result['$err'].indexOf("not master and slaveOk=false") != -1) - || result.errmsg == 'node is recovering')) { - return true; - } - - return false; -} - -module.exports = ReplSet; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js deleted file mode 100644 index 951a043..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js +++ /dev/null @@ -1,483 +0,0 @@ -"use strict"; - -var Logger = require('../connection/logger') - , f = require('util').format - , ObjectId = require('bson').ObjectId - , MongoError = require('../error'); - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -/** - * Creates a new Replicaset State object - * @class - * @property {object} primary Primary property - * @property {array} secondaries List of secondaries - * @property {array} arbiters List of arbiters - * @return {State} A cursor instance - */ -var State = function(replSet, options) { - this.replSet = replSet; - this.options = options; - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.primary = null; - // Initial state is disconnected - this.state = DISCONNECTED; - // Current electionId - this.electionId = null; - // Get a logger instance - this.logger = Logger('ReplSet', options); - // Unpacked options - this.id = options.id; - this.setName = options.setName; - this.connectingServers = options.connectingServers; - this.secondaryOnlyConnectionAllowed = options.secondaryOnlyConnectionAllowed; -} - -/** - * Is there a secondary connected - * @method - * @return {boolean} - */ -State.prototype.isSecondaryConnected = function() { - for(var i = 0; i < this.secondaries.length; i++) { - if(this.secondaries[i].isConnected()) return true; - } - - return false; -} - -/** - * Is there a primary connection - * @method - * @return {boolean} - */ -State.prototype.isPrimaryConnected = function() { - return this.primary != null && this.primary.isConnected(); -} - -/** - * Is the given address the primary - * @method - * @param {string} address Server address - * @return {boolean} - */ -State.prototype.isPrimary = function(address) { - if(this.primary == null) return false; - return this.primary && this.primary.equals(address); -} - -/** - * Is the given address a secondary - * @method - * @param {string} address Server address - * @return {boolean} - */ -State.prototype.isSecondary = function(address) { - // Check if the server is a secondary at the moment - for(var i = 0; i < this.secondaries.length; i++) { - if(this.secondaries[i].equals(address)) { - return true; - } - } - - return false; -} - -/** - * Is the given address a secondary - * @method - * @param {string} address Server address - * @return {boolean} - */ -State.prototype.isPassive = function(address) { - // Check if the server is a secondary at the moment - for(var i = 0; i < this.passives.length; i++) { - if(this.passives[i].equals(address)) { - return true; - } - } - - return false; -} - -/** - * Does the replicaset contain this server - * @method - * @param {string} address Server address - * @return {boolean} - */ -State.prototype.contains = function(address) { - if(this.primary && this.primary.equals(address)) return true; - for(var i = 0; i < this.secondaries.length; i++) { - if(this.secondaries[i].equals(address)) return true; - } - - for(var i = 0; i < this.arbiters.length; i++) { - if(this.arbiters[i].equals(address)) return true; - } - - for(var i = 0; i < this.passives.length; i++) { - if(this.passives[i].equals(address)) return true; - } - - return false; -} - -/** - * Clean out all dead connections - * @method - */ -State.prototype.clean = function() { - if(this.primary != null && !this.primary.isConnected()) { - this.primary = null; - } - - // Filter out disconnected servers - this.secondaries = this.secondaries.filter(function(s) { - return s.isConnected(); - }); - - // Filter out disconnected servers - this.arbiters = this.arbiters.filter(function(s) { - return s.isConnected(); - }); -} - -/** - * Destroy state - * @method - */ -State.prototype.destroy = function() { - this.state = DESTROYED; - if(this.primary) this.primary.destroy(); - this.secondaries.forEach(function(s) { - s.destroy(); - }); -} - -/** - * Remove server from state - * @method - * @param {Server} Server to remove - * @return {string} Returns type of server removed (primary|secondary) - */ -State.prototype.remove = function(server) { - if(this.primary && this.primary.equals(server)) { - this.primary = null; - } - - var length = this.arbiters.length; - // Filter out the server from the arbiters - this.arbiters = this.arbiters.filter(function(s) { - return !s.equals(server); - }); - if(this.arbiters.length < length) return 'arbiter'; - - var length = this.passives.length; - // Filter out the server from the passives - this.passives = this.passives.filter(function(s) { - return !s.equals(server); - }); - - // We have removed a passive - if(this.passives.length < length) { - // Ensure we removed it from the list of secondaries as well if it exists - this.secondaries = this.secondaries.filter(function(s) { - return !s.equals(server); - }); - } - - // Filter out the server from the secondaries - this.secondaries = this.secondaries.filter(function(s) { - return !s.equals(server); - }); - - // Get the isMaster - var isMaster = server.lastIsMaster(); - // Return primary if the server was primary - if(isMaster.ismaster) return 'primary'; - if(isMaster.secondary) return 'secondary'; - if(isMaster.passive) return 'passive'; - return 'arbiter'; -} - -/** - * Get the server by name - * @method - * @param {string} address Server address - * @return {Server} - */ -State.prototype.get = function(server) { - var found = false; - // All servers to search - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - // Locate the server - for(var i = 0; i < servers.length; i++) { - if(servers[i].equals(server)) { - return servers[i]; - } - } -} - -/** - * Get all the servers in the set - * @method - * @return {array} - */ -State.prototype.getAll = function() { - var servers = []; - if(this.primary) servers.push(this.primary); - return servers.concat(this.secondaries); -} - -/** - * All raw connections - * @method - * @return {array} - */ -State.prototype.getAllConnections = function() { - var connections = []; - if(this.primary) connections = connections.concat(this.primary.connections()); - this.secondaries.forEach(function(s) { - connections = connections.concat(s.connections()); - }) - - return connections; -} - -/** - * Return JSON object - * @method - * @return {object} - */ -State.prototype.toJSON = function() { - return { - primary: this.primary ? this.primary.lastIsMaster().me : null - , secondaries: this.secondaries.map(function(s) { - return s.lastIsMaster().me - }) - } -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -State.prototype.lastIsMaster = function() { - if(this.primary) return this.primary.lastIsMaster(); - if(this.secondaries.length > 0) return this.secondaries[0].lastIsMaster(); - return {}; -} - -/** - * Promote server to primary - * @method - * @param {Server} server Server we wish to promote - */ -State.prototype.promotePrimary = function(server) { - var currentServer = this.get(server); - // Server does not exist in the state, add it as new primary - if(currentServer == null) { - this.primary = server; - return; - } - - // We found a server, make it primary and remove it from the secondaries - // Remove the server first - this.remove(currentServer); - // Set as primary - this.primary = currentServer; -} - -var add = function(list, server) { - // Check if the server is a secondary at the moment - for(var i = 0; i < list.length; i++) { - if(list[i].equals(server)) return false; - } - - list.push(server); - return true; -} - -/** - * Add server to list of secondaries - * @method - * @param {Server} server Server we wish to add - */ -State.prototype.addSecondary = function(server) { - return add(this.secondaries, server); -} - -/** - * Add server to list of arbiters - * @method - * @param {Server} server Server we wish to add - */ -State.prototype.addArbiter = function(server) { - return add(this.arbiters, server); -} - -/** - * Add server to list of passives - * @method - * @param {Server} server Server we wish to add - */ -State.prototype.addPassive = function(server) { - return add(this.passives, server); -} - -var compareObjectIds = function(id1, id2) { - var a = new Buffer(id1.toHexString(), 'hex'); - var b = new Buffer(id2.toHexString(), 'hex'); - - if(a === b) { - return 0; - } - - if(typeof Buffer.compare === 'function') { - return Buffer.compare(a, b); - } - - var x = a.length; - var y = b.length; - var len = Math.min(x, y); - - for (var i = 0; i < len; i++) { - if (a[i] !== b[i]) { - break; - } - } - - if (i !== len) { - x = a[i]; - y = b[i]; - } - - return x < y ? -1 : y < x ? 1 : 0; -} - -/** - * Update the state given a specific ismaster result - * @method - * @param {object} ismaster IsMaster result - * @param {Server} server IsMaster Server source - */ -State.prototype.update = function(ismaster, server) { - var self = this; - // Not in a known connection valid state - if(!ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { - // Remove the state - var result = self.remove(server); - if(self.state == CONNECTED) { - if(self.logger.isInfo()) self.logger.info(f('[%s] removing %s from set', self.id, ismaster.me)); - self.replSet.emit('left', self.remove(server), server); - } - - return false; - } - - // Set the setName if it's not set from the first server - if(self.setName == null && ismaster.setName) { - if(self.logger.isInfo()) self.logger.info(f('[%s] setting setName to %s', self.id, ismaster.setName)); - self.setName = ismaster.setName; - } - - // Check if the replicaset name matches the provided one - if(ismaster.setName && self.setName != ismaster.setName) { - if(self.logger.isError()) self.logger.error(f('[%s] server in replset %s is not part of the specified setName %s', self.id, ismaster.setName, self.setName)); - self.remove(server); - self.replSet.emit('error', new MongoError("provided setName for Replicaset Connection does not match setName found in server seedlist")); - return false; - } - - // Log information - if(self.logger.isInfo()) self.logger.info(f('[%s] updating replicaset state %s', self.id, JSON.stringify(this))); - - // It's a master set it - if(ismaster.ismaster && self.setName == ismaster.setName && !self.isPrimary(ismaster.me)) { - // Check if the electionId is not null - if(ismaster.electionId instanceof ObjectId && self.electionId instanceof ObjectId) { - if(compareObjectIds(self.electionId, ismaster.electionId) == -1) { - self.electionId = ismaster.electionId; - } else if(compareObjectIds(self.electionId, ismaster.electionId) == 0) { - self.electionId = ismaster.electionId; - } else { - return false; - } - } - - // Initial electionId - if(ismaster.electionId instanceof ObjectId && self.electionId == null) { - self.electionId = ismaster.electionId; - } - - // Promote to primary - self.promotePrimary(server); - // Log change of primary - if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to primary', self.id, ismaster.me)); - // Emit primary - self.replSet.emit('joined', 'primary', this.primary); - - // We are connected - if(self.state == CONNECTING) { - self.state = CONNECTED; - self.replSet.emit('connect', self.replSet); - } else { - self.state = CONNECTED; - self.replSet.emit('reconnect', server); - } - } else if(!ismaster.ismaster && self.setName == ismaster.setName - && ismaster.arbiterOnly) { - if(self.addArbiter(server)) { - if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to arbiter', self.id, ismaster.me)); - self.replSet.emit('joined', 'arbiter', server); - return true; - }; - - return false; - } else if(!ismaster.ismaster && self.setName == ismaster.setName - && ismaster.secondary && ismaster.passive) { - if(self.addPassive(server) && self.addSecondary(server)) { - if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to passive', self.id, ismaster.me)); - self.replSet.emit('joined', 'passive', server); - - // If we have secondaryOnlyConnectionAllowed and just a passive it's - // still a valid connection - if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { - self.state = CONNECTED; - self.replSet.emit('connect', self.replSet); - } - - return true; - }; - - return false; - } else if(!ismaster.ismaster && self.setName == ismaster.setName - && ismaster.secondary) { - if(self.addSecondary(server)) { - if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to secondary', self.id, ismaster.me)); - self.replSet.emit('joined', 'secondary', server); - - if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { - self.state = CONNECTED; - self.replSet.emit('connect', self.replSet); - } - - return true; - }; - - return false; - } - - // Return update applied - return true; -} - -module.exports = State; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js deleted file mode 100644 index 0fae9ea..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js +++ /dev/null @@ -1,1230 +0,0 @@ - "use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain - , EventEmitter = require('events').EventEmitter - , Pool = require('../connection/pool') - , b = require('bson') - , Query = require('../connection/commands').Query - , MongoError = require('../error') - , ReadPreference = require('./read_preference') - , BasicCursor = require('../cursor') - , CommandResult = require('./command_result') - , getSingleProperty = require('../connection/utils').getSingleProperty - , getProperty = require('../connection/utils').getProperty - , debugOptions = require('../connection/utils').debugOptions - , BSON = require('bson').native().BSON - , PreTwoSixWireProtocolSupport = require('../wireprotocol/2_4_support') - , TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support') - , ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support') - , Session = require('./session') - , Logger = require('../connection/logger') - , MongoCR = require('../auth/mongocr') - , X509 = require('../auth/x509') - , Plain = require('../auth/plain') - , GSSAPI = require('../auth/gssapi') - , SSPI = require('../auth/sspi') - , ScramSHA1 = require('../auth/scram'); - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * @example - * var Server = require('mongodb-core').Server - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new Server({host: 'localhost', port: 27017}); - * // Wait for the connection event - * server.on('connect', function(server) { - * server.destroy(); - * }); - * - * // Start connecting - * server.connect(); - */ - -// All bson types -var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; -// BSON parser -var bsonInstance = null; -// Server instance id -var serverId = 0; -// Callbacks instance id -var callbackId = 0; - -// Single store for all callbacks -var Callbacks = function() { - // EventEmitter.call(this); - var self = this; - // Callbacks - this.callbacks = {}; - // Set the callbacks id - this.id = callbackId++; - // Set the type to server - this.type = 'server'; -} - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for(var name in options) { - opts[name] = options[name]; - } - return opts; -} - -// -// Flush all callbacks -Callbacks.prototype.flush = function(err) { - for(var id in this.callbacks) { - if(!isNaN(parseInt(id, 10))) { - var callback = this.callbacks[id]; - delete this.callbacks[id]; - callback(err, null); - } - } -} - -Callbacks.prototype.emit = function(id, err, value) { - var callback = this.callbacks[id]; - delete this.callbacks[id]; - callback(err, value); -} - -Callbacks.prototype.raw = function(id) { - if(this.callbacks[id] == null) return false; - return this.callbacks[id].raw == true ? true : false -} - -Callbacks.prototype.documentsReturnedIn = function(id) { - if(this.callbacks[id] == null) return false; - return typeof this.callbacks[id].documentsReturnedIn == 'string' ? this.callbacks[id].documentsReturnedIn : null; -} - -Callbacks.prototype.unregister = function(id) { - delete this.callbacks[id]; -} - -Callbacks.prototype.register = function(id, callback) { - this.callbacks[id] = bindToCurrentDomain(callback); -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) return callback; - return domain.bind(callback); -} - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -// Supports server -var supportsServer = function(_s) { - return _s.ismaster && typeof _s.ismaster.minWireVersion == 'number'; -} - -// -// createWireProtocolHandler -var createWireProtocolHandler = function(result) { - // 3.2 wire protocol handler - if(result && result.maxWireVersion >= 4) { - return new ThreeTwoWireProtocolSupport(new TwoSixWireProtocolSupport()); - } - - // 2.6 wire protocol handler - if(result && result.maxWireVersion >= 2) { - return new TwoSixWireProtocolSupport(); - } - - // 2.4 or earlier wire protocol handler - return new PreTwoSixWireProtocolSupport(); -} - -// -// Reconnect server -var reconnectServer = function(self, state) { - // If the current reconnect retries is 0 stop attempting to reconnect - if(state.currentReconnectRetry == 0) { - return self.destroy(true, true); - } - - // Adjust the number of retries - state.currentReconnectRetry = state.currentReconnectRetry - 1; - - // Set status to connecting - state.state = CONNECTING; - // Create a new Pool - state.pool = new Pool(state.options); - // error handler - var reconnectErrorHandler = function(err) { - state.state = DISCONNECTED; - // Destroy the pool - state.pool.destroy(); - // Adjust the number of retries - state.currentReconnectRetry = state.currentReconnectRetry - 1; - // No more retries - if(state.currentReconnectRetry <= 0) { - self.state = DESTROYED; - self.emit('error', f('failed to connect to %s:%s after %s retries', state.options.host, state.options.port, state.reconnectTries)); - } else { - setTimeout(function() { - reconnectServer(self, state); - }, state.reconnectInterval); - } - } - - // - // Attempt to connect - state.pool.once('connect', function() { - // Reset retries - state.currentReconnectRetry = state.reconnectTries; - - // Remove any non used handlers - var events = ['error', 'close', 'timeout', 'parseError']; - events.forEach(function(e) { - state.pool.removeAllListeners(e); - }); - - // Set connected state - state.state = CONNECTED; - - // Add proper handlers - state.pool.once('error', reconnectErrorHandler); - state.pool.once('close', closeHandler(self, state)); - state.pool.once('timeout', timeoutHandler(self, state)); - state.pool.once('parseError', fatalErrorHandler(self, state)); - - // We need to ensure we have re-authenticated - var keys = Object.keys(state.authProviders); - if(keys.length == 0) return self.emit('reconnect', self); - - // Execute all providers - var count = keys.length; - // Iterate over keys - for(var i = 0; i < keys.length; i++) { - state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { - count = count - 1; - // We are done, emit reconnect event - if(count == 0) { - return self.emit('reconnect', self); - } - }); - } - }); - - // - // Handle connection failure - state.pool.once('error', errorHandler(self, state)); - state.pool.once('close', errorHandler(self, state)); - state.pool.once('timeout', errorHandler(self, state)); - state.pool.once('parseError', errorHandler(self, state)); - - // Connect pool - state.pool.connect(); -} - -// -// Handlers -var messageHandler = function(self, state) { - return function(response, connection) { - try { - // Parse the message - response.parse({raw: state.callbacks.raw(response.responseTo), documentsReturnedIn: state.callbacks.documentsReturnedIn(response.responseTo)}); - if(state.logger.isDebug()) state.logger.debug(f('message [%s] received from %s', response.raw.toString('hex'), self.name)); - state.callbacks.emit(response.responseTo, null, response); - } catch (err) { - state.callbacks.flush(new MongoError(err)); - self.destroy(); - } - } -} - -var errorHandler = function(self, state) { - return function(err, connection) { - if(state.state == DISCONNECTED || state.state == DESTROYED) return; - // Set disconnected state - state.state = DISCONNECTED; - if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); - if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); - // Flush out all the callbacks - if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); - // Destroy all connections - self.destroy(); - // Emit error event - if(state.emitError && self.listeners('error').length > 0) self.emit('error', err, self); - // If we specified the driver to reconnect perform it - if(state.reconnect) setTimeout(function() { - // state.currentReconnectRetry = state.reconnectTries, - reconnectServer(self, state) - }, state.reconnectInterval); - } -} - -var fatalErrorHandler = function(self, state) { - return function(err, connection) { - if(state.state == DISCONNECTED || state.state == DESTROYED) return; - // Set disconnected state - state.state = DISCONNECTED; - - if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); - if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); - // Flush out all the callbacks - if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); - // Emit error event - if(self.listeners('error').length > 0) self.emit('error', err, self); - // If we specified the driver to reconnect perform it - if(state.reconnect) setTimeout(function() { - // state.currentReconnectRetry = state.reconnectTries, - reconnectServer(self, state) - }, state.reconnectInterval); - // Destroy all connections - self.destroy(); - } -} - -var timeoutHandler = function(self, state) { - return function(err, connection) { - if(state.state == DISCONNECTED || state.state == DESTROYED) return; - // Set disconnected state - state.state = DISCONNECTED; - - if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'timeout', [self]); - if(state.logger.isInfo()) state.logger.info(f('server %s timed out', self.name)); - // Flush out all the callbacks - if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s timed out", self.name))); - // Emit error event - self.emit('timeout', err, self); - // If we specified the driver to reconnect perform it - if(state.reconnect) setTimeout(function() { - // state.currentReconnectRetry = state.reconnectTries, - reconnectServer(self, state) - }, state.reconnectInterval); - // Destroy all connections - self.destroy(); - } -} - -var closeHandler = function(self, state) { - return function(err, connection) { - if(state.state == DISCONNECTED || state.state == DESTROYED) return; - // Set disconnected state - state.state = DISCONNECTED; - - if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'close', [self]); - if(state.logger.isInfo()) state.logger.info(f('server %s closed', self.name)); - // Flush out all the callbacks - if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); - // Emit error event - self.emit('close', err, self); - // If we specified the driver to reconnect perform it - if(state.reconnect) setTimeout(function() { - // state.currentReconnectRetry = state.reconnectTries, - reconnectServer(self, state) - }, state.reconnectInterval); - // Destroy all connections - self.destroy(); - } -} - -var connectHandler = function(self, state) { - // Apply all stored authentications - var applyAuthentications = function(callback) { - // We need to ensure we have re-authenticated - var keys = Object.keys(state.authProviders); - if(keys.length == 0) return callback(null, null); - - // Execute all providers - var count = keys.length; - // Iterate over keys - for(var i = 0; i < keys.length; i++) { - state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { - count = count - 1; - // We are done, emit reconnect event - if(count == 0) { - return callback(null, null); - } - }); - } - } - - return function(connection) { - // Apply any applyAuthentications - applyAuthentications(function() { - - // Execute an ismaster - self.command('system.$cmd', {ismaster:true}, function(err, r) { - if(err) { - state.state = DISCONNECTED; - return self.emit('close', err, self); - } - - // Set the current ismaster - if(!err) { - state.ismaster = r.result; - } - - // Emit the ismaster - self.emit('ismaster', r.result, self); - - // Determine the wire protocol handler - state.wireProtocolHandler = createWireProtocolHandler(state.ismaster); - - // Set the wireProtocolHandler - state.options.wireProtocolHandler = state.wireProtocolHandler; - - // Log the ismaster if available - if(state.logger.isInfo()) state.logger.info(f('server %s connected with ismaster [%s]', self.name, JSON.stringify(r.result))); - - // Validate if we it's a server we can connect to - if(!supportsServer(state) && state.wireProtocolHandler == null) { - state.state = DISCONNECTED - return self.emit('error', new MongoError("non supported server version"), self); - } - - // Set the details - if(state.ismaster && state.ismaster.me) state.serverDetails.name = state.ismaster.me; - - // No read preference strategies just emit connect - if(state.readPreferenceStrategies == null) { - state.state = CONNECTED; - return self.emit('connect', self); - } - - // Signal connect to all readPreferences - notifyStrategies(self, self.s, 'connect', [self], function(err, result) { - state.state = CONNECTED; - return self.emit('connect', self); - }); - }); - }); - } -} - -var slaveOk = function(r) { - if(r) return r.slaveOk() - return false; -} - -// -// Execute readPreference Strategies -var notifyStrategies = function(self, state, op, params, callback) { - if(typeof callback != 'function') { - // Notify query start to any read Preference strategies - for(var name in state.readPreferenceStrategies) { - if(state.readPreferenceStrategies[name][op]) { - var strat = state.readPreferenceStrategies[name]; - strat[op].apply(strat, params); - } - } - // Finish up - return; - } - - // Execute the async callbacks - var nPreferences = Object.keys(state.readPreferenceStrategies).length; - if(nPreferences == 0) return callback(null, null); - for(var name in state.readPreferenceStrategies) { - if(state.readPreferenceStrategies[name][op]) { - var strat = state.readPreferenceStrategies[name]; - // Add a callback to params - var cParams = params.slice(0); - cParams.push(function(err, r) { - nPreferences = nPreferences - 1; - if(nPreferences == 0) { - callback(null, null); - } - }) - // Execute the readPreference - strat[op].apply(strat, cParams); - } - } -} - -var debugFields = ['reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host' - , 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout' - , 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs']; - -/** - * Creates a new Server instance - * @class - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @return {Server} A cursor instance - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - */ -var Server = function(options) { - var self = this; - - // Add event listener - EventEmitter.call(this); - - // BSON Parser, ensure we have a single instance - if(bsonInstance == null) { - bsonInstance = new BSON(bsonTypes); - } - - // Reconnect retries - var reconnectTries = options.reconnectTries || 30; - - // Keeps all the internal state of the server - this.s = { - // Options - options: options - // Contains all the callbacks - , callbacks: new Callbacks() - // Logger - , logger: Logger('Server', options) - // Server state - , state: DISCONNECTED - // Reconnect option - , reconnect: typeof options.reconnect == 'boolean' ? options.reconnect : true - , reconnectTries: reconnectTries - , reconnectInterval: options.reconnectInterval || 1000 - // Swallow or emit errors - , emitError: typeof options.emitError == 'boolean' ? options.emitError : false - // Current state - , currentReconnectRetry: reconnectTries - // Contains the ismaster - , ismaster: null - // Contains any alternate strategies for picking - , readPreferenceStrategies: options.readPreferenceStrategies - // Auth providers - , authProviders: options.authProviders || {} - // Server instance id - , id: serverId++ - // Grouping tag used for debugging purposes - , tag: options.tag - // Do we have a not connected handler - , disconnectHandler: options.disconnectHandler - // wireProtocolHandler methods - , wireProtocolHandler: options.wireProtocolHandler || new PreTwoSixWireProtocolSupport() - // Factory overrides - , Cursor: options.cursorFactory || BasicCursor - // BSON Parser, ensure we have a single instance - , bsonInstance: bsonInstance - // Pick the right bson parser - , bson: options.bson ? options.bson : bsonInstance - // Internal connection pool - , pool: null - // Server details - , serverDetails: { - host: options.host - , port: options.port - , name: options.port ? f("%s:%s", options.host, options.port) : options.host - } - } - - // Reference state - var s = this.s; - - // Add bson parser to options - options.bson = s.bson; - - // Set error properties - getProperty(this, 'name', 'name', s.serverDetails, {}); - getProperty(this, 'bson', 'bson', s.options, {}); - getProperty(this, 'wireProtocolHandler', 'wireProtocolHandler', s.options, {}); - getSingleProperty(this, 'id', s.id); - - // Add auth providers - this.addAuthProvider('mongocr', new MongoCR()); - this.addAuthProvider('x509', new X509()); - this.addAuthProvider('plain', new Plain()); - this.addAuthProvider('gssapi', new GSSAPI()); - this.addAuthProvider('sspi', new SSPI()); - this.addAuthProvider('scram-sha-1', new ScramSHA1()); -} - -inherits(Server, EventEmitter); - -/** - * Execute a command - * @method - * @param {string} type Type of BSON parser to use (c++ or js) - */ -Server.prototype.setBSONParserType = function(type) { - var nBSON = null; - - if(type == 'c++') { - nBSON = require('bson').native().BSON; - } else if(type == 'js') { - nBSON = require('bson').pure().BSON; - } else { - throw new MongoError(f("% parser not supported", type)); - } - - this.s.options.bson = new nBSON(bsonTypes); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Server.prototype.lastIsMaster = function() { - return this.s.ismaster; -} - -/** - * Initiate server connect - * @method - */ -Server.prototype.connect = function(_options) { - var self = this; - // Set server specific settings - _options = _options || {} - // Set the promotion - if(typeof _options.promoteLongs == 'boolean') { - self.s.options.promoteLongs = _options.promoteLongs; - } - - // Destroy existing pool - if(self.s.pool) { - self.s.pool.destroy(); - self.s.pool = null; - } - - // Set the state to connection - self.s.state = CONNECTING; - // Create a new connection pool - if(!self.s.pool) { - self.s.options.messageHandler = messageHandler(self, self.s); - self.s.pool = new Pool(self.s.options); - } - - // Add all the event handlers - self.s.pool.once('timeout', timeoutHandler(self, self.s)); - self.s.pool.once('close', closeHandler(self, self.s)); - self.s.pool.once('error', errorHandler(self, self.s)); - self.s.pool.once('connect', connectHandler(self, self.s)); - self.s.pool.once('parseError', fatalErrorHandler(self, self.s)); - - // Connect the pool - self.s.pool.connect(); -} - -/** - * Destroy the server connection - * @method - */ -Server.prototype.destroy = function(emitClose, emitDestroy) { - var self = this; - if(self.s.logger.isDebug()) self.s.logger.debug(f('destroy called on server %s', self.name)); - // Emit close - if(emitClose && self.listeners('close').length > 0) self.emit('close', self); - - // Emit destroy event - if(emitDestroy) self.emit('destroy', self); - // Set state as destroyed - self.s.state = DESTROYED; - // Close the pool - self.s.pool.destroy(); - // Flush out all the callbacks - if(self.s.callbacks) self.s.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); -} - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Server.prototype.isConnected = function() { - var self = this; - if(self.s.pool) return self.s.pool.isConnected(); - return false; -} - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Server.prototype.isDestroyed = function() { - return this.s.state == DESTROYED; -} - -var executeSingleOperation = function(self, ns, cmd, queryOptions, options, onAll, callback) { - // Create a query instance - var query = new Query(self.s.bson, ns, cmd, queryOptions); - - // Set slave OK - query.slaveOk = slaveOk(options.readPreference); - - // Notify query start to any read Preference strategies - if(self.s.readPreferenceStrategies != null) - notifyStrategies(self, self.s, 'startOperation', [self, query, new Date()]); - - // Get a connection (either passed or from the pool) - var connection = options.connection || self.s.pool.get(); - - // Double check if we have a valid connection - if(!connection.isConnected()) { - return callback(new MongoError(f("no connection available to server %s", self.name))); - } - - // Print cmd and execution connection if in debug mode for logging - if(self.s.logger.isDebug()) { - var json = connection.toJSON(); - self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(cmd), json.id, json.host, json.port)); - } - - // Execute multiple queries - if(onAll) { - var connections = self.s.pool.getAll(); - var total = connections.length; - // We have an error - var error = null; - // Execute on all connections - for(var i = 0; i < connections.length; i++) { - try { - query.incRequestId(); - connections[i].write(query.toBin()); - } catch(err) { - total = total - 1; - if(total == 0) return callback(MongoError.create(err)); - } - - // Register the callback - self.s.callbacks.register(query.requestId, function(err, result) { - if(err) error = err; - total = total - 1; - - // Done - if(total == 0) { - // Notify end of command - notifyStrategies(self, self.s, 'endOperation', [self, error, result, new Date()]); - if(error) return callback(MongoError.create(error)); - // Execute callback, catch and rethrow if needed - try { callback(null, new CommandResult(result.documents[0], connections)); } - catch(err) { process.nextTick(function() { throw err}); } - } - }); - } - - return; - } - - // Execute a single command query - try { - connection.write(query.toBin()); - } catch(err) { - return callback(MongoError.create(err)); - } - - // Register the callback - self.s.callbacks.register(query.requestId, function(err, result) { - // Notify end of command - notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); - if(err) return callback(err); - if(result.documents[0]['$err'] - || result.documents[0]['errmsg'] - || result.documents[0]['err'] - || result.documents[0]['code']) return callback(MongoError.create(result.documents[0])); - // Execute callback, catch and rethrow if needed - try { callback(null, new CommandResult(result.documents[0], connection)); } - catch(err) { process.nextTick(function() { throw err}); } - }); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.command = function(ns, cmd, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Ensure we have no options - options = options || {}; - // Do we have a read Preference it need to be of type ReadPreference - if(options.readPreference && !(options.readPreference instanceof ReadPreference)) { - throw new Error("readPreference must be an instance of ReadPreference"); - } - - // Debug log - if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command [%s] against %s', JSON.stringify({ - ns: ns, cmd: cmd, options: debugOptions(debugFields, options) - }), self.name)); - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // If we have no connection error - if(!self.s.pool.isConnected()) return callback(new MongoError(f("no connection available to server %s", self.name))); - - // Execute on all connections - var onAll = typeof options.onAll == 'boolean' ? options.onAll : false; - - // Check keys - var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys: false; - - // Serialize function - var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - - // Ignore undefined values - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - - // Query options - var queryOptions = { - numberToSkip: 0, numberToReturn: -1, checkKeys: checkKeys - }; - - // Set up the serialize functions and ignore undefined - if(serializeFunctions) queryOptions.serializeFunctions = serializeFunctions; - if(ignoreUndefined) queryOptions.ignoreUndefined = ignoreUndefined; - - // Single operation execution - if(!Array.isArray(cmd)) { - return executeSingleOperation(self, ns, cmd, queryOptions, options, onAll, callback); - } - - // Build commands for each of the instances - var queries = new Array(cmd.length); - for(var i = 0; i < cmd.length; i++) { - queries[i] = new Query(self.s.bson, ns, cmd[i], queryOptions); - queries[i].slaveOk = slaveOk(options.readPreference); - } - - // Notify query start to any read Preference strategies - if(self.s.readPreferenceStrategies != null) - notifyStrategies(self, self.s, 'startOperation', [self, queries, new Date()]); - - // Get a connection (either passed or from the pool) - var connection = options.connection || self.s.pool.get(); - - // Double check if we have a valid connection - if(!connection.isConnected()) { - return callback(new MongoError(f("no connection available to server %s", self.name))); - } - - // Print cmd and execution connection if in debug mode for logging - if(self.s.logger.isDebug()) { - var json = connection.toJSON(); - self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(queries), json.id, json.host, json.port)); - } - - // Canceled operations - var canceled = false; - // Number of operations left - var operationsLeft = queries.length; - // Results - var results = []; - - // We need to nest the callbacks - for(var i = 0; i < queries.length; i++) { - // Get the query object - var query = queries[i]; - - // Execute a single command query - try { - connection.write(query.toBin()); - } catch(err) { - return callback(MongoError.create(err)); - } - - // Register the callback - self.s.callbacks.register(query.requestId, function(err, result) { - // If it's canceled ignore the operation - if(canceled) return; - // Update the current index - operationsLeft = operationsLeft - 1; - - // If we have an error cancel the operation - if(err) { - canceled = true; - return callback(err); - } - - // Return the result - if(result.documents[0]['$err'] - || result.documents[0]['errmsg'] - || result.documents[0]['err'] - || result.documents[0]['code']) { - - // Set to canceled - canceled = true; - // Return the error - return callback(MongoError.create(result.documents[0])); - } - - // Push results - results.push(result.documents[0]); - - // We are done, return the result - if(operationsLeft == 0) { - // Notify end of command - notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); - - // Turn into command results - var commandResults = new Array(results.length); - for(var i = 0; i < results.length; i++) { - commandResults[i] = new CommandResult(results[i], connection); - } - - // Execute callback, catch and rethrow if needed - try { callback(null, commandResults); } - catch(err) { process.nextTick(function() { throw err}); } - } - }); - } -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.insert = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.s.wireProtocolHandler.insert(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.update = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.s.wireProtocolHandler.update(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.remove = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.s.wireProtocolHandler.remove(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -Server.prototype.auth = function(mechanism, db) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - var callback = args.pop(); - - // If we don't have the mechanism fail - if(self.s.authProviders[mechanism] == null && mechanism != 'default') - throw new MongoError(f("auth provider %s does not exist", mechanism)); - - // If we have the default mechanism we pick mechanism based on the wire - // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr - if(mechanism == 'default' && self.s.ismaster && self.s.ismaster.maxWireVersion >= 3) { - mechanism = 'scram-sha-1'; - } else if(mechanism == 'default') { - mechanism = 'mongocr'; - } - - // Actual arguments - var finalArguments = [self, self.s.pool, db].concat(args.slice(0)).concat([function(err, r) { - if(err) return callback(err); - if(!r) return callback(new MongoError('could not authenticate')); - callback(null, new Session({}, self)); - }]); - - // Let's invoke the auth mechanism - self.s.authProviders[mechanism].auth.apply(self.s.authProviders[mechanism], finalArguments); -} - -// -// Plugin methods -// - -/** - * Add custom read preference strategy - * @method - * @param {string} name Name of the read preference strategy - * @param {object} strategy Strategy object instance - */ -Server.prototype.addReadPreferenceStrategy = function(name, strategy) { - var self = this; - if(self.s.readPreferenceStrategies == null) self.s.readPreferenceStrategies = {}; - self.s.readPreferenceStrategies[name] = strategy; -} - -/** - * Add custom authentication mechanism - * @method - * @param {string} name Name of the authentication mechanism - * @param {object} provider Authentication object instance - */ -Server.prototype.addAuthProvider = function(name, provider) { - var self = this; - self.s.authProviders[name] = provider; -} - -/** - * Compare two server instances - * @method - * @param {Server} server Server to compare equality against - * @return {boolean} - */ -Server.prototype.equals = function(server) { - if(typeof server == 'string') return server == this.name; - return server.name == this.name; -} - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Server.prototype.connections = function() { - return this.s.pool.getAll(); -} - -/** - * Get server - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Server} - */ -Server.prototype.getServer = function(options) { - return this; -} - -/** - * Get connection - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Connection} - */ -Server.prototype.getConnection = function(options) { - return this.s.pool.get(); -} - -/** - * Get callbacks object - * @method - * @return {Callbacks} - */ -Server.prototype.getCallbacks = function() { - return this.s.callbacks; -} - -/** - * Name of BSON parser currently used - * @method - * @return {string} - */ -Server.prototype.parserType = function() { - var s = this.s; - if(s.options.bson.serialize.toString().indexOf('[native code]') != -1) - return 'c++'; - return 'js'; -} - -// // Command -// { -// find: ns -// , query: -// , limit: -// , fields: -// , skip: -// , hint: -// , explain: -// , snapshot: -// , batchSize: -// , returnKey: -// , maxScan: -// , min: -// , max: -// , showDiskLoc: -// , comment: -// , maxTimeMS: -// , raw: -// , readPreference: -// , tailable: -// , oplogReplay: -// , noCursorTimeout: -// , awaitdata: -// , exhaust: -// , partial: -// } - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.cursor = function(ns, cmd, cursorOptions) { - var s = this.s; - cursorOptions = cursorOptions || {}; - // Set up final cursor type - var FinalCursor = cursorOptions.cursorFactory || s.Cursor; - // Return the cursor - return new FinalCursor(s.bson, ns, cmd, cursorOptions, this, s.options); -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Server#connect - * @type {Server} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Server#close - * @type {Server} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Server#error - * @type {Server} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Server#timeout - * @type {Server} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Server#parseError - * @type {Server} - */ - -/** - * The server reestablished the connection - * - * @event Server#reconnect - * @type {Server} - */ - -/** - * This is an insert result callback - * - * @callback opResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {CommandResult} command result - */ - -/** - * This is an authentication result callback - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {Session} an authenticated session - */ - -module.exports = Server; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js deleted file mode 100644 index 032c3c5..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , EventEmitter = require('events').EventEmitter; - -/** - * Creates a new Authentication Session - * @class - * @param {object} [options] Options for the session - * @param {{Server}|{ReplSet}|{Mongos}} topology The topology instance underpinning the session - */ -var Session = function(options, topology) { - this.options = options; - this.topology = topology; - - // Add event listener - EventEmitter.call(this); -} - -inherits(Session, EventEmitter); - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {object} [options.readPreference] Specify read preference if command supports it - * @param {object} [options.connection] Specify connection object to execute command against - * @param {opResultCallback} callback A callback function - */ -Session.prototype.command = function(ns, cmd, options, callback) { - this.topology.command(ns, cmd, options, callback); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {opResultCallback} callback A callback function - */ -Session.prototype.insert = function(ns, ops, options, callback) { - this.topology.insert(ns, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {opResultCallback} callback A callback function - */ -Session.prototype.update = function(ns, ops, options, callback) { - this.topology.update(ns, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {opResultCallback} callback A callback function - */ -Session.prototype.remove = function(ns, ops, options, callback) { - this.topology.remove(ns, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {boolean} [options.tailable=false] Tailable flag set - * @param {boolean} [options.oplogReply=false] oplogReply flag set - * @param {boolean} [options.awaitdata=false] awaitdata flag set - * @param {boolean} [options.exhaust=false] exhaust flag set - * @param {boolean} [options.partial=false] partial flag set - * @param {opResultCallback} callback A callback function - */ -Session.prototype.cursor = function(ns, cmd, options) { - return this.topology.cursor(ns, cmd, options); -} - -module.exports = Session; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js deleted file mode 100644 index 3a7b460..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js +++ /dev/null @@ -1,276 +0,0 @@ -"use strict"; - -var Logger = require('../../connection/logger') - , EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , f = require('util').format; - -/** - * Creates a new Ping read preference strategy instance - * @class - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) - * @return {Ping} A cursor instance - */ -var Ping = function(options) { - // Add event listener - EventEmitter.call(this); - - // Contains the ping state - this.s = { - // Contains all the ping data - pings: {} - // Set no options if none provided - , options: options || {} - // Logger - , logger: Logger('Ping', options) - // Ping interval - , pingInterval: options.pingInterval || 10000 - , acceptableLatency: options.acceptableLatency || 15 - // Debug options - , debug: typeof options.debug == 'boolean' ? options.debug : false - // Index - , index: 0 - // Current ping time - , lastPing: null - - } - - // Log the options set - if(this.s.logger.isDebug()) this.s.logger.debug(f('ping strategy interval [%s], acceptableLatency [%s]', this.s.pingInterval, this.s.acceptableLatency)); - - // If we have enabled debug - if(this.s.debug) { - // Add access to the read Preference Strategies - Object.defineProperty(this, 'data', { - enumerable: true, get: function() { return this.s.pings; } - }); - } -} - -inherits(Ping, EventEmitter); - -/** - * @ignore - */ -var filterByTags = function(readPreference, servers) { - if(readPreference.tags == null) return servers; - var filteredServers = []; - var tags = readPreference.tags; - - // Iterate over all the servers - for(var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - // Did we find the a matching server - var found = true; - // Check if the server is valid - for(var name in tags) { - if(serverTag[name] != tags[name]) found = false; - } - - // Add to candidate list - if(found) filteredServers.push(servers[i]); - } - - // Returned filtered servers - return filteredServers; -} - -/** - * Pick a server - * @method - * @param {State} set The current replicaset state object - * @param {ReadPreference} readPreference The current readPreference object - * @param {readPreferenceResultCallback} callback The callback to return the result from the function - * @return {object} - */ -Ping.prototype.pickServer = function(set, readPreference) { - var self = this; - // Only get primary and secondaries as seeds - var seeds = {}; - var servers = []; - if(set.primary) { - servers.push(set.primary); - } - - for(var i = 0; i < set.secondaries.length; i++) { - servers.push(set.secondaries[i]); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Transform the list - var serverList = []; - // for(var name in seeds) { - for(var i = 0; i < servers.length; i++) { - serverList.push({name: servers[i].name, time: self.s.pings[servers[i].name] || 0}); - } - - // Sort by time - serverList.sort(function(a, b) { - return a.time > b.time; - }); - - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - var lowest = serverList.length > 0 ? serverList[0].time : 0; - - // Filter by latency - serverList = serverList.filter(function(s) { - return s.time <= lowest + self.s.acceptableLatency; - }); - - // No servers, default to primary - if(serverList.length == 0 && set.primary) { - if(self.s.logger.isInfo()) self.s.logger.info(f('picked primary server [%s]', set.primary.name)); - return set.primary; - } else if(serverList.length == 0) { - return null - } - - // We picked first server - if(self.s.logger.isInfo()) self.s.logger.info(f('picked server [%s] with ping latency [%s]', serverList[0].name, serverList[0].time)); - - // Add to the index - self.s.index = self.s.index + 1; - // Select the index - self.s.index = self.s.index % serverList.length; - // Return the first server of the sorted and filtered list - return set.get(serverList[self.s.index].name); -} - -/** - * Start of an operation - * @method - * @param {Server} server The server the operation is running against - * @param {object} query The operation running - * @param {Date} date The start time of the operation - * @return {object} - */ -Ping.prototype.startOperation = function(server, query, date) { -} - -/** - * End of an operation - * @method - * @param {Server} server The server the operation is running against - * @param {error} err An error from the operation - * @param {object} result The result from the operation - * @param {Date} date The start time of the operation - * @return {object} - */ -Ping.prototype.endOperation = function(server, err, result, date) { -} - -/** - * High availability process running - * @method - * @param {State} set The current replicaset state object - * @param {resultCallback} callback The callback to return the result from the function - * @return {object} - */ -Ping.prototype.ha = function(topology, state, callback) { - var self = this; - var servers = state.getAll(); - var count = servers.length; - - // No servers return - if(servers.length == 0) return callback(null, null); - - // Return if we have not yet reached the ping interval - if(self.s.lastPing != null) { - var diff = new Date().getTime() - self.s.lastPing.getTime(); - if(diff < self.s.pingInterval) return callback(null, null); - } - - // Execute operation - var operation = function(_server) { - var start = new Date(); - // Execute ping against server - _server.command('system.$cmd', {ismaster:1}, function(err, r) { - count = count - 1; - var time = new Date().getTime() - start.getTime(); - self.s.pings[_server.name] = time; - // Log info for debug - if(self.s.logger.isDebug()) self.s.logger.debug(f('ha latency for server [%s] is [%s] ms', _server.name, time)); - // We are done with all the servers - if(count == 0) { - // Emit ping event - topology.emit('ping', err, r ? r.result : null); - // Update the last ping time - self.s.lastPing = new Date(); - // Return - callback(null, null); - } - }); - } - - // Let's ping all servers - while(servers.length > 0) { - operation(servers.shift()); - } -} - -var removeServer = function(self, server) { - delete self.s.pings[server.name]; -} - -/** - * Server connection closed - * @method - * @param {Server} server The server that closed - */ -Ping.prototype.close = function(server) { - removeServer(this, server); -} - -/** - * Server connection errored out - * @method - * @param {Server} server The server that errored out - */ -Ping.prototype.error = function(server) { - removeServer(this, server); -} - -/** - * Server connection timeout - * @method - * @param {Server} server The server that timed out - */ -Ping.prototype.timeout = function(server) { - removeServer(this, server); -} - -/** - * Server connection happened - * @method - * @param {Server} server The server that connected - * @param {resultCallback} callback The callback to return the result from the function - */ -Ping.prototype.connect = function(server, callback) { - var self = this; - // Get the command start date - var start = new Date(); - // Execute ping against server - server.command('system.$cmd', {ismaster:1}, function(err, r) { - var time = new Date().getTime() - start.getTime(); - self.s.pings[server.name] = time; - // Log info for debug - if(self.s.logger.isDebug()) self.s.logger.debug(f('connect latency for server [%s] is [%s] ms', server.name, time)); - // Set last ping - self.s.lastPing = new Date(); - // Done, return - callback(null, null); - }); -} - -/** - * This is a result from a readPreference strategy - * - * @callback readPreferenceResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {Server} server The server picked by the strategy - */ - -module.exports = Ping; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js deleted file mode 100644 index e2e6a67..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js +++ /dev/null @@ -1,559 +0,0 @@ -"use strict"; - -var Insert = require('./commands').Insert - , Update = require('./commands').Update - , Remove = require('./commands').Remove - , Query = require('../connection/commands').Query - , copy = require('../connection/utils').copy - , KillCursor = require('../connection/commands').KillCursor - , GetMore = require('../connection/commands').GetMore - , Query = require('../connection/commands').Query - , ReadPreference = require('../topologies/read_preference') - , f = require('util').format - , CommandResult = require('../topologies/command_result') - , MongoError = require('../error') - , Long = require('bson').Long; - -// Write concern fields -var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync']; - -var WireProtocol = function() {} - -// -// Needs to support legacy mass insert as well as ordered/unordered legacy -// emulation -// -WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - options = options || {}; - // Default is ordered execution - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - var legacy = typeof options.legacy == 'boolean' ? options.legacy : false; - ops = Array.isArray(ops) ? ops :[ops]; - - // If we have more than a 1000 ops fails - if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000")); - - // Write concern - var writeConcern = options.writeConcern || {w:1}; - - // We are unordered - if(!ordered || writeConcern.w == 0) { - return executeUnordered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); - } - - return executeOrdered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); -} - -WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - options = options || {}; - // Default is ordered execution - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - ops = Array.isArray(ops) ? ops :[ops]; - - // Write concern - var writeConcern = options.writeConcern || {w:1}; - - // We are unordered - if(!ordered || writeConcern.w == 0) { - return executeUnordered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); - } - - return executeOrdered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); -} - -WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - options = options || {}; - // Default is ordered execution - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - ops = Array.isArray(ops) ? ops :[ops]; - - // Write concern - var writeConcern = options.writeConcern || {w:1}; - - // We are unordered - if(!ordered || writeConcern.w == 0) { - return executeUnordered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); - } - - return executeOrdered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); -} - -WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { - // Create a kill cursor command - var killCursor = new KillCursor(bson, [cursorId]); - // Execute the kill cursor command - if(connection && connection.isConnected()) connection.write(killCursor.toBin()); - // Set cursor to 0 - cursorId = Long.ZERO; - // Return to caller - if(callback) callback(null, null); -} - -WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { - // Create getMore command - var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); - - // Query callback - var queryCallback = function(err, r) { - if(err) return callback(err); - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - return callback(new MongoError("cursor killed or timed out"), null); - } - - // Ensure we have a Long valie cursor id - var cursorId = typeof r.cursorId == 'number' - ? Long.fromNumber(r.cursorId) - : r.cursorId; - - // Set all the values - cursorState.documents = r.documents; - cursorState.cursorId = cursorId; - - // Return - callback(null); - } - - // If we have a raw query decorate the function - if(raw) { - queryCallback.raw = raw; - } - - // Register a callback - callbacks.register(getMore.requestId, queryCallback); - // Write out the getMore command - connection.write(getMore.toBin()); -} - -WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { - // Establish type of command - if(cmd.find) { - return setupClassicFind(bson, ns, cmd, cursorState, topology, options) - } else if(cursorState.cursorId != null) { - } else if(cmd) { - return setupCommand(bson, ns, cmd, cursorState, topology, options); - } else { - throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); - } -} - -// -// Execute a find command -var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Ensure we have at least some options - options = options || {}; - // Set the optional batchSize - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - var numberToReturn = 0; - - // Unpack the limit and batchSize values - if(cursorState.limit == 0) { - numberToReturn = cursorState.batchSize; - } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - var numberToSkip = cursorState.skip || 0; - // Build actual find command - var findCmd = {}; - // Using special modifier - var usesSpecialModifier = false; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - usesSpecialModifier = true; - } - - // Add special modifiers to the query - if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; - if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; - if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; - if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; - if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; - if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; - if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; - if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; - if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; - if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; - - // If we have explain, return a single document and close cursor - if(cmd.explain) { - numberToReturn = -1; - usesSpecialModifier = true; - findCmd['$explain'] = true; - } - - // If we have a special modifier - if(usesSpecialModifier) { - findCmd['$query'] = cmd.query; - } else { - findCmd = cmd.query; - } - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) { - cmd = copy(cmd); - delete cmd['readConcern']; - } - - // Set up the serialize and ignoreUndefined fields - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, numberToReturn: numberToReturn - , checkKeys: false, returnFieldSelector: cmd.fields - , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Set up the option bits for wire protocol - if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; - if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; - if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; - if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; - if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; - // Return the query - return query; -} - -// -// Set up a command cursor -var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Set empty options object - options = options || {} - - // Final query - var finalCmd = {}; - for(var name in cmd) { - finalCmd[name] = cmd[name]; - } - - // Build command namespace - var parts = ns.split(/\./); - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - finalCmd['$readPreference'] = readPreference.toJSON(); - } - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) delete cmd['readConcern']; - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - - // Set up the serialize and ignoreUndefined fields - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) { - return callback; - } else { - return domain.bind(callback); - } -} - -var hasWriteConcern = function(writeConcern) { - if(writeConcern.w - || writeConcern.wtimeout - || writeConcern.j == true - || writeConcern.fsync == true - || Object.keys(writeConcern).length == 0) { - return true; - } - return false; -} - -var cloneWriteConcern = function(writeConcern) { - var wc = {}; - if(writeConcern.w != null) wc.w = writeConcern.w; - if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout; - if(writeConcern.j != null) wc.j = writeConcern.j; - if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync; - return wc; -} - -// -// Aggregate up all the results -// -var aggregateWriteOperationResults = function(opType, ops, results, connection) { - var finalResult = { ok: 1, n: 0 } - - // Map all the results coming back - for(var i = 0; i < results.length; i++) { - var result = results[i]; - var op = ops[i]; - - if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) { - finalResult.upserted = []; - } - - // Push the upserted document to the list of upserted values - if(result.upserted) { - finalResult.upserted.push({index: i, _id: result.upserted}); - } - - // We have an upsert where we passed in a _id - if(result.updatedExisting == false && result.n == 1 && result.upserted == null) { - finalResult.upserted.push({index: i, _id: op.q._id}); - } - - // We have an insert command - if(result.ok == 1 && opType == 'insert' && result.err == null) { - finalResult.n = finalResult.n + 1; - } - - // We have a command error - if(result != null && result.ok == 0 || result.err || result.errmsg) { - if(result.ok == 0) finalResult.ok = 0; - finalResult.code = result.code; - finalResult.errmsg = result.errmsg || result.err || result.errMsg; - - // Check if we have a write error - if(result.code == 11000 - || result.code == 11001 - || result.code == 12582 - || result.code == 16544 - || result.code == 16538 - || result.code == 16542 - || result.code == 14 - || result.code == 13511) { - if(finalResult.writeErrors == null) finalResult.writeErrors = []; - finalResult.writeErrors.push({ - index: i - , code: result.code - , errmsg: result.errmsg || result.err || result.errMsg - }); - } else { - finalResult.writeConcernError = { - code: result.code - , errmsg: result.errmsg || result.err || result.errMsg - } - } - } else if(typeof result.n == 'number') { - finalResult.n += result.n; - } else { - finalResult.n += 1; - } - - // Result as expected - if(result != null && result.lastOp) finalResult.lastOp = result.lastOp; - } - - // Return finalResult aggregated results - return new CommandResult(finalResult, connection); -} - -// -// Execute all inserts in an ordered manner -// -var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - var _ops = ops.slice(0); - // Bind to current domain - callback = bindToCurrentDomain(callback); - // Collect all the getLastErrors - var getLastErrors = []; - - // Execute an operation - var executeOp = function(list, _callback) { - // Get a pool connection - var connection = pool.get(); - // No more items in the list - if(list.length == 0) return _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - - // Get the first operation - var doc = list.shift(); - - // Create an insert command - var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options); - // Write concern - var optionWriteConcern = options.writeConcern || {w:1}; - // Final write concern - var writeConcern = cloneWriteConcern(optionWriteConcern); - - // Get the db name - var db = ns.split('.').shift(); - - // Error out if no connection available - if(connection == null) - return _callback(new MongoError("no connection available")); - - try { - // Execute the insert - connection.write(op.toBin()); - - // If write concern 0 don't fire getLastError - if(hasWriteConcern(writeConcern)) { - var getLastErrorCmd = {getlasterror: 1}; - // Merge all the fields - for(var i = 0; i < writeConcernFields.length; i++) { - if(writeConcern[writeConcernFields[i]] != null) - getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]]; - } - - // Create a getLastError command - var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); - // Write the lastError message - connection.write(getLastErrorOp.toBin()); - // Register the callback - callbacks.register(getLastErrorOp.requestId, function(err, result) { - if(err) return callback(err); - // Get the document - var doc = result.documents[0]; - // Save the getLastError document - getLastErrors.push(doc); - // If we have an error terminate - if(doc.ok == 0 || doc.err || doc.errmsg) return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - // Execute the next op in the list - executeOp(list, callback); - }); - } - } catch(err) { - if(typeof err == 'string') err = new MongoError(err); - // We have a serialization error, rewrite as a write error to have same behavior as modern - // write commands - getLastErrors.push({ ok: 1, errmsg: err.message, code: 14 }); - // Return due to an error - return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - } - } - - // Execute the operations - executeOp(_ops, callback); -} - -var executeUnordered = function(opType, command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - // Bind to current domain - callback = bindToCurrentDomain(callback); - // Total operations to write - var totalOps = ops.length; - // Collect all the getLastErrors - var getLastErrors = []; - // Write concern - var optionWriteConcern = options.writeConcern || {w:1}; - // Final write concern - var writeConcern = cloneWriteConcern(optionWriteConcern); - // Driver level error - var error; - - // Execute all the operations - for(var i = 0; i < ops.length; i++) { - // Create an insert command - var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options); - // Get db name - var db = ns.split('.').shift(); - - // Get a pool connection - var connection = pool.get(); - - // Error out if no connection available - if(connection == null) - return _callback(new MongoError("no connection available")); - - try { - // Execute the insert - connection.write(op.toBin()); - // If write concern 0 don't fire getLastError - if(hasWriteConcern(writeConcern)) { - var getLastErrorCmd = {getlasterror: 1}; - // Merge all the fields - for(var j = 0; j < writeConcernFields.length; j++) { - if(writeConcern[writeConcernFields[j]] != null) - getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]]; - } - - // Create a getLastError command - var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); - // Write the lastError message - connection.write(getLastErrorOp.toBin()); - - // Give the result from getLastError the right index - var callbackOp = function(_index) { - return function(err, result) { - if(err) error = err; - // Update the number of operations executed - totalOps = totalOps - 1; - // Save the getLastError document - if(!err) getLastErrors[_index] = result.documents[0]; - // Check if we are done - if(totalOps == 0) { - if(error) return callback(error); - callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - } - } - } - - // Register the callback - callbacks.register(getLastErrorOp.requestId, callbackOp(i)); - } - } catch(err) { - if(typeof err == 'string') err = new MongoError(err); - // Update the number of operations executed - totalOps = totalOps - 1; - // We have a serialization error, rewrite as a write error to have same behavior as modern - // write commands - getLastErrors[i] = { ok: 1, errmsg: err.message, code: 14 }; - // Check if we are done - if(totalOps == 0) { - callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - } - } - } - - // Empty w:0 return - if(writeConcern - && writeConcern.w == 0 && callback) { - callback(null, null); - } -} - -module.exports = WireProtocol; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js deleted file mode 100644 index b1d1d46..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js +++ /dev/null @@ -1,291 +0,0 @@ -"use strict"; - -var Insert = require('./commands').Insert - , Update = require('./commands').Update - , Remove = require('./commands').Remove - , Query = require('../connection/commands').Query - , copy = require('../connection/utils').copy - , KillCursor = require('../connection/commands').KillCursor - , GetMore = require('../connection/commands').GetMore - , Query = require('../connection/commands').Query - , ReadPreference = require('../topologies/read_preference') - , f = require('util').format - , CommandResult = require('../topologies/command_result') - , MongoError = require('../error') - , Long = require('bson').Long; - -var WireProtocol = function() {} - -// -// Execute a write operation -var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { - if(ops.length == 0) throw new MongoError("insert must contain at least one document"); - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Split the ns up to get db and collection - var p = ns.split("."); - var d = p.shift(); - // Options - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - var writeConcern = options.writeConcern || {}; - // return skeleton - var writeCommand = {}; - writeCommand[type] = p.join('.'); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - writeCommand.writeConcern = writeConcern; - - // Options object - var opts = {}; - if(type == 'insert') opts.checkKeys = true; - // Ensure we support serialization of functions - if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; - if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; - // Execute command - topology.command(f("%s.$cmd", d), writeCommand, opts, callback); -} - -// -// Needs to support legacy mass insert as well as ordered/unordered legacy -// emulation -// -WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); -} - -WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'update', 'updates', ns, ops, options, callback); -} - -WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); -} - -WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { - // Create a kill cursor command - var killCursor = new KillCursor(bson, [cursorId]); - // Execute the kill cursor command - if(connection && connection.isConnected()) connection.write(killCursor.toBin()); - // Set cursor to 0 - cursorId = Long.ZERO; - // Return to caller - if(callback) callback(null, null); -} - -WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { - // Create getMore command - var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); - - // Query callback - var queryCallback = function(err, r) { - if(err) return callback(err); - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - return callback(new MongoError("cursor killed or timed out"), null); - } - - // Ensure we have a Long valie cursor id - var cursorId = typeof r.cursorId == 'number' - ? Long.fromNumber(r.cursorId) - : r.cursorId; - - // Set all the values - cursorState.documents = r.documents; - cursorState.cursorId = cursorId; - - // Return - callback(null); - } - - // If we have a raw query decorate the function - if(raw) { - queryCallback.raw = raw; - } - - // Register a callback - callbacks.register(getMore.requestId, queryCallback); - // Write out the getMore command - connection.write(getMore.toBin()); -} - -WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { - // Establish type of command - if(cmd.find) { - return setupClassicFind(bson, ns, cmd, cursorState, topology, options) - } else if(cursorState.cursorId != null) { - } else if(cmd) { - return setupCommand(bson, ns, cmd, cursorState, topology, options); - } else { - throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); - } -} - -// -// Execute a find command -var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Ensure we have at least some options - options = options || {}; - // Set the optional batchSize - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - var numberToReturn = 0; - - // Unpack the limit and batchSize values - if(cursorState.limit == 0) { - numberToReturn = cursorState.batchSize; - } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - var numberToSkip = cursorState.skip || 0; - // Build actual find command - var findCmd = {}; - // Using special modifier - var usesSpecialModifier = false; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - usesSpecialModifier = true; - } - - // Add special modifiers to the query - if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; - if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; - if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; - if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; - if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; - if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; - if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; - if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; - if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; - if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; - - // If we have explain, return a single document and close cursor - if(cmd.explain) { - numberToReturn = -1; - usesSpecialModifier = true; - findCmd['$explain'] = true; - } - - // If we have a special modifier - if(usesSpecialModifier) { - findCmd['$query'] = cmd.query; - } else { - findCmd = cmd.query; - } - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) { - cmd = copy(cmd); - delete cmd['readConcern']; - } - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, numberToReturn: numberToReturn - , checkKeys: false, returnFieldSelector: cmd.fields - , serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Set up the option bits for wire protocol - if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; - if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; - if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; - if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; - if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; - // Return the query - return query; -} - -// -// Set up a command cursor -var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Set empty options object - options = options || {} - - // Final query - var finalCmd = {}; - for(var name in cmd) { - finalCmd[name] = cmd[name]; - } - - // Build command namespace - var parts = ns.split(/\./); - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - finalCmd['$readPreference'] = readPreference.toJSON(); - } - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) delete cmd['readConcern']; - - // Build Query object - var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) { - return callback; - } else { - return domain.bind(callback); - } -} - -module.exports = WireProtocol; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js deleted file mode 100644 index c5e61aa..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js +++ /dev/null @@ -1,494 +0,0 @@ -"use strict"; - -var Insert = require('./commands').Insert - , Update = require('./commands').Update - , Remove = require('./commands').Remove - , Query = require('../connection/commands').Query - , copy = require('../connection/utils').copy - , KillCursor = require('../connection/commands').KillCursor - , GetMore = require('../connection/commands').GetMore - , Query = require('../connection/commands').Query - , ReadPreference = require('../topologies/read_preference') - , f = require('util').format - , CommandResult = require('../topologies/command_result') - , MongoError = require('../error') - , Long = require('bson').Long; - -var WireProtocol = function(legacyWireProtocol) { - this.legacyWireProtocol = legacyWireProtocol; -} - -// -// Execute a write operation -var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { - if(ops.length == 0) throw new MongoError("insert must contain at least one document"); - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Split the ns up to get db and collection - var p = ns.split("."); - var d = p.shift(); - // Options - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - var writeConcern = options.writeConcern || {}; - // return skeleton - var writeCommand = {}; - writeCommand[type] = p.join('.'); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - writeCommand.writeConcern = writeConcern; - - // Do we have bypassDocumentValidation set, then enable it on the write command - if(typeof options.bypassDocumentValidation == 'boolean') { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Options object - var opts = {}; - if(type == 'insert') opts.checkKeys = true; - // Ensure we support serialization of functions - if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; - if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; - // Execute command - topology.command(f("%s.$cmd", d), writeCommand, opts, callback); -} - -// -// Needs to support legacy mass insert as well as ordered/unordered legacy -// emulation -// -WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); -} - -WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'update', 'updates', ns, ops, options, callback); -} - -WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); -} - -WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { - // Build command namespace - var parts = ns.split(/\./); - // Command namespace - var commandns = f('%s.$cmd', parts.shift()); - // Create getMore command - var killcursorCmd = { - killCursors: parts.join('.'), - cursors: [cursorId] - } - - // Build Query object - var query = new Query(bson, commandns, killcursorCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, returnFieldSelector: null - }); - - // Set query flags - query.slaveOk = true; - - // Execute the kill cursor command - if(connection && connection.isConnected()) { - connection.write(query.toBin()); - } - - // Kill cursor callback - var killCursorCallback = function(err, r) { - if(err) { - if(typeof callback != 'function') return; - return callback(err); - } - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - if(typeof callback != 'function') return; - return callback(new MongoError("cursor killed or timed out"), null); - } - - if(!Array.isArray(r.documents) || r.documents.length == 0) { - if(typeof callback != 'function') return; - return callback(new MongoError(f('invalid getMore result returned for cursor id %s', cursorState.cursorId))); - } - - // Return the result - if(typeof callback == 'function') { - callback(null, r.documents[0]); - } - } - - // Register a callback - callbacks.register(query.requestId, killCursorCallback); -} - -WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - // Build command namespace - var parts = ns.split(/\./); - // Command namespace - var commandns = f('%s.$cmd', parts.shift()); - - // Check if we have an maxTimeMS set - var maxTimeMS = typeof cursorState.cmd.maxTimeMS == 'number' ? cursorState.cmd.maxTimeMS : 3000; - - // Create getMore command - var getMoreCmd = { - getMore: cursorState.cursorId, - collection: parts.join('.'), - batchSize: batchSize, - maxTimeMS: maxTimeMS - } - - // Build Query object - var query = new Query(bson, commandns, getMoreCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, returnFieldSelector: null - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Query callback - var queryCallback = function(err, r) { - if(err) return callback(err); - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - return callback(new MongoError("cursor killed or timed out"), null); - } - - if(!Array.isArray(r.documents) || r.documents.length == 0) - return callback(new MongoError(f('invalid getMore result returned for cursor id %s', cursorState.cursorId))); - - // Raw, return all the extracted documents - if(raw) { - cursorState.documents = r.documents; - cursorState.cursorId = r.cursorId; - return callback(null, r.documents); - } - - // Ensure we have a Long valie cursor id - var cursorId = typeof r.documents[0].cursor.id == 'number' - ? Long.fromNumber(r.documents[0].cursor.id) - : r.documents[0].cursor.id; - - // Set all the values - cursorState.documents = r.documents[0].cursor.nextBatch; - cursorState.cursorId = cursorId; - - // Return the result - callback(null, r.documents[0]); - } - - // If we have a raw query decorate the function - if(raw) { - queryCallback.raw = raw; - } - - // Add the result field needed - queryCallback.documentsReturnedIn = 'nextBatch'; - - // Register a callback - callbacks.register(query.requestId, queryCallback); - // Write out the getMore command - connection.write(query.toBin()); -} - -WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { - // Establish type of command - if(cmd.find) { - if(cmd.exhaust) { - return this.legacyWireProtocol.command(bson, ns, cmd, cursorState, topology, options); - } - - // Create the find command - var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options) - // Mark the cmd as virtual - cmd.virtual = false; - // Signal the documents are in the firstBatch value - query.documentsReturnedIn = 'firstBatch'; - // Return the query - return query; - } else if(cursorState.cursorId != null) { - } else if(cmd) { - return setupCommand(bson, ns, cmd, cursorState, topology, options); - } else { - throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); - } -} - -// // Command -// { -// find: ns -// , query: -// , limit: -// , fields: -// , skip: -// , hint: -// , explain: -// , snapshot: -// , batchSize: -// , returnKey: -// , maxScan: -// , min: -// , max: -// , showDiskLoc: -// , comment: -// , maxTimeMS: -// , raw: -// , readPreference: -// , tailable: -// , oplogReplay: -// , noCursorTimeout: -// , awaitdata: -// , exhaust: -// , partial: -// } - -// FIND/GETMORE SPEC -// { -// “find”: , -// “filter”: { ... }, -// “sort”: { ... }, -// “projection”: { ... }, -// “hint”: { ... }, -// “skip”: , -// “limit”: , -// “batchSize”: , -// “singleBatch”: , -// “comment”: , -// “maxScan”: , -// “maxTimeMS”: , -// “max”: { ... }, -// “min”: { ... }, -// “returnKey”: , -// “showRecordId”: , -// “snapshot”: , -// “tailable”: , -// “oplogReplay”: , -// “noCursorTimeout”: , -// “awaitData”: , -// “partial”: , -// “$readPreference”: { ... } -// } - -// -// Execute a find command -var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Ensure we have at least some options - options = options || {}; - // Set the optional batchSize - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - - // Build command namespace - var parts = ns.split(/\./); - // Command namespace - var commandns = f('%s.$cmd', parts.shift()); - - // Build actual find command - var findCmd = { - find: parts.join('.') - }; - - // I we provided a filter - if(cmd.query) findCmd.filter = cmd.query; - - // Sort value - var sortValue = cmd.sort; - - // Handle issue of sort being an Array - if(Array.isArray(sortValue)) { - var sortObject = {}; - - if(sortValue.length > 0 && !Array.isArray(sortValue[0])) { - var sortDirection = sortValue[1]; - // Translate the sort order text - if(sortDirection == 'asc') { - sortDirection = 1; - } else if(sortDirection == 'desc') { - sortDirection = -1; - } - - // Set the sort order - sortObject[sortValue[0]] = sortDirection; - } else { - for(var i = 0; i < sortValue.length; i++) { - var sortDirection = sortValue[i][1]; - // Translate the sort order text - if(sortDirection == 'asc') { - sortDirection = 1; - } else if(sortDirection == 'desc') { - sortDirection = -1; - } - - // Set the sort order - sortObject[sortValue[i][0]] = sortDirection; - } - } - - sortValue = sortObject; - }; - - // Add sort to command - if(cmd.sort) findCmd.sort = sortValue; - // Add a projection to the command - if(cmd.fields) findCmd.projection = cmd.fields; - // Add a hint to the command - if(cmd.hint) findCmd.hint = cmd.hint; - // Add a skip - if(cmd.skip) findCmd.skip = cmd.skip; - // Add a limit - if(cmd.limit) findCmd.limit = cmd.limit; - // Add a batchSize - if(cmd.batchSize) findCmd.batchSize = cmd.batchSize; - - // Check if we wish to have a singleBatch - if(cmd.limit < 0) { - findCmd.limit = Math.abs(cmd.limit); - findCmd.singleBatch = true; - } - - // If we have comment set - if(cmd.comment) findCmd.comment = cmd.comment; - - // If we have maxScan - if(cmd.maxScan) findCmd.maxScan = cmd.maxScan; - - // If we have maxTimeMS set - if(cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; - - // If we have min - if(cmd.min) findCmd.min = cmd.min; - - // If we have max - if(cmd.max) findCmd.max = cmd.max; - - // If we have returnKey set - if(cmd.returnKey) findCmd.returnKey = cmd.returnKey; - - // If we have showDiskLoc set - if(cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; - - // If we have snapshot set - if(cmd.snapshot) findCmd.snapshot = cmd.snapshot; - - // If we have tailable set - if(cmd.tailable) findCmd.tailable = cmd.tailable; - - // If we have oplogReplay set - if(cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; - - // If we have noCursorTimeout set - if(cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; - - // If we have awaitData set - if(cmd.awaitData) findCmd.awaitData = cmd.awaitData; - if(cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; - - // If we have partial set - if(cmd.partial) findCmd.partial = cmd.partial; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - } - - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - if(cmd.explain) { - findCmd = { - explain: findCmd - } - } - - // Did we provide a readConcern - if(cmd.readConcern) findCmd.readConcern = cmd.readConcern; - - // Set up the serialize and ignoreUndefined fields - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, commandns, findCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, returnFieldSelector: null - , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -// -// Set up a command cursor -var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Set empty options object - options = options || {} - - // Final query - var finalCmd = {}; - for(var name in cmd) { - finalCmd[name] = cmd[name]; - } - - // Build command namespace - var parts = ns.split(/\./); - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - finalCmd['$readPreference'] = readPreference.toJSON(); - } - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - - // Set up the serialize and ignoreUndefined fields - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) { - return callback; - } else { - return domain.bind(callback); - } -} - -module.exports = WireProtocol; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js deleted file mode 100644 index 9c665ee..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js +++ /dev/null @@ -1,357 +0,0 @@ -"use strict"; - -var MongoError = require('../error'); - -// Wire command operation ids -var OP_UPDATE = 2001; -var OP_INSERT = 2002; -var OP_DELETE = 2006; - -var Insert = function(requestId, ismaster, bson, ns, documents, options) { - // Basic options needed to be passed in - if(ns == null) throw new MongoError("ns must be specified for query"); - if(!Array.isArray(documents) || documents.length == 0) throw new MongoError("documents array must contain at least one document to insert"); - - // Validate that we are not passing 0x00 in the colletion name - if(!!~ns.indexOf("\x00")) { - throw new MongoError("namespace cannot contain a null character"); - } - - // Set internal - this.requestId = requestId; - this.bson = bson; - this.ns = ns; - this.documents = documents; - this.ismaster = ismaster; - - // Ensure empty options - options = options || {}; - - // Unpack options - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; - this.continueOnError = typeof options.continueOnError == 'boolean' ? options.continueOnError : false; - // Set flags - this.flags = this.continueOnError ? 1 : 0; -} - -// To Binary -Insert.prototype.toBin = function() { - // Contains all the buffers to be written - var buffers = []; - - // Header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // Flags - + Buffer.byteLength(this.ns) + 1 // namespace - ); - - // Add header to buffers - buffers.push(header); - - // Total length of the message - var totalLength = header.length; - - // Serialize all the documents - for(var i = 0; i < this.documents.length; i++) { - var buffer = this.bson.serialize(this.documents[i] - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - - // Document is larger than maxBsonObjectSize, terminate serialization - if(buffer.length > this.ismaster.maxBsonObjectSize) { - throw new MongoError("Document exceeds maximum allowed bson size of " + this.ismaster.maxBsonObjectSize + " bytes"); - } - - // Add to total length of wire protocol message - totalLength = totalLength + buffer.length; - // Add to buffer - buffers.push(buffer); - } - - // Command is larger than maxMessageSizeBytes terminate serialization - if(totalLength > this.ismaster.maxMessageSizeBytes) { - throw new MongoError("Command exceeds maximum message size of " + this.ismaster.maxMessageSizeBytes + " bytes"); - } - - // Add all the metadata - var index = 0; - - // Write header length - header[index + 3] = (totalLength >> 24) & 0xff; - header[index + 2] = (totalLength >> 16) & 0xff; - header[index + 1] = (totalLength >> 8) & 0xff; - header[index] = (totalLength) & 0xff; - index = index + 4; - - // Write header requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // No flags - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Operation - header[index + 3] = (OP_INSERT >> 24) & 0xff; - header[index + 2] = (OP_INSERT >> 16) & 0xff; - header[index + 1] = (OP_INSERT >> 8) & 0xff; - header[index] = (OP_INSERT) & 0xff; - index = index + 4; - - // Flags - header[index + 3] = (this.flags >> 24) & 0xff; - header[index + 2] = (this.flags >> 16) & 0xff; - header[index + 1] = (this.flags >> 8) & 0xff; - header[index] = (this.flags) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Return the buffers - return buffers; -} - -var Update = function(requestId, ismaster, bson, ns, update, options) { - // Basic options needed to be passed in - if(ns == null) throw new MongoError("ns must be specified for query"); - - // Ensure empty options - options = options || {}; - - // Set internal - this.requestId = requestId; - this.bson = bson; - this.ns = ns; - this.ismaster = ismaster; - - // Unpack options - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Unpack the update document - this.upsert = typeof update[0].upsert == 'boolean' ? update[0].upsert : false; - this.multi = typeof update[0].multi == 'boolean' ? update[0].multi : false; - this.q = update[0].q; - this.u = update[0].u; - - // Create flag value - this.flags = this.upsert ? 1 : 0; - this.flags = this.multi ? this.flags | 2 : this.flags; -} - -// To Binary -Update.prototype.toBin = function() { - // Contains all the buffers to be written - var buffers = []; - - // Header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // ZERO - + Buffer.byteLength(this.ns) + 1 // namespace - + 4 // Flags - ); - - // Add header to buffers - buffers.push(header); - - // Total length of the message - var totalLength = header.length; - - // Serialize the selector - var selector = this.bson.serialize(this.q - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - buffers.push(selector); - totalLength = totalLength + selector.length; - - // Serialize the update - var update = this.bson.serialize(this.u - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - buffers.push(update); - totalLength = totalLength + update.length; - - // Index in header buffer - var index = 0; - - // Write header length - header[index + 3] = (totalLength >> 24) & 0xff; - header[index + 2] = (totalLength >> 16) & 0xff; - header[index + 1] = (totalLength >> 8) & 0xff; - header[index] = (totalLength) & 0xff; - index = index + 4; - - // Write header requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // No flags - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Operation - header[index + 3] = (OP_UPDATE >> 24) & 0xff; - header[index + 2] = (OP_UPDATE >> 16) & 0xff; - header[index + 1] = (OP_UPDATE >> 8) & 0xff; - header[index] = (OP_UPDATE) & 0xff; - index = index + 4; - - // Write ZERO - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Flags - header[index + 3] = (this.flags >> 24) & 0xff; - header[index + 2] = (this.flags >> 16) & 0xff; - header[index + 1] = (this.flags >> 8) & 0xff; - header[index] = (this.flags) & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -} - -var Remove = function(requestId, ismaster, bson, ns, remove, options) { - // Basic options needed to be passed in - if(ns == null) throw new MongoError("ns must be specified for query"); - - // Ensure empty options - options = options || {}; - - // Set internal - this.requestId = requestId; - this.bson = bson; - this.ns = ns; - this.ismaster = ismaster; - - // Unpack options - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Unpack the update document - this.limit = typeof remove[0].limit == 'number' ? remove[0].limit : 1; - this.q = remove[0].q; - - // Create flag value - this.flags = this.limit == 1 ? 1 : 0; -} - -// To Binary -Remove.prototype.toBin = function() { - // Contains all the buffers to be written - var buffers = []; - - // Header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // ZERO - + Buffer.byteLength(this.ns) + 1 // namespace - + 4 // Flags - ); - - // Add header to buffers - buffers.push(header); - - // Total length of the message - var totalLength = header.length; - - // Serialize the selector - var selector = this.bson.serialize(this.q - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - buffers.push(selector); - totalLength = totalLength + selector.length; - - // Index in header buffer - var index = 0; - - // Write header length - header[index + 3] = (totalLength >> 24) & 0xff; - header[index + 2] = (totalLength >> 16) & 0xff; - header[index + 1] = (totalLength >> 8) & 0xff; - header[index] = (totalLength) & 0xff; - index = index + 4; - - // Write header requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // No flags - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Operation - header[index + 3] = (OP_DELETE >> 24) & 0xff; - header[index + 2] = (OP_DELETE >> 16) & 0xff; - header[index + 1] = (OP_DELETE >> 8) & 0xff; - header[index] = (OP_DELETE) & 0xff; - index = index + 4; - - // Write ZERO - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write ZERO - header[index + 3] = (this.flags >> 24) & 0xff; - header[index + 2] = (this.flags >> 16) & 0xff; - header[index + 1] = (this.flags >> 8) & 0xff; - header[index] = (this.flags) & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -} - -module.exports = { - Insert: Insert - , Update: Update - , Remove: Remove -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY deleted file mode 100644 index ecf5994..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY +++ /dev/null @@ -1,113 +0,0 @@ -0.4.16 2015-10-07 ------------------ -- Fixed issue with return statement in Map.js. - -0.4.15 2015-10-06 ------------------ -- Exposed Map correctly via index.js file. - -0.4.14 2015-10-06 ------------------ -- Exposed Map correctly via bson.js file. - -0.4.13 2015-10-06 ------------------ -- Added ES6 Map type serialization as well as a polyfill for ES5. - -0.4.12 2015-09-18 ------------------ -- Made ignore undefined an optional parameter. - -0.4.11 2015-08-06 ------------------ -- Minor fix for invalid key checking. - -0.4.10 2015-08-06 ------------------ -- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. -- Some performance improvements by in lining code. - -0.4.9 2015-08-06 ----------------- -- Undefined fields are omitted from serialization in objects. - -0.4.8 2015-07-14 ----------------- -- Fixed size validation to ensure we can deserialize from dumped files. - -0.4.7 2015-06-26 ----------------- -- Added ability to instruct deserializer to return raw BSON buffers for named array fields. -- Minor deserialization optimization by moving inlined function out. - -0.4.6 2015-06-17 ----------------- -- Fixed serializeWithBufferAndIndex bug. - -0.4.5 2015-06-17 ----------------- -- Removed any references to the shared buffer to avoid non GC collectible bson instances. - -0.4.4 2015-06-17 ----------------- -- Fixed rethrowing of error when not RangeError. - -0.4.3 2015-06-17 ----------------- -- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. - -0.4.2 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.1 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.0 2015-06-16 ----------------- -- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. -- Removed bson-ext extension dependency for now. - -0.3.2 2015-03-27 ----------------- -- Removed node-gyp from install script in package.json. - -0.3.1 2015-03-27 ----------------- -- Return pure js version on native() call if failed to initialize. - -0.3.0 2015-03-26 ----------------- -- Pulled out all C++ code into bson-ext and made it an optional dependency. - -0.2.21 2015-03-21 ------------------ -- Updated Nan to 1.7.0 to support io.js and node 0.12.0 - -0.2.19 2015-02-16 ------------------ -- Updated Nan to 1.6.2 to support io.js and node 0.12.0 - -0.2.18 2015-01-20 ------------------ -- Updated Nan to 1.5.1 to support io.js - -0.2.16 2014-12-17 ------------------ -- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's - -0.2.12 2014-08-24 ------------------ -- Fixes for fortify review of c++ extension -- toBSON correctly allows returns of non objects - -0.2.3 2013-10-01 ----------------- -- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) -- Fixed issue where corrupt CString's could cause endless loop -- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) - -0.1.4 2012-09-25 ----------------- -- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md deleted file mode 100644 index 56327c2..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md +++ /dev/null @@ -1,69 +0,0 @@ -Javascript + C++ BSON parser -============================ - -This BSON parser is primarily meant to be used with the `mongodb` node.js driver. -However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser. -The current build is located in the `browser_build/bson.js` file. - -A simple example of how to use BSON in the browser: - -```html - - - - - - - - -``` - -A simple example of how to use BSON in `node.js`: - -```javascript -var bson = require("bson"); -var BSON = new bson.BSONPure.BSON(); -var Long = bson.BSONPure.Long; - -var doc = {long: Long.fromNumber(100)} - -// Serialize a document -var data = BSON.serialize(doc, false, true, false); -console.log("data:", data); - -// Deserialize the resulting Buffer -var doc_2 = BSON.deserialize(data); -console.log("doc_2:", doc_2); -``` - -The API consists of two simple methods to serialize/deserialize objects to/from BSON format: - - * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** - * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports - - * BSON.deserialize(buffer, options, isArray) - * Options - * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * @param {TypedArray/Array} a TypedArray/Array containing the BSON data - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js deleted file mode 100644 index 555aa79..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js +++ /dev/null @@ -1,1574 +0,0 @@ -var Long = require('../lib/bson/long').Long - , Double = require('../lib/bson/double').Double - , Timestamp = require('../lib/bson/timestamp').Timestamp - , ObjectID = require('../lib/bson/objectid').ObjectID - , Symbol = require('../lib/bson/symbol').Symbol - , Code = require('../lib/bson/code').Code - , MinKey = require('../lib/bson/min_key').MinKey - , MaxKey = require('../lib/bson/max_key').MaxKey - , DBRef = require('../lib/bson/db_ref').DBRef - , Binary = require('../lib/bson/binary').Binary - , BinaryParser = require('../lib/bson/binary_parser').BinaryParser - , writeIEEE754 = require('../lib/bson/float_parser').writeIEEE754 - , readIEEE754 = require('../lib/bson/float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - if(object.toBSON) { - if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); - object = object.toBSON(); - if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); - } - - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - var startIndex = index; - - switch(typeof value) { - case 'string': - // console.log("+++++++++++ index string:: " + index) - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // console.log("====== key :: " + name + " size ::" + size) - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // console.log("+++++++++++ index OBJECTID:: " + index) - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long || value['_bsontype'] == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - // console.log("++++++++++++++++++++++++++++++++++++ OLDJS :: " + buffer.length) - // console.log(buffer.toString('hex')) - // console.log(buffer.toString('ascii')) - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_UNDEFINED: - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -module.exports = BSON; -module.exports.Code = Code; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js deleted file mode 100644 index f19e44f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js +++ /dev/null @@ -1,429 +0,0 @@ -/// reduced to ~ 410 LOCs (parser only 300 vs. 1400+) with (some, needed) BSON classes "inlined". -/// Compare ~ 4,300 (22KB vs. 157KB) in browser build at: https://github.com/mongodb/js-bson/blob/master/browser_build/bson.js - -module.exports.calculateObjectSize = calculateObjectSize; - -function calculateObjectSize(object) { - var totalLength = (4 + 1); /// handles the obj.length prefix + terminating '0' ?! - for(var key in object) { /// looks like it handles arrays under the same for...in loop!? - totalLength += calculateElement(key, object[key]) - } - return totalLength; -} - -function calculateElement(name, value) { - var len = 1; /// always starting with 1 for the data type byte! - if (name) len += Buffer.byteLength(name, 'utf8') + 1; /// cstring: name + '0' termination - - if (value === undefined || value === null) return len; /// just the type byte plus name cstring - switch( value.constructor ) { /// removed all checks 'isBuffer' if Node.js Buffer class is present!? - - case ObjectID: /// we want these sorted from most common case to least common/deprecated; - return len + 12; - case String: - return len + 4 + Buffer.byteLength(value, 'utf8') +1; /// - case Number: - if (Math.floor(value) === value) { /// case: integer; pos.# more common, '&&' stops if 1st fails! - if ( value <= 2147483647 && value >= -2147483647 ) // 32 bit - return len + 4; - else return len + 8; /// covers Long-ish JS integers as Longs! - } else return len + 8; /// 8+1 --- covers Double & std. float - case Boolean: - return len + 1; - - case Array: - case Object: - return len + calculateObjectSize(value); - - case Buffer: /// replaces the entire Binary class! - return len + 4 + value.length + 1; - - case Regex: /// these are handled as strings by serializeFast() later, hence 'gim' opts = 3 + 1 chars - return len + Buffer.byteLength(value.source, 'utf8') + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) +1; - case Date: - case Long: - case Timestamp: - case Double: - return len + 8; - - case MinKey: - case MaxKey: - return len; /// these two return the type byte and name cstring only! - } - return 0; -} - -module.exports.serializeFast = serializeFast; -module.exports.serialize = function(object, checkKeys, asBuffer, serializeFunctions, index) { - var buffer = new Buffer(calculateObjectSize(object)); - return serializeFast(object, checkKeys, buffer, 0); -} - -function serializeFast(object, checkKeys, buffer, i) { /// set checkKeys = false in query(..., options object to save performance IFF you're certain your keys are safe/system-set! - var size = buffer.length; - buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; /// these get overwritten later! - buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; - - if (object.constructor === Array) { /// any need to checkKeys here?!? since we're doing for rather than for...in, should be safe from extra (non-numeric) keys added to the array?! - for(var j = 0; j < object.length; j++) { - i = packElement(j.toString(), object[j], checkKeys, buffer, i); - } - } else { /// checkKeys is needed if any suspicion of end-user key tampering/"injection" (a la SQL) - for(var key in object) { /// mostly there should never be direct access to them!? - if (checkKeys && (key.indexOf('\x00') >= 0 || key === '$where') ) { /// = "no script"?!; could add back key.indexOf('$') or maybe check for 'eval'?! -/// took out: || key.indexOf('.') >= 0... Don't we allow dot notation queries?! - console.log('checkKeys error: '); - return new Error('Illegal object key!'); - } - i = packElement(key, object[key], checkKeys, buffer, i); /// checkKeys pass needed for recursion! - } - } - buffer[i++] = 0; /// write terminating zero; !we do NOT -1 the index increase here as original does! - return i; -} - -function packElement(name, value, checkKeys, buffer, i) { /// serializeFunctions removed! checkKeys needed for Array & Object cases pass through (calling serializeFast recursively!) - if (value === undefined || value === null){ - buffer[i++] = 10; /// = BSON.BSON_DATA_NULL; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; /// buffer.write(...) returns bytesWritten! - return i; - } - switch(value.constructor) { - - case ObjectID: - buffer[i++] = 7; /// = BSON.BSON_DATA_OID; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; -/// i += buffer.write(value.id, i, 'binary'); /// OLD: writes a String to a Buffer; 'binary' deprecated!! - value.id.copy(buffer, i); /// NEW ObjectID version has this.id = Buffer at the ready! - return i += 12; - - case String: - buffer[i++] = 2; /// = BSON.BSON_DATA_STRING; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - - var size = Buffer.byteLength(value) + 1; /// includes the terminating '0'!? - buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; - buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; - - i += buffer.write(value, i, 'utf8'); buffer[i++] = 0; - return i; - - case Number: - if ( ~~(value) === value) { /// double-Tilde is equiv. to Math.floor(value) - if ( value <= 2147483647 && value >= -2147483647){ /// = BSON.BSON_INT32_MAX / MIN asf. - buffer[i++] = 16; /// = BSON.BSON_DATA_INT; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - buffer[i++] = value & 0xff; buffer[i++] = (value >> 8) & 0xff; - buffer[i++] = (value >> 16) & 0xff; buffer[i++] = (value >> 24) & 0xff; - -// Else large-ish JS int!? to Long!? - } else { /// if (value <= BSON.JS_INT_MAX && value >= BSON.JS_INT_MIN){ /// 9007199254740992 asf. - buffer[i++] = 18; /// = BSON.BSON_DATA_LONG; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - var lowBits = ( value % 4294967296 ) | 0, highBits = ( value / 4294967296 ) | 0; - - buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; - buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; - buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; - buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; - } - } else { /// we have a float / Double - buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; -/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); - buffer.writeDoubleLE(value, i); i += 8; - } - return i; - - case Boolean: - buffer[i++] = 8; /// = BSON.BSON_DATA_BOOLEAN; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - buffer[i++] = value ? 1 : 0; - return i; - - case Array: - case Object: - buffer[i++] = value.constructor === Array ? 4 : 3; /// = BSON.BSON_DATA_ARRAY / _OBJECT; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - - var endIndex = serializeFast(value, checkKeys, buffer, i); /// + 4); no longer needed b/c serializeFast writes a temp 4 bytes for length - var size = endIndex - i; - buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; - buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; - return endIndex; - - /// case Binary: /// is basically identical unless special/deprecated options! - case Buffer: /// solves ALL of our Binary needs without the BSON.Binary class!? - buffer[i++] = 5; /// = BSON.BSON_DATA_BINARY; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - var size = value.length; - buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; - buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; - - buffer[i++] = 0; /// write BSON.BSON_BINARY_SUBTYPE_DEFAULT; - value.copy(buffer, i); ///, 0, size); << defaults to sourceStart=0, sourceEnd=sourceBuffer.length); - i += size; - return i; - - case RegExp: - buffer[i++] = 11; /// = BSON.BSON_DATA_REGEXP; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - i += buffer.write(value.source, i, 'utf8'); buffer[i++] = 0x00; - - if (value.global) buffer[i++] = 0x73; // s = 'g' for JS Regex! - if (value.ignoreCase) buffer[i++] = 0x69; // i - if (value.multiline) buffer[i++] = 0x6d; // m - buffer[i++] = 0x00; - return i; - - case Date: - buffer[i++] = 9; /// = BSON.BSON_DATA_DATE; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - var millis = value.getTime(); - var lowBits = ( millis % 4294967296 ) | 0, highBits = ( millis / 4294967296 ) | 0; - - buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; - buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; - buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; - buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; - return i; - - case Long: - case Timestamp: - buffer[i++] = value.constructor === Long ? 18 : 17; /// = BSON.BSON_DATA_LONG / _TIMESTAMP - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - var lowBits = value.getLowBits(), highBits = value.getHighBits(); - - buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; - buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; - buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; - buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; - return i; - - case Double: - buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; -/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); i += 8; - buffer.writeDoubleLE(value, i); i += 8; - return i - - case MinKey: /// = BSON.BSON_DATA_MINKEY; - buffer[i++] = 127; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - return i; - case MaxKey: /// = BSON.BSON_DATA_MAXKEY; - buffer[i++] = 255; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - return i; - - } /// end of switch - return i; /// ?! If no value to serialize -} - - -module.exports.deserializeFast = deserializeFast; - -function deserializeFast(buffer, i, isArray){ //// , options, isArray) { //// no more options! - if (buffer.length < 5) return new Error('Corrupt bson message < 5 bytes long'); /// from 'throw' - var elementType, tempindex = 0, name; - var string, low, high; /// = lowBits / highBits - /// using 'i' as the index to keep the lines shorter: - i || ( i = 0 ); /// for parseResponse it's 0; set to running index in deserialize(object/array) recursion - var object = isArray ? [] : {}; /// needed for type ARRAY recursion later! - var size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - if(size < 5 || size > buffer.length) return new Error('Corrupt BSON message'); -/// 'size' var was not used by anything after this, so we can reuse it - - while(true) { // While we have more left data left keep parsing - elementType = buffer[i++]; // Read the type - if (elementType === 0) break; // If we get a zero it's the last byte, exit - - tempindex = i; /// inlined readCStyleString & removed extra i= buffer.length) return new Error('Corrupt BSON document: illegal CString') - name = buffer.toString('utf8', i, tempindex); - i = tempindex + 1; /// Update index position to after the string + '0' termination - - switch(elementType) { - - case 7: /// = BSON.BSON_DATA_OID: - var buf = new Buffer(12); - buffer.copy(buf, 0, i, i += 12 ); /// copy 12 bytes from the current 'i' offset into fresh Buffer - object[name] = new ObjectID(buf); ///... & attach to the new ObjectID instance - break; - - case 2: /// = BSON.BSON_DATA_STRING: - size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; - object[name] = buffer.toString('utf8', i, i += size -1 ); - i++; break; /// need to get the '0' index "tick-forward" back! - - case 16: /// = BSON.BSON_DATA_INT: // Decode the 32bit value - object[name] = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; break; - - case 1: /// = BSON.BSON_DATA_NUMBER: // Decode the double value - object[name] = buffer.readDoubleLE(i); /// slightly faster depending on dec.points; a LOT cleaner - /// OLD: object[name] = readIEEE754(buffer, i, 'little', 52, 8); - i += 8; break; - - case 8: /// = BSON.BSON_DATA_BOOLEAN: - object[name] = buffer[i++] == 1; break; - - case 6: /// = BSON.BSON_DATA_UNDEFINED: /// deprecated - case 10: /// = BSON.BSON_DATA_NULL: - object[name] = null; break; - - case 4: /// = BSON.BSON_DATA_ARRAY - size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; /// NO 'i' increment since the size bytes are reread during the recursion! - object[name] = deserializeFast(buffer, i, true ); /// pass current index & set isArray = true - i += size; break; - case 3: /// = BSON.BSON_DATA_OBJECT: - size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; - object[name] = deserializeFast(buffer, i, false ); /// isArray = false => Object - i += size; break; - - case 5: /// = BSON.BSON_DATA_BINARY: // Decode the size of the binary blob - size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - buffer[i++]; /// Skip, as we assume always default subtype, i.e. 0! - object[name] = buffer.slice(i, i += size); /// creates a new Buffer "slice" view of the same memory! - break; - - case 9: /// = BSON.BSON_DATA_DATE: /// SEE notes below on the Date type vs. other options... - low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - object[name] = new Date( high * 4294967296 + (low < 0 ? low + 4294967296 : low) ); break; - - case 18: /// = BSON.BSON_DATA_LONG: /// usage should be somewhat rare beyond parseResponse() -> cursorId, where it is handled inline, NOT as part of deserializeFast(returnedObjects); get lowBits, highBits: - low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - - size = high * 4294967296 + (low < 0 ? low + 4294967296 : low); /// from long.toNumber() - if (size < JS_INT_MAX && size > JS_INT_MIN) object[name] = size; /// positive # more likely! - else object[name] = new Long(low, high); break; - - case 127: /// = BSON.BSON_DATA_MIN_KEY: /// do we EVER actually get these BACK from MongoDB server?! - object[name] = new MinKey(); break; - case 255: /// = BSON.BSON_DATA_MAX_KEY: - object[name] = new MaxKey(); break; - - case 17: /// = BSON.BSON_DATA_TIMESTAMP: /// somewhat obscure internal BSON type; MongoDB uses it for (pseudo) high-res time timestamp (past millisecs precision is just a counter!) in the Oplog ts: field, etc. - low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - object[name] = new Timestamp(low, high); break; - -/// case 11: /// = RegExp is skipped; we should NEVER be getting any from the MongoDB server!? - } /// end of switch(elementType) - } /// end of while(1) - return object; // Return the finalized object -} - - -function MinKey() { this._bsontype = 'MinKey'; } /// these are merely placeholders/stubs to signify the type!? - -function MaxKey() { this._bsontype = 'MaxKey'; } - -function Long(low, high) { - this._bsontype = 'Long'; - this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. -} -Long.prototype.getLowBits = function(){ return this.low_; } -Long.prototype.getHighBits = function(){ return this.high_; } - -Long.prototype.toNumber = function(){ - return this.high_ * 4294967296 + (this.low_ < 0 ? this.low_ + 4294967296 : this.low_); -} -Long.fromNumber = function(num){ - return new Long(num % 4294967296, num / 4294967296); /// |0 is forced in the constructor! -} -function Double(value) { - this._bsontype = 'Double'; - this.value = value; -} -function Timestamp(low, high) { - this._bsontype = 'Timestamp'; - this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. -} -Timestamp.prototype.getLowBits = function(){ return this.low_; } -Timestamp.prototype.getHighBits = function(){ return this.high_; } - -/////////////////////////////// ObjectID ///////////////////////////////// -/// machine & proc IDs stored as 1 string, b/c Buffer shouldn't be held for long periods (could use SlowBuffer?!) - -var MACHINE = parseInt(Math.random() * 0xFFFFFF, 10); -var PROCESS = process.pid % 0xFFFF; -var MACHINE_AND_PROC = encodeIntBE(MACHINE, 3) + encodeIntBE(PROCESS, 2); /// keep as ONE string, ready to go. - -function encodeIntBE(data, bytes){ /// encode the bytes to a string - var result = ''; - if (bytes >= 4){ result += String.fromCharCode(Math.floor(data / 0x1000000)); data %= 0x1000000; } - if (bytes >= 3){ result += String.fromCharCode(Math.floor(data / 0x10000)); data %= 0x10000; } - if (bytes >= 2){ result += String.fromCharCode(Math.floor(data / 0x100)); data %= 0x100; } - result += String.fromCharCode(Math.floor(data)); - return result; -} -var _counter = ~~(Math.random() * 0xFFFFFF); /// double-tilde is equivalent to Math.floor() -var checkForHex = new RegExp('^[0-9a-fA-F]{24}$'); - -function ObjectID(id) { - this._bsontype = 'ObjectID'; - if (!id){ this.id = createFromScratch(); /// base case, DONE. - } else { - if (id.constructor === Buffer){ - this.id = id; /// case of - } else if (id.constructor === String) { - if ( id.length === 24 && checkForHex.test(id) ) { - this.id = new Buffer(id, 'hex'); - } else { - this.id = new Error('Illegal/faulty Hexadecimal string supplied!'); /// changed from 'throw' - } - } else if (id.constructor === Number) { - this.id = createFromTime(id); /// this is what should be the only interface for this!? - } - } -} -function createFromScratch() { - var buf = new Buffer(12), i = 0; - var ts = ~~(Date.now()/1000); /// 4 bytes timestamp in seconds, BigEndian notation! - buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; - buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; - - buf.write(MACHINE_AND_PROC, i, 5, 'utf8'); i += 5; /// write 3 bytes + 2 bytes MACHINE_ID and PROCESS_ID - _counter = ++_counter % 0xFFFFFF; /// 3 bytes internal _counter for subsecond resolution; BigEndian - buf[i++] = (_counter >> 16) & 0xFF; - buf[i++] = (_counter >> 8) & 0xFF; - buf[i++] = (_counter) & 0xFF; - return buf; -} -function createFromTime(ts) { - ts || ( ts = ~~(Date.now()/1000) ); /// 4 bytes timestamp in seconds only - var buf = new Buffer(12), i = 0; - buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; - buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; - - for (;i < 12; ++i) buf[i] = 0x00; /// indeces 4 through 11 (8 bytes) get filled up with nulls - return buf; -} -ObjectID.prototype.toHexString = function toHexString() { - return this.id.toString('hex'); -} -ObjectID.prototype.getTimestamp = function getTimestamp() { - return this.id.readUIntBE(0, 4); -} -ObjectID.prototype.getTimestampDate = function getTimestampDate() { - var ts = new Date(); - ts.setTime(this.id.readUIntBE(0, 4) * 1000); - return ts; -} -ObjectID.createPk = function createPk () { ///?override if a PrivateKey factory w/ unique factors is warranted?! - return new ObjectID(); -} -ObjectID.prototype.toJSON = function toJSON() { - return "ObjectID('" +this.id.toString('hex')+ "')"; -} - -/// module.exports.BSON = BSON; /// not needed anymore!? exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.Long = Long; /// ?! we really don't want to do the complicated Long math anywhere for now!? - -//module.exports.Double = Double; -//module.exports.Timestamp = Timestamp; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js deleted file mode 100644 index 8e942dd..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,4843 +0,0 @@ -var bson = (function(){ - - var pkgmap = {}, - global = {}, - nativeRequire = typeof require != 'undefined' && require, - lib, ties, main, async; - - function exports(){ return main(); }; - - exports.main = exports; - exports.module = module; - exports.packages = pkgmap; - exports.pkg = pkg; - exports.require = function require(uri){ - return pkgmap.main.index.require(uri); - }; - - - ties = {}; - - aliases = {}; - - - return exports; - -function join() { - return normalize(Array.prototype.join.call(arguments, "/")); -}; - -function normalize(path) { - var ret = [], parts = path.split('/'), cur, prev; - - var i = 0, l = parts.length-1; - for (; i <= l; i++) { - cur = parts[i]; - - if (cur === "." && prev !== undefined) continue; - - if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { - ret.pop(); - prev = ret.slice(-1)[0]; - } else { - if (prev === ".") ret.pop(); - ret.push(cur); - prev = cur; - } - } - - return ret.join("/"); -}; - -function dirname(path) { - return path && path.substr(0, path.lastIndexOf("/")) || "."; -}; - -function findModule(workingModule, uri){ - var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), - moduleIndexId = join(moduleId, 'index'), - pkg = workingModule.pkg, - module; - - var i = pkg.modules.length, - id; - - while(i-->0){ - id = pkg.modules[i].id; - - if(id==moduleId || id == moduleIndexId){ - module = pkg.modules[i]; - break; - } - } - - return module; -} - -function newRequire(callingModule){ - function require(uri){ - var module, pkg; - - if(/^\./.test(uri)){ - module = findModule(callingModule, uri); - } else if ( ties && ties.hasOwnProperty( uri ) ) { - return ties[uri]; - } else if ( aliases && aliases.hasOwnProperty( uri ) ) { - return require(aliases[uri]); - } else { - pkg = pkgmap[uri]; - - if(!pkg && nativeRequire){ - try { - pkg = nativeRequire(uri); - } catch (nativeRequireError) {} - - if(pkg) return pkg; - } - - if(!pkg){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module = pkg.index; - } - - if(!module){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module.parent = callingModule; - return module.call(); - }; - - - return require; -} - - -function module(parent, id, wrapper){ - var mod = { pkg: parent, id: id, wrapper: wrapper }, - cached = false; - - mod.exports = {}; - mod.require = newRequire(mod); - - mod.call = function(){ - if(cached) { - return mod.exports; - } - - cached = true; - - global.require = mod.require; - - mod.wrapper(mod, mod.exports, global, global.require); - return mod.exports; - }; - - if(parent.mainModuleId == mod.id){ - parent.index = mod; - parent.parents.length === 0 && ( main = mod.call ); - } - - parent.modules.push(mod); -} - -function pkg(/* [ parentId ...], wrapper */){ - var wrapper = arguments[ arguments.length - 1 ], - parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), - ctx = wrapper(parents); - - - pkgmap[ctx.name] = ctx; - - arguments.length == 1 && ( pkgmap.main = ctx ); - - return function(modules){ - var id; - for(id in modules){ - module(ctx, id, modules[id]); - } - }; -} - - -}(this)); - -bson.pkg(function(parents){ - - return { - 'name' : 'bson', - 'mainModuleId' : 'bson', - 'modules' : [], - 'parents' : parents - }; - -})({ 'binary': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - - -}, - - - -'binary_parser': function(module, exports, global, require, undefined){ - /** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; - -}, - - - -'bson': function(module, exports, global, require, undefined){ - var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] || true; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; - -}, - - - -'code': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; -}, - - - -'db_ref': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; -}, - - - -'double': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; -}, - - - -'float_parser': function(module, exports, global, require, undefined){ - // Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; -}, - - - -'index': function(module, exports, global, require, undefined){ - try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -}, - - - -'long': function(module, exports, global, require, undefined){ - // 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; -}, - - - -'max_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; -}, - - - -'min_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; -}, - - - -'objectid': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id, _hex) { - if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId as well as ObjectID -var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' == typeof time) { - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } else { - var unixTime = parseInt(Date.now()/1000,10); - var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; - -}, - - - -'symbol': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; -}, - - - -'timestamp': function(module, exports, global, require, undefined){ - // 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; -}, - - }); - - -if(typeof module != 'undefined' && module.exports ){ - module.exports = bson; - - if( !module.parent ){ - bson(); - } -} - -if(typeof window != 'undefined' && typeof require == 'undefined'){ - window.require = bson.require; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json deleted file mode 100644 index 3ebb587..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../lib/bson/bson" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index ef74b16..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,344 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, offset, 'binary'); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) - return this.buffer; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @method - * @return {number} the length of the binary. - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -/** - * Binary default subtype - * @ignore - */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -module.exports = Binary; -module.exports.Binary = Binary; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js deleted file mode 100644 index d2fc811..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 36f0057..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,323 +0,0 @@ -// "use strict" - -var writeIEEE754 = require('./float_parser').writeIEEE754, - readIEEE754 = require('./float_parser').readIEEE754, - Map = require('./map'), - Long = require('./long').Long, - Double = require('./double').Double, - Timestamp = require('./timestamp').Timestamp, - ObjectID = require('./objectid').ObjectID, - BSONRegExp = require('./regexp').BSONRegExp, - Symbol = require('./symbol').Symbol, - Code = require('./code').Code, - MinKey = require('./min_key').MinKey, - MaxKey = require('./max_key').MaxKey, - DBRef = require('./db_ref').DBRef, - Binary = require('./binary').Binary; - -// Parts of the parser -var deserialize = require('./parser/deserializer'), - serializer = require('./parser/serializer'), - calculateObjectSize = require('./parser/calculate_size'); - -/** - * @ignore - * @api private - */ -// Max Size -var MAXSIZE = (1024*1024*17); -// Max Document Buffer size -var buffer = new Buffer(MAXSIZE); - -var BSON = function() { -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function serialize(object, checkKeys, asBuffer, serializeFunctions, index, ignoreUndefined) { - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, index || 0, 0, serializeFunctions, ignoreUndefined); - // Create the final buffer - var finishedBuffer = new Buffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, finalBuffer, startIndex, serializeFunctions, ignoreUndefined) { - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - // Return the index - return startIndex + serializationIndex - 1; -} - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return deserialize(data, options); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions, ignoreUndefined) { - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// Return BSON -module.exports = BSON; -module.exports.Code = Code; -module.exports.Map = Map; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.BSONRegExp = BSONRegExp; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js deleted file mode 100644 index 83a42c9..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -var Code = function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -module.exports = Code; -module.exports.Code = Code; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index 06789a6..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -module.exports = DBRef; -module.exports.DBRef = DBRef; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js deleted file mode 100644 index 09ed222..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Double.prototype.toJSON = function() { - return this.value; -} - -module.exports = Double; -module.exports.Double = Double; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 6fca392..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js deleted file mode 100644 index f4147b2..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js +++ /dev/null @@ -1,86 +0,0 @@ -try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('bson-ext'); -} catch(err) { -} - -[ './binary_parser' - , './binary' - , './code' - , './map' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './regexp' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './map' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './regexp' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './map' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './regexp' - , './symbol' - , './timestamp' - , './long' - ].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - - // Catch error and return no classes found - try { - classes['BSON'] = require('bson-ext') - } catch(err) { - return exports.pure(); - } - - // Return classes list - return classes; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js deleted file mode 100644 index 6f18885..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,856 +0,0 @@ -// 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @ignore - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Long; -module.exports.Long = Long; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js deleted file mode 100644 index f53c8c1..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js +++ /dev/null @@ -1,126 +0,0 @@ -"use strict" - -// We have an ES6 Map available, return the native instance -if(typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; -} else { - // We will return a polyfill - var Map = function(array) { - this._keys = []; - this._values = {}; - - for(var i = 0; i < array.length; i++) { - if(array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = {v: value, i: this._keys.length - 1}; - } - } - - Map.prototype.clear = function() { - this._keys = []; - this._values = {}; - } - - Map.prototype.delete = function(key) { - var value = this._values[key]; - if(value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - } - - Map.prototype.entries = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - } - } - }; - } - - Map.prototype.forEach = function(callback, self) { - self = self || this; - - for(var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - } - - Map.prototype.get = function(key) { - return this._values[key] ? this._values[key].v : undefined; - } - - Map.prototype.has = function(key) { - return this._values[key] != null; - } - - Map.prototype.keys = function(key) { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - } - } - }; - } - - Map.prototype.set = function(key, value) { - if(this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = {v: value, i: this._keys.length - 1}; - return this; - } - - Map.prototype.values = function(key, value) { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - } - } - }; - } - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable:true, - get: function() { return this._keys.length; } - }); - - module.exports = Map; - module.exports.Map = Map; -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index 03ee9cd..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -module.exports = MaxKey; -module.exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 5e120fb..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -module.exports = MinKey; -module.exports.MinKey = MinKey; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 3ddcb14..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class -* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @property {number} generationTime The generation time of this ObjectId instance -* @return {ObjectID} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - if(!(this instanceof ObjectID)) return new ObjectID(id); - if((id instanceof ObjectID)) return id; - - this._bsontype = 'ObjectID'; - var __id = null; - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if(!valid && id != null){ - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - } else if(valid && typeof id == 'string' && id.length == 24) { - return ObjectID.createFromHexString(id); - } else if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId as well as ObjectID -var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @method -* @return {string} return the 24 byte hex string representation. -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @method -* @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {string} return the 12 byte id binary string. -*/ -ObjectID.prototype.generate = function(time) { - if ('number' != typeof time) { - time = parseInt(Date.now()/1000,10); - } - - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid % 0xFFFF); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @method -* @param {object} otherID ObjectID instance to compare against. -* @return {boolean} the result of comparing two ObjectID's -*/ -ObjectID.prototype.equals = function equals (otherID) { - if(otherID == null) return false; - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @method -* @return {date} the generation date -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -/** -* @ignore -*/ -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @method -* @param {number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @method -* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* Checks if a value is a valid bson ObjectId -* -* @method -* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. -*/ -ObjectID.isValid = function isValid(id) { - if(id == null) return false; - - if(typeof id == 'number') - return true; - if(typeof id == 'string') { - return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id)); - } - return false; -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -module.exports = ObjectID; -module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js deleted file mode 100644 index 03513f3..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js +++ /dev/null @@ -1,310 +0,0 @@ -"use strict" - -var writeIEEE754 = require('../float_parser').writeIEEE754 - , readIEEE754 = require('../float_parser').readIEEE754 - , Long = require('../long').Long - , Double = require('../double').Double - , Timestamp = require('../timestamp').Timestamp - , ObjectID = require('../objectid').ObjectID - , Symbol = require('../symbol').Symbol - , BSONRegExp = require('../regexp').BSONRegExp - , Code = require('../code').Code - , MinKey = require('../min_key').MinKey - , MaxKey = require('../max_key').MaxKey - , DBRef = require('../db_ref').DBRef - , Binary = require('../binary').Binary; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - switch(typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } - case 'undefined': - if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); - return 0; - case 'boolean': - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 - + Buffer.byteLength(value.options, 'utf8') + 1 - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else if(serializeFunctions) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; - } - } - } - - return 0; -} - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = calculateObjectSize; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js deleted file mode 100644 index 5f1cc10..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js +++ /dev/null @@ -1,544 +0,0 @@ -"use strict" - -var writeIEEE754 = require('../float_parser').writeIEEE754, - readIEEE754 = require('../float_parser').readIEEE754, - f = require('util').format, - Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - DBRef = require('../db_ref').DBRef, - BSONRegExp = require('../regexp').BSONRegExp, - Binary = require('../binary').Binary; - -var deserialize = function(buffer, options, isArray) { - var index = 0; - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || buffer.length < size) { - throw new Error("corrupt bson message"); - } - - // Illegal end value - if(buffer[size - 1] != 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, options, isArray); -} - -// Reads in a C style string -var readCStyleStringSpecial = function(buffer, index) { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Grab utf8 encoded string - var string = buffer.toString('utf8', index, i); - // Update index position - index = i + 1; - // Return string - return {s: string, i: index}; -} - -var deserializeObject = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var fieldsAsRaw = options['fieldsAsRaw'] == null ? {} : options['fieldsAsRaw']; - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // Create holding object - var object = isArray ? [] : {}; - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var r = readCStyleStringSpecial(buffer, index); - var name = r.s; - index = r.i; - - // Switch on the type - if(elementType == BSON.BSON_DATA_OID) { - var string = buffer.toString('binary', index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - } else if(elementType == BSON.BSON_DATA_STRING) { - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Validate if string Size is larger than the actual provided buffer - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Add string to object - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - } else if(elementType == BSON.BSON_DATA_INT) { - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } else if(elementType == BSON.BSON_DATA_NUMBER) { - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - } else if(elementType == BSON.BSON_DATA_DATE) { - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if(elementType == BSON.BSON_DATA_BOOLEAN) { - // Parse the boolean value - object[name] = buffer[index++] == 1; - } else if(elementType == BSON.BSON_DATA_UNDEFINED || elementType == BSON.BSON_DATA_NULL) { - // Parse the boolean value - object[name] = null; - } else if(elementType == BSON.BSON_DATA_BINARY) { - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - } else if(elementType == BSON.BSON_DATA_ARRAY) { - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - var arrayOptions = options; - - // All elements of array to be returned as raw bson - if(fieldsAsRaw[name]) { - arrayOptions = {}; - for(var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - // Set the array to the object - object[name] = deserializeObject(buffer, arrayOptions, true); - // Adjust the index - index = index + objectSize; - } else if(elementType == BSON.BSON_DATA_OBJECT) { - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Validate if string Size is larger than the actual provided buffer - if(objectSize <= 0 || objectSize > (buffer.length - index)) throw new Error("bad embedded document length in bson"); - - // We have a raw value - if(options['raw']) { - // Set the array to the object - object[name] = buffer.slice(index, index + objectSize); - } else { - // Set the array to the object - object[name] = deserializeObject(buffer, options, false); - } - - // Adjust the index - index = index + objectSize; - } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { - // Create the regexp - var r = readCStyleStringSpecial(buffer, index); - var source = r.s; - index = r.i; - - var r = readCStyleStringSpecial(buffer, index); - var regExpOptions = r.s; - index = r.i; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { - // Create the regexp - var r = readCStyleStringSpecial(buffer, index); - var source = r.s; - index = r.i; - - var r = readCStyleStringSpecial(buffer, index); - var regExpOptions = r.s; - index = r.i; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if(elementType == BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - } else if(elementType == BSON.BSON_DATA_SYMBOL) { - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Validate if string Size is larger than the actual provided buffer - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - } else if(elementType == BSON.BSON_DATA_TIMESTAMP) { - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - } else if(elementType == BSON.BSON_DATA_MIN_KEY) { - // Parse the object - object[name] = new MinKey(); - } else if(elementType == BSON.BSON_DATA_MAX_KEY) { - // Parse the object - object[name] = new MaxKey(); - } else if(elementType == BSON.BSON_DATA_CODE) { - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Validate if string Size is larger than the actual provided buffer - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Function string - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - } else if(elementType == BSON.BSON_DATA_CODE_W_SCOPE) { - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Validate if string Size is larger than the actual provided buffer - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Javascript function - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = deserializeObject(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = deserialize diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js deleted file mode 100644 index 285e45b..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js +++ /dev/null @@ -1,909 +0,0 @@ -"use strict" - -var writeIEEE754 = require('../float_parser').writeIEEE754, - readIEEE754 = require('../float_parser').readIEEE754, - Long = require('../long').Long, - Map = require('../map'), - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - BSONRegExp = require('../regexp').BSONRegExp, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - DBRef = require('../db_ref').DBRef, - Binary = require('../binary').Binary; - -var regexp = /\x00/ - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -} - -var serializeString = function(buffer, key, value, index) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = (size + 1 >> 24) & 0xff; - buffer[index + 2] = (size + 1 >> 16) & 0xff; - buffer[index + 1] = (size + 1 >> 8) & 0xff; - buffer[index] = size + 1 & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -} - -var serializeNumber = function(buffer, key, value, index) { - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; -} - -var serializeUndefined = function(buffer, key, value, index) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -var serializeBoolean = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -} - -var serializeDate = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -var serializeRegExp = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -} - -var serializeBSONRegExp = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options, index, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; -} - -var serializeMinMax = function(buffer, key, value, index) { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -var serializeObjectId = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - buffer.write(value.id, index, 'binary') - - // Ajust index - return index + 12; -} - -var serializeBuffer = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; -} - -var serializeObject = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - // Write size - var size = endIndex - index; - return endIndex; -} - -var serializeLong = function(buffer, key, value, index) { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -var serializeDouble = function(buffer, key, value, index) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; -} - -var serializeFunction = function(buffer, key, value, index, checkKeys, depth) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -} - -var serializeCode = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined) - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -} - -var serializeBinary = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; -} - -var serializeSymbol = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -} - -var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if(null != value.db) { - endIndex = serializeInto(buffer, { - '$ref': value.namespace - , '$id' : value.oid - , '$db' : value.db - }, false, index, depth + 1, serializeFunctions); - } else { - endIndex = serializeInto(buffer, { - '$ref': value.namespace - , '$id' : value.oid - }, false, index, depth + 1, serializeFunctions); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -} - -var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined) { - startingIndex = startingIndex || 0; - - // Start place to serialize into - var index = startingIndex + 4; - var self = this; - - // Special case isArray - if(Array.isArray(object)) { - // Get object keys - for(var i = 0; i < object.length; i++) { - var key = "" + i; - var value = object[i]; - - // Is there an override value - if(value && value.toBSON) { - if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); - value = value.toBSON(); - } - - var type = typeof value; - if(type == 'string') { - index = serializeString(buffer, key, value, index); - } else if(type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if(value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if(type == 'undefined' || value == null) { - index = serializeUndefined(buffer, key, value, index); - } else if(value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if(Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if(value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if(type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if(value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if(typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if(value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if(value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if(value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if(value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else if(object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while(!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if(done) continue; - - // Get the entry values - var key = entry.value[0]; - var value = entry.value[1]; - - // Check the type of the value - var type = typeof value; - - // Check the key and throw error if it's illegal - if(key != '$db' && key != '$ref' && key != '$id') { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - - if (checkKeys) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } - } - - // console.log("---------------------------------------------------") - // console.dir("key = " + key) - // console.dir("value = " + value) - - if(type == 'string') { - index = serializeString(buffer, key, value, index); - } else if(type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if(value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if(value === undefined && ignoreUndefined == true) { - } else if(value === null || value === undefined) { - index = serializeUndefined(buffer, key, value, index); - } else if(value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if(Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if(value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if(type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if(value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if(value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if(value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if(value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if(value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if(value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - if(object.toBSON) { - if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); - object = object.toBSON(); - if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); - } - - // Iterate over all the keys - for(var key in object) { - var value = object[key]; - // Is there an override value - if(value && value.toBSON) { - if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); - value = value.toBSON(); - } - - // Check the type of the value - var type = typeof value; - - // Check the key and throw error if it's illegal - if(key != '$db' && key != '$ref' && key != '$id') { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - - if (checkKeys) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } - } - - if(type == 'string') { - index = serializeString(buffer, key, value, index); - } else if(type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if(value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if(value === undefined && ignoreUndefined == true) { - } else if(value === null || value === undefined) { - index = serializeUndefined(buffer, key, value, index); - } else if(value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if(Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if(value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if(type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if(value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if(value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if(value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if(value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if(value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if(value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = serializeInto; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js deleted file mode 100644 index 6b148b2..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ -function BSONRegExp(pattern, options) { - if(!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern; - this.options = options; - - // Validate options - for(var i = 0; i < options.length; i++) { - if(!(this.options[i] == 'i' - || this.options[i] == 'm' - || this.options[i] == 'x' - || this.options[i] == 'l' - || this.options[i] == 's' - || this.options[i] == 'u' - )) { - throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); - } - } -} - -module.exports = BSONRegExp; -module.exports.BSONRegExp = BSONRegExp; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index 7681a4d..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -module.exports = Symbol; -module.exports.Symbol = Symbol; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index 7718caf..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,856 +0,0 @@ -// 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @ignore - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Timestamp; -module.exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json deleted file mode 100644 index 1eb5b0a..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "version": "0.4.16", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [], - "repository": { - "type": "git", - "url": "git://github.com/mongodb/js-bson.git" - }, - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "devDependencies": { - "nodeunit": "0.9.0", - "gleak": "0.2.3", - "one": "2.X.X", - "benchmark": "1.0.0", - "colors": "1.1.0" - }, - "config": { - "native": false - }, - "main": "./lib/bson/index", - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "test": "nodeunit ./test/node" - }, - "browser": "lib/bson/bson.js", - "license": "Apache-2.0", - "gitHead": "4166146d0539a050946c1cae9188f274dd751ed9", - "homepage": "https://github.com/mongodb/js-bson", - "_id": "bson@0.4.16", - "_shasum": "e78fb993535123851f857fb83c7f68b1cd7e6caa", - "_from": "bson@>=0.4.0 <0.5.0", - "_npmVersion": "2.14.4", - "_nodeVersion": "4.1.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "octave", - "email": "chinsay@gmail.com" - }, - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "e78fb993535123851f857fb83c7f68b1cd7e6caa", - "tarball": "http://registry.npmjs.org/bson/-/bson-0.4.16.tgz" - }, - "_resolved": "https://registry.npmjs.org/bson/-/bson-0.4.16.tgz" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js deleted file mode 100644 index c707cfc..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js +++ /dev/null @@ -1,21 +0,0 @@ - -var gleak = require('gleak')(); -gleak.ignore('AssertionError'); -gleak.ignore('testFullSpec_param_found'); -gleak.ignore('events'); -gleak.ignore('Uint8Array'); -gleak.ignore('Uint8ClampedArray'); -gleak.ignore('TAP_Global_Harness'); -gleak.ignore('setImmediate'); -gleak.ignore('clearImmediate'); - -gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); -gleak.ignore('DTRACE_NET_STREAM_END'); -gleak.ignore('DTRACE_NET_SOCKET_READ'); -gleak.ignore('DTRACE_NET_SOCKET_WRITE'); -gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); -gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); -gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); -gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); - -module.exports = gleak; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml deleted file mode 100644 index b0fb9f4..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" - - "0.12" - - "iojs-v1.8.4" - - "iojs-v2.5.0" - - "iojs-v3.3.0" - - "4" -addons: - apt: - sources: - - ubuntu-toolchain-r-test - packages: - - g++-4.8 -before_install: - - '[ "${TRAVIS_NODE_VERSION}" != "0.8" ] || npm install -g npm@1.4.28' - - if [[ $TRAVIS_OS_NAME == "linux" ]]; then export CXX=g++-4.8; fi - - $CXX --version - - npm explore npm -g -- npm install node-gyp@latest \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md deleted file mode 100644 index 7428b0d..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md +++ /dev/null @@ -1,4 +0,0 @@ -kerberos -======== - -Kerberos library for node.js \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp deleted file mode 100644 index 6655299..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp +++ /dev/null @@ -1,46 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'kerberos', - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'include_dirs': [ '> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,kerberos.target.mk)))),) - include kerberos.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/fmason/hub/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/fmason/.node-gyp/0.12.7/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/fmason/.node-gyp/0.12.7" "-Dmodule_root_dir=/home/fmason/hub/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../.node-gyp/0.12.7/common.gypi $(srcdir)/../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d deleted file mode 100644 index 0bc3206..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/kerberos.node := rm -rf "Release/kerberos.node" && cp -af "Release/obj.target/kerberos.node" "Release/kerberos.node" diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d deleted file mode 100644 index 2ec56f5..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/kerberos.node := g++ -shared -pthread -rdynamic -m64 -Wl,-soname=kerberos.node -o Release/obj.target/kerberos.node -Wl,--start-group Release/obj.target/kerberos/lib/kerberos.o Release/obj.target/kerberos/lib/worker.o Release/obj.target/kerberos/lib/kerberosgss.o Release/obj.target/kerberos/lib/base64.o Release/obj.target/kerberos/lib/kerberos_context.o -Wl,--end-group -lkrb5 -lgssapi_krb5 diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d deleted file mode 100644 index cfee5be..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d +++ /dev/null @@ -1,4 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/base64.o := cc '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/base64.o.d.raw -c -o Release/obj.target/kerberos/lib/base64.o ../lib/base64.c -Release/obj.target/kerberos/lib/base64.o: ../lib/base64.c ../lib/base64.h -../lib/base64.c: -../lib/base64.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d deleted file mode 100644 index a313cb5..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d +++ /dev/null @@ -1,71 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberos.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos.o ../lib/kerberos.cc -Release/obj.target/kerberos/lib/kerberos.o: ../lib/kerberos.cc \ - ../lib/kerberos.h /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /usr/include/mit-krb5/gssapi/gssapi.h \ - /usr/include/mit-krb5/gssapi/gssapi_generic.h \ - /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ - /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ - /usr/include/mit-krb5/krb5/krb5.h ../node_modules/nan/nan.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ - /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ - /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ - ../node_modules/nan/nan_callbacks.h \ - ../node_modules/nan/nan_callbacks_12_inl.h \ - ../node_modules/nan/nan_maybe_pre_43_inl.h \ - ../node_modules/nan/nan_converters.h \ - ../node_modules/nan/nan_converters_pre_43_inl.h \ - ../node_modules/nan/nan_new.h \ - ../node_modules/nan/nan_implementation_12_inl.h \ - ../node_modules/nan/nan_persistent_12_inl.h \ - ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h \ - ../lib/kerberosgss.h ../lib/worker.h ../lib/kerberos_context.h -../lib/kerberos.cc: -../lib/kerberos.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/usr/include/mit-krb5/gssapi/gssapi.h: -/usr/include/mit-krb5/gssapi/gssapi_generic.h: -/usr/include/mit-krb5/gssapi/gssapi_krb5.h: -/usr/include/mit-krb5/gssapi/gssapi_ext.h: -/usr/include/mit-krb5/krb5.h: -/usr/include/mit-krb5/krb5/krb5.h: -../node_modules/nan/nan.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: -/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/src/smalloc.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: -../node_modules/nan/nan_callbacks.h: -../node_modules/nan/nan_callbacks_12_inl.h: -../node_modules/nan/nan_maybe_pre_43_inl.h: -../node_modules/nan/nan_converters.h: -../node_modules/nan/nan_converters_pre_43_inl.h: -../node_modules/nan/nan_new.h: -../node_modules/nan/nan_implementation_12_inl.h: -../node_modules/nan/nan_persistent_12_inl.h: -../node_modules/nan/nan_weak.h: -../node_modules/nan/nan_object_wrap.h: -../lib/kerberosgss.h: -../lib/worker.h: -../lib/kerberos_context.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d deleted file mode 100644 index fcffab4..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d +++ /dev/null @@ -1,70 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberos_context.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos_context.o ../lib/kerberos_context.cc -Release/obj.target/kerberos/lib/kerberos_context.o: \ - ../lib/kerberos_context.cc ../lib/kerberos_context.h \ - /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /usr/include/mit-krb5/gssapi/gssapi.h \ - /usr/include/mit-krb5/gssapi/gssapi_generic.h \ - /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ - /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ - /usr/include/mit-krb5/krb5/krb5.h ../node_modules/nan/nan.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ - /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ - /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ - ../node_modules/nan/nan_callbacks.h \ - ../node_modules/nan/nan_callbacks_12_inl.h \ - ../node_modules/nan/nan_maybe_pre_43_inl.h \ - ../node_modules/nan/nan_converters.h \ - ../node_modules/nan/nan_converters_pre_43_inl.h \ - ../node_modules/nan/nan_new.h \ - ../node_modules/nan/nan_implementation_12_inl.h \ - ../node_modules/nan/nan_persistent_12_inl.h \ - ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h \ - ../lib/kerberosgss.h -../lib/kerberos_context.cc: -../lib/kerberos_context.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/usr/include/mit-krb5/gssapi/gssapi.h: -/usr/include/mit-krb5/gssapi/gssapi_generic.h: -/usr/include/mit-krb5/gssapi/gssapi_krb5.h: -/usr/include/mit-krb5/gssapi/gssapi_ext.h: -/usr/include/mit-krb5/krb5.h: -/usr/include/mit-krb5/krb5/krb5.h: -../node_modules/nan/nan.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: -/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/src/smalloc.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: -../node_modules/nan/nan_callbacks.h: -../node_modules/nan/nan_callbacks_12_inl.h: -../node_modules/nan/nan_maybe_pre_43_inl.h: -../node_modules/nan/nan_converters.h: -../node_modules/nan/nan_converters_pre_43_inl.h: -../node_modules/nan/nan_new.h: -../node_modules/nan/nan_implementation_12_inl.h: -../node_modules/nan/nan_persistent_12_inl.h: -../node_modules/nan/nan_weak.h: -../node_modules/nan/nan_object_wrap.h: -../lib/kerberosgss.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d deleted file mode 100644 index d4cefbf..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d +++ /dev/null @@ -1,16 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberosgss.o := cc '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberosgss.o ../lib/kerberosgss.c -Release/obj.target/kerberos/lib/kerberosgss.o: ../lib/kerberosgss.c \ - ../lib/kerberosgss.h /usr/include/mit-krb5/gssapi/gssapi.h \ - /usr/include/mit-krb5/gssapi/gssapi_generic.h \ - /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ - /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ - /usr/include/mit-krb5/krb5/krb5.h ../lib/base64.h -../lib/kerberosgss.c: -../lib/kerberosgss.h: -/usr/include/mit-krb5/gssapi/gssapi.h: -/usr/include/mit-krb5/gssapi/gssapi_generic.h: -/usr/include/mit-krb5/gssapi/gssapi_krb5.h: -/usr/include/mit-krb5/gssapi/gssapi_ext.h: -/usr/include/mit-krb5/krb5.h: -/usr/include/mit-krb5/krb5/krb5.h: -../lib/base64.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d deleted file mode 100644 index 02da394..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d +++ /dev/null @@ -1,57 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/worker.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/worker.o.d.raw -c -o Release/obj.target/kerberos/lib/worker.o ../lib/worker.cc -Release/obj.target/kerberos/lib/worker.o: ../lib/worker.cc \ - ../lib/worker.h /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ - ../node_modules/nan/nan.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ - /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ - /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - ../node_modules/nan/nan_callbacks.h \ - ../node_modules/nan/nan_callbacks_12_inl.h \ - ../node_modules/nan/nan_maybe_pre_43_inl.h \ - ../node_modules/nan/nan_converters.h \ - ../node_modules/nan/nan_converters_pre_43_inl.h \ - ../node_modules/nan/nan_new.h \ - ../node_modules/nan/nan_implementation_12_inl.h \ - ../node_modules/nan/nan_persistent_12_inl.h \ - ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h -../lib/worker.cc: -../lib/worker.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: -../node_modules/nan/nan.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: -/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/src/smalloc.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -../node_modules/nan/nan_callbacks.h: -../node_modules/nan/nan_callbacks_12_inl.h: -../node_modules/nan/nan_maybe_pre_43_inl.h: -../node_modules/nan/nan_converters.h: -../node_modules/nan/nan_converters_pre_43_inl.h: -../node_modules/nan/nan_new.h: -../node_modules/nan/nan_implementation_12_inl.h: -../node_modules/nan/nan_persistent_12_inl.h: -../node_modules/nan/nan_weak.h: -../node_modules/nan/nan_object_wrap.h: diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node deleted file mode 100755 index 2bcec8ec0121131fd8bf4a7bd02d25f4198f6fc3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 85259 zcmeFad3=;b@;^R-fC0org$3~%6&3Ix0fGTU6T-km14IIX2ZoSLAQF<8OgKa|Y!YM~ zN8^33(bW}iyb(o%AVJpyT~}Ez@T7;hinwXJZiK~9=Me(vhjN{eyJC#w&!8p zTuG^}qg?}BgQmJy)+VK<4oFE{ol<)=N9xwiHPDqn+Mbv9Oz6`kA@%H(9&0lby5zXe zopV&r{rTATj-%APL=Q4eX`M1_U%gwdHTvwRu<+ujS=PPi%3cro`y#~M6 z;rDv{-iY6u@XMc@@p}t?Z^iE&_`MUqP5AvQe(%9Af9};6*L}FI!tebCegM~p%;!gN zebjvBWi@^u!|&txeGjk&JH^*Q{m!|%c8ZrPK0U)^UXZSvf7$LkrB zZt;$7$v$T8irc=vcIm#u-+JPK0T)iWzW<80w+?#Z9N(QKE0zyG;NzYD_~wAWFSu>^ zd0(#W+q3&gr@l7(vVXh!5Bu}7e{A*MKIxf%HXJ{9MR@*236-zBx#!u?w+Fm3_n|&1 zeLkPp`onF*XWh7R_YI4mS=m-GKPzYR!5=rCwPnwbzD2uQcJ=*uVgDgRavr&q za!%G>_dV&ot8N>9$Ii8V8^&~R+jzp<6}OzS^|;4g$GE3YT6)sn+lDuGJMyVzecyWG z$;T5*-uk@c&TP*=zj|x>mOXcLfBC}KXMA?=+Rv`Nr0}(mj%(A zto-S+eYXww{i*LWFCOyN6Cbwpo$;@WW*&CTZ6%ILjix$Yy21lzj*rD(d4S91tOdIz z1I~SrjWC~|KDcxISU7iQmdYIF5by#*y=9=&dumyp3en8GcTjal)`8RMg?;9u9$=o#~-V9RFl}+8O-=apqeRN6$yZ zi6^JW(evmy{=Y7c9+Kk3&((3}^=X_qd~FlB;6K9-5YsuAJD0yG&ieW*{Gqct;T;Iy8GaY^(3yT#K%Ymudbt{>YZskqJT)xy?d7U`K_mR| z8~!AL{vgoTZq)Gm`r`Tm>x<*eepw@qG5BSOKg7GHX~cMgFE-GL*d{6HgTmFOS%b2R<|$jzUR%=nE)&ese+!;F(+#u={3 zT_ePQdbyhZsu5orJau`HYk$}IuNs8841-@$o|GnyfP2f2!oSo*$`lP_S;@~bqlaBa z500MCmG$1s)oeD7>&?9OA>VO)*9E%2*NjtO_|_I{#5ab)56JJN-?BpE+su5=bnI*R zI{NfTJ>Sc<{Si&y!|;6=bsfj4yjJ6n(HGY|(ND*H*%avcK-VFz?TJSTCCKFGEa>?t zoIEs{bC^_v_sM$i<=WNG?#Fc1^saXFFDQvjUNt}KQ9=0nv8xNKddwJN^KG{ zmt(J!jQ(9_d`EfQT))v$!2MF zxrQSCQ~z78(}?%s2mEO@{#?0A!{x?L#>CNc1<1s&CTn^pNB9ii_Hp%2*q3(9Y`5;_ znfbQY=iE5)(^XI~cR@vYLAAfI%3o06Dkv!}FLf2TsR#jN)ug=LIR^ah?#t-u>B;)_%GI+b1w81 z`G=+EmsKp9==0~4Lu*jOgi>Ewu?PA*ck-Da%kV7L`1G?2%W8a)?rCY>!t&xWUw%eAM<2L_lV^Nu}u)Jf}YG2htUlm07wN{ZVVi!HB8IUAx*bHCc z{OrQAvN?rC^F33~)b_WL;|u+TIrjAPQ(rKQ5ZvumoV;9QZ$-|fK8DD9jV+#_MZS*}q;994}^75>F#d9u8t z^cpW-V=t`iG+9g$5sbT>!o@n*S0%HhpF{{E>sBl3lxY=pc0X+f-%v*q+nqxxkf}y&niJcXdeJE^vHaFRcZO$v^1DtLRH0r z>Hd<8Sn2c5ESe0jPovnHc-oRmpN=&cV3cQZk*|{RGTl>ERZ)d#Suj$E6fB$qGrqAr zW0Rg^#n1nUV5pX>Y~C*24gFt#ZmmQPKig#2)<>Sc$CHc zc#!~=M^AIOKu4*TqVd`2(}R}b1<-wJL57pcp#D;LoIywQNk)<`oY{=>7FK5$*36w} zR-Be%!~{gavWT7G9=04@_h97=;l!&5!UUk<#ic&D5?s|+RaIV5P*#Bi0u;xrk!aoL;EkPFQgHaZ{JKuRdnVZpV2A)`bz zV8m!}&yHNG036m%3V671R;JRgP0|G?lz#EB&K08*NjQ4ODl*-iWujt28 zWrnE;v&u^6mivnHDqvq<6+?QA{5oz&RW&MRZ6K?lF8ZU&ijEe$(pY2t&&SG$k&LBJ z`Tu+{N3eXU7yl839F_*jVkFUvT|y^TT3Wk-rDlq(QYVu~wq70i>S;ySY}&~73_Yd4zSuj4 zicYwgQaoO6vyzk@TJlF=V>3BFiG z(eSc8pIo@0eN>Ar6QQE01RZA>tD}ybq}s_(cWT9s1Ziogvtsiu?b~sFJUQ@J_)+h6 zm|%v3>7-zd&W5><3LU|XB;>-!G!BZQ$G;@YkJ@`q4Ne%0h9mXbDNxmKYALcHe?7gJ zb(b-rqN>P;ac!eRoJhV!br@f|5v;0Wm!4H{Qv41{@As}+7PG zr~rikcf2u7B6L)82ddKYi)u=%d@(&8iKXWp2s&~EilZWE(q$l2WP~7Sc~RvOVP}qC zI6XOPfhPPo_h7-T&m~YI7i1Sqo>nkD-!rvfa@Hh|^eZef0#x~m3otdk%fx&vxuX=W z$SB?^`P0T_<$J~#V7Rk$vOA6zqlF?2@0wpVC%r(_;3!Hkm4#I>hVWZ3AICWhDo2jc zv_(a*6%Gs*`XVs9>tvx(bA5j9IZ$~mz#(AaTyB@4m*SdA-Oe+sb_Bu{Ll^r%Sh2*S zqw5rvRu-07I7d`!wy=o1;TR*8 zi^@5(=&;(HW1fx;W+8NFNE0?+ zVAM{v?^JLds3o;VZ0jV%SliMibUCXJ?^x|d@>C}!5VzGFS2od+V#t%XP?Fzp#E(-Z z6mlQ5BxhQIC!@-TDx@0pew$=4m~EM%=LtgGtkUpZdF2_&t^!{$yI|PKBO;%MTc3xWobJk= zIWucqPC*)^6yljP(QyPrwj*xAu!2cB({vylE+6$RC07@Dnp^{k_{>{{`ZjAfJcHkz zk8lZ2Kao#5ebbixy5o00)5;d7jTGkAu6!b${X-s6oGn3=u8T|GB-FP|yJ7_PqHO$6 z_l}MsP134w*^zq>^yucotwH%=FPAIf|B?T+Oq6Dn+?#W`+(6|Ww*+?zd%7+Mjz0;I zd4_4v1l*^z6nFTNTvr>M|BzBV$+Dm876aD|Al%(`Z=`=0*AUajd-nf$bUvQ2=;3fgh(qr2^S)5IQT&p{wZtxd2#TYwFRD_&Z5?Q_eOtMz92r2pAt z;s0#mU2SfGNYC$~I6p}i9=F~jKPeVIIf8Y$`dj!LExg;pn@1<4b&!R>$)ZoS@NNsA zVc{RJ@R=6=Nel0_@cf>M^OI-cA9Ikn&b08yTlm=)-aJwvt@AAW9Tt71g|D;li!HqK ztPh)OE&Np${Yndeg@tdl@aY!*W(#i~g^<=J3*ThXud?uWS@_i!{#gsZ#=@_*@XZ$f zdJDhV!Urt;77K44<&f5`7CvOrZ@2J^EWEPti!J=kCeARP)LQsv3twsB`{U^j{zP-K zZggAtTQo}k9c1C7nbqY=weUL2>P{IJ9*H9IlWF0jdEJHQqN4KXysNw9S$HR=vt_1* zN1}@S%(n1OzGmY*3y(w+`Kh$~skjvI{@KESZk4MuYKdUXg^Gp>R*I4+z5o(vK*}~(|tH{r03y(*6B0pO!eE$g6 z<=SfDO-h#5?G}E3MXxOUp%#9Zg}>9n@3HWQS$J1MRR4!t_#_Lz&cdfy_#-TQe+z%4 zg?C$c%}F;7vhYV+^r;s97z>|a;RjmyObdUkh4)(c<1Bohg&$<$XIl8d7JjycA7bI> zS@;tye5Hjy(ZVmb@F!XLS_^-&gAPaxGg-^BcnHE07!e?3dObb8G!h0=z zwuR5L@Z&A~Obc(H!Y{V)UJGAq;d3nfN(+C6g>SU*XIl81 zE&S~kzRAMpTKH8K-fU5%b+v_`Y|*c=@KY>&vxU#I@S83CSr&eag`aBSw_5mo3%}jM zKWyQZg>SU*yDa=P3%|$0Pq*-{u2KI#+rlSV_!$;H#lp|D@ck|PITqe+;m@`3gDm`c z7CzO&KV#uDEd2QvKGVX_vhZFDe}RS1v+ye{{7eh~Hw!=8!WUThc@}=Qg|D>mg%*CX zg`Z>LYc2eh7Jj9LFS78B7QWcR-)!N17QV^Cmst2!7JjaUUv1&%S@<;;zSP1uTlfnt z{ALS3-@O_!NEgpY0Me}2yGYCEwTvd@$kF0)I-FTZeFy!0!|0mLc3I@Y{s{M7UPqR|#{A5Uv#X zCBobqgl7x9mN2&j;XHvKCp>^~roaynK9q2(z;_d7i63?gd@JF@38x5rEn$}KVVA&H z5N639-t`OT|7XH(!rKMDm@tz>c#FVQgjuqOn+3j*@G*o}3p|JLK*CJ|pG%mfdAL#F zsf3RsTr2PygpVg&DeySLg9y(Scr@X`g!2R*Mwq2|I8)#ugij!xD)7;SPbBOXcmUy( z2&V{q5Mh?uVVA%?2@fT_>u0e);Z(xg1>XBC;55Qp1pbaNOYCs7z&i;KC%jtVPYJW6 z4mSz>K4F&9;YNYqCOndGt-!AmW+@!56!;~=8H8sGyp}La-*BG5j}snEI8)#U2#+D0 zD)8NeS+a)R0^drQrD`}u;A;u96b-uszJf4I(D1IG#Quac32ztpV!~O3w+LKCn5Aa8 zS>Ou^XA@p6@EpS92{#FRE@76A;YNX{5}rV~R^T%TPb6F^@HoO=!m|Y)O*n^ep1{Kh zpFucN;30%r3Wie!KALbYVYk2o2u~uMBJe?kS=xnN0{0}$k}kY!uh^e3OS$lNf%mQf z%n~lVMd0rUvvdnL3%rwXKH=2@e@d98SGY;w_X)G)3O5S;Her@p;aY)TCCm~lTq*EN zgl7_-E$~{x=Mc^l_;JGL63!I(0mA1IP8IlW!Yq-(Zh>zl%+e^FBJj0@SrUa^0$)Lx zrA>I(f5rZUXA|Bo@Wq4+32za&iZDxR|-6iFcVOCw!otamlDnsco^Xe31N5gtrTPG2!Kew+LKC_|Jr!1-_7Q z9pTji&mmk-xJlr12{#aK1U%gv>b(lB-cb4>VCoHxy$`aj?T>bE;0qOkNF@0J3_$WD zI1*7q@z1;-u)5Y*ll)-bMF;rB68v=it*c}&wU*YuwPwCNv+ zr4M!6OuEq6wYW_84&FoBx;+Oh>N0Bs3b+yMjRNkwS#8@XuQ$}~8clzNMZbPeS8w1Y z@A{pmdlR;J-`Z0no%{Ba&Tpf$H?XPgQ}(YNdk*@!YL55TjZH=~SO&iE?~i%C{gm6K zPQsE<^WX-vHg!t{VZ!$tO865|3c95}jBftpAl#JITDSq!;sBsAR@;_Y;Taep`N&!q ze!^$sbF_QobZ_uiLIMWM4Sb^x!vws67BvvDjbu52P2S+dw%Wy@8k6=TN&X81 z8hxZ;T3;e59z) zk`6WZosAI18|>;0Rs&kx9~K*h<>_ts(VIMemwNC&ZEZP$mxHdlJ#GH9tU&$1Cxw1# zlDDA^b@~`A5^rFe8qO=~bx16d%?cj{Od~t2Mu(iBCn;-F{lF%CPRIdr6+X1Cfqp~X zUPW}E+M-H}iUpapAR^)7{%Q;q^=tAx_@kERue`>{a}6-ROPtQ5J=pf-YKSccS*Y$Q!iL>a%-=MgBZ{R2Hp>l(d(wDLHINMwT{;q|F{U4-{BvD zFSx8BNI^<4JE@_$W{zXp(aBFw>{YitxlVOGHDS?-s*+2h;RA0=b_x{f@*hlp32gHQ zGn2^qJcP(b{b2)A$T)<1q>v{#m(bW_7a@fp9k|qx?=VWJ_c6NpdfoiPLNu>nb1yVU zS2)%a<pBe0Q8?SV~ge~XT< zM@&(F!x(khNeR)}jL_nKfoWhiS5e&aDDL^++Txb9lUK$|u3rgCBju@G{1=FtFU_b^ z2@TDG>?D6L!$$H;uQUW1NH-s%n_oh0w3hXpYDBZFKZ*4!i`0P)Il=mYH>24b$absO zW#uDi1X|LX5jFhqn_;R2O2Dc^-jMn0T%i&=^zW}io%X*xwtv(f-D>WKE`HtKd%vfe zbTI0zUgI)oXYVBVZRhsx*7vu@AFOVT8NaOE`0)SpW`#$7gS34Y=GM;s-JV+Y8}biU zqhrS3zti#G{TkzEIpdpL9GbNS3pZ7bqQheu1~#e5P^2e#kEAqp6!7B%UosmngnYa{ zLYE?`XS2GNoPwUs@TycXUQS>m+SJ9s=LUADIp}WN)9dhig&j4&k742nzsG<#{JI-{ zr&;`tj>E5~;rAV`o$@<}9W}pln_m|2hTo0Q59jv==I_k!anWnX`O%)7-=E|03$vr< zw-57(%@jZ8LSv{Ll38*_B5$=`Bz&R zVnRav4Sn@)>M(d{?Q>0Na3$BjjS@09_*dp;RRXeS(YY<{?Og4_eaIaae(fu{!dKNb z5FX{__~3I)@oE?-#s~J1=yFY@UKENJ)sLM+>BnFfX+|a0dKfP^uotrA26n3=f$psY zQ?-MiL-(fQv$XC|FJnZt1!yqL4K1!z8}WHkLtAqFPhD7@EUe^+FA84_w?mDW;dX#r z1t3Lk$k&(~cxo|5Wb3A#7&%zSyxb9ss~E@QT-4m!BZS6H`KsMJ_|B1eQm1f?)>g_TDyl>?Rka3kaTc>Ne0_6reE^nIPe`Lgn>83N%ojhQKF308 zyRI3msEMmd15FsER$^$i6gcqqhBBc-t%`X-dF$43Qt*o_Fi=i#ktp~AN0=SzGio&e z1-Ga{BG0-!(5n;CcT&TT$@Nc2w~?H}AoKz$hM!529MMIL@_)o&M)@ZQix%~S=uRvD zJ+a_ZmFR6$@f4=0n%OH>`Mtr_DF1QV7-{lHwOEnPQ9i}Am47b8;Vh~!nt0T+)K*ZG zUoK;a^1qi!?p9;4G^za0&{W^-Pf?>OoL(fSV<@)m2idWd=w6c=KKCDy6FhYwYxUmh zVf4;vNgRk4l+8QTGK$vlfxm|?<=XPN-%*R`c*{3(#Y!=qbwO5v*_WmL7`_z8){%N0 zaBm#r+VEsdFbcPY_qL;dEQY=*u(a5S}k zhEJ^@;~&oDKv=HzEjTEf`>;7|T6RNMtP<8ST`0E>f!nGC zFnba9bg8*JBKsJGkxx)+c?0iDQ(CjS5RI+x+4TjZUrykc7YCs)!k@Ys6e!{lvy$t1 zFq9L#gL|6Xz^B3Cs9ciNA_&V5TqDoXBH;c6u32@bwfPU96u6i5mskRGz!o`tBO0~* zIl&3ohc+~UAOT9qYH46FgazPJ4H8Q)1a0d}j(jLyPlWuc7%aopv{dA1A)*gQ{ydCC z`L})T7<$WWK~zCgbj8GOwU9;xE5F zpIbrR`l2%l!-6lXq?k0K`+Grht6>K3PT^%tR}S*_>~kP!=8B|}weCt)ND zXvsLk|}A#rWG364}rGs)2`mSy$SwF!nIz; z6Rx*lLds7#l>RX0VsSk}s9My!UudqA0UNH_;M%$p<7c)dKb_gDZqH?x{monVO_J&f z%OWt`k`qiEh-r37zIu;j1n!@)PivX2=3$zQ+cZC^f_W)O99LZ=WQ&v3RtO}~@MZPz zXKihv#R+n}<1K1a>liy5nz61B_CfDSYfgJ*Eyh8IkGWD`gIF)5z)AGV32AybMRI)> z=#5Yb$yf1(Us@u_{3l36?e4=ovjW{ol@quiNsE8KP=c7-%;woBepbGi1P*F7qhkv` zVcfvWDh*(6XqnC~ZE74Wr4A7zq!&s3MkmEYg-G*8QP&1I~ zNRA)uz3O&1wA1$!TyjE-k~m)G2KFMh+ct#m|xBkl_1r$sR@SaG>vLq2j6OC zfTx3ulA(5}qoP9`XHW+KWe40$eSX;?KJ^QZO9^@R)%`bNVTpu`=@`J6@$6?Y>vodF1}TaAb$hxb*B4-g*6rzk<-G&Cn) zbwpP#(uv?)fTGa!G(*NHmu)&s+24FgUs4bV1DQ=dD}XAN~?Zq=zLA^rZbe zOQHgUZ*u({jBQ1VA}#|aNkoeKOplzv5t9PtN#n;XPD#G#$A*FHF~Ls5KoDId47|<0(J=5CbgW)rqZ0;}Lusb=ds?*Zgn`XQ z_ij+rd-~(5!@$=ZQ-^^fx>Ts!iCCAvCkzy$&UL~-e~usQeb>!y@bCLRE>0M@0OPAe zgvmB0xP99I_WwZM* zob@|!KImDQJ9ybjd3Zwb=ORFDQ}19j?5rFLuBQTry(?-GQ%gA-otd?E6T@BK0h($h0-sH<#Vq@!WK2l z@cAcT!{^lx!RImDx|en14R(pdwReH!-1dmQH>f5K66|}{O>S2jJ{-jJvIC5VT#tca zc_x~FLETKpKOoLg!B`&1kJ;kx%-G0}^e2+MEhK#gB0Pli!L6hb@p2lFcD!5x9Yo+r zitQ>wVSl+vZT%oNsVll3m)^_C^`&4NP3pOUuUT=*OH$RhocI|s@k|7OZ7Rjga}9Ki zd6wST$vhu|Rm?oU#gsXT8Z%D>W7I>*SG`3S2zoKoFiNE!-oP7mU!qjnmyq0W21vcZ z98@?tz3TpZS@PARfT-JxnnvHWK|fQ|TyK=vUk2A28jX}{=a;8A8hv0t3am@M!#;)& z?3T5cuI9w}+FisV&YgpK)7RbtYQ~bNW7h9NTUNengVAZBXN2hnHI!5V><4lG@n2-xrXC_mynHto5nJ-zCVXHj zJI={>>2zDOWxL$uy8|%~5?unA>ol710>I=3XZOpgy9Dn&Pp*G2k%m6lllEiX#Y}aJ zVpH8>n$@hg^Ff*$aOVap;V)ffNua|;z+wrHhj?5e_em^}!V1CDDSsd1)SSGxQ4Ir_ z8>-Re?{1ZiMXrt@3AFJgIP#3)0Kjq>5Gj9e$3&e20h~VQ@;5iIPhBTn5(ldH@qsph zEvV2|=vr-JW3Uen6;S?iA7G-|3(z|FneumwvB4mYfO8`^t~&4ih)g}QBo zcV}%{(F9jU`MVJ1@85L!`-m=oSFAw;=yF-W2Uau#Qf_h!_P+lbH~9Dc6qlUPLMeYs zFupoU*n-a{)g6?I_JiZ*hUU#y-S8RpY;yhcP;E}oKTy}dTPc=IvmScEbV09PfhJ)a zoTNzk`-tQ{%so!tgDlaFiX3L}zD{m%4vtoKs1Gq1^WHm{fOz^+&4^MqQp)-CyiodA zvtm5GFR?J->+kWpL3sogPapj*g2#csn0(~$@f$wOd&1{n^uUD3XAt>x zW3iEs&+z$3VBz!jKf&jI#HJ2;?+roLV@CAl9cmB8r{bE}8TqfVle}=fFla$MRsVw4 znHT=OkK|o-`r~`EBf0At3`mN<3&p|AejeeO=|cXS1Z*VVVZU%GbP<7By-Eu0iZR6H zURGP*X_x=#f~NH3S*D%;@@<5FRl0o6gq1!^QV<3f0Rj>{CE_`f$*1|1L0}^a0yz~ zY^pred%^{f9``>nGteY~uTFw*U|d)TsdE~X4j&Acf{A3+Nid(Jxi)pPxWYD7D+0-e zuEC%dL{U`+b#4^(qB!j~HPJ!sR;Pj^Q|1VuWO;2+qtKDzE={gG)FFoCK;26pT4GZs zjQ2NO{(~#^E%#sJ5~>L!t3gGwfq z&X0+2i@fSel60CMk%k_Hlho}=Os+owzRJ|cx3bHAurJ-)tKi(Q&#CL@f9S7m({ShVpr)nD&MTq?ufy%O6y*w4#Ecj*7-6L z{~!$G?1z|wj(?b_6aTRORaZ_tlztfe%hK4xVqwHTsE0oLk-$3sZGjWM0wB`t`CLdog$^Hkf1xYH=zil35HTLD z#C#ZUQ#lCEfv)Hz9u1TUNjxfrSd2$spt}{dVMIJPbFKvc$8iX>R)f76+Uv7z~YM&-hhvc1w-yX&Yy-5c|8;#&0F%I zohJ?V2iaG0DpqkamfZ{eu^{x>?6;VMQ-<=-q~rz`r?e|Y(dh!TKyILRLxf|N)I|CP|6#W34)Q!Rxd^V}2pj6C%SOHRsUX0HuMg6`= z8M>H*=_&rA!!%dRIIf6j8F~b!DkXSlWoV|ckxAw=#P@0;DC(uw`AzER7yCD`CMxdOlfl1KwIeR4d ze4P>KL^BO4Gm7#U)JYBs_ve9Pv>PB}ZBqy7rq)(j`5V+hXm5SjaOr0H|68t78B7(6 zY*X($sNL$#SG6oHK$&v}yIwHQ6q@^6UCjNh0eWcq-q6=E^`3-7=?`MER8Cum=y0?*8=y7m?%c(P)2x z<+YBoK`v%fwp5^r65(81?{auw&A7j{vENF|JJIxIbq+v8J-xASQx{^Uit&s>^_J@f zm5yudf%XPWq0qG0%|UZiMZ-$ zdbpO00sdM#YpB}^h_AorK>IUP$IgNFM2;Wqy=A!@+UeWl&y1$}zE%jFlo$VCNz%Pe z0;S3TjKC%LwNAumIncfi7H|%=a0cN}x)?gCB;{ z_ruq;5C_-bqT}GD7)O0YK8&TGK~OMaG@Op%7~IC9&7khakVFlMqJ|o(eo@q629?M` z^%m&AFN;*_TQuphcw_E+ScksVD%Wq+KMd91L4}TH7Zr1!7#sf*o%kmm#9M}L#&miT z4yAv9Nm|N$5^N;?Va8PE=fYNQo&9U0mamW`9pfKDN+WU2?-HKy^zF#lgT(e4;m++ms;6G+Sf$d z>yH!6whS@ujo%;%E zz$6lVj*LesLJ%Ep#c(s{rP#8nN_U4ZC)bytd$g>=7M*3)a!ep5TQp1NF^a8*%Ve#b zkYu<@eLh17B85||iR;fntB|b{GE9|2;du}xOG|`Yw?0Cn$ZXX%PJh0Is0?IaFe<&IJ%!&080&PKBg9)0 zg}S|sg!Ow8+XJXtoWxcRZ6UGkzSs@z^i5qFO>9qsld8Z!Cb3Ner78gIB({8fmc+JK zR+4^TV=~7JNMiekc-l64T7O0pE3t8BALmXj>bHm=gr`VJO`|DYj8Bk-QLER5SwHtl zGBd`-BPIM2H0%DL6FY7JfsP$l<5Nz{1eW}+@TX3{D8CG#Z2mk)j+FFw$^oPy#`7Cz z>;A}}2fzg*`4agv6H-QC`)=V?6EQ}(3;v0oKOnuG=s`X#hK|AkkzLO(G`0`%xx^2n zAfd5ci5NpfH<1)6@LBNEIZ8baH(;jA3>bKni5utB{QMZIfKF8~#t8{_nE?+1FKk8!divD(#MjD^5@+k}{W zcn`5~_VXb>1M54&Q3C5L>+~$oB1y-5I8*im|AA*l_5(M`VB1*FJk$)9mlF=94~k`( zCR8md{DNj#2-qaUv%xaDAGjG}b3c&D4#B?PF6v}IFhcY$`++53`5XIzvoYeY?FWt{ z$9DUHE|}qO?FZbh_s|)C`-a;HtxBZ!H(Y=AU6! zgv}rV>F)`f-%HJSc{5^%I)&p0dpFle*!(Xp&VFDSIH?T$V?6qBP^v+Iov?WrK6ls; z^b>g{Y~C)uw2fi&6S}$;Hviw*56sX)a{ZKXf)fdc(rZ!ISS9SY@N@dW{m*gw8`V*u zGVAA0$lHO2olcSVwmSZ;(ej-|lDP2?c8bP7 z8BAC{1mmd735U|3KP`r3nouGBVP<4m2-t~#U}?oah%NDt9T5MjI*Wgh8}g${Q%k_o zj(<|7;lMvlif~EmC>gEiZv0cF0{=vOLZtqYc7ID2aC+6a7^#;ERf`&Kq<&D$E{bY; z20q3|mZUz2+&;MME~!HAZdZlAZNz*DcvIB!Ooo3bokfAV8|_XEeuGF@=Tc~bG5Ag) zvd&~42O>8(4^Lz)V+`i~B95s~T{a76Q%ARIMe+Q%`RUl=cMJ7wqJAHYAQd`JkI{q5 z{a9_o1g%FHn>0O!O0MUrkpz>#$*EPj#_KK~cv$C2$- zxaDUGE%kDW99|CRVG1<9>Wt_(x&Be+l*Re(=snJ&gKz6r_s4BG-PxaU112jB?SVAy;Z_ zJi1G-40Vo?>n*@Wu1!xsu04Cr^KYY&Px_!S`~d`Vo_`CC-AMe;P!(6M^~&!!fD640ZPTSz!2)MhRl!Nc!I+=1^csUB2!BFDg2bP%lc z_aLqVsq@8YerfC=n3{LWf>_j|X?zhq*!LvJE<67n>Szq(d_6s}7GF=-?`X)w`oLGV z_wMnhdV^E37s%^xz7T`=sf2oebt;XYen$o`V<(;h9~cSYRG-H=T3$-)8z5@YM2j`i zVEEBm5W3Vik43D$5g$3j=OJEH!{+<0czy!km2AXv(64q_{uN)C=MAh|43z4DE|?j; z{|Kt$zqD}Z-qr9j;Kar|)H{?1E_5Y``7}J!4U5F{SF`gs>Phg&yJn7^??%fuwmc3~ z;1r8T`q2G1Y8>?wN`DScViLzr4md{0aQ||La%;Ejs$E;qDpHRcC2BXl;=M*yAn3LnRj+s3C;=s*LHfmK)O z@$eQsYgm{ve{8gRBO0Aqqr*yem;-6N!FBTaX=nkn-&X3Tn>iG##Uq5mQG_~`Yb6+x zljqi}bD3pHth!{O>6&;I{GG5qv`b8#!hrIE9cuo|Kb1|sZ7vvFIw=1fr??I{F0NT>i zH=L@`(-YD|zVZz@jX!bz9D4%BZm*|<9**j%M0A#3FgM1ZW=l+n)zeorO?!Wu0e3Ze z`cPb4{As-?NA%QP++l~>_mI|8cL)nTtr#Aor`4ik(bEt3XzS^pG7-_!xtu8UG!-Oj z9eIS-rD*RU`tP7rf0OQ!b=ShF8a)N2$HS?TARIk${?rrWQF}e@d@!n~(?nS8DrzfdL?N7Ieazsxb14}vH1yB0Z$Fx8wy=qvDo>mg8*WK&* zXzS@=nTY6V7$*va3;~I{0slZxsZl-s6_n~y=^oM3oiLB1ry}X`a9)g_IDg9bBO2T5 z>7@tI*{r)iaiCy&fiFf+DV(#Wh{UJc#q-+fX+OBD(bJXGqt??!5*$TOPm4S3P>+Bo z_4G6?fQRzaV)Qgyd{O-AUVOCm)F2ZPJ@w>7p{Fh&Q48=7^pqFX(^62Xv!#1PPmAah z#-GMWkB2K`^u+m7Pj8^Hy`FBpKcWTowdgE;VsVU~l;|YZpZwx^?ew$_CN_F1W*@Dm z9C0Gi(^bGyjuqfZJzYf$gwiLb#^@=7SnW^C@X^-OESZSt=~EfDO})%l;Pfq8Dct>NX|JT3Rp@D)=@n5}`qZKrC2bIe#42fu zxLrFXt%ZG!l1^tIt)zkCL87EmU@1o-cv4BFbh%La2)q;3%J>HptCchpA8jRNz#UAo zTPMS|si&ZL(Rea)D7wxvJIv8JSj$)LSlnbbEdt5!W)xPlOR5;>b`7SzL90A^>uNn zJ$I`;qJeE{JBV6a1=*%P1G4oK)JJ4E5<0{?3_dq)Eo^()v<--DdysASo3?#WLbM<6 z7pNfH1E&3BwtvyOU5_j6^U)qIL3A-B&ynQQ){itvqdJrA6Qb?6#SGD?PGI|S(e|b7 z+Iz9Rd$j#L(+*>U1;z&){t_;XEi6tYxgT=g52dcA({a}$FJUUgNVuQXZG8dvSDkLC z^!^~y|4sCW_P^*}-GBM-?tdp1NA!IWZ$a_;nV(ZIQe+>T{@4)i9wP6H7>&ku?~90h z|Mx#~nnd|zAiUmbW?=g5fk`*FcvfRu;ZkFv4LOqXG$z+i!d62z3op77(RP$>gBK^) z>u(Qw8goP4K0&a}3H%G@dzNHtxj%Vk zryKf2j$X^r17CWJwlI(-yo-_5R~RN(b8}>Pz17;L20Fw056AF)tz67|6|CoRBD~uW zFu|K!JI&tao!ANQO7ixs#s;}z0Hkfb5j)c4!O-M=AP(Qnuo)V=Zx9eS67dia`gs$1 zU*Phu_CS;M&ECLM8R+c|+>j}kkXL5jkSCYWOkDiOB@b?xjStC#LzQxwUYk64R%7yD zUsLkn1*?+>*EA;&Ube*>@}%U3Lj6IK6WD{(keGS=gfEfmH{^Ij4XL1Mk+;(%L5h}! zM8MEJ9IYV*AH6|o1H{2NEDqjUu{2oQ|YiZzs5q~IQE*WDoHt*MRvN{9j5LX54p z5GKo9{#PV}6mZk-z6yFoKmVb*f!Rqd?8ewe?MQ6nn`5}yfAV+{Zx7U{Jd#rz__-A? zV$5Xw^=MZoqM`NA(H*^#JwGxhh^2 z<;4Nrb_9q2oaY9wGn2fbn(bb^d=xJtRo-BV>f`uZ%}LhG-uRoISx$?K%LZPkUzHY> zFE|NSOAjLQV+K>;fq|FQARc!$G;2-xS4Vo8c|LR;i1`M#OolJ4oz}ae<5}@-khku1 z7rrnYTDD!1wQ8a?bxV_6{@&gYUc7<^wLfverTz6G&ZV?qOSaYq-oC1_^EB2?U09R* z7J-On>l2yWpz~;}TGC-QiCWIB>So$E=-JvCo!DnaPM}S{Bo?9Td++kER&j*jWo~ba zrwJcnArDc!t~S>-a+Q}7ZN7`CcA{Hj@G_#>F*w8G>YWsvf@7sAn5w4vX*J3O zu8i>m>FyYD{J=r{kQ*o-2!7-71x$hVdIRGJ!c)c%Odb09nf!uQPJO!e{ z<2l9Lz%DDH^ZD2sNc``H=B(uFU&cENqdFUdWGV0 zUCFex+>w_xeTOMPe~oNbKR^(PzR3-I9t8Sn2B${W86;{Z5%xG(=8Lf!)kt`NkOy8$ zuK$K@b;~xp{Dn;%>rTY2F9q|01smWH%R}#fgQ9J6bL$dhbb*I_Vg1W z%IN=E>I%Px6|McerWyU!hfN&bv&vfp2?L&{@L(Z;cPv|@lA%CoHYYIAP1@}M<*9VU z3(HS)sC0A3{2Iva37j0hN=6y)a%mf;YIz=oDY5=m?Xe}|6PdV+(d-RfjCa4v+*J3! zm?0e5Tz%C~^qdz>JGcYRJl-R|kP8WHp7Z^}o16_qbloPG7TaSh& zD&bh+3#iY~*cKuRfFSFf;AQ<=?~c?jSj%C9>K#$}@~>uMooTH%G<|~?&Ecom z8%#VFGjKto&3L_OOT#MDf{&}6j}1_N!x{tOm1;fjunqEW8ezoJa<;cYx zXA}9Y#myiW0*U@V-Cd;S4;v%MFYeNS#i*Ror1V+?#Z< z9&w)-dYw#?u}_?0oZ|)vB$&yh&Bfl~`-{5Z56KPdiCw;tYPFoBF&LsWaE*1$Cirp) zlDu{ezAriI8jX>>^AzV!5%1!}@DeljFA`mtDTeReM_;G~N2-)!s*NDFT;>KCB|Hi) zW5tmKxKWJ1oPu_Ubl8#bmnWgr*0A~o{i4Y@_Wq0GJ%2|TlIP_!gkay2Wx{k8CN8ik zMY7xmrbCe~)m$@p&0Kj=CU9Pj^K3EKt-PwOunh#o!?)UnlIy<)nkL8E=Js4YO^SeL zi#OQq(0n)aT7yF7TUqJ8tt@9eFqQ;-|7pQVsPfap10h6c>`AZ!BIJtiE#1r7z7iZz zsN_Z0HcNp_=(iegP|tQVj3JnGlAy2`&U%*0ki!ZZZr)9in5?@N9ztLA9D?MWRkyv1y8RZXcRjyUsFl0( z7%&cv-2xp$xr4v6lpFqw_$u-gt#F*S!hM?11wtq%vIr>Msn7-u(olhZl1=r#SNFeG zGn%XWH-Bq0N=F9>G5Iif(3hBF_#GhZ_YrrfC-b<#+SQZK-zK;eU1O$5jk!wW`fD8A z0d?m+y02T~U{v55i3=_rq^r*F-~~uj+Wmt|Q#JNOjn#`GxHLm!H)*Ua4UFK`iDxyi zmLFtMj9;l&ryVNh->Q_z@oV*}E>?2_|1rtnX1Y`GvWyP(X{RZ;zb$RuQa)gEZx?1> zd3!9}tr-rL!o#PXJhFQBX5%vcIYHU}!4a-Iimn24UBWtHHzHWX3(`J7GHyl!8H_Qb zS@^Fvnk;-VoQrO4668hJlwF4B8W=+Xpr%ndX~&1P>Pdr)ow#bb-gW7G&{4;r^A zF%_#vUe5IzM#B=o6!`vKAUPX(KAKM$ws>m6#-;vtz1&A`xRktu)q@~bBPxtqwctA4 z&>Iae9!rsezFNq@u1x@4>Na$h)r(V!Hxto)&4ip>&*-841z9Z~_e}g`ZSoAn2?bv8 zzov5N{Hi(WMMZ#;ylV=|D~f&deN})`yldw8sw%1rX3hlEA4##B`W7=plw5fTM#b#L zK@`Z;Bo)SP^}UE((+@fT3ikzft0p~*`Wx8+w}^JDOQF=Lhw&Mf4`D1P*z5;7o)hjt zKL#BJgB}9Fp@lCOx#6Ypfjy`ckJ^IAuNtO8 zMfG@LI#>C-7|~OYw+G9EOu?F34uN;DE^Aa{;9S^L@K1s)L$&mydY|6LmgU!C!~Ow- z!}S}qi`0Mgi*qi96wvI&fjC4|H$$%QOK3v=LSlc8!7^-~+eY_Dx!4GNboS~KGBR;? zEPU@pRB@3%iMW{vqcj&X-2!Af zSx@Q~C<|d-*NP#;(O`amL~A4wNk{#`1Nqh2IPtp^WdoDEk$n@65j}{#NMSIYTRn&Q znDC!TkH>mp6Ls&N`ba$vT;bq|y(Wv9FrLV_mexomLRxiX z2^!%reIR-s7EwfG=Nm$4ZnS}N(4<}zf;%E>^ghf{R|~Tv5$Yr45yYnt50{)az150P z;d6e9)L)vOp)9>SNW+7riFO>ju`k@`d^lD3aS^^&42AU)iHvt*$r@XHx))jx`VhM= z8JM6-8fgp(Ua45T3|`ksJj+f+@N&DtIl^YV=q_+W8NL3`=o6HW;TyyV!cYAK9>EN? zk!~CsyM(g}Y=Zju{$Rvhd94c?`cc?Nxo}J#?M}pBh~VQ#p!lH=5FsLzFt6uyL`7`y zv%!Z3UE(Z*6Mv^(yvot*6um!6)=FK33kn6-PFtxzpfh8`6_^L22ZCr5e9((1;@Alr zDlF&lGr~m&hY++9buM)Tmx{QgKgB7N;96n6%>`2!MoC{qmsb2OA}zml-jt-?gp#7? z*$E)j2Yhoe52xP7`;QN%4kPE;7ostGo*ml%DXL}q+OwxmpB_N=`66rD?w#xZdt{bQ zwu4_q^_)`oQa5kWUUeC|LfqtfzD6Re?&mJv!20B?mTR@%4JDN{CO>^}R^3;49o+gv zZ{3Ej%{#l)eR_KG(|!7_JnQG=r}KXqpZs+8zV)9bW;LtCx=&L*$xkl?$cA-)9eFH8%Cu7x>ws}D?JULU%C{`;n#;ikO<#DtvnD|Fbup` zw<8r@5-vRz{S%sZCid8?Mf=mrvl55`M{vW4Ky>kj&Pv>r)pac1G={pBf9y!t*BAs8 zr=iQ*v6y%3JC2?MuiB(AUd=&NyGN-&h+gJV;aB09&iSaWWT0C8XR*}vP;DqNGqkuX z^qaG1eOs5hmIS`Rw-y%hvm z$xn|sFtc_aG8QXvZ}JQI2}0Hz(D>vR68mMh_NH_Y;a%pmK}e9#?y6 zKM;JR36^%PYa>A$IK3(a?`7AXdLRg%2jmI7wEoL3Fn40s`n`#{p>q<(_josRWm;Ap z3V)7#an}0ni5NXMbXJ!an3WeD;4S(tEBS>HY3uiO8Q)_QwpR(78f?x7r8jg@*Q_w zbztoBx$rQHSUW?JPo@Az18xo)11`hp(a;?|ANm7-Z|fnN6XEemE~U=@-WL7k_x-)C z3WOf}?`;(j?&R-n;ruEm@T0us+-!>LzQTFg01A*B!m)GY?}G86!#1^_cr4lizGi4( zbL20AWuaB>Dyz@0)bsd?q@n4}dehj3zi_hAd47;JF3wXI^;0cZL#{_eUx1HS&j5xJ zTGyNN9!R%O|Me{_3;B~}M`+QkKUp?e|1q*M@}=0$A0!K!KUQ`cVzJy@Q#nSovqUuR zw0DbKT*S^_EJGauxrS1%$lohFQXOgJvQ%itTW_%24ddMKlVAONMgz3+Rn0CKLZq?WTo^b zRi&Si=!2<8ANBU1Z+-vKX3F=WysSOpXspUGZ;Igo)b9N-X?*{sH!ovX9pF5vTz)yE zIht0*JLouv@G0zo=T=$#hKB$^O+itv$7n1c4}-YTCGPmA<(%>K|5ps~`}L0PBd9HakNL1FYiMfYQkd;JxERR4Fwj*k9U zp!kCR7ws?l9|SY#_Yr*E0BP=)1@RmD?*snS|LqXz59$91WHj-A3_$(M-I5sp=l2ZY z`|yA4cVrE`&07cO;vU=w{weAK7%tWZGl8+!z?*T`K&Fcesuva%4pBa+c>?#3LRb$o zFo0PPr>=koCUQVyk1_ZhV~^3GF!p#6b1>^65!(H|>j4X(8!AN@;K!a~fcttm23SxJ z_D4addd++d+lT+d9OyKk{_+`wE}Y%}pZY zp@#E)g%7A$#$frr!m=@L`+x0=8u10;dvHqq4a<6CyKwRI}|V9S14Z2(aiT1 zZqh`XHPMnJ5XtuyP6v_62Yv8S{2%kM^{wl7+}Ga1O2w_pAim6dlUmMspAQ({yXeh% z=r@StPqz+Z-kSu zy8kG`crZW~nTXMk#$i2x7U!Wwe!=g~OWAX`+I<wlccB=*| zHq-9#)5b(n0@mtTXW$Uv5cdoYjYz=U@yqLP&6ai7Vf( zf{Dq?Djr%!G4XvLOqu7K`;#u1K31lV?~98QIbT|7QzB3BsU(gb>ia0BAGs%Db~QLZ z!ee06$PQINS)k8}n7DeJ77e9)VnsinSo3$i8u1yT=S4;T3;kz_khG|y+KK+{C0g_x zXp*9zMY>@6&QoYLocFd9{cVheyO~Dx|9lU~IRfiM^m`}^M8A@YY&Q*vLwS@Nme%hQ zvudsX6Q3b^WmNRfpiuRKkhG{0jAmNi9W zQx=H+7M=f8jvPw=3>n%I{Y%k}7JUH8qwfVjfpTN(3#;JoLE>u5ed$sT-KO4!{FM7+ zjuT9OFI}trP0ATrC3rsx#)_(Z`FDVRMdfJ}1acojx$E&yZt&Rjk$miSQ}nUh{h^wU zkKOK8iJ*5LyUl=E|k6&+0dH%PAWGjp(66w?YlCsZ`5DdwtOR_iP?E@Qz^j< z@7ocpY*VEemT&2kzav%#Bp4Zr5oqY1pveG$2adSyzJh`aI<$Ttb0s-$n6)dPIt|{|X4=pb&=Wl^lX8{E~ zc^*io`Yx&|t@2f4^3{-`w8-bK_E(jb&vn;Sm7a*(Ab#ImUzNM0tZ*)9%8Nl)1WnE< zESm2wsVOg_KFQG<$5P^n?utrM6qdP*=AoOfd~RfX4%TrfE#FC}<$!S&`b{YHl@(`K z)X-(zw66KFn7B);-Q^W9rM^SshtSpj!tx^DugT?~=fe%2>Y6g%2Exr9!ZC)P>Z`7- zD6a;#1d_zIX#-o6tAXy^<%J7C-RZ32=_f9^tfGv8G)=&V@h2tJ=|ZvPLwe{uiF^FD-IU8{(c^SU!666p5A$Hls&t zFCDZnWAx};M82|9`AHL;HrRdMqEi1n_cZrdw-e~Hb>N$25ARx7QCi$_XflX1a7=HP z%g7gJ7=-R@6HNw*Te~SEBf5hgkDIfW;3u}1<+S4lx8oQKE-bC`*C70KF2MA1qzxpG z_&>kif9h}acDbDX9jtR{)Kn1Q*y=&YRu6U|VVyjr+BLVjx}bDHWkr?0fXi6J$PES6 zzM=vrKM7H}MDG|}acOmBS>cjs&l;VMNYAh@qZJmJj#XF%F(WyM!lEKyWh}=9^O3t3 zR3Z@T1j_U(o%zrMWT;$HP*hY{G>?IoW74j-rgiSzlXq^yJGb7QJM_+d zcfT=FwZEduSHRJWAZfMaPo(8iWOj|#YqtQBRMy} z-}H~m-?TgY+kXGgX&^m)MEb~6GDeLabLv>r(Us7pYht(V`z7`0*=zsa2PCH)c+kOp z`u?e3|3fsvfI|;E{D>pnM;(34z+;a)e$e0{C!BcF$wO1qh7FhYtZ~`nJrgE+bIv$3 zchcl3d1p<{pEmvM88gp0w{T8Tv9DzAywVHjmn|r-sJy7E+F!G9(c&c+v$K}tgrSi# z$wUv-VLETRoFwG(BkuY9;>adl`HHh)JesAjtUB9x46V`er}K6DhvU!xT73Nfo7V*l()~mEy zM7?d%Yw>|vXpy3}mR6-$AB``dwrZ>vt*^QN+I#IYXU?1h;_bcn`|ij2zL~Ypzt>)S z@3q%n`!RFQE+2}=H-jDl-3Qu?Rn#cxKG4a?uNkYvTF|#ZH`6^h$f1C;C&wgYMgjc+j^%CzIapLp?z=A4Iw69&`k>7F1y2-2qw%x)!to^dRUWx_=ly zxPiX)E9eFE$giP4(9MrPF7_Js{T6aT%O6Glper7a$G6e_LC6QKeFA#Kc1rUI$_cs+ zv>9~rbI>E`k>^of(6uk19YLqR2)StYeV}VWryqj;Kx;ww6Mh)-XeaMaC@1K_myj=L z$6vq)O6Sh+C;Vm93wA>1yazy!fHs2Ch2I6_l{PeAq~V~#f6B?o+<+fMrUJ$PBt&3o zJl+G{im~}MV<(@Jm%Ti5mH6UEKKJR;si#vy;;F`G#Xvkhj)2Os`NQcox&BHB!Y#$O z;Y0Cga*nSuYZ(_3y-dc@aU;aTrp=c`@qPhT_!vTC4cT*Q9|J_o`79Rg&2 z;ICfqS%<%r_|h-5a4Y^7z*devli)wc!rzp_KLPdM4E~!;`BwfY@z<-;C_Pn!e=_>w zQj;I$2~&AcoC;!}lRXu2UEo`E96qYwzk+WY_!8wkcK!B%KNEfa>ZJTvd(x{Z@2cz? zB9*Gd)E;kuf8WLN_$N&MujIBGpzZNUK&+Fb-oeusmI}?cAzV5sIgx5yo~SprWcBT(*2M0LOLFS zoNiF>SK*+vt*g4KY`I;DKY~voe7oc~j?cda{EIYy)$#eM-)+(SXB?mZ1@Mn({_NxP zQ@<<3SR~8;DjfDP>RSfc)bAF7{}wOw^QeWt<~yD%yz71Etn;tV@a*+a>#+Nf_V@<) z4`QsUg$y$fv?JY;9w+b^b{he@4Atb1=C1R>AI&F$a})lk8vL6v#_e|Dm;IqZ@t+Nz zcTw(gjDZ`e+{2b~*Q#=_^VhDg)7N1vk)^%rcezlu)lz0ECsx2m?M zUZ$^B*~|2oAbst+c>FYssa_fwbsg(;{>XlSlSh)0%k=kB|GO$4{}j5Kx7yOKPU(00 zNKlxwm+9X{`pMtJbernG(URV={x8Y`u)0HmwzOaDu0e|4Nc_4|I5d*5yBe`{&HoS*BjMIjMK_IDcD zC*tX;81JA(zQqRbrb?mjQ$MID{@dg6KY-QSY~`o+Y+CP={owm!I0;gyars@8W7Ylf zIG&eE=m7m-0YpXA^UQis`Y$8C0`e!A@fb(Ao)mux z$Ghc!?QzoI%ki}&U$>#9A3ufo9_0TM=+TTf+qe$Cp)iefLbgSE&p}rh{TY4*u=3Zd zaojUivg&Rm`OgM_V0S!z$eKU<=5H&(ONo&2PX$jG$p`<(Z%-d!=Hz({L&V~>wML4h%c#Hrr$zTd0MLPmyxa! zbLK2-xv0KRCf9cj_{x8Uxh(9_EKgGTA2J1#-P{3wdEgVmCcmZKA47aC=HNY)ue3|p z?HoBj@Qjre3um{JMD!ohH@N^hb8ok`oT?o?EzI9X{AftxF9ZMd10Q_8+6Mm3;J*%O z&GJ@L-wdz!LE+@>+ekk2E!!XbnZJ+6H(B{-U*VafC&Y3y319&rC(yn?-HbIev;GO`@z!5`eRMD{VDVt zWUK57e!Cg~#Or@Y@tNEc~#&y4BwFHMw&Y{TH(b9h3yY#py_zZZq)kHj$+X~enPOx5WQ6ZZ z5518oUP#6l;7w zgxC3ez&H7j{`)@PZ!*PGzR%zd2L2!hrl0$7N6I@%_CuNYpViwGTA!t|`bOF`F%8>@hr=aT^AWHQAwG=ZIfsUnsmvU7x zzRAV7e5{C#pcqf2PgpZnyqw+~&lL}NijWBkfbcsWAMne(NVP#0<6$bs+ujnC|8^f{ z>s$Px8*;^AD#qH3(0e)J`Ha_4jK{J=8*;@RIpt6aWqBQa-9}%s7;jVP-^St#+P|F3 zf_;nF-%*w$>7jqm6F>1le` zmHAK)O0!(q!lo>7(PxFYF)cKjDV|UJ8!~;)GvVzlan#fNw=D69x9B%n;$5!~VORw4 zE65hE@%iq}5|5EBto8?2XNi0Kw;<&U8KIlA#7&tKkQW)lm1GPz($}3?$aR!$qfcf1 zYOXdzG{b9YZ$iKkPY5P(o$o5tU}wez*vD@&n&A^}$}GA&S3I8SLm0*k{4mM?YbF`b zkFrpVr?P@DldH!34k<6qEfV7QqLezCAs3Fk9U1 zxfJEz<)qY#I(k>c;!(ERn(J8q}12k7fyj(&t+LN4o?*KWexoS-(!jpeq~I--ihM!Y#+i`W)shkvS;j>2y-90 z6W=*S2yeRC$63^qgGj5zH){hDO@5_n{RR+TJPgu#KX{o$nBamA3~3(sf-uMmYsyrqrT;5S>iv_)}$ePXZq0X zS>g`Q7ZCodXXu73@v4`?Kk^O1HQeI=9KtX9hc3?&&t=pgd~4=szL}*4ly6XXK6#zg zz)209)WAs%oYcTc4V=`#Ne!ITz)209)WAs%xN2Z~gNj-;Pth$*_cQI`cvk`c&myqu zl~>lOit77`w);=p?q}KV=h*Jg=X-4Z%4;RxV~by2&DDxx%UNDuen?Sf6T99ilmOn* zCa*%KA7MJe@w9JE7wwVL^|$xqF`}bf5xq(dOe9nY{G=+cMcBip3tQUqdXY0$yW#l# zhjIFeOkGnX!A_C9HgH9-+a@pUhRbUb(|y==piARxaU=>|x||hUF#3ssE}h@|aaI1! zI2wd5{E95=qsu+Y_Y(su{_lLRs)-YYjw4Lc7(_yBYm~LgdgXvzT2bdmWdX%ZZhVy4SjcJH!4bz28+nEkB z9cH?T=~kvYnC@kIfaxKoN16KPaQ;lEF%2=TVY-lMJJUg?!%R0Z-O6+a)4fa&Fg?Wd zC{uqe=g)K+(-6}drVE+2GaY0)%ybjetxR_?-OKa<(?d*;GWFMS{!FJa4Kb}@x{zr* z(?O=gOgAyz%5(?Qy-W`3K;)IXQ=XF82(h-nSeg-qL-4l*5Px{2vlraPGKWqN?=A*M%}`s+D=rqh^)nAR{| z$h4j5Ak$%{o0x88x`XLnrU#fFVybdY{a)l%<4kIdLiBj5)g2{_c#)h~+W z6C1_y(a_>{+#oJSPpydJXou0>i|2HVjy9y#cM#gzYD8DG(ql9zXjfFpFj{(hTUH7w zLx(SFMM4rrIYX{2Wy`Y8RtSk9Z+sQYLZ}QE_w|Y5*4VOTc!a{P$Pal>^O_8N^n79; z&sQ{^YLn}=-52BjD8_!BUe9+l?cxYMf626^FUNg0K03Xg4{5qz{@EJ8^D~c5ujeTh zz)7}Fujf~q>iHB{BAYulY1xfb=w1()W74r0FQHKwiUH@*Rv8LDaJx%rekkXIA$DV!#FsdSzjV?VO)>O}P zRjkTOhl%##V@*$IyVIqq{7=1t3_tx~=4k!jq>Dd?SWzT;LBCY8IPbh9p zr`jB?Za*#a7F+trVHKn4Eb82ri}JEw_u_`K(DtR*JG#gBTq^Fz$8epo^f69gvFI}3Fd)Il( z2>yDF^B<=f8Moa^Ikqk)IoHw~K5*mrezP<+A5* ziAo82P&z%1S|dI1HhO$a#yvuhd&#(0=2UrfgHh4y#J_&9U_CK(?u zw4X}GPZ8SxB;(j!(SF4e;SmKw`wI&Udzy&;UucD7*du6HW{Lwo8SU3q?lUKYJxAIY#_O;S6!zw&i#mHyR5d3GxcQO7Q6)k8yCjQ1o1!#N=<0FjUq@u+x z#y6a&fTfH-%ea`IjMFJnB)^AoE&p`jX(;WM{ffVhmX zoALR;Nk5CYU3mLYT+94=|9Twr|3van7OU8vD;VF&{Cb~T>+=BcW7+M7dz1iew=c1r zz)po<$MP@qse0{aT>hsVaoVm{J+2trnE&U@AF|nlwyRY;j$&T}m10-GFd zSB0Ff-L3@7(R$E&9(ha&)_R`d=X$Yx&EE{%NpG#d(?qHt>tQ*ffeX&$GR6Zod^6+r z-ywc1J_bpAT;Oyo^1#qoHu976Q z4jm8viXSReK68ZNdWl;(RrqEX{27+h!vh^XTS(WLm`FP1Tjzp*#Rb321>XsLyvi!+ z`w4NtFr*eurRerUKhyjW7jfLP@49TC*_F2ktKX8%1$A$lC z#(P*l+7BFMeEaoEu-4n8Jm-4N0Z#V6=mEw52`V+m;;{eS zihB+Bqw~>-PVz66c(&Lzr1V!9pyPIg;iv)iX!L~{%Qf^J&fyiX$S69 z{_ncrBT`Os8R_n*3;&c;RC)HZ{lHVmD*)Un--zUACJSkI;ok||Y5aQBMb2S~!=GQE zgx|vU;77pRvwE zj$kctr}8gy!Jl@)GqGRlRL}Y9Q|&aD!6?2 z0)iPIb1r9*3ts1fe?{WZ{}v@*`|U2^WG8Rg)`=H0|CSpR{~<-h6^s}DhXUj~91y%! z;>=_rk4X6zfP?S2@aLo9ob2th5{I+?XC*+-d#iyv>HlIEe5VWks0%)}&{_U@F8D^^ z)E`G|{c(p2{{i4m^?lm~pEyPJqtOLIUWOu~7`T%j=DOf3fji~9UgGeFJU^#r|LJM>)>sS5KOFi+9*zo+h4JCu+B>{VUU3Yt|uAwPt%vjjcH4qJl z!w^^>EH{$g+fA=WZw#Fu>&5%fDZV6-9IxJrY~`>^pmHR|&q|gc-^uRG&?H|RoyuUA zQ8C!csI(FcB;E)dEU~@=nKcp&S;1=jTS#gnq>_c30tQqPoMjk|^TUzI1xC$+hN?*2 zxebP)6>rU=x+FYU+|$zAUmPq!d};yQBnS5q~Fy_>sJG-*pF!}}-8+9g+^{fT`;_VdY z7Ho?4L$KYo*-O|Yk6J*tZD=Ynl6@PzAY5HZps_awr`W$zi;`Y&Q2IWLGY!r;vHXrH z-R@&k`mV)y1e|=!hwO(5cjT;jtF~Kv`|&#J_V!|oD#kfg^NsqtrU*P;ThwgS{$)mM zSFAhQhj&tQJ0~E+Xp0$3x?+o4x{NlwQygzAA6S8-LzeY)Mf;;|#i3aMz**36j*-9j_+!^5PPhwpz$0e%?;Z^3S1HI5Z+S?oJ6*0W8yqCie zhB4AGif7J{r7`bj!DX9qp}bw!l=HWp>kebm6H{bl@X4iAXugbxd>iA--S25mr(yo zJt8FBdF=PG%lFh{%l-Zky?5>4VkD!CPL}T_3#y(RcSpa zM!8QKx@pSeHk+Yg&N7>6mRX&c`svTFc}Lou@BaQ8A~!Zg!PXQe09zLn_Js zvVRx7q>SsO4bkN%qz;);dv7$V`+ZV-@mw+(XfzKMs*|RYq7Bp!j&x>2th)+F6wn{B z6GM!6_OSwskcQa{D$n z8>Pi%BD$ipKe@#XgSa7tj(o61T^L!IGBjXLZuH>%p#FBFwPR@_0ZCVVnN7I7Cf3^; zMK>n%3)SM-l&&a7z=S%QN)6lwXKKY&_G7SIJkTFS7V`i1Nu6(IQs<)yMMCwuCnOD_ zaws;tp0qXTt@(HjyRDVcX-dJ8c`Zw$T1>c+WawUnYM|ZCdLYd6avI!AX>bo1<+>y= zjLt?APO^X$aY7ndhI3hBt%(Mt?hlPCJ(Sg8 z_0g5^Ajz7b$ptE_?UwB${NB#~C^@%qV{2z)XD1uRtftN-I38r6H!58P^kZ0* zYtgL{Ozq>OP%IQgTW7RH40LyOc3X^(%budzs>BF0lSUJqbd{R5EM96->YS)oN(4KR zGBPHzkAz8BEJD}V)ZmOT4gR*SknkeJFIUdg-Xyg=yaLlpoR1Z5#9R=XqBZr*nwC~f zWmeWjjBt5x6q@Wd`ooccA(YQL#=B{4JP;76ZT|~1^Xxog!@`s zdT6jyE~yE}^F%SCB=ss`)J5i@D0+U3Ng7RDAf$McDDmWj%+5%O(hVPXqajyHN~QJOkqOAJ%gGiVN1Mw^o`Au=<^`I}nQ zrHtZ1>bY`$+JMI?k2xAbhe2!CO?7S7_6e47^XO(!>t47%c~~f_pE8aI%NAhXOQ%-- zgRREwC&2(YcQqW#1w_I>SZ9yqDyg=q+Cu&N%-J7wok*|yvFgQ0&HcY5(9{)Mjtbe_ zp_(8piT10F2V+?jOWh^OgBGhS+O1WV5E~4k-E1P=$^-8qH#(9{oUB$KTt`Q04fMI# zEi#?So-i~=Zr`XL2i)vadbCRP!tzK=EvmsR2WGjfl;v=&tCK-Usn&9mZMc_GJO6Ul zc=CW$gEL2M3QHOiQMeEj{bx;Y$im*t4FwsGVWCC2KB!bz$`4N&T3ER!fY8^fL~f31=SV*D6ok zRY&n9ReNS62IZ9|X78z;BXu6H2R^s07|YVr>Uo;Vur<)oR4E->Vu?a4IPRGkc4yI8 z)q9L_*J5=vVQlT}X~AmRG6grN=XJ+0A4K)BDU;kiP|9UYptrq~tyI-d2%<}e+=Z04#u5?QVOk%zUzJvmsO)M4eB#LD;R z`5Q0PE#0%O&+MM$IphX|-Im(g zToBTIY9yP2jFg&BoVw~%2p9{Lm+EbTAw3T3c@iuGZPVS_gVwQ6&*&6PoK|`qLohBZ z#b!q1T=}y(a@7M$>IBSmq1b0~>e0tq)&v8!(Uu;zQrpr-RW`{t@H&tz$Z>@klFQDh z%j$y*N5)sKtPVR7_}v%_P#o9ow%&3omEI$#4KNx@)ov2z9EoMx+*aC!3XkzGLj^VLk$T0P&QAewGxdf9SQUps?DQLpn8|$KJjnjHeFWb-zTxfGA zmiGb3?rfDzof6Pl>S`Nt0d@}!{H_;v>KAZoK_Q1iIkt4u8PmOkovr#eIrOd6U)l5! P%l;=Z#GwXJZiK~9=Me(vhjN{eyJC#w&!8p zTuG^}qg?}BgQmJy)+VK<4oFE{ol<)=N9xwiHPDqn+Mbv9Oz6`kA@%H(9&0lby5zXe zopV&r{rTATj-%APL=Q4eX`M1_U%gwdHTvwRu<+ujS=PPi%3cro`y#~M6 z;rDv{-iY6u@XMc@@p}t?Z^iE&_`MUqP5AvQe(%9Af9};6*L}FI!tebCegM~p%;!gN zebjvBWi@^u!|&txeGjk&JH^*Q{m!|%c8ZrPK0U)^UXZSvf7$LkrB zZt;$7$v$T8irc=vcIm#u-+JPK0T)iWzW<80w+?#Z9N(QKE0zyG;NzYD_~wAWFSu>^ zd0(#W+q3&gr@l7(vVXh!5Bu}7e{A*MKIxf%HXJ{9MR@*236-zBx#!u?w+Fm3_n|&1 zeLkPp`onF*XWh7R_YI4mS=m-GKPzYR!5=rCwPnwbzD2uQcJ=*uVgDgRavr&q za!%G>_dV&ot8N>9$Ii8V8^&~R+jzp<6}OzS^|;4g$GE3YT6)sn+lDuGJMyVzecyWG z$;T5*-uk@c&TP*=zj|x>mOXcLfBC}KXMA?=+Rv`Nr0}(mj%(A zto-S+eYXww{i*LWFCOyN6Cbwpo$;@WW*&CTZ6%ILjix$Yy21lzj*rD(d4S91tOdIz z1I~SrjWC~|KDcxISU7iQmdYIF5by#*y=9=&dumyp3en8GcTjal)`8RMg?;9u9$=o#~-V9RFl}+8O-=apqeRN6$yZ zi6^JW(evmy{=Y7c9+Kk3&((3}^=X_qd~FlB;6K9-5YsuAJD0yG&ieW*{Gqct;T;Iy8GaY^(3yT#K%Ymudbt{>YZskqJT)xy?d7U`K_mR| z8~!AL{vgoTZq)Gm`r`Tm>x<*eepw@qG5BSOKg7GHX~cMgFE-GL*d{6HgTmFOS%b2R<|$jzUR%=nE)&ese+!;F(+#u={3 zT_ePQdbyhZsu5orJau`HYk$}IuNs8841-@$o|GnyfP2f2!oSo*$`lP_S;@~bqlaBa z500MCmG$1s)oeD7>&?9OA>VO)*9E%2*NjtO_|_I{#5ab)56JJN-?BpE+su5=bnI*R zI{NfTJ>Sc<{Si&y!|;6=bsfj4yjJ6n(HGY|(ND*H*%avcK-VFz?TJSTCCKFGEa>?t zoIEs{bC^_v_sM$i<=WNG?#Fc1^saXFFDQvjUNt}KQ9=0nv8xNKddwJN^KG{ zmt(J!jQ(9_d`EfQT))v$!2MF zxrQSCQ~z78(}?%s2mEO@{#?0A!{x?L#>CNc1<1s&CTn^pNB9ii_Hp%2*q3(9Y`5;_ znfbQY=iE5)(^XI~cR@vYLAAfI%3o06Dkv!}FLf2TsR#jN)ug=LIR^ah?#t-u>B;)_%GI+b1w81 z`G=+EmsKp9==0~4Lu*jOgi>Ewu?PA*ck-Da%kV7L`1G?2%W8a)?rCY>!t&xWUw%eAM<2L_lV^Nu}u)Jf}YG2htUlm07wN{ZVVi!HB8IUAx*bHCc z{OrQAvN?rC^F33~)b_WL;|u+TIrjAPQ(rKQ5ZvumoV;9QZ$-|fK8DD9jV+#_MZS*}q;994}^75>F#d9u8t z^cpW-V=t`iG+9g$5sbT>!o@n*S0%HhpF{{E>sBl3lxY=pc0X+f-%v*q+nqxxkf}y&niJcXdeJE^vHaFRcZO$v^1DtLRH0r z>Hd<8Sn2c5ESe0jPovnHc-oRmpN=&cV3cQZk*|{RGTl>ERZ)d#Suj$E6fB$qGrqAr zW0Rg^#n1nUV5pX>Y~C*24gFt#ZmmQPKig#2)<>Sc$CHc zc#!~=M^AIOKu4*TqVd`2(}R}b1<-wJL57pcp#D;LoIywQNk)<`oY{=>7FK5$*36w} zR-Be%!~{gavWT7G9=04@_h97=;l!&5!UUk<#ic&D5?s|+RaIV5P*#Bi0u;xrk!aoL;EkPFQgHaZ{JKuRdnVZpV2A)`bz zV8m!}&yHNG036m%3V671R;JRgP0|G?lz#EB&K08*NjQ4ODl*-iWujt28 zWrnE;v&u^6mivnHDqvq<6+?QA{5oz&RW&MRZ6K?lF8ZU&ijEe$(pY2t&&SG$k&LBJ z`Tu+{N3eXU7yl839F_*jVkFUvT|y^TT3Wk-rDlq(QYVu~wq70i>S;ySY}&~73_Yd4zSuj4 zicYwgQaoO6vyzk@TJlF=V>3BFiG z(eSc8pIo@0eN>Ar6QQE01RZA>tD}ybq}s_(cWT9s1Ziogvtsiu?b~sFJUQ@J_)+h6 zm|%v3>7-zd&W5><3LU|XB;>-!G!BZQ$G;@YkJ@`q4Ne%0h9mXbDNxmKYALcHe?7gJ zb(b-rqN>P;ac!eRoJhV!br@f|5v;0Wm!4H{Qv41{@As}+7PG zr~rikcf2u7B6L)82ddKYi)u=%d@(&8iKXWp2s&~EilZWE(q$l2WP~7Sc~RvOVP}qC zI6XOPfhPPo_h7-T&m~YI7i1Sqo>nkD-!rvfa@Hh|^eZef0#x~m3otdk%fx&vxuX=W z$SB?^`P0T_<$J~#V7Rk$vOA6zqlF?2@0wpVC%r(_;3!Hkm4#I>hVWZ3AICWhDo2jc zv_(a*6%Gs*`XVs9>tvx(bA5j9IZ$~mz#(AaTyB@4m*SdA-Oe+sb_Bu{Ll^r%Sh2*S zqw5rvRu-07I7d`!wy=o1;TR*8 zi^@5(=&;(HW1fx;W+8NFNE0?+ zVAM{v?^JLds3o;VZ0jV%SliMibUCXJ?^x|d@>C}!5VzGFS2od+V#t%XP?Fzp#E(-Z z6mlQ5BxhQIC!@-TDx@0pew$=4m~EM%=LtgGtkUpZdF2_&t^!{$yI|PKBO;%MTc3xWobJk= zIWucqPC*)^6yljP(QyPrwj*xAu!2cB({vylE+6$RC07@Dnp^{k_{>{{`ZjAfJcHkz zk8lZ2Kao#5ebbixy5o00)5;d7jTGkAu6!b${X-s6oGn3=u8T|GB-FP|yJ7_PqHO$6 z_l}MsP134w*^zq>^yucotwH%=FPAIf|B?T+Oq6Dn+?#W`+(6|Ww*+?zd%7+Mjz0;I zd4_4v1l*^z6nFTNTvr>M|BzBV$+Dm876aD|Al%(`Z=`=0*AUajd-nf$bUvQ2=;3fgh(qr2^S)5IQT&p{wZtxd2#TYwFRD_&Z5?Q_eOtMz92r2pAt z;s0#mU2SfGNYC$~I6p}i9=F~jKPeVIIf8Y$`dj!LExg;pn@1<4b&!R>$)ZoS@NNsA zVc{RJ@R=6=Nel0_@cf>M^OI-cA9Ikn&b08yTlm=)-aJwvt@AAW9Tt71g|D;li!HqK ztPh)OE&Np${Yndeg@tdl@aY!*W(#i~g^<=J3*ThXud?uWS@_i!{#gsZ#=@_*@XZ$f zdJDhV!Urt;77K44<&f5`7CvOrZ@2J^EWEPti!J=kCeARP)LQsv3twsB`{U^j{zP-K zZggAtTQo}k9c1C7nbqY=weUL2>P{IJ9*H9IlWF0jdEJHQqN4KXysNw9S$HR=vt_1* zN1}@S%(n1OzGmY*3y(w+`Kh$~skjvI{@KESZk4MuYKdUXg^Gp>R*I4+z5o(vK*}~(|tH{r03y(*6B0pO!eE$g6 z<=SfDO-h#5?G}E3MXxOUp%#9Zg}>9n@3HWQS$J1MRR4!t_#_Lz&cdfy_#-TQe+z%4 zg?C$c%}F;7vhYV+^r;s97z>|a;RjmyObdUkh4)(c<1Bohg&$<$XIl8d7JjycA7bI> zS@;tye5Hjy(ZVmb@F!XLS_^-&gAPaxGg-^BcnHE07!e?3dObb8G!h0=z zwuR5L@Z&A~Obc(H!Y{V)UJGAq;d3nfN(+C6g>SU*XIl81 zE&S~kzRAMpTKH8K-fU5%b+v_`Y|*c=@KY>&vxU#I@S83CSr&eag`aBSw_5mo3%}jM zKWyQZg>SU*yDa=P3%|$0Pq*-{u2KI#+rlSV_!$;H#lp|D@ck|PITqe+;m@`3gDm`c z7CzO&KV#uDEd2QvKGVX_vhZFDe}RS1v+ye{{7eh~Hw!=8!WUThc@}=Qg|D>mg%*CX zg`Z>LYc2eh7Jj9LFS78B7QWcR-)!N17QV^Cmst2!7JjaUUv1&%S@<;;zSP1uTlfnt z{ALS3-@O_!NEgpY0Me}2yGYCEwTvd@$kF0)I-FTZeFy!0!|0mLc3I@Y{s{M7UPqR|#{A5Uv#X zCBobqgl7x9mN2&j;XHvKCp>^~roaynK9q2(z;_d7i63?gd@JF@38x5rEn$}KVVA&H z5N639-t`OT|7XH(!rKMDm@tz>c#FVQgjuqOn+3j*@G*o}3p|JLK*CJ|pG%mfdAL#F zsf3RsTr2PygpVg&DeySLg9y(Scr@X`g!2R*Mwq2|I8)#ugij!xD)7;SPbBOXcmUy( z2&V{q5Mh?uVVA%?2@fT_>u0e);Z(xg1>XBC;55Qp1pbaNOYCs7z&i;KC%jtVPYJW6 z4mSz>K4F&9;YNYqCOndGt-!AmW+@!56!;~=8H8sGyp}La-*BG5j}snEI8)#U2#+D0 zD)8NeS+a)R0^drQrD`}u;A;u96b-uszJf4I(D1IG#Quac32ztpV!~O3w+LKCn5Aa8 zS>Ou^XA@p6@EpS92{#FRE@76A;YNX{5}rV~R^T%TPb6F^@HoO=!m|Y)O*n^ep1{Kh zpFucN;30%r3Wie!KALbYVYk2o2u~uMBJe?kS=xnN0{0}$k}kY!uh^e3OS$lNf%mQf z%n~lVMd0rUvvdnL3%rwXKH=2@e@d98SGY;w_X)G)3O5S;Her@p;aY)TCCm~lTq*EN zgl7_-E$~{x=Mc^l_;JGL63!I(0mA1IP8IlW!Yq-(Zh>zl%+e^FBJj0@SrUa^0$)Lx zrA>I(f5rZUXA|Bo@Wq4+32za&iZDxR|-6iFcVOCw!otamlDnsco^Xe31N5gtrTPG2!Kew+LKC_|Jr!1-_7Q z9pTji&mmk-xJlr12{#aK1U%gv>b(lB-cb4>VCoHxy$`aj?T>bE;0qOkNF@0J3_$WD zI1*7q@z1;-u)5Y*ll)-bMF;rB68v=it*c}&wU*YuwPwCNv+ zr4M!6OuEq6wYW_84&FoBx;+Oh>N0Bs3b+yMjRNkwS#8@XuQ$}~8clzNMZbPeS8w1Y z@A{pmdlR;J-`Z0no%{Ba&Tpf$H?XPgQ}(YNdk*@!YL55TjZH=~SO&iE?~i%C{gm6K zPQsE<^WX-vHg!t{VZ!$tO865|3c95}jBftpAl#JITDSq!;sBsAR@;_Y;Taep`N&!q ze!^$sbF_QobZ_uiLIMWM4Sb^x!vws67BvvDjbu52P2S+dw%Wy@8k6=TN&X81 z8hxZ;T3;e59z) zk`6WZosAI18|>;0Rs&kx9~K*h<>_ts(VIMemwNC&ZEZP$mxHdlJ#GH9tU&$1Cxw1# zlDDA^b@~`A5^rFe8qO=~bx16d%?cj{Od~t2Mu(iBCn;-F{lF%CPRIdr6+X1Cfqp~X zUPW}E+M-H}iUpapAR^)7{%Q;q^=tAx_@kERue`>{a}6-ROPtQ5J=pf-YKSccS*Y$Q!iL>a%-=MgBZ{R2Hp>l(d(wDLHINMwT{;q|F{U4-{BvD zFSx8BNI^<4JE@_$W{zXp(aBFw>{YitxlVOGHDS?-s*+2h;RA0=b_x{f@*hlp32gHQ zGn2^qJcP(b{b2)A$T)<1q>v{#m(bW_7a@fp9k|qx?=VWJ_c6NpdfoiPLNu>nb1yVU zS2)%a<pBe0Q8?SV~ge~XT< zM@&(F!x(khNeR)}jL_nKfoWhiS5e&aDDL^++Txb9lUK$|u3rgCBju@G{1=FtFU_b^ z2@TDG>?D6L!$$H;uQUW1NH-s%n_oh0w3hXpYDBZFKZ*4!i`0P)Il=mYH>24b$absO zW#uDi1X|LX5jFhqn_;R2O2Dc^-jMn0T%i&=^zW}io%X*xwtv(f-D>WKE`HtKd%vfe zbTI0zUgI)oXYVBVZRhsx*7vu@AFOVT8NaOE`0)SpW`#$7gS34Y=GM;s-JV+Y8}biU zqhrS3zti#G{TkzEIpdpL9GbNS3pZ7bqQheu1~#e5P^2e#kEAqp6!7B%UosmngnYa{ zLYE?`XS2GNoPwUs@TycXUQS>m+SJ9s=LUADIp}WN)9dhig&j4&k742nzsG<#{JI-{ zr&;`tj>E5~;rAV`o$@<}9W}pln_m|2hTo0Q59jv==I_k!anWnX`O%)7-=E|03$vr< zw-57(%@jZ8LSv{Ll38*_B5$=`Bz&R zVnRav4Sn@)>M(d{?Q>0Na3$BjjS@09_*dp;RRXeS(YY<{?Og4_eaIaae(fu{!dKNb z5FX{__~3I)@oE?-#s~J1=yFY@UKENJ)sLM+>BnFfX+|a0dKfP^uotrA26n3=f$psY zQ?-MiL-(fQv$XC|FJnZt1!yqL4K1!z8}WHkLtAqFPhD7@EUe^+FA84_w?mDW;dX#r z1t3Lk$k&(~cxo|5Wb3A#7&%zSyxb9ss~E@QT-4m!BZS6H`KsMJ_|B1eQm1f?)>g_TDyl>?Rka3kaTc>Ne0_6reE^nIPe`Lgn>83N%ojhQKF308 zyRI3msEMmd15FsER$^$i6gcqqhBBc-t%`X-dF$43Qt*o_Fi=i#ktp~AN0=SzGio&e z1-Ga{BG0-!(5n;CcT&TT$@Nc2w~?H}AoKz$hM!529MMIL@_)o&M)@ZQix%~S=uRvD zJ+a_ZmFR6$@f4=0n%OH>`Mtr_DF1QV7-{lHwOEnPQ9i}Am47b8;Vh~!nt0T+)K*ZG zUoK;a^1qi!?p9;4G^za0&{W^-Pf?>OoL(fSV<@)m2idWd=w6c=KKCDy6FhYwYxUmh zVf4;vNgRk4l+8QTGK$vlfxm|?<=XPN-%*R`c*{3(#Y!=qbwO5v*_WmL7`_z8){%N0 zaBm#r+VEsdFbcPY_qL;dEQY=*u(a5S}k zhEJ^@;~&oDKv=HzEjTEf`>;7|T6RNMtP<8ST`0E>f!nGC zFnba9bg8*JBKsJGkxx)+c?0iDQ(CjS5RI+x+4TjZUrykc7YCs)!k@Ys6e!{lvy$t1 zFq9L#gL|6Xz^B3Cs9ciNA_&V5TqDoXBH;c6u32@bwfPU96u6i5mskRGz!o`tBO0~* zIl&3ohc+~UAOT9qYH46FgazPJ4H8Q)1a0d}j(jLyPlWuc7%aopv{dA1A)*gQ{ydCC z`L})T7<$WWK~zCgbj8GOwU9;xE5F zpIbrR`l2%l!-6lXq?k0K`+Grht6>K3PT^%tR}S*_>~kP!=8B|}weCt)ND zXvsLk|}A#rWG364}rGs)2`mSy$SwF!nIz; z6Rx*lLds7#l>RX0VsSk}s9My!UudqA0UNH_;M%$p<7c)dKb_gDZqH?x{monVO_J&f z%OWt`k`qiEh-r37zIu;j1n!@)PivX2=3$zQ+cZC^f_W)O99LZ=WQ&v3RtO}~@MZPz zXKihv#R+n}<1K1a>liy5nz61B_CfDSYfgJ*Eyh8IkGWD`gIF)5z)AGV32AybMRI)> z=#5Yb$yf1(Us@u_{3l36?e4=ovjW{ol@quiNsE8KP=c7-%;woBepbGi1P*F7qhkv` zVcfvWDh*(6XqnC~ZE74Wr4A7zq!&s3MkmEYg-G*8QP&1I~ zNRA)uz3O&1wA1$!TyjE-k~m)G2KFMh+ct#m|xBkl_1r$sR@SaG>vLq2j6OC zfTx3ulA(5}qoP9`XHW+KWe40$eSX;?KJ^QZO9^@R)%`bNVTpu`=@`J6@$6?Y>vodF1}TaAb$hxb*B4-g*6rzk<-G&Cn) zbwpP#(uv?)fTGa!G(*NHmu)&s+24FgUs4bV1DQ=dD}XAN~?Zq=zLA^rZbe zOQHgUZ*u({jBQ1VA}#|aNkoeKOplzv5t9PtN#n;XPD#G#$A*FHF~Ls5KoDId47|<0(J=5CbgW)rqZ0;}Lusb=ds?*Zgn`XQ z_ij+rd-~(5!@$=ZQ-^^fx>Ts!iCCAvCkzy$&UL~-e~usQeb>!y@bCLRE>0M@0OPAe zgvmB0xP99I_WwZM* zob@|!KImDQJ9ybjd3Zwb=ORFDQ}19j?5rFLuBQTry(?-GQ%gA-otd?E6T@BK0h($h0-sH<#Vq@!WK2l z@cAcT!{^lx!RImDx|en14R(pdwReH!-1dmQH>f5K66|}{O>S2jJ{-jJvIC5VT#tca zc_x~FLETKpKOoLg!B`&1kJ;kx%-G0}^e2+MEhK#gB0Pli!L6hb@p2lFcD!5x9Yo+r zitQ>wVSl+vZT%oNsVll3m)^_C^`&4NP3pOUuUT=*OH$RhocI|s@k|7OZ7Rjga}9Ki zd6wST$vhu|Rm?oU#gsXT8Z%D>W7I>*SG`3S2zoKoFiNE!-oP7mU!qjnmyq0W21vcZ z98@?tz3TpZS@PARfT-JxnnvHWK|fQ|TyK=vUk2A28jX}{=a;8A8hv0t3am@M!#;)& z?3T5cuI9w}+FisV&YgpK)7RbtYQ~bNW7h9NTUNengVAZBXN2hnHI!5V><4lG@n2-xrXC_mynHto5nJ-zCVXHj zJI={>>2zDOWxL$uy8|%~5?unA>ol710>I=3XZOpgy9Dn&Pp*G2k%m6lllEiX#Y}aJ zVpH8>n$@hg^Ff*$aOVap;V)ffNua|;z+wrHhj?5e_em^}!V1CDDSsd1)SSGxQ4Ir_ z8>-Re?{1ZiMXrt@3AFJgIP#3)0Kjq>5Gj9e$3&e20h~VQ@;5iIPhBTn5(ldH@qsph zEvV2|=vr-JW3Uen6;S?iA7G-|3(z|FneumwvB4mYfO8`^t~&4ih)g}QBo zcV}%{(F9jU`MVJ1@85L!`-m=oSFAw;=yF-W2Uau#Qf_h!_P+lbH~9Dc6qlUPLMeYs zFupoU*n-a{)g6?I_JiZ*hUU#y-S8RpY;yhcP;E}oKTy}dTPc=IvmScEbV09PfhJ)a zoTNzk`-tQ{%so!tgDlaFiX3L}zD{m%4vtoKs1Gq1^WHm{fOz^+&4^MqQp)-CyiodA zvtm5GFR?J->+kWpL3sogPapj*g2#csn0(~$@f$wOd&1{n^uUD3XAt>x zW3iEs&+z$3VBz!jKf&jI#HJ2;?+roLV@CAl9cmB8r{bE}8TqfVle}=fFla$MRsVw4 znHT=OkK|o-`r~`EBf0At3`mN<3&p|AejeeO=|cXS1Z*VVVZU%GbP<7By-Eu0iZR6H zURGP*X_x=#f~NH3S*D%;@@<5FRl0o6gq1!^QV<3f0Rj>{CE_`f$*1|1L0}^a0yz~ zY^pred%^{f9``>nGteY~uTFw*U|d)TsdE~X4j&Acf{A3+Nid(Jxi)pPxWYD7D+0-e zuEC%dL{U`+b#4^(qB!j~HPJ!sR;Pj^Q|1VuWO;2+qtKDzE={gG)FFoCK;26pT4GZs zjQ2NO{(~#^E%#sJ5~>L!t3gGwfq z&X0+2i@fSel60CMk%k_Hlho}=Os+owzRJ|cx3bHAurJ-)tKi(Q&#CL@f9S7m({ShVpr)nD&MTq?ufy%O6y*w4#Ecj*7-6L z{~!$G?1z|wj(?b_6aTRORaZ_tlztfe%hK4xVqwHTsE0oLk-$3sZGjWM0wB`t`CLdog$^Hkf1xYH=zil35HTLD z#C#ZUQ#lCEfv)Hz9u1TUNjxfrSd2$spt}{dVMIJPbFKvc$8iX>R)f76+Uv7z~YM&-hhvc1w-yX&Yy-5c|8;#&0F%I zohJ?V2iaG0DpqkamfZ{eu^{x>?6;VMQ-<=-q~rz`r?e|Y(dh!TKyILRLxf|N)I|CP|6#W34)Q!Rxd^V}2pj6C%SOHRsUX0HuMg6`= z8M>H*=_&rA!!%dRIIf6j8F~b!DkXSlWoV|ckxAw=#P@0;DC(uw`AzER7yCD`CMxdOlfl1KwIeR4d ze4P>KL^BO4Gm7#U)JYBs_ve9Pv>PB}ZBqy7rq)(j`5V+hXm5SjaOr0H|68t78B7(6 zY*X($sNL$#SG6oHK$&v}yIwHQ6q@^6UCjNh0eWcq-q6=E^`3-7=?`MER8Cum=y0?*8=y7m?%c(P)2x z<+YBoK`v%fwp5^r65(81?{auw&A7j{vENF|JJIxIbq+v8J-xASQx{^Uit&s>^_J@f zm5yudf%XPWq0qG0%|UZiMZ-$ zdbpO00sdM#YpB}^h_AorK>IUP$IgNFM2;Wqy=A!@+UeWl&y1$}zE%jFlo$VCNz%Pe z0;S3TjKC%LwNAumIncfi7H|%=a0cN}x)?gCB;{ z_ruq;5C_-bqT}GD7)O0YK8&TGK~OMaG@Op%7~IC9&7khakVFlMqJ|o(eo@q629?M` z^%m&AFN;*_TQuphcw_E+ScksVD%Wq+KMd91L4}TH7Zr1!7#sf*o%kmm#9M}L#&miT z4yAv9Nm|N$5^N;?Va8PE=fYNQo&9U0mamW`9pfKDN+WU2?-HKy^zF#lgT(e4;m++ms;6G+Sf$d z>yH!6whS@ujo%;%E zz$6lVj*LesLJ%Ep#c(s{rP#8nN_U4ZC)bytd$g>=7M*3)a!ep5TQp1NF^a8*%Ve#b zkYu<@eLh17B85||iR;fntB|b{GE9|2;du}xOG|`Yw?0Cn$ZXX%PJh0Is0?IaFe<&IJ%!&080&PKBg9)0 zg}S|sg!Ow8+XJXtoWxcRZ6UGkzSs@z^i5qFO>9qsld8Z!Cb3Ner78gIB({8fmc+JK zR+4^TV=~7JNMiekc-l64T7O0pE3t8BALmXj>bHm=gr`VJO`|DYj8Bk-QLER5SwHtl zGBd`-BPIM2H0%DL6FY7JfsP$l<5Nz{1eW}+@TX3{D8CG#Z2mk)j+FFw$^oPy#`7Cz z>;A}}2fzg*`4agv6H-QC`)=V?6EQ}(3;v0oKOnuG=s`X#hK|AkkzLO(G`0`%xx^2n zAfd5ci5NpfH<1)6@LBNEIZ8baH(;jA3>bKni5utB{QMZIfKF8~#t8{_nE?+1FKk8!divD(#MjD^5@+k}{W zcn`5~_VXb>1M54&Q3C5L>+~$oB1y-5I8*im|AA*l_5(M`VB1*FJk$)9mlF=94~k`( zCR8md{DNj#2-qaUv%xaDAGjG}b3c&D4#B?PF6v}IFhcY$`++53`5XIzvoYeY?FWt{ z$9DUHE|}qO?FZbh_s|)C`-a;HtxBZ!H(Y=AU6! zgv}rV>F)`f-%HJSc{5^%I)&p0dpFle*!(Xp&VFDSIH?T$V?6qBP^v+Iov?WrK6ls; z^b>g{Y~C)uw2fi&6S}$;Hviw*56sX)a{ZKXf)fdc(rZ!ISS9SY@N@dW{m*gw8`V*u zGVAA0$lHO2olcSVwmSZ;(ej-|lDP2?c8bP7 z8BAC{1mmd735U|3KP`r3nouGBVP<4m2-t~#U}?oah%NDt9T5MjI*Wgh8}g${Q%k_o zj(<|7;lMvlif~EmC>gEiZv0cF0{=vOLZtqYc7ID2aC+6a7^#;ERf`&Kq<&D$E{bY; z20q3|mZUz2+&;MME~!HAZdZlAZNz*DcvIB!Ooo3bokfAV8|_XEeuGF@=Tc~bG5Ag) zvd&~42O>8(4^Lz)V+`i~B95s~T{a76Q%ARIMe+Q%`RUl=cMJ7wqJAHYAQd`JkI{q5 z{a9_o1g%FHn>0O!O0MUrkpz>#$*EPj#_KK~cv$C2$- zxaDUGE%kDW99|CRVG1<9>Wt_(x&Be+l*Re(=snJ&gKz6r_s4BG-PxaU112jB?SVAy;Z_ zJi1G-40Vo?>n*@Wu1!xsu04Cr^KYY&Px_!S`~d`Vo_`CC-AMe;P!(6M^~&!!fD640ZPTSz!2)MhRl!Nc!I+=1^csUB2!BFDg2bP%lc z_aLqVsq@8YerfC=n3{LWf>_j|X?zhq*!LvJE<67n>Szq(d_6s}7GF=-?`X)w`oLGV z_wMnhdV^E37s%^xz7T`=sf2oebt;XYen$o`V<(;h9~cSYRG-H=T3$-)8z5@YM2j`i zVEEBm5W3Vik43D$5g$3j=OJEH!{+<0czy!km2AXv(64q_{uN)C=MAh|43z4DE|?j; z{|Kt$zqD}Z-qr9j;Kar|)H{?1E_5Y``7}J!4U5F{SF`gs>Phg&yJn7^??%fuwmc3~ z;1r8T`q2G1Y8>?wN`DScViLzr4md{0aQ||La%;Ejs$E;qDpHRcC2BXl;=M*yAn3LnRj+s3C;=s*LHfmK)O z@$eQsYgm{ve{8gRBO0Aqqr*yem;-6N!FBTaX=nkn-&X3Tn>iG##Uq5mQG_~`Yb6+x zljqi}bD3pHth!{O>6&;I{GG5qv`b8#!hrIE9cuo|Kb1|sZ7vvFIw=1fr??I{F0NT>i zH=L@`(-YD|zVZz@jX!bz9D4%BZm*|<9**j%M0A#3FgM1ZW=l+n)zeorO?!Wu0e3Ze z`cPb4{As-?NA%QP++l~>_mI|8cL)nTtr#Aor`4ik(bEt3XzS^pG7-_!xtu8UG!-Oj z9eIS-rD*RU`tP7rf0OQ!b=ShF8a)N2$HS?TARIk${?rrWQF}e@d@!n~(?nS8DrzfdL?N7Ieazsxb14}vH1yB0Z$Fx8wy=qvDo>mg8*WK&* zXzS@=nTY6V7$*va3;~I{0slZxsZl-s6_n~y=^oM3oiLB1ry}X`a9)g_IDg9bBO2T5 z>7@tI*{r)iaiCy&fiFf+DV(#Wh{UJc#q-+fX+OBD(bJXGqt??!5*$TOPm4S3P>+Bo z_4G6?fQRzaV)Qgyd{O-AUVOCm)F2ZPJ@w>7p{Fh&Q48=7^pqFX(^62Xv!#1PPmAah z#-GMWkB2K`^u+m7Pj8^Hy`FBpKcWTowdgE;VsVU~l;|YZpZwx^?ew$_CN_F1W*@Dm z9C0Gi(^bGyjuqfZJzYf$gwiLb#^@=7SnW^C@X^-OESZSt=~EfDO})%l;Pfq8Dct>NX|JT3Rp@D)=@n5}`qZKrC2bIe#42fu zxLrFXt%ZG!l1^tIt)zkCL87EmU@1o-cv4BFbh%La2)q;3%J>HptCchpA8jRNz#UAo zTPMS|si&ZL(Rea)D7wxvJIv8JSj$)LSlnbbEdt5!W)xPlOR5;>b`7SzL90A^>uNn zJ$I`;qJeE{JBV6a1=*%P1G4oK)JJ4E5<0{?3_dq)Eo^()v<--DdysASo3?#WLbM<6 z7pNfH1E&3BwtvyOU5_j6^U)qIL3A-B&ynQQ){itvqdJrA6Qb?6#SGD?PGI|S(e|b7 z+Iz9Rd$j#L(+*>U1;z&){t_;XEi6tYxgT=g52dcA({a}$FJUUgNVuQXZG8dvSDkLC z^!^~y|4sCW_P^*}-GBM-?tdp1NA!IWZ$a_;nV(ZIQe+>T{@4)i9wP6H7>&ku?~90h z|Mx#~nnd|zAiUmbW?=g5fk`*FcvfRu;ZkFv4LOqXG$z+i!d62z3op77(RP$>gBK^) z>u(Qw8goP4K0&a}3H%G@dzNHtxj%Vk zryKf2j$X^r17CWJwlI(-yo-_5R~RN(b8}>Pz17;L20Fw056AF)tz67|6|CoRBD~uW zFu|K!JI&tao!ANQO7ixs#s;}z0Hkfb5j)c4!O-M=AP(Qnuo)V=Zx9eS67dia`gs$1 zU*Phu_CS;M&ECLM8R+c|+>j}kkXL5jkSCYWOkDiOB@b?xjStC#LzQxwUYk64R%7yD zUsLkn1*?+>*EA;&Ube*>@}%U3Lj6IK6WD{(keGS=gfEfmH{^Ij4XL1Mk+;(%L5h}! zM8MEJ9IYV*AH6|o1H{2NEDqjUu{2oQ|YiZzs5q~IQE*WDoHt*MRvN{9j5LX54p z5GKo9{#PV}6mZk-z6yFoKmVb*f!Rqd?8ewe?MQ6nn`5}yfAV+{Zx7U{Jd#rz__-A? zV$5Xw^=MZoqM`NA(H*^#JwGxhh^2 z<;4Nrb_9q2oaY9wGn2fbn(bb^d=xJtRo-BV>f`uZ%}LhG-uRoISx$?K%LZPkUzHY> zFE|NSOAjLQV+K>;fq|FQARc!$G;2-xS4Vo8c|LR;i1`M#OolJ4oz}ae<5}@-khku1 z7rrnYTDD!1wQ8a?bxV_6{@&gYUc7<^wLfverTz6G&ZV?qOSaYq-oC1_^EB2?U09R* z7J-On>l2yWpz~;}TGC-QiCWIB>So$E=-JvCo!DnaPM}S{Bo?9Td++kER&j*jWo~ba zrwJcnArDc!t~S>-a+Q}7ZN7`CcA{Hj@G_#>F*w8G>YWsvf@7sAn5w4vX*J3O zu8i>m>FyYD{J=r{kQ*o-2!7-71x$hVdIRGJ!c)c%Odb09nf!uQPJO!e{ z<2l9Lz%DDH^ZD2sNc``H=B(uFU&cENqdFUdWGV0 zUCFex+>w_xeTOMPe~oNbKR^(PzR3-I9t8Sn2B${W86;{Z5%xG(=8Lf!)kt`NkOy8$ zuK$K@b;~xp{Dn;%>rTY2F9q|01smWH%R}#fgQ9J6bL$dhbb*I_Vg1W z%IN=E>I%Px6|McerWyU!hfN&bv&vfp2?L&{@L(Z;cPv|@lA%CoHYYIAP1@}M<*9VU z3(HS)sC0A3{2Iva37j0hN=6y)a%mf;YIz=oDY5=m?Xe}|6PdV+(d-RfjCa4v+*J3! zm?0e5Tz%C~^qdz>JGcYRJl-R|kP8WHp7Z^}o16_qbloPG7TaSh& zD&bh+3#iY~*cKuRfFSFf;AQ<=?~c?jSj%C9>K#$}@~>uMooTH%G<|~?&Ecom z8%#VFGjKto&3L_OOT#MDf{&}6j}1_N!x{tOm1;fjunqEW8ezoJa<;cYx zXA}9Y#myiW0*U@V-Cd;S4;v%MFYeNS#i*Ror1V+?#Z< z9&w)-dYw#?u}_?0oZ|)vB$&yh&Bfl~`-{5Z56KPdiCw;tYPFoBF&LsWaE*1$Cirp) zlDu{ezAriI8jX>>^AzV!5%1!}@DeljFA`mtDTeReM_;G~N2-)!s*NDFT;>KCB|Hi) zW5tmKxKWJ1oPu_Ubl8#bmnWgr*0A~o{i4Y@_Wq0GJ%2|TlIP_!gkay2Wx{k8CN8ik zMY7xmrbCe~)m$@p&0Kj=CU9Pj^K3EKt-PwOunh#o!?)UnlIy<)nkL8E=Js4YO^SeL zi#OQq(0n)aT7yF7TUqJ8tt@9eFqQ;-|7pQVsPfap10h6c>`AZ!BIJtiE#1r7z7iZz zsN_Z0HcNp_=(iegP|tQVj3JnGlAy2`&U%*0ki!ZZZr)9in5?@N9ztLA9D?MWRkyv1y8RZXcRjyUsFl0( z7%&cv-2xp$xr4v6lpFqw_$u-gt#F*S!hM?11wtq%vIr>Msn7-u(olhZl1=r#SNFeG zGn%XWH-Bq0N=F9>G5Iif(3hBF_#GhZ_YrrfC-b<#+SQZK-zK;eU1O$5jk!wW`fD8A z0d?m+y02T~U{v55i3=_rq^r*F-~~uj+Wmt|Q#JNOjn#`GxHLm!H)*Ua4UFK`iDxyi zmLFtMj9;l&ryVNh->Q_z@oV*}E>?2_|1rtnX1Y`GvWyP(X{RZ;zb$RuQa)gEZx?1> zd3!9}tr-rL!o#PXJhFQBX5%vcIYHU}!4a-Iimn24UBWtHHzHWX3(`J7GHyl!8H_Qb zS@^Fvnk;-VoQrO4668hJlwF4B8W=+Xpr%ndX~&1P>Pdr)ow#bb-gW7G&{4;r^A zF%_#vUe5IzM#B=o6!`vKAUPX(KAKM$ws>m6#-;vtz1&A`xRktu)q@~bBPxtqwctA4 z&>Iae9!rsezFNq@u1x@4>Na$h)r(V!Hxto)&4ip>&*-841z9Z~_e}g`ZSoAn2?bv8 zzov5N{Hi(WMMZ#;ylV=|D~f&deN})`yldw8sw%1rX3hlEA4##B`W7=plw5fTM#b#L zK@`Z;Bo)SP^}UE((+@fT3ikzft0p~*`Wx8+w}^JDOQF=Lhw&Mf4`D1P*z5;7o)hjt zKL#BJgB}9Fp@lCOx#6Ypfjy`ckJ^IAuNtO8 zMfG@LI#>C-7|~OYw+G9EOu?F34uN;DE^Aa{;9S^L@K1s)L$&mydY|6LmgU!C!~Ow- z!}S}qi`0Mgi*qi96wvI&fjC4|H$$%QOK3v=LSlc8!7^-~+eY_Dx!4GNboS~KGBR;? zEPU@pRB@3%iMW{vqcj&X-2!Af zSx@Q~C<|d-*NP#;(O`amL~A4wNk{#`1Nqh2IPtp^WdoDEk$n@65j}{#NMSIYTRn&Q znDC!TkH>mp6Ls&N`ba$vT;bq|y(Wv9FrLV_mexomLRxiX z2^!%reIR-s7EwfG=Nm$4ZnS}N(4<}zf;%E>^ghf{R|~Tv5$Yr45yYnt50{)az150P z;d6e9)L)vOp)9>SNW+7riFO>ju`k@`d^lD3aS^^&42AU)iHvt*$r@XHx))jx`VhM= z8JM6-8fgp(Ua45T3|`ksJj+f+@N&DtIl^YV=q_+W8NL3`=o6HW;TyyV!cYAK9>EN? zk!~CsyM(g}Y=Zju{$Rvhd94c?`cc?Nxo}J#?M}pBh~VQ#p!lH=5FsLzFt6uyL`7`y zv%!Z3UE(Z*6Mv^(yvot*6um!6)=FK33kn6-PFtxzpfh8`6_^L22ZCr5e9((1;@Alr zDlF&lGr~m&hY++9buM)Tmx{QgKgB7N;96n6%>`2!MoC{qmsb2OA}zml-jt-?gp#7? z*$E)j2Yhoe52xP7`;QN%4kPE;7ostGo*ml%DXL}q+OwxmpB_N=`66rD?w#xZdt{bQ zwu4_q^_)`oQa5kWUUeC|LfqtfzD6Re?&mJv!20B?mTR@%4JDN{CO>^}R^3;49o+gv zZ{3Ej%{#l)eR_KG(|!7_JnQG=r}KXqpZs+8zV)9bW;LtCx=&L*$xkl?$cA-)9eFH8%Cu7x>ws}D?JULU%C{`;n#;ikO<#DtvnD|Fbup` zw<8r@5-vRz{S%sZCid8?Mf=mrvl55`M{vW4Ky>kj&Pv>r)pac1G={pBf9y!t*BAs8 zr=iQ*v6y%3JC2?MuiB(AUd=&NyGN-&h+gJV;aB09&iSaWWT0C8XR*}vP;DqNGqkuX z^qaG1eOs5hmIS`Rw-y%hvm z$xn|sFtc_aG8QXvZ}JQI2}0Hz(D>vR68mMh_NH_Y;a%pmK}e9#?y6 zKM;JR36^%PYa>A$IK3(a?`7AXdLRg%2jmI7wEoL3Fn40s`n`#{p>q<(_josRWm;Ap z3V)7#an}0ni5NXMbXJ!an3WeD;4S(tEBS>HY3uiO8Q)_QwpR(78f?x7r8jg@*Q_w zbztoBx$rQHSUW?JPo@Az18xo)11`hp(a;?|ANm7-Z|fnN6XEemE~U=@-WL7k_x-)C z3WOf}?`;(j?&R-n;ruEm@T0us+-!>LzQTFg01A*B!m)GY?}G86!#1^_cr4lizGi4( zbL20AWuaB>Dyz@0)bsd?q@n4}dehj3zi_hAd47;JF3wXI^;0cZL#{_eUx1HS&j5xJ zTGyNN9!R%O|Me{_3;B~}M`+QkKUp?e|1q*M@}=0$A0!K!KUQ`cVzJy@Q#nSovqUuR zw0DbKT*S^_EJGauxrS1%$lohFQXOgJvQ%itTW_%24ddMKlVAONMgz3+Rn0CKLZq?WTo^b zRi&Si=!2<8ANBU1Z+-vKX3F=WysSOpXspUGZ;Igo)b9N-X?*{sH!ovX9pF5vTz)yE zIht0*JLouv@G0zo=T=$#hKB$^O+itv$7n1c4}-YTCGPmA<(%>K|5ps~`}L0PBd9HakNL1FYiMfYQkd;JxERR4Fwj*k9U zp!kCR7ws?l9|SY#_Yr*E0BP=)1@RmD?*snS|LqXz59$91WHj-A3_$(M-I5sp=l2ZY z`|yA4cVrE`&07cO;vU=w{weAK7%tWZGl8+!z?*T`K&Fcesuva%4pBa+c>?#3LRb$o zFo0PPr>=koCUQVyk1_ZhV~^3GF!p#6b1>^65!(H|>j4X(8!AN@;K!a~fcttm23SxJ z_D4addd++d+lT+d9OyKk{_+`wE}Y%}pZY zp@#E)g%7A$#$frr!m=@L`+x0=8u10;dvHqq4a<6CyKwRI}|V9S14Z2(aiT1 zZqh`XHPMnJ5XtuyP6v_62Yv8S{2%kM^{wl7+}Ga1O2w_pAim6dlUmMspAQ({yXeh% z=r@StPqz+Z-kSu zy8kG`crZW~nTXMk#$i2x7U!Wwe!=g~OWAX`+I<wlccB=*| zHq-9#)5b(n0@mtTXW$Uv5cdoYjYz=U@yqLP&6ai7Vf( zf{Dq?Djr%!G4XvLOqu7K`;#u1K31lV?~98QIbT|7QzB3BsU(gb>ia0BAGs%Db~QLZ z!ee06$PQINS)k8}n7DeJ77e9)VnsinSo3$i8u1yT=S4;T3;kz_khG|y+KK+{C0g_x zXp*9zMY>@6&QoYLocFd9{cVheyO~Dx|9lU~IRfiM^m`}^M8A@YY&Q*vLwS@Nme%hQ zvudsX6Q3b^WmNRfpiuRKkhG{0jAmNi9W zQx=H+7M=f8jvPw=3>n%I{Y%k}7JUH8qwfVjfpTN(3#;JoLE>u5ed$sT-KO4!{FM7+ zjuT9OFI}trP0ATrC3rsx#)_(Z`FDVRMdfJ}1acojx$E&yZt&Rjk$miSQ}nUh{h^wU zkKOK8iJ*5LyUl=E|k6&+0dH%PAWGjp(66w?YlCsZ`5DdwtOR_iP?E@Qz^j< z@7ocpY*VEemT&2kzav%#Bp4Zr5oqY1pveG$2adSyzJh`aI<$Ttb0s-$n6)dPIt|{|X4=pb&=Wl^lX8{E~ zc^*io`Yx&|t@2f4^3{-`w8-bK_E(jb&vn;Sm7a*(Ab#ImUzNM0tZ*)9%8Nl)1WnE< zESm2wsVOg_KFQG<$5P^n?utrM6qdP*=AoOfd~RfX4%TrfE#FC}<$!S&`b{YHl@(`K z)X-(zw66KFn7B);-Q^W9rM^SshtSpj!tx^DugT?~=fe%2>Y6g%2Exr9!ZC)P>Z`7- zD6a;#1d_zIX#-o6tAXy^<%J7C-RZ32=_f9^tfGv8G)=&V@h2tJ=|ZvPLwe{uiF^FD-IU8{(c^SU!666p5A$Hls&t zFCDZnWAx};M82|9`AHL;HrRdMqEi1n_cZrdw-e~Hb>N$25ARx7QCi$_XflX1a7=HP z%g7gJ7=-R@6HNw*Te~SEBf5hgkDIfW;3u}1<+S4lx8oQKE-bC`*C70KF2MA1qzxpG z_&>kif9h}acDbDX9jtR{)Kn1Q*y=&YRu6U|VVyjr+BLVjx}bDHWkr?0fXi6J$PES6 zzM=vrKM7H}MDG|}acOmBS>cjs&l;VMNYAh@qZJmJj#XF%F(WyM!lEKyWh}=9^O3t3 zR3Z@T1j_U(o%zrMWT;$HP*hY{G>?IoW74j-rgiSzlXq^yJGb7QJM_+d zcfT=FwZEduSHRJWAZfMaPo(8iWOj|#YqtQBRMy} z-}H~m-?TgY+kXGgX&^m)MEb~6GDeLabLv>r(Us7pYht(V`z7`0*=zsa2PCH)c+kOp z`u?e3|3fsvfI|;E{D>pnM;(34z+;a)e$e0{C!BcF$wO1qh7FhYtZ~`nJrgE+bIv$3 zchcl3d1p<{pEmvM88gp0w{T8Tv9DzAywVHjmn|r-sJy7E+F!G9(c&c+v$K}tgrSi# z$wUv-VLETRoFwG(BkuY9;>adl`HHh)JesAjtUB9x46V`er}K6DhvU!xT73Nfo7V*l()~mEy zM7?d%Yw>|vXpy3}mR6-$AB``dwrZ>vt*^QN+I#IYXU?1h;_bcn`|ij2zL~Ypzt>)S z@3q%n`!RFQE+2}=H-jDl-3Qu?Rn#cxKG4a?uNkYvTF|#ZH`6^h$f1C;C&wgYMgjc+j^%CzIapLp?z=A4Iw69&`k>7F1y2-2qw%x)!to^dRUWx_=ly zxPiX)E9eFE$giP4(9MrPF7_Js{T6aT%O6Glper7a$G6e_LC6QKeFA#Kc1rUI$_cs+ zv>9~rbI>E`k>^of(6uk19YLqR2)StYeV}VWryqj;Kx;ww6Mh)-XeaMaC@1K_myj=L z$6vq)O6Sh+C;Vm93wA>1yazy!fHs2Ch2I6_l{PeAq~V~#f6B?o+<+fMrUJ$PBt&3o zJl+G{im~}MV<(@Jm%Ti5mH6UEKKJR;si#vy;;F`G#Xvkhj)2Os`NQcox&BHB!Y#$O z;Y0Cga*nSuYZ(_3y-dc@aU;aTrp=c`@qPhT_!vTC4cT*Q9|J_o`79Rg&2 z;ICfqS%<%r_|h-5a4Y^7z*devli)wc!rzp_KLPdM4E~!;`BwfY@z<-;C_Pn!e=_>w zQj;I$2~&AcoC;!}lRXu2UEo`E96qYwzk+WY_!8wkcK!B%KNEfa>ZJTvd(x{Z@2cz? zB9*Gd)E;kuf8WLN_$N&MujIBGpzZNUK&+Fb-oeusmI}?cAzV5sIgx5yo~SprWcBT(*2M0LOLFS zoNiF>SK*+vt*g4KY`I;DKY~voe7oc~j?cda{EIYy)$#eM-)+(SXB?mZ1@Mn({_NxP zQ@<<3SR~8;DjfDP>RSfc)bAF7{}wOw^QeWt<~yD%yz71Etn;tV@a*+a>#+Nf_V@<) z4`QsUg$y$fv?JY;9w+b^b{he@4Atb1=C1R>AI&F$a})lk8vL6v#_e|Dm;IqZ@t+Nz zcTw(gjDZ`e+{2b~*Q#=_^VhDg)7N1vk)^%rcezlu)lz0ECsx2m?M zUZ$^B*~|2oAbst+c>FYssa_fwbsg(;{>XlSlSh)0%k=kB|GO$4{}j5Kx7yOKPU(00 zNKlxwm+9X{`pMtJbernG(URV={x8Y`u)0HmwzOaDu0e|4Nc_4|I5d*5yBe`{&HoS*BjMIjMK_IDcD zC*tX;81JA(zQqRbrb?mjQ$MID{@dg6KY-QSY~`o+Y+CP={owm!I0;gyars@8W7Ylf zIG&eE=m7m-0YpXA^UQis`Y$8C0`e!A@fb(Ao)mux z$Ghc!?QzoI%ki}&U$>#9A3ufo9_0TM=+TTf+qe$Cp)iefLbgSE&p}rh{TY4*u=3Zd zaojUivg&Rm`OgM_V0S!z$eKU<=5H&(ONo&2PX$jG$p`<(Z%-d!=Hz({L&V~>wML4h%c#Hrr$zTd0MLPmyxa! zbLK2-xv0KRCf9cj_{x8Uxh(9_EKgGTA2J1#-P{3wdEgVmCcmZKA47aC=HNY)ue3|p z?HoBj@Qjre3um{JMD!ohH@N^hb8ok`oT?o?EzI9X{AftxF9ZMd10Q_8+6Mm3;J*%O z&GJ@L-wdz!LE+@>+ekk2E!!XbnZJ+6H(B{-U*VafC&Y3y319&rC(yn?-HbIev;GO`@z!5`eRMD{VDVt zWUK57e!Cg~#Or@Y@tNEc~#&y4BwFHMw&Y{TH(b9h3yY#py_zZZq)kHj$+X~enPOx5WQ6ZZ z5518oUP#6l;7w zgxC3ez&H7j{`)@PZ!*PGzR%zd2L2!hrl0$7N6I@%_CuNYpViwGTA!t|`bOF`F%8>@hr=aT^AWHQAwG=ZIfsUnsmvU7x zzRAV7e5{C#pcqf2PgpZnyqw+~&lL}NijWBkfbcsWAMne(NVP#0<6$bs+ujnC|8^f{ z>s$Px8*;^AD#qH3(0e)J`Ha_4jK{J=8*;@RIpt6aWqBQa-9}%s7;jVP-^St#+P|F3 zf_;nF-%*w$>7jqm6F>1le` zmHAK)O0!(q!lo>7(PxFYF)cKjDV|UJ8!~;)GvVzlan#fNw=D69x9B%n;$5!~VORw4 zE65hE@%iq}5|5EBto8?2XNi0Kw;<&U8KIlA#7&tKkQW)lm1GPz($}3?$aR!$qfcf1 zYOXdzG{b9YZ$iKkPY5P(o$o5tU}wez*vD@&n&A^}$}GA&S3I8SLm0*k{4mM?YbF`b zkFrpVr?P@DldH!34k<6qEfV7QqLezCAs3Fk9U1 zxfJEz<)qY#I(k>c;!(ERn(J8q}12k7fyj(&t+LN4o?*KWexoS-(!jpeq~I--ihM!Y#+i`W)shkvS;j>2y-90 z6W=*S2yeRC$63^qgGj5zH){hDO@5_n{RR+TJPgu#KX{o$nBamA3~3(sf-uMmYsyrqrT;5S>iv_)}$ePXZq0X zS>g`Q7ZCodXXu73@v4`?Kk^O1HQeI=9KtX9hc3?&&t=pgd~4=szL}*4ly6XXK6#zg zz)209)WAs%oYcTc4V=`#Ne!ITz)209)WAs%xN2Z~gNj-;Pth$*_cQI`cvk`c&myqu zl~>lOit77`w);=p?q}KV=h*Jg=X-4Z%4;RxV~by2&DDxx%UNDuen?Sf6T99ilmOn* zCa*%KA7MJe@w9JE7wwVL^|$xqF`}bf5xq(dOe9nY{G=+cMcBip3tQUqdXY0$yW#l# zhjIFeOkGnX!A_C9HgH9-+a@pUhRbUb(|y==piARxaU=>|x||hUF#3ssE}h@|aaI1! zI2wd5{E95=qsu+Y_Y(su{_lLRs)-YYjw4Lc7(_yBYm~LgdgXvzT2bdmWdX%ZZhVy4SjcJH!4bz28+nEkB z9cH?T=~kvYnC@kIfaxKoN16KPaQ;lEF%2=TVY-lMJJUg?!%R0Z-O6+a)4fa&Fg?Wd zC{uqe=g)K+(-6}drVE+2GaY0)%ybjetxR_?-OKa<(?d*;GWFMS{!FJa4Kb}@x{zr* z(?O=gOgAyz%5(?Qy-W`3K;)IXQ=XF82(h-nSeg-qL-4l*5Px{2vlraPGKWqN?=A*M%}`s+D=rqh^)nAR{| z$h4j5Ak$%{o0x88x`XLnrU#fFVybdY{a)l%<4kIdLiBj5)g2{_c#)h~+W z6C1_y(a_>{+#oJSPpydJXou0>i|2HVjy9y#cM#gzYD8DG(ql9zXjfFpFj{(hTUH7w zLx(SFMM4rrIYX{2Wy`Y8RtSk9Z+sQYLZ}QE_w|Y5*4VOTc!a{P$Pal>^O_8N^n79; z&sQ{^YLn}=-52BjD8_!BUe9+l?cxYMf626^FUNg0K03Xg4{5qz{@EJ8^D~c5ujeTh zz)7}Fujf~q>iHB{BAYulY1xfb=w1()W74r0FQHKwiUH@*Rv8LDaJx%rekkXIA$DV!#FsdSzjV?VO)>O}P zRjkTOhl%##V@*$IyVIqq{7=1t3_tx~=4k!jq>Dd?SWzT;LBCY8IPbh9p zr`jB?Za*#a7F+trVHKn4Eb82ri}JEw_u_`K(DtR*JG#gBTq^Fz$8epo^f69gvFI}3Fd)Il( z2>yDF^B<=f8Moa^Ikqk)IoHw~K5*mrezP<+A5* ziAo82P&z%1S|dI1HhO$a#yvuhd&#(0=2UrfgHh4y#J_&9U_CK(?u zw4X}GPZ8SxB;(j!(SF4e;SmKw`wI&Udzy&;UucD7*du6HW{Lwo8SU3q?lUKYJxAIY#_O;S6!zw&i#mHyR5d3GxcQO7Q6)k8yCjQ1o1!#N=<0FjUq@u+x z#y6a&fTfH-%ea`IjMFJnB)^AoE&p`jX(;WM{ffVhmX zoALR;Nk5CYU3mLYT+94=|9Twr|3van7OU8vD;VF&{Cb~T>+=BcW7+M7dz1iew=c1r zz)po<$MP@qse0{aT>hsVaoVm{J+2trnE&U@AF|nlwyRY;j$&T}m10-GFd zSB0Ff-L3@7(R$E&9(ha&)_R`d=X$Yx&EE{%NpG#d(?qHt>tQ*ffeX&$GR6Zod^6+r z-ywc1J_bpAT;Oyo^1#qoHu976Q z4jm8viXSReK68ZNdWl;(RrqEX{27+h!vh^XTS(WLm`FP1Tjzp*#Rb321>XsLyvi!+ z`w4NtFr*eurRerUKhyjW7jfLP@49TC*_F2ktKX8%1$A$lC z#(P*l+7BFMeEaoEu-4n8Jm-4N0Z#V6=mEw52`V+m;;{eS zihB+Bqw~>-PVz66c(&Lzr1V!9pyPIg;iv)iX!L~{%Qf^J&fyiX$S69 z{_ncrBT`Os8R_n*3;&c;RC)HZ{lHVmD*)Un--zUACJSkI;ok||Y5aQBMb2S~!=GQE zgx|vU;77pRvwE zj$kctr}8gy!Jl@)GqGRlRL}Y9Q|&aD!6?2 z0)iPIb1r9*3ts1fe?{WZ{}v@*`|U2^WG8Rg)`=H0|CSpR{~<-h6^s}DhXUj~91y%! z;>=_rk4X6zfP?S2@aLo9ob2th5{I+?XC*+-d#iyv>HlIEe5VWks0%)}&{_U@F8D^^ z)E`G|{c(p2{{i4m^?lm~pEyPJqtOLIUWOu~7`T%j=DOf3fji~9UgGeFJU^#r|LJM>)>sS5KOFi+9*zo+h4JCu+B>{VUU3Yt|uAwPt%vjjcH4qJl z!w^^>EH{$g+fA=WZw#Fu>&5%fDZV6-9IxJrY~`>^pmHR|&q|gc-^uRG&?H|RoyuUA zQ8C!csI(FcB;E)dEU~@=nKcp&S;1=jTS#gnq>_c30tQqPoMjk|^TUzI1xC$+hN?*2 zxebP)6>rU=x+FYU+|$zAUmPq!d};yQBnS5q~Fy_>sJG-*pF!}}-8+9g+^{fT`;_VdY z7Ho?4L$KYo*-O|Yk6J*tZD=Ynl6@PzAY5HZps_awr`W$zi;`Y&Q2IWLGY!r;vHXrH z-R@&k`mV)y1e|=!hwO(5cjT;jtF~Kv`|&#J_V!|oD#kfg^NsqtrU*P;ThwgS{$)mM zSFAhQhj&tQJ0~E+Xp0$3x?+o4x{NlwQygzAA6S8-LzeY)Mf;;|#i3aMz**36j*-9j_+!^5PPhwpz$0e%?;Z^3S1HI5Z+S?oJ6*0W8yqCie zhB4AGif7J{r7`bj!DX9qp}bw!l=HWp>kebm6H{bl@X4iAXugbxd>iA--S25mr(yo zJt8FBdF=PG%lFh{%l-Zky?5>4VkD!CPL}T_3#y(RcSpa zM!8QKx@pSeHk+Yg&N7>6mRX&c`svTFc}Lou@BaQ8A~!Zg!PXQe09zLn_Js zvVRx7q>SsO4bkN%qz;);dv7$V`+ZV-@mw+(XfzKMs*|RYq7Bp!j&x>2th)+F6wn{B z6GM!6_OSwskcQa{D$n z8>Pi%BD$ipKe@#XgSa7tj(o61T^L!IGBjXLZuH>%p#FBFwPR@_0ZCVVnN7I7Cf3^; zMK>n%3)SM-l&&a7z=S%QN)6lwXKKY&_G7SIJkTFS7V`i1Nu6(IQs<)yMMCwuCnOD_ zaws;tp0qXTt@(HjyRDVcX-dJ8c`Zw$T1>c+WawUnYM|ZCdLYd6avI!AX>bo1<+>y= zjLt?APO^X$aY7ndhI3hBt%(Mt?hlPCJ(Sg8 z_0g5^Ajz7b$ptE_?UwB${NB#~C^@%qV{2z)XD1uRtftN-I38r6H!58P^kZ0* zYtgL{Ozq>OP%IQgTW7RH40LyOc3X^(%budzs>BF0lSUJqbd{R5EM96->YS)oN(4KR zGBPHzkAz8BEJD}V)ZmOT4gR*SknkeJFIUdg-Xyg=yaLlpoR1Z5#9R=XqBZr*nwC~f zWmeWjjBt5x6q@Wd`ooccA(YQL#=B{4JP;76ZT|~1^Xxog!@`s zdT6jyE~yE}^F%SCB=ss`)J5i@D0+U3Ng7RDAf$McDDmWj%+5%O(hVPXqajyHN~QJOkqOAJ%gGiVN1Mw^o`Au=<^`I}nQ zrHtZ1>bY`$+JMI?k2xAbhe2!CO?7S7_6e47^XO(!>t47%c~~f_pE8aI%NAhXOQ%-- zgRREwC&2(YcQqW#1w_I>SZ9yqDyg=q+Cu&N%-J7wok*|yvFgQ0&HcY5(9{)Mjtbe_ zp_(8piT10F2V+?jOWh^OgBGhS+O1WV5E~4k-E1P=$^-8qH#(9{oUB$KTt`Q04fMI# zEi#?So-i~=Zr`XL2i)vadbCRP!tzK=EvmsR2WGjfl;v=&tCK-Usn&9mZMc_GJO6Ul zc=CW$gEL2M3QHOiQMeEj{bx;Y$im*t4FwsGVWCC2KB!bz$`4N&T3ER!fY8^fL~f31=SV*D6ok zRY&n9ReNS62IZ9|X78z;BXu6H2R^s07|YVr>Uo;Vur<)oR4E->Vu?a4IPRGkc4yI8 z)q9L_*J5=vVQlT}X~AmRG6grN=XJ+0A4K)BDU;kiP|9UYptrq~tyI-d2%<}e+=Z04#u5?QVOk%zUzJvmsO)M4eB#LD;R z`5Q0PE#0%O&+MM$IphX|-Im(g zToBTIY9yP2jFg&BoVw~%2p9{Lm+EbTAw3T3c@iuGZPVS_gVwQ6&*&6PoK|`qLohBZ z#b!q1T=}y(a@7M$>IBSmq1b0~>e0tq)&v8!(Uu;zQrpr-RW`{t@H&tz$Z>@klFQDh z%j$y*N5)sKtPVR7_}v%_P#o9ow%&3omEI$#4KNx@)ov2z9EoMx+*aC!3XkzGLj^VLk$T0P&QAewGxdf9SQUps?DQLpn8|$KJjnjHeFWb-zTxfGA zmiGb3?rfDzof6Pl>S`Nt0d@}!{H_;v>KAZoK_Q1iIkt4u8PmOkovr#eIrOd6U)l5! P%l;=Z#GuazH0^uT%U1ZAQC?N;)rgRTgJ*1435^qaOQ_Bv=idZ4pul7ZvryPOa z-bgSI4@JU`u0W_)?VJh(tzAj}(yAo?R%Ll~fI;>AED1%$K$Mc16pGigwMOzGu_Mc1t5=<-^U7rIFSr z_0mY)WM)j1(|1H|tja5mr0WZ=D#2Si=Lv8ok(14g*?^O$ja8dDlfcPBR-Awyl|4V~ z9s2p)87R)yo2$EUxD-$*n7pn1Rs|u#xoU_P()YxI34Lk{hnoe2pdwU*i~!h_RI_+p zw%1&@5k>pF{QQ>LC<}uB5X6ZeRTfdEora>KyBi@ z^p+bG=pw5tOC#=5Phv7F4OXB-8f_IQtq81oX;dti6OX_-iOIle(%P8KV{-(_jk?aEBr>I<%WhK~z68_FC7rjj~tmoKN0THuBG zmO_R+D1U`U&#q5il?%(Z!#>d{CHYYA$It_4@wEN&CBM7-C4f@pAj}k&mi+2&+F)OY zgM33=j;?8OmK%5$0+DGDoX@|MUBKJz-m>+DZQFP3tgc~EM6lV#S$VVb3kv7VEh?5u zO6SclTd=Tv(PEwOOvRF=&sI8?J@@?b6)RV*UbA-H`VG#FRjy5&sb8+GtM@iEDtq?s z^X)&-bg;RlwXOZoi!U8M66gqas$H*jhmQ61_Jt$;$D^_MiPujKoH~uc`aITcB&4yf zZii!ad&h}z{Di~p+~#y|*mQzgu5&K8v&y|jNA*RQv9$}QTZk}FB2>(soqq`q)gr)` zFrR{>TwL;|t*$6f*6i!S+{S$Uz$FU$_7>$ezHP79M0>GN2wA*yx^R%^kSd^bGkym7 zJXfvG4={dA57U{>*r~pFpo2JL@u)s_b1kk8#EG*r5DyS%M=VC1(FhvIbU9sMs=Wax zlAN6(b(7KV2*lK_Zoe81MmkjsN2kghdcsh+QyuVcb>}KTd?-eNV5F~44Z}3Tk+|w? zJkY)&77qk_SWdOu-xUq?scg~zW2k^wY?_Jz zaOA`FU*qwtV9rf&8O6g4`lK2hygnb1hq`(F{Vax_O{U{eV$f0D372TX&>Sw-!2#x* z2jeWbaIGkK{!tFXWmP|oP7r$jb(P-D_4fg4Ri8+Dkg@)3fXwwnfLYbAvgz^kdD2yS zH`nh3)T;gftAB~b;`$5VGS@!~7}jUyKx4v^Cb-Q;hsnMOwpDzB#mgqXIsQEsUuEKD zSo~TOj|A586YfK6{?;nRRgJM-GpKX-Fh}eJJ5+2Xb zUnyYbXAeV$@vws2(1+ZeubTsCo9B+cgL8Do`^-5XOq_$cKAs7y`VZ)b3nB05X>xaS z{hY(3AWtL@%|E}CWzX&2^dP(CN^pKwGeq2~^N6$NO-~OvK7rGv5KMv0&4F@G!#voX z>4JR}2x~6r34_~izzs0unaV#MXD=xu2)doWJPf%0TmAHUmr;&rS=mn5CK~dr1bv>N zKm2^I1Kj*>!7%KH72Yxfes~7_)fw;}z~>qEg}-l4&A?Ak{?xwk_anZCtmaAdPXcEU z75%q;>Q~=aS4Et@Iv1he5&lMBQ?2atH#Ic0dfWVMa;?wnCw{*gjfNwB{wI(0gB^(y zbs!W6XMZ#lj(7Qk-94-l|M=*m{|hBC{B$UpkK^`QU& diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o deleted file mode 100644 index bd32e748e877f91bad7aebd4e0e4efff1e686b1b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 86232 zcmeHw34B!5_5VvI2?-Dq5ftk-AX*f~On?ZeNK66~4HyY1)#@aK2}D9BCKEPA(FA2W z1W{|%{@RLF>sI%=i$-LTE*7m?+(8zJQNg9wJ^yp=^5#2t-U|Uy+kd^EyuACq@7#0F zJ@?%8y?5v0qLQ)6NlBItN!Dm9cBN6vnlV2XA0wh;tYubR{s>_m8}$u!p3FC&iGh5be@6b~{7J=; zugd&Q?`8X=hx(%zcuQJldi~KeI~LCG@kIFaCt2T;$d2ut(jQqX&qP)nS>un6>sUCK zsE+r2s!2*B!S((~(FT9Zg7x_wFZ-KTWuKk@^Zax2&pqdvtV0WlM|94if=T;*`g(tP zy~>(XUr~3===xw)L%@6DiQXIq%&4fHRuc>iDQ=h$tf(&xR)l8^I?}2O);Cl)goCx= zK}Q<5`WyF(X4Qq~QIh_lspkbN!$fT(2IZN-ikUHg>q%h*Mt9)GlfuIBdhx1fL?)FPdvB0|Ht{eEbD%Ba4vPA`yg);sD{ z1&#n6LFG1(j>}i9bLry$620N70=$6r&_y2fAwky`hNVC zYF90_ErD5~X^l0(hGT0hYWWDrCMv+Sd&ms3)5PHUjn(zR25L|mr~+442E7g8`s&*0 z-p2asqrKJCzDy6+d#h?HrV~x=G@`4d)@f=*JR|tEq~pAB z7+P=8In)uRmiF|sD2ZEA|&1GX!F49 zgh~anyYxqCP!U<{Yo$>|nEWnRP*ShV4zcp~|ESN8_WA$Af6n9; zi;|YRvO79D@+XPr=#uv~kk6~iu|wB2fAqkGk1yxSkk$MGEn$>IZ@NvBJxYl?d@qzZ z)xfn>*90$G-YASd&Qln1Ss3}otggkn+RCn2an)2MkuOM>lE}Z6X1COlP#JHzC5PhT zuB^;jU`fl|IuRegs3WWS%VeH?&92iNApx}lq@UszTvif!a4vDwZG%7Bw3zhvM;4`P znZ(0ZSF0UaWa--_Ef1Dzm88Ogw?Ep#9Q@IJs6)wWzJnB^P9>(#THmLN?m=c%(z1v% z`6!W*@RcPInO`kfWa{tlI?F9LnZ`MG_BxFkzf3R7!^n7xEgq^61{?LBjV#1eVWz$fJm07vp`lS_ER*; z9vPp_2HqlM8OF~fsk<;ftJ$gXA7yJryJq~b9E(9E(e6c6X)!Sxzi3PNkmBeG19>e% zcE81IQwGu}B6HoWt2+@1E-)HhE*g!<;9lG`$@UnU*7Bi&k+v_HjPOY*&)Ze5k!kK&Ic z=Y5iHeUMy#NrtuAb2!DXPC1zHds9wan{IuaGK}I6rsgfpu-a4W|1ZPZnAV@-&D~BU zd{sBS{KqYh{&trmakPLYX7G&KK&Ep2WoAL zBVRu?h_0!*6%;h+r8Y9F`9i{qqrY87r;^Cq(V;ZANtXl^(RETw&u<#t5k7c)Xi6h7EW$ zH@)rgH+_*59>4dbwl60BV>+@P8q=fcvx_hOgTHBqbf)Ik@b$&fl!27Z`XXPe zZ{1_WhZ^EHb<6N1)nY4FbA;=!$!g9gdZkoS*3x#-GP6cXXKmg5NE%ZWN6t-`>fbIX zNqwHyx0cgjfALf4Bte$cT8a^0rE5vcf@Pvhkg7@&yX%&%RB?0xb%R9~#?T)5>W zUtX|KPgjd0MM?~L3h~v&Ecg~jCtIS2pOVnY_@k2->t5b&CZ$SGJxijrUb>T4YpD5a zE?>@yjE`KLK0b2KViA3q+lu0dcs!-(=&F@K$t5aRCgeQ3xMfbdHlz|lvm@|qGE_-R zUAed?`sFBdk2aE7WycM0-ywPgxe)_3Bl{j#lzIv(o37LYe#e{~P`S8?sv-IPG{mrFV#Uu{)@3#Z?a-Ihj} zpFF*-h`nA+4ND@M1-%|}Y5&!wEU6TU>YKT1Q`JBfEY*ef75tAIc%4-De-04$bN#7? z`10OMx6Y%5s9TfrI?}BVlXj3Bz3b`oPP+AtXA1RrFQ*LtRl3!jno98{si}njDwR5~ z8&gyNo^HLKdaPwd(|k{)TPxG;o;eQ)#RvlrJgj`-pEAL z`I?`Pm5PU}S&L2*z?A*{O&9bde~hHacBRPoe!ggRxN*;Fo=Uu3TB2K3isHy2<0G}{ zg~!j$&RTMZsKq4dKed^;gp3wHmi;ekX8uIh-Mwa}l*&&uv5CzL&ts^Vil2Um)_aQ< zmmIlZaa*ZqR0uzd8o;+irKLV@(O;^%=}J3zE7g>#II$+j{f*WiP`+)VeEo_x~ab#rod@;qK7?GRX^qq|ZQV9@@%C zTGcXYk0)XK>+5K{jBH@H&r-Qq7p{kY4ub~jOR}1)No;J;P!jooN3>6oXUpEK?G%ym zG1LIaGTeiFHmZD5V^8C)tfkMh3q<|YEw#~5EW;mpu4x+$#lA_(T67AL`lH1(f-3IO z^!deESBxZ}=?fY&$%pKe&KNWG6U?QBMt#YtZJM?RncLp;fxEuw=vWrl-}y559|K!6dsddr+AsjD|LW(N;k5{C(pD!K$4_4Ij*($*QMjon{^GM zQZzeP0ZFOto8!1_Zr>Jn?b`D?P*LZ4Y0?qYyXNIRlxc-FkheXb+~=}PYish9>octt zp22^}wAwwX6#v+hO8D0v>P!}=q^`@fo=KrD^`jKu>zUT=sUgd{E-mllp4MAwl>LR> z@;3Ig{?Y9|YLl9KSS$UX2ssXz5c_bu{$+BBcL-Z?H^FV+8_6KP4rTN0@w z|MiF}N(s&gvsWEpP?#t!Il9om}+{fiNWeq*H7K<&$a9=LC(9)V5 z?w3Tq5$<0cNf{_2TqaZ&+Mx1gv=1%X(1IS%dyG~#Hr&@qs96)KjN!fKCa$9#5#<|5AT^QG99Cy7;{q8omLOblJDZMy?R3SpUH)G1aCvHL&h@=78D z50_;$?C^BKNH;i(t`S`~OjWNJUF#SW))poqd(oH95&b#z+nu>hgRdiS6 z*ZJLp{*)ncn@UJ^<>Z5H)g(krbH`KhK_3g_DcwZv0VLZrolrD3au}+cJMAu-gfx(g z!t~fSVdhMo_2sIwj`XrZ8_7XlN$%6!%X&X~N=K%(+B2BCV(O+T{-r0C@I@)q@hlUa z^%|^<%QCG$^&CNyW$u`N z$N%o*f167#k|XHY^>aj|9exkm|E-i9+Q*YcIXJeD zj|)m@AMYSQw2udiMC233G$kTZi1zVu?jG#+@muKo+jxCnr80M!RyCOVPSyIZ5Q*%m zi!mKL-b{CtNaxAA;wq6YF`pSCg~;dYqQCM(`}&Z$soK{~bV2I|d(lTuB!O}BvsgbW zUhFUOsrEa{eLU6TEUI=-(iFj58>eA$5#1_@%*{52#+2w>xa64d&A;GD66i+Vjf4p;Nnc-dkd-L>G^E?tvo)aaT|N2 zT0YTF$~t@ILi3rd=4**X%*|-tqNmkuH;ECkezj4J4C2Q>C6N;jr>QaNCdWZ3S&MF= zR7%x;V#)rGf(`3$SJJja$kFZbm0U>4Zp-KKg`o(* zFT1DyD%*Of2aRvG_88KXZC&4UHMIfPWzoGm`QMZL?-l;{4gb3`o0}9JaQvd)*;mgy zlfS3uol{`_wXt;Xt%tQo#rvdtzAkt^`DASUb0*nT`LBLvn$^s&N-&9fB6_Hzk;8EH zc;YJtVYu}-K?IK{t-G!lx|KItcez4kFMM3SoE`T2e9n0_$=kgL5dA2-E)O7L z<0+V&w!I`8Q&oU!J%nen@;zwfZEMThT0|Qw*AHku-$+h}^Z8pTiG98I>Q9^B9Iv!3 zWQ8Md!Ah{7k8RXCwOZK~ZP)iBbER$O0Ir8D^uQIIj zMp@R)NqIZdt<6dQqQZRJ)8~r}>r>B^e`Q$Dr40UihV@lSD#hs$E8$D|;p+9NsZV5B zFY?3HrZituhV@t)KNsB6E${XW>(=x>)aLTj)hqew>dpM`;S6ehcdCc2 zjijrlc?Wv379C45u1`&0(5xUpjGzJv&*aBg-H9mH(%&xT4q_T$xAcoviRM7RA@ii3 zUZ{aJJ=BT4uyf&Ftb>K3IVfbcWwzTk3Iwgy_Mw29NkgU+PrbQpJ4bOhI4|B;$*?`Db)j zkliN8D67m$y`MxqtbX^z;ZY)0_^jr4DcNIWiVmS^f|BQEtEUTBJR;nT_;)&O`T;xE zwL-!F(vI~DQImG(1tMPQaOqg-eKy+<+D;Qw3^9+AlasNcVl0&PLe-yJMQ5rCcYAi* z7)m7G572GL^+X`sjw>iuyml;4fvmQ-b-I|m5d@)pUgx)`I5&s|Vns~v6P+Q`Q~%wI zT+r^XXGINX#G@^l{=xVGXH5~IyUZWrxvU5RsX|lgf*&PW4qdQAPb#1t zYM}U*I@?RKU3vuTAjkotF1SHSF_XI1!H;HIFQunaoL&WkDkU}-Tehhc}XU1`S4F( zyA@Aczvh?A{;%OgbDM_=G3!#Tf^`(kI44_T!_AZxo~M-#d)DdGfT9aF{yu5L)V~ zgIWW7jzL%hyFn1a8rb~=ltgFH8$t`X58&s8v99M?AsOZkVz4h?jd2_7_aP2qoKH^= z#GqflqVMvGFR#+E#PN|Ku`db!{+~V(c<#S>BEY+R?cNI8??ej6F9~AL8-$-^xBXm? z*X`+K+gdR`hvzKE!u(+Gy@$Ds2kbF@V)KPIAwPDVLn_jIpqnut;CD)6>Gz&qpNaQL za9Z%1%lzSEF@JE{!J zQ|J}Dd(#H*>}kE3mP+w$X{m(oOrxROmuabQ^t2x8#?NND`TpF~`c3*m^5NfP9W$Xx92^XQXZd)>c?-}Xo^rae&T6NzjqYY`9r^pk&n zMdUWR=4aIO4eqP4;^%!<=%ujOcTsw075-?oH@&*1pWF(g(?%Zl-X5B_-rgf+A#Lv= z_rNNp`fAaKZ=Z#8{LzWjH<$KPAIP2KvMWm-DJPU-=WBn?c{%zxP2}KARN}q%B|9II zdS$Y8;yYA8v7qON^zHUCs;<1}S(*Qm_hxXH6j?EsAR(G^8uu=4Ny{zwQY|1%_@G?q z)|G|7X5sEoFIeekvi_*tZ6@{^6|E}rBOWRXH4~TL8LE!$UCmIulPP70GE%Slt4Cjg zgYJE$pNX@!=%*2`Rzm9@^gtaYv_ z!D5}jA6)@)k$aJW1PW~kRn9HqNksG-POM&gCYxwULStz#Qi4=bMPxs2=+p>r>0(=2|g;(yGUmhHBY_}iHODI-M>=Mf|gB%F6{ z;e7+L@Bt)!M-&^&snMJB7%eKsoW6B55GSLmfsK02{*qNZEQReP#Mm?b9sKro0m|V^ z`z9J6>1jZFTl*Hgx4M&iw>#eB=j=kG_6XkJ+P+cpwePo8QR{*vZ@0f8NtTK9ZDWo5 zHVbwCh+W)IOS~@!#wz_ba$y?vuSy<3lc?OEtmtc>!GAGDcX`eeC__$>g4&4 z(SOfiiht_qd;9*@l_{wdzdq$4qIoc7_^ta}@2AZFHT_Q=O!42P^^NRrJ(`wE@u$<6 z=8d%Bm+x;~({272`&rkd52pB<^uBHTS)0;RDc+XOG>bBZzq6mUB4hrm^uPOHiht0( z@0$IrNRL#CU)h6c?&>jo)qeDD-~5N^f6u`b|5aw+KkUb!B~bj)Os07$bNJ2sSuMTh zUrYb922=dWtiHe4k6-(v_@*qT`8q3i@qX6*+4H~bYu&%kV2W?vr|$=St#9^8rTAsN zndbMsbKmQ0{j>M{x9I=AgDJkaPu~~%S~vAcrTCqF#uCjZeU4q<*ZMF!$kNWrp9CbZ*i zxVq9i=_v1nirP`5P7^zk^N!u4M#+T_0|wZHS!}m|RO+veU-w?xFMa6L*o?vUK`{(zz&BRGli|uG;r< zr`O(+GOnOtly}hNskEbWqj%Vl5krO@liMh+d>8qK4apgHq(qfGdXr3qr1=xAB>DpI zz@FXGm(kL|L4@+bVITgN-z)pFQ)=>AiqaCa{7pQE80{&UX*O+H z9PLIyNt>JSS?GwgL8dL~LAM6d(NnF^@Sd)=zD2A9sW65~$Ms;kVO^jT`B!u?Jt_aT zp7D8FtZ1)^lilP=E@Zg{J;w4WzlX(ZZM=sChr{@v$kREQTn1h`)~kC{C~oH=pZJWI z44CEbWG%-_$L+nz;t^8#NRWSFo zwK9vI5|Or$^2%~cRN8~O8EK2PToT);l1{RdinNPW+9T7ukoNIZW>UoM7|UIy(spzy zzgvZ1GOI{y(eq6X$)?VZwt6y!1)r?ao}kk1iQKs=?Ny!HS(njT;ZwyVm+R{)(E+Kp z%Fq4O#LP55DMt5>rsGA$o4?JBD?{+DM>!)@XW6e)1Q9)yA^!37TyAA8slu;s?5>gs z9sFc34u|qT?O){AlZh?sI78i!^`+DgslL=p_ZO@CM^M}nc{tt914Gu3hIzBX6;tUP zu9xQ-IwpRiW(aSRZw;B+&|nQ=U`XJs2_y87^SILbP-U>8p{R6Z4L3Kg^H z;b&CTGzN)3@eXlr*%ZDZzIah3z7c`AADZAF!zs->lkyy_H%N1H;z{L5-i6rY%X+(! zj*RCkexhfWv}NK~5jv%{vnFYctbtKR#OHK^EaKQu*q4ige`R}L9)dh05O&X#$%@Ky zsBn>QV{J|K%wWwtb~RG~`@oR8iu&*nUoNI`A>9SZP?`Y5`&4JL^JF;|`-W@(S5vN{ zqS8qL_Ojt(qDHwJ9?-cfDpKkW+l4N}#bhR4o4{Emxw(N^6?MAYW%=-rHMtafJbCPg zqnycOHQA+Z`Ep`qTbN@i2gwue8H!6y;(dF1Wn~~Zw=!544p7Te6QuI)LMp8Pj^y#) z+f^a)sp5qUO)LVVIyp+&b+ULd!%&PgnAvhT%IQM7ctLTBNkO}vAID_zVjMg--pY=- z*<~se67#^}`TTo7@g0!^|IQO2>!H)CgQcfd#@E_}UZ9hz7;D&fRcm8P`HsssfAWnR zQEmm@dN6KwVm(-=S^n1C(LSz9a~XekO7A{*7o|tWSz1=Ky{Y!M=kKC;yo+#?x;NGS zw%lEm9ua44(c0`yt-m#U7qzuDVl{YgYW;1wyC|)VA(j5lY`w?qUDS@Z#_reit~Gs9 z>)q$>taL%*l*FDK4V@62vlqQ(_t`nC?91UktGc45dOl6PsQ1Y8({G>E1ZmWo1EW@J zNayzKDi>5@ST#wG7a1opMoW(!Xx+bVNT5DAoqx@>K0vc9`J1S60?3>K74`KM^RR=q zlZ`7m?d1HDK%k*cac^pTq*f6uY8G90Q8g!Nhm@+dr$e6?ywATWLI z+yMWgF#n)tb$DK2c8)cqGBj%z{iv@sgnj}uIAq*}$;XiMR?bxEgEInE_4K=xR151v zjdfzB=3D(+P76e0jmY3KMqTro7Kf#DTt$aksHVCD0;a!*uDhCEuVZ6+ey-Ei z^kUuKkk1?VcQt)E(Q-if57Tv5)6Wp8_Q!{X&QI59~(z z#SZEDH&?o9zhw^TdF|aye;{GJ+^&{nRVvyx$d1KF)Y7~S_NN$QYRT5dyPE!|l!D7> zPt)^yv6KGG3Flze&1?zV|H~*Q(yKLieWO)HOuLxrxlTCAU$4@OXQ?XACo}zhgy}K? zGHat^p#6~B56+AB=YEQqf2fM(=c;Rcs$`JDo$4&FBrV4^+@B&GPspb#5b-QjC#JKh z|3Q@4N&hL&%S5O@Kf5;d=Y4mbCp1ompCld^5v!de~prV zn2pGYp{B)~k~_(NL_LHqSLsUg*|0d zyhmcAiSn;@k-z+(GLc`UW%jaZ-|is)SO@u^YWar!E%DW)djCb` zflsFWd9!J!^3T~I6P3%8m_PU^Zsxx?C3dQRm)z@6{$4JAMPOkbS+yWiHrP&N`9+K&;G~X4x0AA zK*=|Yf2oqsV;&4<{eQ?s|9iWr|9vj{k9k!}ZB@cqf7;eALH~^|`X7=d6Yfg?1F4@D z{-@;V(-@V$Rs-s6+J8SvPbwsa*Cf=c?y&y+%CBkvu}Z#a|GT@W|D`VaukWJ%3taSX zbM*DnevZrXo88Ygl2oA!UM zi~3Jg>D6#cNu&4vx~TtnO6cT2W8RRgS`|n3pRsh9`d_HzoBE&2lPwCnvj4*>J)Pph zLY1E1wZovYWkdH?{S z@3&LRh^c=jrFYUleXFF$_Pc~2Q~#g3$ls~t-?t0-16<@URPtL@dbZyLI!yT!UF6@p zzfAbFO0Q35{>Qt>AG1xSP~E8Lze@=+BqfnW|MeCg*=5 z9j5%hEBU7X_dZyr-ffy7 zoBD?a%Ji4Zll|ZH|94#U7n2Q2#qWY*F!g`iMgKvc$yBKS6oO3skI!&!KM&%CEecEI z$^LKZzg(p^%xvAO()0VM7)<@?x2_%SKbL=Yhr&j%|Jih{*(vw5K626jm0=>e@Ov4P z|4scT6Mx1`{p)zJM}gl>#bD~s_BBWZ`4nClqcBJ*%>HvO9j5-bDftQh!-FLX7s!+S z-_*Y+&9j{J->K5`d$|}){ku_mC;b=pm6FDQ{uRW?)c;&1-_-x3d?|Gf3a7Z_8Uvqp z(ZB9wNwX{aKjET(EC0d>1+@P(x;FLi)6?1iL*qp9UD|)HN^knlPL-bDPsU){zk$*_ z*?;@tQvd6~|ECipQ-9jaMcCA||E1j7P`Fl}?Ej|ykD+-IV}_cR_cWR0FgvA;nEDT* z^iKLO%#o6GJ!Sttj}BA+Vi)j7b*zmp`Y%)I`JHeKrv9(F=wF^IC0(b+A*_Fh4paZ1^l~o$^L{R+78?p1msU`v zH_N~E9GPCcpDv@~zo~yYrFSa-&-_wSj!Mh=*VAF@f2E83jY_^6#wsp}>jz6*l6}sO={uBrKvmN9=OX=BCrv0RPs&#AEV??Qt9={t0U@sHqBF6e>44ZmEK&}Hq+nbl76E~ z&uumaFJ4gm05XV^{BpJMWZKV6KglKia+Q9dA7DA|c8Bs`NW9GQ|HwstdASt4EBWuc$oHQj>%U?n#$lH_$nQ-RoGCq0oc(`! zxr~mn5gG9s*O`>wDgU=A`F=&u{@+Z8ng2nQo-tGY#&QBFXnJ{-*#4ZM^*74TExpO_ zbQk@1D*bgmW&JM)eKbB-$v4Ysd%4v3D0#B~%TkdxXYdl0-X>6y-W4VyuXTET_g5;t zk$tP5N`G57O)1Z2{;zb&fBLCX(t27S;=uWj(xKDq{8RFTvLnc9ox%U@VG8;3h%OPnczh zr$0o)_L--*$yN-H*WYW?VZ*ab@g&f` zB_fXt`UN(K{k}&$xwCJH$Ol61F*Z2bj=@SJmHB4^MqV}@*_j7j?md-jfAUM)FYm>#I8AZmf)in1?W1S&k6Cw>dGUYc*Nhj zNbot)2IKjhWaAj|SYz-~#BUOOVt72ClN0C}@K^;2_&UKShR5?MN}!i~#wOq&2tF}9 zo{v9)Uh*k+!B2I;OI+{?2{=DjO%^N0^45Jo;jwoKh=I9+zSIVuwqtBJUU^Ln9t&$# z?7l~=bjGfA%wwIYqj6`C++`sS;|q^9NWaL4jAe z;FT^owwf^#k5v`BfSAXc4p*_L$EuE9K+GdnJ^)Zrk64k2$0t%bCc&x`&YwJSwKkT{ zBUT1t*E;60&ezenvq#Lt;~;V2v3Q0YAATeJDu(Of)ICDaW}A479piH0nQmh6h#6=+ z{j*9PO;?O6M76Hvqh_KC-1{a`#E>lfnjSU(ky$NIr|d?8-iagTMW9mj}A%s3E{ zagTLbB1niwjPMh0d8}U~f`Xn$#PQ)}vZv)R?s`q&-gsiV+NkJz8+W!UoVxS4@UFs# z#G#h8L*ZtN_=&>J8u_`x&76Is@CJjwN6Z8EwSH;f{A)X$-|G!r{xr4 zUMqO(Ckn4akm6p2Z#3{D6#j^TAFc3o!*IC@UuNJV6y9p!qZM9C;}i^q3g2$vrzm_7 z^SA3Qk^ivi7h=I>geAMd(Hn&=Ze`F&v5?1(^20mZm z>amG^ccH=$HSBYl!iO685``BT_*Dv@V&K;){5%8yox&Fw_{{=0K+^Urfg8plyiXcu zMf~GPT<}&I0cX6$_TeJLfM2Q9#=iPCD1b9v1h~aw>?%y zJfN;TR(BV?M*@C0nXEU=Pj$aDmhb^EKh>7~oeTac;j~1R5PDLUobX&1{8ShG8W;S2 z7yMxt{ACyXV;6iMT8MDc|5z8igzy0{f4oLnO%j93;r(`e4i|5J&$t1$GPAWT<}^KJnDj9>4M+qf`8(IA44r&_CgVzvO}^QO8ZU62eI?_#DD}!+L^#|7o?rW9tU`y`p_+;?f(| z2lV?Q=L)>SmaE@`xr1;geO9^PZwo%tY(AR*v9z?^8`c5zdma}E{5+ffFcn)ucz>8D z<|zEvF7$T_yvF9E--FmrxRd?|^sA&b-pK_1BbZH!uWot zyWhnTz}6(FLrllmE+B9}aYKl`y{UrBE_L>Xc21j8bh7b*6M3f_EI7#D!#ywTP3@d? z*h8K!+dDW(*u@SM>~9YHh{bKzl|Uo?wktHIXU5BN@&C9@*IXPlch_6FvD$I0oHk-h z$eW|TC)8Op?`C~5?kColJ=@mAVUriifW7rbpp(s9N(yKzjgkV|tFxqFDF35PAxjEq ztHqLn;ruU;|IwzEB?ZUvzmfdUCzFUYyon?sBB@WL@QK7ek~bs|n2+ z7YrBI(l$f1LCe_cV9m6mYNk4s$VL>+mAKkuPneT%pHFU^R8|?P3;J>k>VveEt%Qn7 zCzJ(7R4abI9DlH)PVIF{cVheeSiGMs?EzC=Nl63K8yW(YHPv(-pbd}etg8B8(3PUG zb`I_P=6bu+o0T=eirU1a4Pu*EQlYcELNmLxVta$`aYv~NBlnCEzM+NH4RxW0;JBL5 z)QXy-(l{&X?NqHmprV0P4F{?!s%sowo44e0*#JnEJP8}gyQ0 zU1S~1qPwYBE=P>7m>KLuZt3jOv9oE%$FhLquDN=%;@P}iF$qlAidO6rrhW9d;)W3K zuynk$G`z6Ve zi>q`6K2gzZ^^}p1(uPj_&T|3?9qdnoq)`wnfiyr{lDR8N~`2Vxty1r&ef72IygJdT(YQZ0}6300AXmIcEG4|^BUvZ1<- z%*`oksH~{t&3U1H=K%vG}2PYMzkxQ;|_Tf$WCI@yb*e9aWa23 zd7Of6d$J(WmFV1z^j9<#R5VVXp=zVlV%S*P8N0?VXG0He6LJE!K}78*J#9cWPI}kc zKpiiyGGirJV`t) z)7QBAG&Glb`FJNSt~FfL7>IRscUV=OhRM39f660q%%$2fpFx=GBhBJ8k(FIEomA6I zdNFXaYpL$e?YUW^T$!y{o%Q9J0*k6Uuk49Ug@Y6|R(IQ*ow_T%H9IyfWy9zfFD8`b z^Y9@svWyy$ig06nkcSW2UJ1XF;>*+7*T$ALf{m3(%mrUiLo=lbw23H+<~*yePIjD> zKBhrp4&!Zv+McESc7#=kH^ zdQsHJOljm3o|hk{0r=EL`n4IQsXb^rj!d;nE7=vY^X^6UVMMi9*RZ_p3^YV^ z*KQZPBvZ{x==8c;Yk9P*cC@t@-Dos8tsxYcAvS@gi^{nb0h%-NIFW*W{**%TTj=y@juX^@iGP}nDqM1O2%)cL({h~F$ELXZ;tRIj#@f2y^o10F#T54zx4gB|3xf~7ox)=ECH`dut*yh?k`bje5{FGJW zGbql1@j5y*uAc;QIo=2OJc@HL`7acx#F4*#1BmI*r$h6Gc{B z7)So}c-zKVXHBo4Uz+^06nzGr9{~DXg){x103QQ5+If<~S)T*w&~oW9tq3NcK?-O3 zARU_iSimt~d4M+n{TPLt`QmF1%%96z^Y4n?xIxwQZgwjm8V+o?d+5;gr!q)^y3c7Xll8KBqS?=ij#aP03^13s1F9GD() z{iYA&Yv|B+`%!;6p8V1N(hfiRkF>*oOZ|20M~j71rkx92@N)sj{8j^w z`3(b(`CSM&>iJ8+k^fDAqrW`_IP!TKaP+rzfTO>?1UT|}2XM68dw?T7?s037XK4LJH+J>V#J0pRFwivZ^~O8emrfaARN9>8&& zyc%#EA5LJ$q`)WC{|vy9{#?LuJXsAm^5OlzIq(VfUko_XUjsPO{~mCp&lKDx|5qrk z?QxWg9>vGZ*OR~>^Tl42%KNE1I4*`z- z<^sUq13rrYM?Y_I!LJ1z?fiSd-v|D;E1XYb0Dm6vBLIIx;cVv*0N7LH-aZF6Xq}S_*T#gseq3OpnF$Jc_c7C!zC64X< zIe?=+GXUR2am~LDaI_CUd*#4#aovD@l>_4+(xLfeKzq0i@B+ZG9he9>>RACe+N}z3 zq^|`W+uPZIBmH8)vAw+!aBOey037)|3OMTdB;ZK@GT>O>asG?#EzWJ6u^l)T z=+^BA7U(fwIA6wm z-3s)`|9-$RUoQfV?U?=@L^EHT6+Qdy$8_lO{S5eE{q-;d3Viy64o!aq;F|%*dG{8; z!$7|k@MgfVUA+@<949{kIOca1;ApqMDBR5NMxe+1wgZm&^{0~36!-UD%OjIM zHH{chVEZ8b!GQmZ?&*9TrEunRDBwQ8D*zt>cnI*50AB!jvBFuO`v9K=_-ep^4)_|t zrvr}kA;6J-KHx}yDd0%o0yvKMt^pkBmjjOc?{dLcxZtY+UjzAF4>;3^?{9 z?SLcwkK;-CTrVYwj81|5a~mDHUZ`!n1>OeuSwN5Vx*Bk7XK>tz^f+#O7x-TUe2`x6 zzsGvwc=C3j$MNL-fFqx$0Y^R80FLx;0*>u7jvH}2={9cU-z(<8`eS|3zkka(+Ib&t zkSH*Y#s=TlEQba{;dd>G&*zz4^ZWeVs122LZkk?9d-@q}Tg5viJ*t9>2~aMZIIaLiW(aHQA!Nt*e>aU@>9O?OYNI7u1AU%%vupRy`#(Ss_j`tA%81%&P{@L9`wnV;=Pd~ts{<|1Y zUPLPBavU$!N$~&wwDrjj&~ppu-#tm*U_aRk_)h@e2DtheGLc{G*M0`{Sg)r6z7qK0 zxD@I2^DnMh3(Acz#rS0D*#9SzXp60=yNaNm@gccBA>qkJ?0DF|3Uf*S`Tr{>jXk0+-_^I<$Wd104IW697j(`uUpKe@y{;?7wi`68o>GfFAoV z{d|h`M19=epZQqvG4)AT;|k`3`s@oh>VxAS)MqQuqaE;h&`Pl9zg+0QQaG!N{bLVS zkOH5ud~uwE<$EB|qdvHvhUGg{(X(6}58(4A>>p19{y5H=2{_hw{ylpRd}^aZ`_*c| zQO_3vN4vcOIMQzd{9WMR1~}4x2{_I-el_6R0RI!CXZj$C=ZC4~~0l0j~i4 z8v)00?}dQlxc4%JvpzWPy%O-%!2f!{*8qMq;7I>Rz>%K!cjv%zk^U*bk^awsBmE12 z<2dtGz>&|pfFqxOyWkywBcJZ+LVck>`eARtk^W%7QP0BxNBRMheM0+o4B#s%uKhe0 zaIAMD70!NmG0^*gejVVYfMfqP1#skF2{`s&GXY0CF9saPW7hzV{Feic`Mm{jr2nJB z&HQrP!h!t_^ZSfIC64*!F$@Q$NB;ayEClEI9Qm9A_)4HZ4REBN4mg%eBj7kr!1vA2|J~j< zy8`&2oqr8DjuUQFIG?gXfBoJ&C}$7n1z!T6 zb-)Lor(-*V^9a;uKQ;^nK5e2ym*ZgyXSp~I!S~j1TyY%m!Ewb{;8Owo#{-Vzhe?3r z_yONf!|_8U(Brsej>7qb_2Oc{u^;>e;8>3O_Ye3s(*G9dk^e1#BmKRABmEyy3N5~)NM~LJ62>E~L!hZnep99}U|M@oKgoVUQ``ZsSPPmSA;9%zKCJ751 z>*;NPqaE&1IMMx%27GxET~J{BOFFckuKyOVLw*ijtr)>co-%r~L_+!8y`Md`B zJ3#+A;Aqc6XrEE;X@H~L0N^NhA>b(YF2J!Le*$nU$G-r+67*jWIMU<$&p2Mf{tM|p z0zNoi!hQ$GOMSRtDVXJ}`yIwnPwaP4?ik>M{WX5)h2tfB{~6mu>|YR{0sPU<4S?f# zX}-eQEl#FG`=|b%i}8Vg-wk|lyriEeW)Llom-PE-jNb@+o&`QT0RJ1{Xtxc3<9O)} zz>yyN3&g(xdbEE=Dk(vMZ{v6g*V(Y29hxS{#d9!OHqd7c>8kzb0l?8eTU~H`&kE_g@}3pa<8wFEhkwV91KSzt zzX2TS2MFrK`u=Uk4;K?pZJ!@%{ID4E_2W9jkLwIL&cS{Y$2r)3{b!h(r(|yIztoK`NwqzY3Co;8KfQl8`l|{!Jq#Z#tDlczdR=Az~i)abm;NY zGYnE-9OvD=f7tHj_VJ&&V%!&=|GP-em{tIz7Xhf{h>+WY>qyl|DAx30{mg%gX<4ZDm;T| zas5H>tHbz>z~_13gX<431CDmv1URlgYy%wWaeWE#ZtSoW_=NWF4LGhp91J+l>stUv z{?`GH{($TMNPn}UXZv4Hhprb70H1Y$KMpvyC%FEP{GS8*O~B{yRJx$Rw~;;vaMXV| z;7EUh!dd?&I<)?$0zK+q1~}?}HsHv=3UJhaci&5oDn6_yuIDTR{3_fZvmgxK>rTlxPF4~H6i^MF7)`lB(5)I zrjalTtPk?<2RQQg0*>^90Y`ehj%V^8?Lx2Lt2gOS2YRfhKLdOX)%6dfR!+gJ{)e;XZIANBzbj9W=DT<=rCIQHXZOhEwb zss`i=X_y( z;kv-Vtm+EP5%7=M}P1Fj{b0%;GSsbA%L%>xX#y5z_DC#eu4d3 zDbVw`nVL^I;HiMm06YzFZlgGGIVJ%KwWt(&0a^Y_TH2=Q}RN|Q5=K)81avRQp^^DM=`S2K(1M^=;hsJpgmILEG zK<>W53>|K`@=>$ zv>h%4KIjkly)F8~EsEas2mG!9{o!%okN&U*aP)`g0OvZZ^?Vs{wA&jBXMNa*H9dZx zi{*~*eR0`odR%wS0=zdfroiQ%4LCku#`gbEphrD%{WTZT zt^_^Lb)laHIQoy$DDVmW2fvHKaydrPvp!4c(DnKR;Di1%4si6J zGXY2cnF=`i&v}5O|AYWXJud+q{pT{kkskM(MgO_cg&x1(LH~IY=+S>(037}2O~BEA zwkn+chx=%4=TCqh{U<$@h$!%F^dJ45j_E&xfFAv4DB$QnqX9?%84Ec2&ji5H&XX0+ z`n1rY^ED0V(SJgKqyJnCIQq{o07w713h>n+_gcVF&)We<|G67*q+bCz`p-JRk^W7< z(SNo9j{bx5S@fSYn8%_2==m)B&u5U|gMc3WM}H4)`cILfH~k0SCqe%?8~CIDQ~{3u zQwuoy&uqZaZVMF7`YeTf;dkHYKlt4@`p>PvAN>cv??(T54Cq&b+@}CXJ)Z|0{pV%C zk$x-S=szCfp#K~IIMNRW9Q|h~;OIZ&07w5R104P5EQPcG z@Y;p;pK72-|5*Sy`p;DgH~r_gK#%@&8{p_a4*-t-^Elw>KhFS;cKfr!S)XN)uUCK` z{bvi{=s%wTj{egDIQmaFHY5cuU-X}zfTNy=0FM517~n{s3po1EXuy%a6mayPDS)H@ z)BukDGZ%35pNkdFr?2VI{<9S5(SLpqIQq}S3OD^{CD5b){0(sQpACSc|7-*t{bxJi zXtx~-XMK3BN$2YupkD`gMt8cPz~zqqa{%DzKLY_r|2Z0P^dBGKsOJcUvs(MWIzTbd z-%Izj{uO}Z`syse(LRlUqudJ>&i07_|0vL-eQp4}H|TjQ;F#Z4F8E&oUjuSq0UY^k z104O~Uw|What~rkfy)u;_W>N~4*?wMeSjnVXuy&Fbik3m0&t{1A8@3<1aPFk5^$uy z5pblx4{)S^8gQh4-UZJT)|B?-HE`{R2Lj#)aJD-K_N!_-G(Ga^3-nCOfgtN_5tIK^ z^DOWH;A&bg)}OJyDD{Qh{eVBe%g2H1*G+V2eFiW{f%V-V=(7bX^?6Xm`P2_^{Y?!+ zUcetxaXt+KT(40xg#1@18a^TaR=~X~&i2_|{+#D4I3We(ufMTn9Q9=S-z$2)$AK@` zikST8RdFugR2Apb7!_w+4W$KA4!9ap353@)I554c%HsMF@n7OSRh&;-0Ph7jx4j&g zkG3sej{scz0ORF=>t|<-F9Cdi22^+i@B=hRXZ^h}%RLD2&w&15zz;?hXBg1y_d^)Z1AII1IS%j-0Urst{yvEL zi~?N0zrpwkfR9lPALAziUJST?_R6=zfS&~P%K#q(xc=^j`JW8E_X$VaMrC27@WZJ||Gug?c zO$$OG4LD8%WfephT-g zcjP&Ro~P3DG7HSJv%@2nBp^xU8Y0p*@uTU7IuVvvMah z+sRz*3y*E`Iho534sS2}YUChV zI_cnx&e%uxHXMAx8F`}o%7za$tZTSx-R_yQn?Ocp>ue?Dz`ybPDf;~hvP?geeU~>} z7D~U}&=E@i9_@S{?W}Mz@7H!-E$l=K4rYx5E5^Z!r?VC|K?FIsz;>R+%m*IV{zU8kpk4SDx$yJ?7q;Y_qte(x?7ZcmUU`|N z>*v_u-f;RIWta3I`j70&`cL~43g-a0u&V03zC?E{vN_Q`7>^B{*B9->E0S3M;aFEH zvNaj)uj&Cu==X)oLw%`OvM(BM?v2H}8xw-$2Y79Kft?j#;T_a$_u|qTR80Y-2PP>uyZO zy20MwXndeC+SL=wt9`nBu}n*yOr$*1SUNgBxE{){+!;NXS~~M9E6Yaq%^cZpFDu%5 zt}d|A?>T!K%TY?|1SexV=^r|o`ckM?rB|*yxNnz^>~_XxAc-@!SU<4IT94iYH!60w zHuk@0dTJ@OM} zPdApP%E*kFv+JSVoCL%m_XkR~lW7DejHg~2cFM{pv^EZ0n#I-in42t4=5K?qQSJPw62 zC(Z{#Co^m24jkH?43zJR3MfvW7<6_(3Z#v#8`oKahM9g!Mb#~oelk4P->>4UM&C{~ zhcbixtN|z?qs#}Snk6%3{;JWRgSym*LYWRw+G;Ab0&gF9GS~CJR*9CoRv;Y2l~k=I zvjW=aii+2kAVa1VURo<&I~!g?=_lBfaQan6eDGk=NtHXnuMZY2{86#>YS9wQdc9bc z?a?X^=Wpe4l*;3DqkX)Nl{T+^;A|4w2DA^TZmNwumvWrU+6pX_OH_@RxQ+am66w}P z>Md+=WzgU%LD=AzH|+XTw3o>=5YeXI`U5r*YA@%=_Hz0J?d4AJ;uA#+-z>J?DT0yc z;AGp&k(Up2X7674)cuu~kCRdTT8Fb|rJ7{zSy>9T8S3&YfZ+Vcf~QYC^)yF*>;TN) zJMby-^-6eeXm3+326}oYy<0^?nV=QUbe4v2ArYI~C{j(eY~=aMDb3fx$DN zCpsnT92n1?^oua0uiL$0=4?Hl2M!*%Kkzn>h#>61UiS>o;S6inq<3e<(!dU*XvIvZ zQ?oDJQ)F#{?0>3gD#X5Bqz6)Rft)OMg`23#DI#({vH?IUdgqoZ&J@enwG`|#!XwQ`S_y`7`S(W|`dPGmA z@-6VlYo6(?f4Qdj|HYaUNtkZXa%yeiPX6rH~>mn$AKTom*>UHhFu4q z6t4#!7Cpj&`=E#Hm_QpNaH7(CWA(qLps`t#?*nf_EXxp!M_Dn1k2Wwsg@7Y@ly|jmpxcM<3uwX z2|4dza|ej?0kn_OBSw00t5(QmT(rG4tZKlte?ZDpxgIQn7d792X9{FZ!Bo~G%6b&V zh02QK_-rb(knclC3*m72KB3vH9TVtFYx9e*5&E7z0zSDSjJrb--UP{{feD-Xk<$9R;0bCOtr6J(w(a- zy3VZw5w^E$TWM+6jHBbK2I{w1b&^LOJ|fgIzLv`z_!h) z=z4gjlKR=hG4<<1RX6n9R@M4}0jmmus>s@w8t4TB{?_b|B%zk-Ep>s~=E1(MRBxiM zJ+`?&4!=nRTiODV>Lo3SzQ#oVw&?nJEXUHGjP|AmLT%NNU@+KJ9o%A7C1deuo{E~@ z&Hdr(8Wzh#2@ZER(HY7r*dhun^_+Sj=d&&;9#ZvHlktrGFE>=UX zl2hB3O7`|`1VJreZ@y?S0yF7vO(wvm)HW8SjMy@f>XnD5dO}5JZWCB&SfYWdI>@|u z4Y>Fs;LnX=foeHwlaB+n62zfg`$e+_+x$?7Qtn`1ymwP9zAaZ*atg4ltNNqKR8_z) zd9u|ipY#wUH867L*PV%U*XpTID6rU=>jZiQPU%cVb(tJ_e)P=!ZTZh=A;?P+6IS0pyn z73)t$pwo!Qu%zER?Rh;#f!dltlh==;@4XM+D`O^hNnlY2{dWA`d*CSPK2(NR)34@# ziVPnW-4kcHv2X}2Y#1%Et=OaMX6`<0;>ed9HYe50YYtoN#92}DU_LN;<*t(luu9EK z>ViXhOGvO4#^aW@2u>@OG)KEqiR89Wdn8zwjHL#XeUVhK-5)Xf_yQjW{Gq;H+-1?b z9p*RSty)LzAb|l9I@9csF-hwuEiLCU_z;IL;r^<~%J3yC8p4stz~K5wD6)w*jYQz{ zTTRotx+p8XU~eRvOh&f>pl1S+wLFK*4JV6mT9rRK1Vn~{f%7Ag*44rG_A4UI9W9OR zp-WmK=q+!FM>yIZfubsh9_5dKRZmuqfUzkM+~UcGvt~8jgE|7m0V8qyWi&(2 zl`c=uOu~Ztt!DbJqj|Mot?VQRvEf8gJjbV6rUW-#4wLu|RguWXp`i#&hX)d{6RS71 zEwTlsdR>Xln_+{JRn?bB#i~}ebS#9b+_j1LV?B`#N!;61wK16(?8h&aKPudMtYsbV zBB7oz{FcLj-_on#Qr}YI>Ba8=4F<{I3Gb8TZ$)MZk{|aqPL^MN`y2cl4}-rGXfa6r zJ@7tR{YZ;J^7p~}Wcj&dC4c5H_=iwA1j*kG?~~O(jLZ-u|8?*_S^keI?tFgClgZC} zTh&?_@!(^Zh|4H_)@PwP5JQYU-Lv>)`Ed^|=J81Rah(J8m*6f_5m>*OuW~_y(OckB z{04qEy{k1sk!JFL4AR)Ag3Q`S%hFsAuszI#i_5cuh!4QiO@BRt5Y)P(j;gz<|EGYu z>0fh|W|I1`pE31s06lK{_mO_Jj;TedyQx14bZ+|hy68W_MgQ}pzgp$iUft zGSB*n2mj;5|E9sueEfWe_|5t=P8CwE%?cT2{(lMlZuxiA!lh-sNW577xSyQu=kmV< z>_l74dU_cNok#rqFsiwA5dd!beVv+v9%}q}A3&!55!P=A9wwn^w+v?ful3MB+^MYL z{cEC{qLTvI{}le;&M>_Adj)ZuWnoOtD*svj1zuZ`%I= z@gK_mhk?<}eqXQFFYU)M+O&V+GOVCw&-hyMMf|7of}s2}$Ln)*)zz^(irJPx&4 z)-3(V-i_*LZ6kiue|w1^f6J4>v_A#>ZvJ~9uDR|I_AdpT?qU;t$x#a zaer*N}cA`_{9x!Ql$29O7pA-{)b!Uv1~HtTPRM)BewU*k3xN z89Rv|?Oy?xY5$LaAFCP+LwR8h>1TRQG~d7Pp}&XpR}drWZ-R^Y8UH!u-}GN6={LVC zd?b$_7eYUeJ~jF8CjNFNq^Hk#zsG~$I$0BT8}ugsNzhNb=^rM3v;0i{RuBGh;-7yA z{b>(=^|1oHXB~q7N#eH+2iD`q4g_w0`pvR@9HHkp@Vm92VJiPlqQmkJ!)2ELFFf=Q zPg4JD9{TsW=x=e+fBdo9CbRxOK>FEU$_95U{A#TPek^~}e_s5iycNLj=D+%FS_QWg z^dFu_W`4$dNxxZ650m|8Ycbh7+KPdnN#fUN?*3!q&mlU-e2m{j{6_V$_7ndbhGW@& z=D)!s|7$4!`$;h7zXLAj=ltWEh@nD>ei1)bA>0A-Wiai>chh#He`C4k>c`Fz0`}u; z;WG6@_vNa;6Bm0STxWFHrhZLTct^S^)|&?lQ&1mNdY52ZMrMh|wrDbB@Yt&7H$Zr` z)k;@Bj@@aoz~#D{?Xm*CLD6IB=pfg@YztSC^1}=8S}gF}MY3&CXD%>|+T2MO;DwcU zIXJY)aQjzZ{`cM{>CG1Tl?1k^hxvG}-R0xCdYF&r+C@H|Yj^p0SiWZCwuK{pVX&>% zLJ$yJjj)ADwk2CtF5OlmQtlmNTfv`}OMi8Z!cQ*fDX%9Sxn#JJ@P!hDc!qG(qq_+2 zH0W<5JZ<2gCOm22|ETbj)P7Q#^f{uJ{XVAOL-@Ut7~)?f{80mci16J8{vU)tYv7L) z{v89~qj2a%jWAnHrc|Plg5}#*fFWRKXG8hPHna@4U;~F+uw7?zC?6J?T!LNr)vBm$ z3l=3@f}NdxDU9Oyy$3!Ivg$^^%mcp> z@VWf40+Medd;Z6R-Ufr+~0@u}1)Rv-3D8+F4?pWjoLE!0Q!$Mpizrr(XfMoBU3|=ZbNe*T099oZPs~ z>$)!kKBpMJEOg-cEmk!*`FIx44R7$kZ}7ms=z;&*1NTD}chl>5;KLsHEgtyi0G}o1 zA?%;o(1d1*`3A4YrWKwW?HT`-!WXkU_1=DXI~JzwbHsS$CyKd%&l2;E8p1!Q@Z5ZZ z*D;3yck{!I9{8gk`0thc+&tvFq_+Y-A>8CI1N?X~ZbC7s(BnbB%L9MF1AiLuxniC( zkK|8-PZu|P&H;RunE&uP-$oC5Tn~1WGwy-^)B~Rl--B*)?)1Q)@xZ6U`ly?nB_8+( zfY^;bhPcZxmGq#u+&1vhp7?j~97LYL_u%kDzCOJbmrqFWF^;?q>9FN6d)VSIPCU46 zXneOf1yWw*VTru63~n||uyN0ge8LTaF8Ysfhh_FWgPRRUDAQwmqML?8?4WdGIkL^E zli4C0ZiKCg;YK*y5pIODG2zAjF6zUb%`ztOy4qs10{g z>%3L_+v16>&{yRBE5BebQe6yW+5OzKPhA-ccp#v6Vz+g{NvuFM{69Q6f~KKhD{T9& z>xGTcN!XAY@H??+zgC7Rxoyt5Z0Fp3#N7zxs`|3JKuuFG{0qN<*vfcfeKa0y%`=BL zja!jObO26iq#_%ly>T~F)WIQ-?Y-KCpzQp{IQ%0+Jg?=cr*QK(_ET;e>3CJPHssvG zjX0Ofx>eClu?h6HZfR}af_-|#^*9-yE`mM!K@?iBGnsPll0e26a^MN6$lC6Bt83<( zbaJ7hkKo`Zt!kfS{f)2@NFhbY;K~ZKQE9nS@Q%*+d#W0|7Yw z(40(c?nrH@Q?;MDf~^;K;ZcPEp0dzGZTq(Vm~LJmz1klf=!*8^nJ&?s8Uy)4sMIIj zPi~oy&L;t-K`1L2cTo}9E`b#qk+AB-4Qst zGYGrTUAM5i)yntie3zT*qjRvzUDMGx(d4E{9b>{SuAniy_6blgRnsn@KI}6|k+pqW zH&eCd+EWdugY#=nsL!Z3x@W;k4BdR4?%&~L5S&VlLA&gN>MKW{Tr(&bcHDEIGH2Fv zx5ik&?sZxNoR0De&T0n&(3|j)Fzr+|*fOMglo0%9k0|EK)h;=Rp#P8L^p!R*JH)GE zL>J~f=U(2EJxE2_U!(^zKB!)(hC4Weuo}Oa@~VLDo7Ln5{c6y=dyRYfT2olC7qXf= zP{u=|9uQrNt+ zU`OUEMjx^C zU_Rh%RBBs83jVFY`a$|X3F!C05;j^EKz^@O*PKXp#UOu1zOtt_+iJitS2ZxIbq^#W zJ?g+BymSpkBQTK|>P_YLlfd$^wGOV|!GF}kP)F-Mh~v=%#(Blwr2mMZ$2Cr-AM?O@ zMb4DN>#ru>Ddb3dMg=bQ^13z3k+@&b%lvxf>q*P#O9O>i;&wHhwSFSk=u{!XGd<$qk@ zK_UMx5BZ-H^wR$O1TO9WlE7C$obCTA;pm_B0zcaI5SF)9K)svbVtaT83*uN7jK5p< zaQ}w>m+j&*c*kJsU7%rw{~g5Ho~s0oeG%jR0v{0gzX)8?KOk_dV=U((flK`x<`^ghU{k%coa(*=|aIBLUupP;9uuY*FAAvZ_m)|wA z{o))91ImfQ#q`%B2m$dOa4~)hf)LRDPPiEVG{i9=J<4Q!FM<$?;i`s<@$VoA0dd*B zexOi|uY@?$%kdHGHsik*^iuxs1TN*<)Q(WEY`-%^`;zi21TN=4K7q^jh;tYW=m+U% zIgh##(%60<#4(ukXK7gZ8NZ2`o_A;O)Z3N0+(2L&$u{}|z@SNeaqpqKsUw*vD^`YM6Ta>Tr2K>H;!=290StJ{L1o`{`|J0)^<7&XE`quj&cSB{<^?FA@Fwuew)A#3S8L_Z+)&JnnjQzLL$f9eD->FWh9>q)D?rQg;FT-K9LflK)t3CH?_Yf9|TgrJx8 z=Q@GQ`ZGp2`UkeWW#!y2=x-PJLjsrW_fdgMJ0BPFFA{S03VP}P?+aYY`Gvrx|9>TL zN&j1cOaGT)Mj@E>_5^`T|DP&wDId>qU_k$00~h=MY(X#mzf|DT{|@2!kpAxx^wR(R z0+;^B^CK8AU((KN2*(Gm;jo<?mCF%cpgrl9(|K|u?`rj{bY3C9lKMbP8tdg=e42weJqzrdxPuM>{-M9#-l1q2MsH!AF}KmYDS^xR1G&FoK3t}x=yJaU;_T;HgkyQ(8YAO#2}d=b5;(yYcK7G;3p~pyj`#+F z^Slx9K7sovj`&7_R|>pG;8H%WyK<27;|#*nNAbzZXI7-&&M)xvQ5@^lREp!Hp5lm? zP#hm@1LCCuzmwvKA0zOm1%8~s-x4_I9iehG5CY0MLB;eZslUD^)c&0 zE4pgcidBn4b29I-I#T_E=`EqozP`a^XSR26Ak@>@+n4IL=42Y@WST5cHGeE)U6;uu zdi#e4)7iv8XMal72YR!KOe&d34i02fH)J(<{cvwORfcu| z^Sjly^QJxeV(l>k@>Xsldyeh=hHDR#Ex8n&JwnZP;Zn|=Uvg7;f*X%NMIa^O7r7?# zsmR*MnwayaAJhRO{!9%a>zuWBIvsaRM)wdkceZmAwi6u>j&(rT4@ls{R!ylb<~$Z0 zYXfZOqvP?yH0l>~ei3(G*+*m#QimTTU#5OlCT-!Wl?C10~Ae|QQh?!2MtYh3Qm z^LFwu7{sc64$eHF{O}zv`)X)c#y)!ijl&+@zwX+|XCvz)pNk~cKibnAoIOSZqd|IP zL#P&iTC$^iaudPaxzP6b?RMc4#FLdO-t(7Jr^mn*4q5i2!KT~>6oO5KAJh&wOGofnvpJ+x0h<kvKgD`zv7L0CJ-MWo z+U-el7i3H7bskcA^r+66pOWT8kJ@=&4R&E!tz8&CY8SR0jytJicD{~DlsjKsVPvsM z4wCS~77R)HU%msgrk1!Gq4S6mmzz+Q$nJ4_iE&~9A5?Vk-{W_awknDE(rAxfWo6HT zmPf-++RihIespWCm7Qf5G8n?PqngLodOLS2J4@9j+mto(TSH}Nh$K`P+=k2wdlBad#|Yh`D~ z5w>)QxAWU}lU=7VVMp%u;MfX^w%hmb2IIJMLdL0aJ3kDKU&>8Hg10?pgE&_W;%NBw z$mrWu!*|CE!{f31!f5yq4eJo8TSxkp^wwI(oj*VU*lnDeSv0$AF!yI7FGMFGX&fAw zXo84r=MgNo8?YKnVblX8Id!C(tfZEZ?$x&cp!u(Du#+}y*-s$#-wenmm zw;6YF%~kv{R=4u=VMIo?DZ<%z+ev8XM0XXNm;m0fZ7+9)Wn<3LkfAO9R<%#{Q^*L8 z{S$PLI?csfnW`Pz@6q|Mx3=_LbWPm`D^O2 zv(N~%i4N3ME2}HJU;&GpCcp*ivH_xdQYNH3Q1#W5M3 zpe~s7gPgmI#hz>n5z>)+E?(&0m7N(GxuO9}<}P6HD7eBryRa61M_z@<9(P`4ZF3XD z*IF64WPQJ9VWCcjNh0o%DPWYj5sh6yUfFWRnVM4c-diW@wp zKVFpfjybQ<5$k7c^6f9K!#Yz|&+U2z8#_|Bov)eGNP|Rl4o}#Vx!t-2#XY8&JB8X_ zT`R@h5OL_py+o6-&BA0{Lh&p2Ty_9^G4VM-@*bj6JU^GG46+MQ$Z z!nY>Sj#YaHvOIss3fpR&9Ki?pyNbJF7mhpMB4%8*M<;5~iv|K7kN7&-VDup#B*i}0DKMVk7~&2_(s8ico_8jj3;qzy{gBY@ z`^l`rImYt^(&pV=W8B?$9-y%s6)`9pq@842=ph#G<<&m|iDXhzQyT>#OSsHs@P|rq z#Q4j?DgMH2h%G+}$ma@rgh{0{g9Dw}lzJLrGHdx@sB<{GG11+b?F?=1>>EyndIv)3 z)b+!uOg7Y$9_$Y#`+8FYSw*haKTi8G=WXMSkKC7U^tVJTAjm?T-QgNNJ!Tk zb>5=$MU=PRa(yfM+6s#v*7*_2c~FRU!Q5QslEJZ;0h0?MRv>`vQ4~(}ux$=V!#Ehd zib=rn=t$Y|D0^kT15XX*E1mnh%bcBL2PEL&v$7N`=xEW3`O4JWg|-ldMFgh`8=h0s z5ZOn@*oWzH9RW^<0Fj%92H}t37P1Sg>&*UX+(uJ>0My#AD*8ci>^x9Ju*H(Rsp=xG zArzFXvJB5j{YS`RI6eZd^T?yUYh-I{71XMY7nape*~K5!LyDe*%|0@Ew3;oav>oe0 z?{_tB@!#0@vF}x$1sKPj2%{ZMNNy1Qcz5p6@w#$ps8h&E*c(@#aNS&b#llr7La82Enm=@n91#+{*{CLjMFDsxEve?)=_7 zeX+}AyYl=vsh1;;d*a;TPGtCLZ0-}-kea}gj$I{V@JhWg0C@X;Qn|EP=^>l_B#z@k ztZ; zAcm(DM3ujo-oze{30YuD0OlwX+&PJpMR4aM?aoP@JU?`J3?^Cy6OBDdgzCvXI(8~J z_CIXU;SpjngRII*;vpq_Ce;uf7;sy{Pm>Sa_Na1^v0vjftKtI!+=N|t$UQ9=A3+nI z<8e^WLTJ6%6^I$lpoFLU-RAdco& z*CSeE6XETs9x|{Gn+GxHnYh!}P;0x-VK2~mmA5cVU5L5q?WUF79P5Q1^TuLt(do-Q z%)X3ugM+iWJ1Kq~jmpkG_M(U1h;x2Ju?v)H-&{ZL957EwrCwMEWrqG|bc9Ek=M!TQ z?Pk#8H%wl9%C!$ayXcD`xM{J77IDAk8p3^&E_CcN*1+*nZ@oBJzEHMCRfO757NK-} z(pMyIgerdeO&a6~8D7y-DB~kWv5A{#9>p`(cUXC*r}Z*5G6r+c{+Z6%Da5WXG?WFe z7A#&o^C_d{+gcF3LRK-xV%phu&dxq8OeV;4vAB~bf#oT9k?O8=vYi9Me3#R_OJ%3* zqwBpJ>oFESM#C>3X9^AKh_ek&{0A1Q?7AY4NqEOoSn)Mh?yrm zpkX-|zsFKa!J*__YLvW$vvuZ}1lKBlmAZ&Q9)FgV$5$phh%0=$giqo&K4a107^mM} zydh9qUQM*UoyOJ7KY^G&3f@C8; zlzJq6yb#z?GdeBMz@+UUwTSm^M2Pe}eHpn+b_Ci-YpU~#=_bme=+FR?{X~ZZ7c0?2 z&+4s2WzXDzZ{qtRwIf}G&8EcnD}hfcrJ?gIR-_GliT-@j6=^`~?2fU0bb9p4x^gt>ue^X=I-89S)JBXDxDroOQJ!ntn^fP%8HU6EoAu7CHqpH z15%D3AuplRV5pbkX;AW_F0;y_cT_~j5?-tC#9q_A`^aQ)GI}HuJ;MXZM51}&f`tp9 zj+!%pE|^ydop)I!^pg3N(3XW2&`U47q!PLi(vpMy{dA?!JTRC|H7{Mh_To&oGr0-m zg8gp)`w6cj6#J>t+FD@-u@S&trnlZwm-!m z;&}-^GPUZ;A0>#gk#BOMqwxPbK-Zw@~7JLlybkD}Nc#O7dIv#xtV%kbDYpUisujmE^bT3E_PRG$wiFZ$LvO z`4g9^9uq3#y=?}{Uin`DR!ROI&6M{x&4V(p{LcfcB!6VF>U2b9ET8rtul#=pR!ROY znk*#VD^-!dz4GZwzLNZPV zY0pGz#0R(0Q{=w}tdjf@nk*#V(^Zkbz4A{0tt5Z%m8#PsVva=e{|+DT_-CWNlKd0z zpNF(g@BM&`d=o!z@{!-F4aMi5caXouNB+?^)hUE_N{#rC zOt1W}`^aBOlTGv#bVTyb-#tF^t*GiWt_@4_&&9_p|3_NBHj^u9gEo*?p0|F~r~i=d ze}T(U6};in!D(6kL0H1)$ zaoQ8B1uoB90ZVU!q6@i2wZP^1C}7bEqdd`^S6Lr+LAf3Rmfj@XR#gb_PF)VpL$!)e z+X^q|ql2yJ5@Gs~i^w<-uxKYNPb*NZvPx9t{NGnjtZM;_cBJyO9@Q%AgDzOk$9TQl z%!L3)_Ht|!s#R90w<&F5+}ya7@23IxCZ?QMK=6?*0ikC(Ua~_u9+FkJ91!#3f+z&U zyqDt*vg(!t93k8)7rxBjQ~i90#=V^A4`^uRUBr3m>vk^IO!3gKY217M*`@I%oR_}t z)i}+MOyA^6jdhI#QU12Z>6|aqcezqysqvLs_Gx^)1aawM{+{ZGk7@e5J@k)jdL0Jc z*8kP?-*FLDcuM1kJov9Q{)`8wYQXx)6!iaqoGs#yttpNn_nsZ7=`TKb5COCj{ri1z zdeL2pzR?Gt>w{nEgVQ;+68~-=e3K8p75Lf03(fQ09X|AT`QZ2a;Eyu@Qe6E885!xf zKJ+Jj@EO=tD~Da<6+4Ec<{0bku!w28!gKq(TwtL#LEb~0{FFy3U znVz0BR5H&mkNMC)<%7TAgTLy7zu|+^JLQUY^TESD_+lS?l@H$KgKzf1Z}GwJ^1<)( z!N2W;@Attiyzl2X{kTGJPV%31sf%=ZdtSQCy%g80qJ}HjQf&dQX+;fJxuS;aUQxr9 zu&B|salEaCzHp@*Z^I34ybbsJ@iyEB$J;KYFWdmf+n5el-tjhE9)pCtgqbqTJ;U4~ ztQc^=@B)ip79^I&S1gId6DzL1dUbS7VohX8Jeq(K80^4c!u&$V!r!pbTZGgNc)ONJ z45fPqvOS69#!Xg|f5rnWGayiU?_hp{gDd9ju=Gfrr3QFD2Iz-5>CL@K{fBiVRQ_PdkB_>}XBD9jUN3roP-N8PpB?q2Q>k}; z8_071svjnG!59nXC%RKf{DFz3YpDUQVW0!ap)J0m#SfZv(Qmx&@13}SnW8&?n!E)4 z?rN$4`F3RK>eY$1#PT(XwX37663ZhU(bM<~M`aN4Q!1B>y<+v6C6U$9_5|2{D%LiY zo3A>hSu@i^FN%H1`6UzoB#Yd}{cRW{L!D_jA*$OIO%Hve)7Ex zZ3d_3OiDygSKkJw=SE7{miZm9!IvocNOthW=JT{|SMs z^SzQwSHyANFWl?Q(uGML?9C3QvdrHRsKxR zc83020{@V})pMqzpDys93VJy&($3Nj=WBY>XQ|-RB5-=vGy0J4Q6l;nJ_cVyAd(k1 z&(q%V<`p@wU#X}0+Yh3bdbVqNFaP@mPHWld^N7aDADRSyNZ=uXOS?&X(qEiYBDr!s zzQyR&@qS+TPaHHxAGt0%1pb7em;9d>xU@gr%TuCp(H*kk|F*zG0%W zEyu_3p+9(}L^$1@89XjJbpDplL1TO77UHF^yhdBb5{xDzQQctrVk^a&jlA7LYXSq*F zJ9lY4y>`392RG}N=%qhAE9l!$HujPGDa9^>f6`}Mj?n*NK`-~s4+{KW1--QM_XU4x z=VJnwc78+P(#|u^wQ3A1-=%2j2*JX9Etc#yWP&{RQzs@&p=Lh zrH0S<1ijn`4{DsmHwyYE1b%_Qe=cxoPw9v21ihR`x!${kJwGkzM+GkZ_InzqaeYS6 z)2{?5k$vR2>V!S7MVqn19F0@fEbxyDT#nb=Q&F=VFTIzfMA=+?4F9zPmwY}eaLLEK ze<%H=eQp)>bOtc|cM4qczf<6n|9=YnLcvGIbLofYgN736vlJgA*Y6zCPQ*xF{mBO? z5xyQD!>5lxBrkrWf*F@_b=(Ix=QQFY>Hph@{&9gzzdEjQGLy8=p9HF5G zx#G(jC;sxBV8%r_+1%J?r=XuMaQR##$tNqv?HT-eDU0O#;7A;6oZGePrBF{~sNtr;HEx3HnyS zXP?03`u(NADV7?2UKRKvfu9t3zrasvoa{4C;4{uZ1&MHJ=X!z5@m`>D?|7Sh=$n1$ z7yHm(3`omv*iuVMty(hZt4!rMoghJSh<$-IeQR|26Z=Aim6bp75ClM1D}037;kK69PX= i;2|B)iM~$YD+PYGz()iw-@boW;2#k5zY=)8!2ciIXxHEX diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o deleted file mode 100644 index bd3b5c200e2c35bd962ff105477e09423c49beb3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2720 zcmbtV%}*0i5PxM65CsczFk)gkiAFY*G{zWXT58KCHqZ#DK}jiPl>|yjyH(^MhbG3x z3rDa130^#tXrljxTue0a;>|=8oZs6w-IwJx5S?V-%>3r-eeUdJa@meZL@-6fEfHvp z3X$&!>ok8mjUPSVU~n2Adz|K% zhl}5(+fng)u4Bnl>GX}*==^eh!>h*<_H{ckHc^*a{6#!rk0&nss7f}Zcx3yoh-^h8 z!>7A@c4Y7`b^-X_$|1<7U@PHvf zQeoI@&>($h=<9?+#C(`!+}|#M8abM*i{ZOILPlVg?nLr&<1djf=J>Diaf&s~KTkM_ z@29T`5oJN~tHgOPbkpaPzIIN5*gw2f-cQEw5N4{+M=S5P$^jOxpC!yxe_z!fSFxzy zO<%aaOPHztu8KQq{Y&I$svqt36Yx4wA5#j~-yuw%zxKaFh#4tZ$RaRDV>} z*Vm8#X1M+v!cd?6NR+g%_!Y&O!575*ttLx@8hY752MxaO6&6~)h^qLlP(06{;ddmM z*8f1Q-%*bIemS1c1#dt6b`bJP)&Hd8nT3}HJv?{#=5g7GeyM=7B=^x5u8%ums_&@# zi~FHdxV~=FW%zZ9p9ea|vSpkx=3$x%aMKP0m%W$MwzwrdN_rAA0yg4W6B3T*pvtVwLxtk_&>Hl zxG8^8`l~}Hndh_F1{cp{7q&|!5$ef>soczDDp#1vW@j^Vg}KyZE>j?u1YA8;ss9C?`PYm9 diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile deleted file mode 100644 index 69e964f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= ./build/. -.PHONY: all -all: - $(MAKE) kerberos diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi deleted file mode 100644 index e8ac042..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi +++ /dev/null @@ -1,138 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 0, - "gcc_version": 44, - "host_arch": "x64", - "icu_data_file": "icudt54l.dat", - "icu_data_in": "../../deps/icu/source/data/in/icudt54l.dat", - "icu_endianness": "l", - "icu_gyp_path": "tools/icu/icu-generic.gyp", - "icu_locales": "en,root", - "icu_path": "./deps/icu", - "icu_small": "true", - "icu_ver_major": "54", - "node_install_npm": "true", - "node_prefix": "/", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_mdb": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "openssl_no_asm": 0, - "python": "/data/opt/bin/python", - "target_arch": "x64", - "uv_library": "static_library", - "uv_parent_path": "/deps/uv/", - "uv_use_dtrace": "false", - "v8_enable_gdbjit": 0, - "v8_enable_i18n_support": 1, - "v8_no_strict_aliasing": 1, - "v8_optimized_debug": 0, - "v8_random_seed": 0, - "v8_use_snapshot": "false", - "want_separate_host_toolset": 0, - "nodedir": "/home/fmason/.node-gyp/0.12.7", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "cache_lock_stale": "60000", - "sign_git_tag": "", - "user_agent": "npm/2.11.3 node/v0.12.7 linux x64", - "always_auth": "", - "bin_links": "true", - "key": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "if_present": "", - "init_version": "1.0.0", - "user": "", - "force": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "tag_version_prefix": "v", - "cache_max": "Infinity", - "userconfig": "/home/fmason/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "tmp": "/tmp", - "depth": "Infinity", - "save_dev": "", - "usage": "", - "cafile": "", - "https_proxy": "", - "onload_script": "", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/bash", - "prefix": "/usr/local", - "browser": "", - "cache_lock_wait": "10000", - "registry": "https://registry.npmjs.org/", - "save_optional": "", - "scope": "", - "searchopts": "", - "versions": "", - "cache": "/home/fmason/.npm", - "ignore_scripts": "", - "searchsort": "name", - "version": "", - "local_address": "", - "viewer": "man", - "color": "true", - "fetch_retry_mintimeout": "10000", - "umask": "0002", - "fetch_retry_maxtimeout": "60000", - "message": "%s", - "ca": "", - "cert": "", - "global": "", - "link": "", - "access": "", - "save": "", - "unicode": "true", - "long": "", - "production": "", - "unsafe_perm": "true", - "node_version": "0.12.7", - "tag": "latest", - "git_tag_version": "true", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "npat": "", - "proprietary_attribs": "true", - "save_exact": "", - "strict_ssl": "true", - "dev": "", - "globalconfig": "/usr/local/etc/npmrc", - "init_module": "/home/fmason/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/local/etc/npmignore", - "cache_lock_retries": "10", - "save_prefix": "^", - "group": "1002", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "json": "", - "spin": "true" - } -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk deleted file mode 100644 index 36824f0..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk +++ /dev/null @@ -1,151 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := kerberos -DEFS_Debug := \ - '-DNODE_GYP_MODULE_NAME=kerberos' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -g \ - -O0 - -# Flags passed to only C files. -CFLAGS_C_Debug := - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti - -INCS_Debug := \ - -I/home/fmason/.node-gyp/0.12.7/src \ - -I/home/fmason/.node-gyp/0.12.7/deps/uv/include \ - -I/home/fmason/.node-gyp/0.12.7/deps/v8/include \ - -I$(srcdir)/node_modules/nan \ - -I/usr/include/mit-krb5 - -DEFS_Release := \ - '-DNODE_GYP_MODULE_NAME=kerberos' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -O3 \ - -ffunction-sections \ - -fdata-sections \ - -fno-tree-vrp \ - -fno-tree-sink \ - -fno-omit-frame-pointer - -# Flags passed to only C files. -CFLAGS_C_Release := - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti - -INCS_Release := \ - -I/home/fmason/.node-gyp/0.12.7/src \ - -I/home/fmason/.node-gyp/0.12.7/deps/uv/include \ - -I/home/fmason/.node-gyp/0.12.7/deps/v8/include \ - -I$(srcdir)/node_modules/nan \ - -I/usr/include/mit-krb5 - -OBJS := \ - $(obj).target/$(TARGET)/lib/kerberos.o \ - $(obj).target/$(TARGET)/lib/worker.o \ - $(obj).target/$(TARGET)/lib/kerberosgss.o \ - $(obj).target/$(TARGET)/lib/base64.o \ - $(obj).target/$(TARGET)/lib/kerberos_context.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m64 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m64 - -LIBS := \ - -lkrb5 \ - -lgssapi_krb5 - -$(obj).target/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/kerberos.node: LIBS := $(LIBS) -$(obj).target/kerberos.node: TOOLSET := $(TOOLSET) -$(obj).target/kerberos.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/kerberos.node -# Add target alias -.PHONY: kerberos -kerberos: $(builddir)/kerberos.node - -# Copy this to the executable output path. -$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) -$(builddir)/kerberos.node: $(obj).target/kerberos.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/kerberos.node -# Short alias for building this executable. -.PHONY: kerberos.node -kerberos.node: $(obj).target/kerberos.node $(builddir)/kerberos.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/kerberos.node - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log deleted file mode 100644 index 5679d63..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log +++ /dev/null @@ -1,25 +0,0 @@ -../lib/kerberos.cc:848:43: error: no viable conversion from 'Handle' to 'Local' - Local info[2] = { Nan::Null(), result}; - ^~~~~~ -/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:269:26: note: candidate constructor (the implicit copy constructor) not viable: cannot bind base class object of type 'Handle' to derived class reference 'const v8::Local &' for 1st argument -template class Local : public Handle { - ^ -/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:272:29: note: candidate template ignored: could not match 'Local' against 'Handle' - template inline Local(Local that) - ^ -/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:281:29: note: candidate template ignored: could not match 'S *' against 'Handle' - template inline Local(S* that) : Handle(that) { } - ^ -1 error generated. -make: *** [Release/obj.target/kerberos/lib/kerberos.o] Error 1 -gyp ERR! build error -gyp ERR! stack Error: `make` failed with exit code: 2 -gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23) -gyp ERR! stack at ChildProcess.emit (events.js:98:17) -gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:820:12) -gyp ERR! System Darwin 14.3.0 -gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" -gyp ERR! cwd /Users/christkv/coding/projects/kerberos -gyp ERR! node -v v0.10.35 -gyp ERR! node-gyp -v v1.0.1 -gyp ERR! not ok diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js deleted file mode 100644 index b8c8532..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js +++ /dev/null @@ -1,6 +0,0 @@ -// Get the Kerberos library -module.exports = require('./lib/kerberos'); -// Set up the auth processes -module.exports['processes'] = { - MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js deleted file mode 100644 index f1e9231..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js +++ /dev/null @@ -1,281 +0,0 @@ -var format = require('util').format; - -var MongoAuthProcess = function(host, port, service_name) { - // Check what system we are on - if(process.platform == 'win32') { - this._processor = new Win32MongoProcessor(host, port, service_name); - } else { - this._processor = new UnixMongoProcessor(host, port, service_name); - } -} - -MongoAuthProcess.prototype.init = function(username, password, callback) { - this._processor.init(username, password, callback); -} - -MongoAuthProcess.prototype.transition = function(payload, callback) { - this._processor.transition(payload, callback); -} - -/******************************************************************* - * - * Win32 SSIP Processor for MongoDB - * - *******************************************************************/ -var Win32MongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.ssip = require("../kerberos").SSIP; - // Set up first transition - this._transition = Win32MongoProcessor.first_transition(this); - // Set up service name - service_name = service_name || "mongodb"; - // Set up target - this.target = format("%s/%s", service_name, host); - // Number of retries - this.retries = 10; -} - -Win32MongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - // Save the values used later - this.username = username; - this.password = password; - // Aquire credentials - this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { - if(err) return callback(err); - // Save credentials - self.security_credentials = security_credentials; - // Callback with success - callback(null); - }); -} - -Win32MongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -Win32MongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.ssip.SecurityContext.initialize( - self.security_credentials, - self.target, - payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.second_transition(self); - self.security_context = security_context; - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.second_transition = function(self) { - return function(payload, callback) { - // Perform a step - self.security_context.initialize(self.target, payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - self._transition = Win32MongoProcessor.first_transition(self); - // Retry - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.third_transition(self); - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.third_transition = function(self) { - return function(payload, callback) { - var messageLength = 0; - // Get the raw bytes - var encryptedBytes = new Buffer(payload, 'base64'); - var encryptedMessage = new Buffer(messageLength); - // Copy first byte - encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); - // Set up trailer - var securityTrailerLength = encryptedBytes.length - messageLength; - var securityTrailer = new Buffer(securityTrailerLength); - // Copy the bytes - encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); - - // Types used - var SecurityBuffer = self.ssip.SecurityBuffer; - var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; - - // Set up security buffers - var buffers = [ - new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) - , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) - ]; - - // Set up the descriptor - var descriptor = new SecurityBufferDescriptor(buffers); - - // Decrypt the data - self.security_context.decryptMessage(descriptor, function(err, security_context) { - if(err) return callback(err); - - var length = 4; - if(self.username != null) { - length += self.username.length; - } - - var bytesReceivedFromServer = new Buffer(length); - bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION - bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION - - if(self.username != null) { - var authorization_id_bytes = new Buffer(self.username, 'utf8'); - authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); - } - - self.security_context.queryContextAttributes(0x00, function(err, sizes) { - if(err) return callback(err); - - var buffers = [ - new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) - , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) - , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) - ] - - var descriptor = new SecurityBufferDescriptor(buffers); - - self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { - if(err) return callback(err); - callback(null, security_context.payload); - }); - }); - }); - } -} - -/******************************************************************* - * - * UNIX MIT Kerberos processor - * - *******************************************************************/ -var UnixMongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.Kerberos = require("../kerberos").Kerberos; - this.kerberos = new this.Kerberos(); - service_name = service_name || "mongodb"; - // Set up first transition - this._transition = UnixMongoProcessor.first_transition(this); - // Set up target - this.target = format("%s@%s", service_name, host); - // Number of retries - this.retries = 10; -} - -UnixMongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - this.username = username; - this.password = password; - // Call client initiate - this.kerberos.authGSSClientInit( - self.target - , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - self.context = context; - // Return the context - callback(null, context); - }); -} - -UnixMongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -UnixMongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, '', function(err, result) { - if(err) return callback(err); - // Set up the next step - self._transition = UnixMongoProcessor.second_transition(self); - // Return the payload - callback(null, self.context.response); - }) - } -} - -UnixMongoProcessor.second_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { - if(err && self.retries == 0) return callback(err); - // Attempt to re-establish a context - if(err) { - // Adjust the number of retries - self.retries = self.retries - 1; - // Call same step again - return self.transition(payload, callback); - } - - // Set up the next step - self._transition = UnixMongoProcessor.third_transition(self); - // Return the payload - callback(null, self.context.response || ''); - }); - } -} - -UnixMongoProcessor.third_transition = function(self) { - return function(payload, callback) { - // GSS Client Unwrap - self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { - if(err) return callback(err, false); - - // Wrap the response - self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { - if(err) return callback(err, false); - // Set up the next step - self._transition = UnixMongoProcessor.fourth_transition(self); - // Return the payload - callback(null, self.context.response); - }); - }); - } -} - -UnixMongoProcessor.fourth_transition = function(self) { - return function(payload, callback) { - // Clean up context - self.kerberos.authGSSClientClean(self.context, function(err, result) { - if(err) return callback(err, false); - // Set the transition to null - self._transition = null; - // Callback with valid authentication - callback(null, true); - }); - } -} - -// Set the process -exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c deleted file mode 100644 index aca0a61..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "base64.h" - -#include -#include -#include -#include - -void die2(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - if(result == NULL) die2("Memory allocation failed"); - char *out = result; - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - unsigned char oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - *rlen = 0; - int c1, c2, c3, c4; - - int vlen = strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - if(result == NULL) die2("Memory allocation failed"); - unsigned char *out = result; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h deleted file mode 100644 index 9152e6a..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ -#ifndef BASE64_H -#define BASE64_H - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); - -#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc deleted file mode 100644 index 5b25d74..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc +++ /dev/null @@ -1,893 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "worker.h" -#include "kerberos_context.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -void die(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -// Call structs -typedef struct AuthGSSClientCall { - uint32_t flags; - char *uri; -} AuthGSSClientCall; - -typedef struct AuthGSSClientStepCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientStepCall; - -typedef struct AuthGSSClientUnwrapCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientUnwrapCall; - -typedef struct AuthGSSClientWrapCall { - KerberosContext *context; - char *challenge; - char *user_name; -} AuthGSSClientWrapCall; - -typedef struct AuthGSSClientCleanCall { - KerberosContext *context; -} AuthGSSClientCleanCall; - -typedef struct AuthGSSServerInitCall { - char *service; - bool constrained_delegation; - char *username; -} AuthGSSServerInitCall; - -typedef struct AuthGSSServerCleanCall { - KerberosContext *context; -} AuthGSSServerCleanCall; - -typedef struct AuthGSSServerStepCall { - KerberosContext *context; - char *auth_data; -} AuthGSSServerStepCall; - -Kerberos::Kerberos() : Nan::ObjectWrap() { -} - -Nan::Persistent Kerberos::constructor_template; - -void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("Kerberos").ToLocalChecked()); - - // Set up method for the Kerberos instance - Nan::SetPrototypeMethod(t, "authGSSClientInit", AuthGSSClientInit); - Nan::SetPrototypeMethod(t, "authGSSClientStep", AuthGSSClientStep); - Nan::SetPrototypeMethod(t, "authGSSClientUnwrap", AuthGSSClientUnwrap); - Nan::SetPrototypeMethod(t, "authGSSClientWrap", AuthGSSClientWrap); - Nan::SetPrototypeMethod(t, "authGSSClientClean", AuthGSSClientClean); - Nan::SetPrototypeMethod(t, "authGSSServerInit", AuthGSSServerInit); - Nan::SetPrototypeMethod(t, "authGSSServerClean", AuthGSSServerClean); - Nan::SetPrototypeMethod(t, "authGSSServerStep", AuthGSSServerStep); - - constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("Kerberos").ToLocalChecked(), t->GetFunction()); -} - -NAN_METHOD(Kerberos::New) { - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientInit(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - - // Allocate state - state = (gss_client_state *)malloc(sizeof(gss_client_state)); - if(state == NULL) die("Memory allocation failed"); - - // Unpack the parameter data struct - AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; - // Start the kerberos client - response = authenticate_gss_client_init(call->uri, call->flags, state); - - // Release the parameter struct memory - free(call->uri); - free(call); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - free(state); - } else { - worker->return_value = state; - } - - // Free structure - free(response); -} - -static Local _map_authGSSClientInit(Worker *worker) { - KerberosContext *context = KerberosContext::New(); - context->state = (gss_client_state *)worker->return_value; - return context->handle(); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientInit) { - // Ensure valid call - if(info.Length() != 3) return Nan::ThrowError("Requires a service string uri, integer flags and a callback function"); - if(info.Length() == 3 && (!info[0]->IsString() || !info[1]->IsInt32() || !info[2]->IsFunction())) - return Nan::ThrowError("Requires a service string uri, integer flags and a callback function"); - - Local service = info[0]->ToString(); - // Convert uri string to c-string - char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); - if(service_str == NULL) die("Memory allocation failed"); - - // Write v8 string to c-string - service->WriteUtf8(service_str); - - // Allocate a structure - AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); - if(call == NULL) die("Memory allocation failed"); - call->flags =info[1]->ToInt32()->Uint32Value(); - call->uri = service_str; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[2]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientInit; - worker->mapper = _map_authGSSClientInit; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientStep -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientStep(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; - // Get the state - state = call->context->state; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_step(state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Local _map_authGSSClientStep(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientStep) { - // Ensure valid call - if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsClientInstance()) { - return Nan::ThrowError("GSS context is not a client instance"); - } - - int callbackArg = 1; - - // If we have a challenge string - if(info.Length() == 3) { - // Unpack the challenge string - Local challenge = info[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - if(challenge_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - - callbackArg = 2; - } - - // Allocate a structure - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientStepCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[callbackArg]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientStep; - worker->mapper = _map_authGSSClientStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientUnwrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientUnwrap(Worker *worker) { - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_unwrap(call->context->state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Local _map_authGSSClientUnwrap(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientUnwrap) { - // Ensure valid call - if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsClientInstance()) { - return Nan::ThrowError("GSS context is not a client instance"); - } - - // If we have a challenge string - if(info.Length() == 3) { - // Unpack the challenge string - Local challenge = info[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - if(challenge_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callbackHandle = info.Length() == 3 ? Local::Cast(info[2]) : Local::Cast(info[1]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientUnwrap; - worker->mapper = _map_authGSSClientUnwrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientWrap(Worker *worker) { - gss_client_response *response; - char *user_name = NULL; - - // Unpack the parameter data struct - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; - user_name = call->user_name; - - // Check what kind of challenge we have - if(call->user_name == NULL) { - user_name = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - if(call->user_name != NULL) free(call->user_name); - free(call); - free(response); -} - -static Local _map_authGSSClientWrap(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientWrap) { - // Ensure valid call - if(info.Length() != 3 && info.Length() != 4) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(info.Length() == 4 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsString() || !info[3]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - - // Challenge string - char *challenge_str = NULL; - char *user_name_str = NULL; - - // Let's unpack the kerberos context - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsClientInstance()) { - return Nan::ThrowError("GSS context is not a client instance"); - } - - // Unpack the challenge string - Local challenge = info[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - if(challenge_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - - // If we have a user string - if(info.Length() == 4) { - // Unpack user name - Local user_name = info[2]->ToString(); - // Convert uri string to c-string - user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); - if(user_name_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - user_name->WriteUtf8(user_name_str); - } - - // Allocate a structure - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->challenge = challenge_str; - call->user_name = user_name_str; - - // Unpack the callback - Local callbackHandle = info.Length() == 4 ? Local::Cast(info[3]) : Local::Cast(info[2]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientWrap; - worker->mapper = _map_authGSSClientWrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientClean -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientClean(Worker *worker) { - gss_client_response *response; - - // Unpack the parameter data struct - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; - - // Perform authentication step - response = authenticate_gss_client_clean(call->context->state); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - free(call); - free(response); -} - -static Local _map_authGSSClientClean(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientClean) { - // Ensure valid call - if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function"); - if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function"); - - // Let's unpack the kerberos context - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsClientInstance()) { - return Nan::ThrowError("GSS context is not a client instance"); - } - - // Allocate a structure - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[1]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientClean; - worker->mapper = _map_authGSSClientClean; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSServerInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSServerInit(Worker *worker) { - gss_server_state *state; - gss_client_response *response; - - // Allocate state - state = (gss_server_state *)malloc(sizeof(gss_server_state)); - if(state == NULL) die("Memory allocation failed"); - - // Unpack the parameter data struct - AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)worker->parameters; - // Start the kerberos service - response = authenticate_gss_server_init(call->service, call->constrained_delegation, call->username, state); - - // Release the parameter struct memory - free(call->service); - free(call->username); - free(call); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - free(state); - } else { - worker->return_value = state; - } - - // Free structure - free(response); -} - -static Local _map_authGSSServerInit(Worker *worker) { - KerberosContext *context = KerberosContext::New(); - context->server_state = (gss_server_state *)worker->return_value; - return context->handle(); -} - -// Server Initialize method -NAN_METHOD(Kerberos::AuthGSSServerInit) { - // Ensure valid call - if(info.Length() != 4) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function"); - - if(!info[0]->IsString() || - !info[1]->IsBoolean() || - !(info[2]->IsString() || info[2]->IsNull()) || - !info[3]->IsFunction() - ) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function"); - - if (!info[1]->BooleanValue() && !info[2]->IsNull()) return Nan::ThrowError("S4U2Self only possible when constrained delegation is enabled"); - - // Allocate a structure - AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)calloc(1, sizeof(AuthGSSServerInitCall)); - if(call == NULL) die("Memory allocation failed"); - - Local service = info[0]->ToString(); - // Convert service string to c-string - char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); - if(service_str == NULL) die("Memory allocation failed"); - - // Write v8 string to c-string - service->WriteUtf8(service_str); - - call->service = service_str; - - call->constrained_delegation = info[1]->BooleanValue(); - - if (info[2]->IsNull()) - { - call->username = NULL; - } - else - { - Local tmpString = info[2]->ToString(); - - char *tmpCstr = (char *)calloc(tmpString->Utf8Length() + 1, sizeof(char)); - if(tmpCstr == NULL) die("Memory allocation failed"); - - tmpString->WriteUtf8(tmpCstr); - - call->username = tmpCstr; - } - - // Unpack the callback - Local callbackHandle = Local::Cast(info[3]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSServerInit; - worker->mapper = _map_authGSSServerInit; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSServerClean -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSServerClean(Worker *worker) { - gss_client_response *response; - - // Unpack the parameter data struct - AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)worker->parameters; - - // Perform authentication step - response = authenticate_gss_server_clean(call->context->server_state); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - free(call); - free(response); -} - -static Local _map_authGSSServerClean(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSServerClean) { - // // Ensure valid call - if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function"); - if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function"); - - // Let's unpack the kerberos context - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsServerInstance()) { - return Nan::ThrowError("GSS context is not a server instance"); - } - - // Allocate a structure - AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)calloc(1, sizeof(AuthGSSServerCleanCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[1]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSServerClean; - worker->mapper = _map_authGSSServerClean; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSServerStep -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSServerStep(Worker *worker) { - gss_server_state *state; - gss_client_response *response; - char *auth_data; - - // Unpack the parameter data struct - AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)worker->parameters; - // Get the state - state = call->context->server_state; - auth_data = call->auth_data; - - // Check if we got auth_data or not - if(call->auth_data == NULL) { - auth_data = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_server_step(state, auth_data); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->auth_data != NULL) free(call->auth_data); - free(call); - free(response); -} - -static Local _map_authGSSServerStep(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSServerStep) { - // Ensure valid call - if(info.Length() != 3) return Nan::ThrowError("Requires a GSS context, auth-data string and callback function"); - if(!KerberosContext::HasInstance(info[0])) return Nan::ThrowError("1st arg must be a GSS context"); - if (!info[1]->IsString()) return Nan::ThrowError("2nd arg must be auth-data string"); - if (!info[2]->IsFunction()) return Nan::ThrowError("3rd arg must be a callback function"); - - // Auth-data string - char *auth_data_str = NULL; - // Let's unpack the parameters - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsServerInstance()) { - return Nan::ThrowError("GSS context is not a server instance"); - } - - // Unpack the auth_data string - Local auth_data = info[1]->ToString(); - // Convert uri string to c-string - auth_data_str = (char *)calloc(auth_data->Utf8Length() + 1, sizeof(char)); - if(auth_data_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - auth_data->WriteUtf8(auth_data_str); - - // Allocate a structure - AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)calloc(1, sizeof(AuthGSSServerStepCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->auth_data = auth_data_str; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[2]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSServerStep; - worker->mapper = _map_authGSSServerStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Kerberos::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void Kerberos::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); - Local obj = err->ToObject(); - obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); - Local info[2] = { err, Nan::Null() }; - // Execute the error - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } else { - // // Map the data - Local result = worker->mapper(worker); - // Set up the callback with a null first - #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - Local info[2] = { Nan::Null(), result}; - #else - Local info[2] = { Nan::Null(), Nan::New(result)}; - #endif - - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } - - // Clean up the memory - delete worker->callback; - delete worker; -} - -// Exporting function -NAN_MODULE_INIT(init) { - Kerberos::Initialize(target); - KerberosContext::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h deleted file mode 100644 index beafa4d..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include - -#include "nan.h" -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public Nan::ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Nan::Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - - // Method available - static NAN_METHOD(AuthGSSClientInit); - static NAN_METHOD(AuthGSSClientStep); - static NAN_METHOD(AuthGSSClientUnwrap); - static NAN_METHOD(AuthGSSClientWrap); - static NAN_METHOD(AuthGSSClientClean); - static NAN_METHOD(AuthGSSServerInit); - static NAN_METHOD(AuthGSSServerClean); - static NAN_METHOD(AuthGSSServerStep); - -private: - static NAN_METHOD(New); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js deleted file mode 100644 index c7bae58..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js +++ /dev/null @@ -1,164 +0,0 @@ -var kerberos = require('../build/Release/kerberos') - , KerberosNative = kerberos.Kerberos; - -var Kerberos = function() { - this._native_kerberos = new KerberosNative(); -} - -// callback takes two arguments, an error string if defined and a new context -// uri should be given as service@host. Services are not always defined -// in a straightforward way. Use 'HTTP' for SPNEGO / Negotiate authentication. -Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { - return this._native_kerberos.authGSSClientInit(uri, flags, callback); -} - -// This will obtain credentials using a credentials cache. To override the default -// location (posible /tmp/krb5cc_nnnnnn, where nnnn is your numeric uid) use -// the environment variable KRB5CNAME. -// The credentials (suitable for using in an 'Authenticate: ' header, when prefixed -// with 'Negotiate ') will be available as context.response inside the callback -// if no error is indicated. -// callback takes one argument, an error string if defined -Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientStep(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { - if(typeof user_name == 'function') { - callback = user_name; - user_name = ''; - } - - return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); -} - -// free memory used by a context created using authGSSClientInit. -// callback takes one argument, an error string if defined. -Kerberos.prototype.authGSSClientClean = function(context, callback) { - return this._native_kerberos.authGSSClientClean(context, callback); -} - -// The server will obtain credentials using a keytab. To override the -// default location (probably /etc/krb5.keytab) set the KRB5_KTNAME -// environment variable. -// The service name should be in the form service, or service@host.name -// e.g. for HTTP, use "HTTP" or "HTTP@my.host.name". See gss_import_name -// for GSS_C_NT_HOSTBASED_SERVICE. -// -// a boolean turns on "constrained_delegation". this enables acquisition of S4U2Proxy -// credentials which will be stored in a credentials cache during the authGSSServerStep -// method. this parameter is optional. -// -// when "constrained_delegation" is enabled, a username can (optionally) be provided and -// S4U2Self protocol transition will be initiated. In this case, we will not -// require any "auth" data during the authGSSServerStep. This parameter is optional -// but constrained_delegation MUST be enabled for this to work. When S4U2Self is -// used, the username will be assumed to have been already authenticated, and no -// actual authentication will be performed. This is basically a way to "bootstrap" -// kerberos credentials (which can then be delegated with S4U2Proxy) for a user -// authenticated externally. -// -// callback takes two arguments, an error string if defined and a new context -// -Kerberos.prototype.authGSSServerInit = function(service, constrained_delegation, username, callback) { - if(typeof(constrained_delegation) === 'function') { - callback = constrained_delegation; - constrained_delegation = false; - username = null; - } - - if (typeof(constrained_delegation) === 'string') { - throw new Error("S4U2Self protocol transation is not possible without enabling constrained delegation"); - } - - if (typeof(username) === 'function') { - callback = username; - username = null; - } - - constrained_delegation = !!constrained_delegation; - - return this._native_kerberos.authGSSServerInit(service, constrained_delegation, username, callback); -}; - -//callback takes one argument, an error string if defined. -Kerberos.prototype.authGSSServerClean = function(context, callback) { - return this._native_kerberos.authGSSServerClean(context, callback); -}; - -// authData should be the base64 encoded authentication data obtained -// from client, e.g., in the Authorization header (without the leading -// "Negotiate " string) during SPNEGO authentication. The authenticated user -// is available in context.username after successful authentication. -// callback takes one argument, an error string if defined. -// -// Note: when S4U2Self protocol transition was requested in the authGSSServerInit -// no actual authentication will be performed and authData will be ignored. -// -Kerberos.prototype.authGSSServerStep = function(context, authData, callback) { - return this._native_kerberos.authGSSServerStep(context, authData, callback); -}; - -Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { - return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); -} - -Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { - return this._native_kerberos.prepareOutboundPackage(principal, inputdata); -} - -Kerberos.prototype.decryptMessage = function(challenge) { - return this._native_kerberos.decryptMessage(challenge); -} - -Kerberos.prototype.encryptMessage = function(challenge) { - return this._native_kerberos.encryptMessage(challenge); -} - -Kerberos.prototype.queryContextAttribute = function(attribute) { - if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); - return this._native_kerberos.queryContextAttribute(attribute); -} - -// Some useful result codes -Kerberos.AUTH_GSS_CONTINUE = 0; -Kerberos.AUTH_GSS_COMPLETE = 1; - -// Some useful gss flags -Kerberos.GSS_C_DELEG_FLAG = 1; -Kerberos.GSS_C_MUTUAL_FLAG = 2; -Kerberos.GSS_C_REPLAY_FLAG = 4; -Kerberos.GSS_C_SEQUENCE_FLAG = 8; -Kerberos.GSS_C_CONF_FLAG = 16; -Kerberos.GSS_C_INTEG_FLAG = 32; -Kerberos.GSS_C_ANON_FLAG = 64; -Kerberos.GSS_C_PROT_READY_FLAG = 128; -Kerberos.GSS_C_TRANS_FLAG = 256; - -// Export Kerberos class -exports.Kerberos = Kerberos; - -// If we have SSPI (windows) -if(kerberos.SecurityCredentials) { - // Put all SSPI classes in it's own namespace - exports.SSIP = { - SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext: require('./win32/wrappers/security_context').SecurityContext - , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - } -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc deleted file mode 100644 index bf24118..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc +++ /dev/null @@ -1,134 +0,0 @@ -#include "kerberos_context.h" - -Nan::Persistent KerberosContext::constructor_template; - -KerberosContext::KerberosContext() : Nan::ObjectWrap() { - state = NULL; - server_state = NULL; -} - -KerberosContext::~KerberosContext() { -} - -KerberosContext* KerberosContext::New() { - Nan::HandleScope scope; - Local obj = Nan::New(constructor_template)->GetFunction()->NewInstance(); - KerberosContext *kerberos_context = Nan::ObjectWrap::Unwrap(obj); - return kerberos_context; -} - -NAN_METHOD(KerberosContext::New) { - // Create code object - KerberosContext *kerberos_context = new KerberosContext(); - // Wrap it - kerberos_context->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -void KerberosContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(static_cast(New)); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("KerberosContext").ToLocalChecked()); - - // Get prototype - Local proto = t->PrototypeTemplate(); - - // Getter for the response - Nan::SetAccessor(proto, Nan::New("response").ToLocalChecked(), KerberosContext::ResponseGetter); - - // Getter for the username - Nan::SetAccessor(proto, Nan::New("username").ToLocalChecked(), KerberosContext::UsernameGetter); - - // Getter for the targetname - server side only - Nan::SetAccessor(proto, Nan::New("targetname").ToLocalChecked(), KerberosContext::TargetnameGetter); - - Nan::SetAccessor(proto, Nan::New("delegatedCredentialsCache").ToLocalChecked(), KerberosContext::DelegatedCredentialsCacheGetter); - - // Set persistent - constructor_template.Reset(t); - // NanAssignPersistent(constructor_template, t); - - // Set the symbol - target->ForceSet(Nan::New("KerberosContext").ToLocalChecked(), t->GetFunction()); -} - - -// Response Setter / Getter -NAN_GETTER(KerberosContext::ResponseGetter) { - gss_client_state *client_state; - gss_server_state *server_state; - - // Unpack the object - KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); - - // Response could come from client or server state... - client_state = context->state; - server_state = context->server_state; - - // If client state is in use, take response from there, otherwise from server - char *response = client_state != NULL ? client_state->response : - server_state != NULL ? server_state->response : NULL; - - if(response == NULL) { - info.GetReturnValue().Set(Nan::Null()); - } else { - // Return the response - info.GetReturnValue().Set(Nan::New(response).ToLocalChecked()); - } -} - -// username Getter -NAN_GETTER(KerberosContext::UsernameGetter) { - // Unpack the object - KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); - - gss_client_state *client_state = context->state; - gss_server_state *server_state = context->server_state; - - // If client state is in use, take response from there, otherwise from server - char *username = client_state != NULL ? client_state->username : - server_state != NULL ? server_state->username : NULL; - - if(username == NULL) { - info.GetReturnValue().Set(Nan::Null()); - } else { - info.GetReturnValue().Set(Nan::New(username).ToLocalChecked()); - } -} - -// targetname Getter - server side only -NAN_GETTER(KerberosContext::TargetnameGetter) { - // Unpack the object - KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); - - gss_server_state *server_state = context->server_state; - - char *targetname = server_state != NULL ? server_state->targetname : NULL; - - if(targetname == NULL) { - info.GetReturnValue().Set(Nan::Null()); - } else { - info.GetReturnValue().Set(Nan::New(targetname).ToLocalChecked()); - } -} - -// targetname Getter - server side only -NAN_GETTER(KerberosContext::DelegatedCredentialsCacheGetter) { - // Unpack the object - KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); - - gss_server_state *server_state = context->server_state; - - char *delegated_credentials_cache = server_state != NULL ? server_state->delegated_credentials_cache : NULL; - - if(delegated_credentials_cache == NULL) { - info.GetReturnValue().Set(Nan::Null()); - } else { - info.GetReturnValue().Set(Nan::New(delegated_credentials_cache).ToLocalChecked()); - } -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h deleted file mode 100644 index 23eb577..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef KERBEROS_CONTEXT_H -#define KERBEROS_CONTEXT_H - -#include -#include -#include -#include - -#include "nan.h" -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class KerberosContext : public Nan::ObjectWrap { - -public: - KerberosContext(); - ~KerberosContext(); - - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - inline bool IsClientInstance() { - return state != NULL; - } - - inline bool IsServerInstance() { - return server_state != NULL; - } - - // Constructor used for creating new Kerberos objects from C++ - static Nan::Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - - // Public constructor - static KerberosContext* New(); - - // Handle to the kerberos client context - gss_client_state *state; - - // Handle to the kerberos server context - gss_server_state *server_state; - -private: - static NAN_METHOD(New); - // In either client state or server state - static NAN_GETTER(ResponseGetter); - static NAN_GETTER(UsernameGetter); - // Only in the "server_state" - static NAN_GETTER(TargetnameGetter); - static NAN_GETTER(DelegatedCredentialsCacheGetter); -}; -#endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c deleted file mode 100644 index 2fbca00..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c +++ /dev/null @@ -1,931 +0,0 @@ -/** - * Copyright (c) 2006-2010 Apple Inc. All rights reserved. - * - * 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. - * - **/ -/* - * S4U2Proxy implementation - * Copyright (C) 2015 David Mansfield - * Code inspired by mod_auth_kerb. - */ - -#include "kerberosgss.h" - -#include "base64.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - -void die1(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -static gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min); -static gss_client_response *other_error(const char *fmt, ...); -static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem); - -static gss_client_response *store_gss_creds(gss_server_state *state); -static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context context, krb5_principal princ, krb5_ccache *ccache); - -/* -char* server_principal_details(const char* service, const char* hostname) -{ - char match[1024]; - int match_len = 0; - char* result = NULL; - - int code; - krb5_context kcontext; - krb5_keytab kt = NULL; - krb5_kt_cursor cursor = NULL; - krb5_keytab_entry entry; - char* pname = NULL; - - // Generate the principal prefix we want to match - snprintf(match, 1024, "%s/%s@", service, hostname); - match_len = strlen(match); - - code = krb5_init_context(&kcontext); - if (code) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot initialize Kerberos5 context", code)); - return NULL; - } - - if ((code = krb5_kt_default(kcontext, &kt))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get default keytab", code)); - goto end; - } - - if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get sequence cursor from keytab", code)); - goto end; - } - - while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) - { - if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot parse principal name from keytab", code)); - goto end; - } - - if (strncmp(pname, match, match_len) == 0) - { - result = malloc(strlen(pname) + 1); - strcpy(result, pname); - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - break; - } - - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - } - - if (result == NULL) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Principal not found in keytab", -1)); - } - -end: - if (cursor) - krb5_kt_end_seq_get(kcontext, kt, &cursor); - if (kt) - krb5_kt_close(kcontext, kt); - krb5_free_context(kcontext); - - return result; -} -*/ -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_COMPLETE; - - state->server_name = GSS_C_NO_NAME; - state->context = GSS_C_NO_CONTEXT; - state->gss_flags = gss_flags; - state->username = NULL; - state->response = NULL; - - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); - - if (GSS_ERROR(maj_stat)) { - response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - -end: - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - - if(state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - - if(state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - - if(state->username != NULL) { - free(state->username); - state->username = NULL; - } - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_init_sec_context(&min_stat, - GSS_C_NO_CREDENTIAL, - &state->context, - state->server_name, - GSS_C_NO_OID, - (OM_uint32)state->gss_flags, - 0, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - NULL, - &output_token, - NULL, - NULL); - - if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { - response = gss_error(__func__, "gss_init_sec_context", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; - // Grab the client response to send back to the server - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Try to get the user name if we have completed all GSS operations - if (ret == AUTH_GSS_COMPLETE) { - gss_name_t gssuser = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); - - if(GSS_ERROR(maj_stat)) { - response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - gss_buffer_desc name_token; - name_token.length = 0; - maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); - - if(GSS_ERROR(maj_stat)) { - if(name_token.value) - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - - response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - state->username = (char *)malloc(name_token.length + 1); - if(state->username == NULL) die1("Memory allocation failed"); - strncpy(state->username, (char*) name_token.value, name_token.length); - state->username[name_token.length] = 0; - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - } - } - -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_unwrap(&min_stat, - state->context, - &input_token, - &output_token, - NULL, - NULL); - - if(maj_stat != GSS_S_COMPLETE) { - response = gss_error(__func__, "gss_unwrap", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - ret = AUTH_GSS_COMPLETE; - } - - // Grab the client response - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - gss_release_buffer(&min_stat, &output_token); - } -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - char buf[4096], server_conf_flags; - unsigned long buf_size; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - if(user) { - // get bufsize - server_conf_flags = ((char*) input_token.value)[0]; - ((char*) input_token.value)[0] = 0; - buf_size = ntohl(*((long *) input_token.value)); - free(input_token.value); -#ifdef PRINTFS - printf("User: %s, %c%c%c\n", user, - server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', - server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', - server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); - printf("Maximum GSS token size is %ld\n", buf_size); -#endif - - // agree to terms (hack!) - buf_size = htonl(buf_size); // not relevant without integrity/privacy - memcpy(buf, &buf_size, 4); - buf[0] = GSS_AUTH_P_NONE; - // server decides if principal can log in as user - strncpy(buf + 4, user, sizeof(buf) - 4); - input_token.value = buf; - input_token.length = 4 + strlen(user); - } - - // Do GSSAPI wrap - maj_stat = gss_wrap(&min_stat, - state->context, - 0, - GSS_C_QOP_DEFAULT, - &input_token, - NULL, - &output_token); - - if (maj_stat != GSS_S_COMPLETE) { - response = gss_error(__func__, "gss_wrap", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else - ret = AUTH_GSS_COMPLETE; - // Grab the client response to send back to the server - if (output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - gss_release_buffer(&min_stat, &output_token); - } -end: - if (output_token.value) - gss_release_buffer(&min_stat, &output_token); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_server_init(const char *service, bool constrained_delegation, const char *username, gss_server_state *state) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - gss_cred_usage_t usage = GSS_C_ACCEPT; - - state->context = GSS_C_NO_CONTEXT; - state->server_name = GSS_C_NO_NAME; - state->client_name = GSS_C_NO_NAME; - state->server_creds = GSS_C_NO_CREDENTIAL; - state->client_creds = GSS_C_NO_CREDENTIAL; - state->username = NULL; - state->targetname = NULL; - state->response = NULL; - state->constrained_delegation = constrained_delegation; - state->delegated_credentials_cache = NULL; - - // Server name may be empty which means we aren't going to create our own creds - size_t service_len = strlen(service); - if (service_len != 0) - { - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); - - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - if (state->constrained_delegation) - { - usage = GSS_C_BOTH; - } - - // Get credentials - maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, usage, &state->server_creds, NULL, NULL); - - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_acquire_cred", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - } - - // If a username was passed, perform the S4U2Self protocol transition to acquire - // a credentials from that user as if we had done gss_accept_sec_context. - // In this scenario, the passed username is assumed to be already authenticated - // by some external mechanism, and we are here to "bootstrap" some gss credentials. - // In authenticate_gss_server_step we will bypass the actual authentication step. - if (username != NULL) - { - gss_name_t gss_username; - - name_token.length = strlen(username); - name_token.value = (char *)username; - - maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_USER_NAME, &gss_username); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - maj_stat = gss_acquire_cred_impersonate_name(&min_stat, - state->server_creds, - gss_username, - GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, - GSS_C_INITIATE, - &state->client_creds, - NULL, - NULL); - - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_acquire_cred_impersonate_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - } - - gss_release_name(&min_stat, &gss_username); - - if (response != NULL) - { - goto end; - } - - // because the username MAY be a "local" username, - // we want get the canonical name from the acquired creds. - maj_stat = gss_inquire_cred(&min_stat, state->client_creds, &state->client_name, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_inquire_cred", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - } - -end: - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_server_clean(gss_server_state *state) -{ - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - - if (state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - if (state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - if (state->client_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->client_name); - if (state->server_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->server_creds); - if (state->client_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->client_creds); - if (state->username != NULL) - { - free(state->username); - state->username = NULL; - } - if (state->targetname != NULL) - { - free(state->targetname); - state->targetname = NULL; - } - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - if (state->delegated_credentials_cache) - { - // TODO: what about actually destroying the cache? It can't be done now as - // the whole point is having it around for the lifetime of the "session" - free(state->delegated_credentials_cache); - } - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *auth_data) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - - // Always clear out the old response - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - // we don't need to check the authentication token if S4U2Self protocol - // transition was done, because we already have the client credentials. - if (state->client_creds == GSS_C_NO_CREDENTIAL) - { - if (auth_data && *auth_data) - { - int len; - input_token.value = base64_decode(auth_data, &len); - input_token.length = len; - } - else - { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->message = strdup("No auth_data value in request from client"); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - maj_stat = gss_accept_sec_context(&min_stat, - &state->context, - state->server_creds, - &input_token, - GSS_C_NO_CHANNEL_BINDINGS, - &state->client_name, - NULL, - &output_token, - NULL, - NULL, - &state->client_creds); - - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_accept_sec_context", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - // Grab the server response to send back to the client - if (output_token.length) - { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - } - - // Get the user name - maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - state->username = (char *)malloc(output_token.length + 1); - strncpy(state->username, (char*) output_token.value, output_token.length); - state->username[output_token.length] = 0; - - // Get the target name if no server creds were supplied - if (state->server_creds == GSS_C_NO_CREDENTIAL) - { - gss_name_t target_name = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - state->targetname = (char *)malloc(output_token.length + 1); - strncpy(state->targetname, (char*) output_token.value, output_token.length); - state->targetname[output_token.length] = 0; - } - - if (state->constrained_delegation && state->client_creds != GSS_C_NO_CREDENTIAL) - { - if ((response = store_gss_creds(state)) != NULL) - { - goto end; - } - } - - ret = AUTH_GSS_COMPLETE; - -end: - if (output_token.length) - gss_release_buffer(&min_stat, &output_token); - if (input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -static gss_client_response *store_gss_creds(gss_server_state *state) -{ - OM_uint32 maj_stat, min_stat; - krb5_principal princ = NULL; - krb5_ccache ccache = NULL; - krb5_error_code problem; - krb5_context context; - gss_client_response *response = NULL; - - problem = krb5_init_context(&context); - if (problem) { - response = other_error("No auth_data value in request from client"); - return response; - } - - problem = krb5_parse_name(context, state->username, &princ); - if (problem) { - response = krb5_ctx_error(context, problem); - goto end; - } - - if ((response = create_krb5_ccache(state, context, princ, &ccache))) - { - goto end; - } - - maj_stat = gss_krb5_copy_ccache(&min_stat, state->client_creds, ccache); - if (GSS_ERROR(maj_stat)) { - response = gss_error(__func__, "gss_krb5_copy_ccache", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - krb5_cc_close(context, ccache); - ccache = NULL; - - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - // TODO: something other than AUTH_GSS_COMPLETE? - response->return_code = AUTH_GSS_COMPLETE; - - end: - if (princ) - krb5_free_principal(context, princ); - if (ccache) - krb5_cc_destroy(context, ccache); - krb5_free_context(context); - - return response; -} - -static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context kcontext, krb5_principal princ, krb5_ccache *ccache) -{ - char *ccname = NULL; - int fd; - krb5_error_code problem; - krb5_ccache tmp_ccache = NULL; - gss_client_response *error = NULL; - - // TODO: mod_auth_kerb used a temp file under /run/httpd/krbcache. what can we do? - ccname = strdup("FILE:/tmp/krb5cc_nodekerberos_XXXXXX"); - if (!ccname) die1("Memory allocation failed"); - - fd = mkstemp(ccname + strlen("FILE:")); - if (fd < 0) { - error = other_error("mkstemp() failed: %s", strerror(errno)); - goto end; - } - - close(fd); - - problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache); - if (problem) { - error = krb5_ctx_error(kcontext, problem); - goto end; - } - - problem = krb5_cc_initialize(kcontext, tmp_ccache, princ); - if (problem) { - error = krb5_ctx_error(kcontext, problem); - goto end; - } - - state->delegated_credentials_cache = strdup(ccname); - - // TODO: how/when to cleanup the creds cache file? - // TODO: how to expose the credentials expiration time? - - *ccache = tmp_ccache; - tmp_ccache = NULL; - - end: - if (tmp_ccache) - krb5_cc_destroy(kcontext, tmp_ccache); - - if (ccname && error) - unlink(ccname); - - if (ccname) - free(ccname); - - return error; -} - - -gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - - gss_client_response *response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - - char *message = NULL; - message = calloc(1024, 1); - if(message == NULL) die1("Memory allocation failed"); - - response->message = message; - - int nleft = 1024; - int n; - - n = snprintf(message, nleft, "%s(%s)", func, op); - message += n; - nleft -= n; - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - n = snprintf(message, nleft, ": %.*s", - (int)status_string.length, (char*)status_string.value); - message += n; - nleft -= n; - - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if(!GSS_ERROR(maj_stat)) { - n = snprintf(message, nleft, ": %.*s", - (int)status_string.length, (char*)status_string.value); - message += n; - nleft -= n; - - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); - - return response; -} - -static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem) -{ - gss_client_response *response = NULL; - const char *error_text = krb5_get_error_message(context, problem); - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->message = strdup(error_text); - // TODO: something other than AUTH_GSS_ERROR? AUTH_KRB5_ERROR ? - response->return_code = AUTH_GSS_ERROR; - krb5_free_error_message(context, error_text); - return response; -} - -static gss_client_response *other_error(const char *fmt, ...) -{ - size_t needed; - char *msg; - gss_client_response *response = NULL; - va_list ap, aps; - - va_start(ap, fmt); - - va_copy(aps, ap); - needed = snprintf(NULL, 0, fmt, aps); - va_end(aps); - - msg = malloc(needed); - if (!msg) die1("Memory allocation failed"); - - vsnprintf(msg, needed, fmt, ap); - va_end(ap); - - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->message = msg; - - // TODO: something other than AUTH_GSS_ERROR? - response->return_code = AUTH_GSS_ERROR; - - return response; -} - - -#pragma clang diagnostic pop - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h deleted file mode 100644 index fa7e311..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright (c) 2006-2009 Apple Inc. All rights reserved. - * - * 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. - **/ -#ifndef KERBEROS_GSS_H -#define KERBEROS_GSS_H - -#include - -#include -#include -#include - -#define krb5_get_err_text(context,code) error_message(code) - -#define AUTH_GSS_ERROR -1 -#define AUTH_GSS_COMPLETE 1 -#define AUTH_GSS_CONTINUE 0 - -#define GSS_AUTH_P_NONE 1 -#define GSS_AUTH_P_INTEGRITY 2 -#define GSS_AUTH_P_PRIVACY 4 - -typedef struct { - int return_code; - char *message; -} gss_client_response; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - long int gss_flags; - char* username; - char* response; -} gss_client_state; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - gss_name_t client_name; - gss_cred_id_t server_creds; - gss_cred_id_t client_creds; - char* username; - char* targetname; - char* response; - bool constrained_delegation; - char* delegated_credentials_cache; -} gss_server_state; - -// char* server_principal_details(const char* service, const char* hostname); - -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); -gss_client_response *authenticate_gss_client_clean(gss_client_state *state); -gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); -gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); - -gss_client_response *authenticate_gss_server_init(const char* service, bool constrained_delegation, const char *username, gss_server_state* state); -gss_client_response *authenticate_gss_server_clean(gss_server_state *state); -gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *challenge); - -#endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js deleted file mode 100644 index d9120fb..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js +++ /dev/null @@ -1,15 +0,0 @@ -// Load the native SSPI classes -var kerberos = require('../build/Release/kerberos') - , Kerberos = kerberos.Kerberos - , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; -var SSPI = function() { -} - -exports.SSPI = SSPI; -exports.SecurityBuffer = SecurityBuffer; -exports.SecurityBufferDescriptor = SecurityBufferDescriptor; -exports.SecurityCredentials = SecurityCredentials; -exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c deleted file mode 100644 index 502a021..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - unsigned char oval; - - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - int c1, c2, c3, c4; - int vlen = (int)strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - *rlen = 0; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h deleted file mode 100644 index f0e1f06..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc deleted file mode 100644 index c7b583f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc +++ /dev/null @@ -1,51 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "base64.h" -#include "wrappers/security_buffer.h" -#include "wrappers/security_buffer_descriptor.h" -#include "wrappers/security_context.h" -#include "wrappers/security_credentials.h" - -Nan::Persistent Kerberos::constructor_template; - -Kerberos::Kerberos() : Nan::ObjectWrap() { -} - -void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("Kerberos").ToLocalChecked()); - - // Set persistent - constructor_template.Reset(t); - - // Set the symbol - Nan::Set(target, Nan::New("Kerberos").ToLocalChecked(), t->GetFunction()); -} - -NAN_METHOD(Kerberos::New) { - // Load the security.dll library - load_library(); - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -// Exporting function -NAN_MODULE_INIT(init) { - Kerberos::Initialize(target); - SecurityContext::Initialize(target); - SecurityBuffer::Initialize(target); - SecurityBufferDescriptor::Initialize(target); - SecurityCredentials::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h deleted file mode 100644 index 0fd2760..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include "nan.h" - -extern "C" { - #include "kerberos_sspi.h" - #include "base64.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public Nan::ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Nan::Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - - // Method available - static NAN_METHOD(AcquireAlternateCredentials); - static NAN_METHOD(PrepareOutboundPackage); - static NAN_METHOD(DecryptMessage); - static NAN_METHOD(EncryptMessage); - static NAN_METHOD(QueryContextAttributes); - -private: - static NAN_METHOD(New); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - // package info - SecPkgInfo m_PkgInfo; - // context - CtxtHandle m_Context; - // Do we have a context - bool m_HaveContext; - // Attributes - DWORD CtxtAttr; - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c deleted file mode 100644 index d75c9ab..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c +++ /dev/null @@ -1,244 +0,0 @@ -#include "kerberos_sspi.h" -#include -#include - -static HINSTANCE _sspi_security_dll = NULL; -static HINSTANCE _sspi_secur32_dll = NULL; - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { - // Create function pointer instance - encryptMessage_fn pfn_encryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function to library method - pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); - // Check if the we managed to map function pointer - if(!pfn_encryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); -} - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); - #else - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_acquireCredentialsHandle) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Status - status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, - pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry - ); - - // Call the function - return status; -} - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { - // Create function pointer instance - deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); - - // Check if the we managed to map function pointer - if(!pfn_deleteSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_deleteSecurityContext)(phContext); -} - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { - // Create function pointer instance - decryptMessage_fn pfn_decryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); - - // Check if the we managed to map function pointer - if(!pfn_decryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); -} - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, PCtxtHandle phContext, - LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, - PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, - unsigned long * pfContextAttr, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); - #else - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_initializeSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Execute intialize context - status = (*pfn_initializeSecurityContext)( - phCredential, phContext, pszTargetName, fContextReq, - Reserved1, TargetDataRep, pInput, Reserved2, - phNewContext, pOutput, pfContextAttr, ptsExpiry - ); - - // Call the function - return status; -} -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer -) { - // Create function pointer instance - queryContextAttributes_fn pfn_queryContextAttributes = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - #ifdef _UNICODE - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); - #else - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_queryContextAttributes) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_queryContextAttributes)( - phContext, ulAttribute, pBuffer - ); -} - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface() { - INIT_SECURITY_INTERFACE InitSecurityInterface; - PSecurityFunctionTable pSecurityInterface = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return NULL; - - #ifdef _UNICODE - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceW")); - #else - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceA")); - #endif - - if(!InitSecurityInterface) { - printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); - return NULL; - } - - // Use InitSecurityInterface to get the function table. - pSecurityInterface = (*InitSecurityInterface)(); - - if(!pSecurityInterface) { - printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); - return NULL; - } - - return pSecurityInterface; -} - -/** - * Load security.dll dynamically - */ -int load_library() { - DWORD err; - // Load the library - _sspi_security_dll = LoadLibrary("security.dll"); - - // Check if the library loaded - if(_sspi_security_dll == NULL) { - err = GetLastError(); - return err; - } - - // Load the library - _sspi_secur32_dll = LoadLibrary("secur32.dll"); - - // Check if the library loaded - if(_sspi_secur32_dll == NULL) { - err = GetLastError(); - return err; - } - - return 0; -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h deleted file mode 100644 index a3008dc..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef SSPI_C_H -#define SSPI_C_H - -#define SECURITY_WIN32 1 - -#include -#include - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); - -typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, // Name of principal - LPSTR pszPackage, // Name of package - unsigned long fCredentialUse, // Flags indicating use - void * pvLogonId, // Pointer to logon ID - void * pAuthData, // Package specific data - SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func - void * pvGetKeyArgument, // Value to pass to GetKey() - PCredHandle phCredential, // (out) Cred Handle - PTimeStamp ptsExpiry // (out) Lifetime (optional) -); - -typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry - ); - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( - PCtxtHandle phContext // Context to delete -); - -typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( - PCtxtHandle phContext, - PSecBufferDesc pMessage, - unsigned long MessageSeqNo, - unsigned long pfQOP -); - -typedef DWORD (WINAPI *decryptMessage_fn)( - PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, // Cred to base context - PCtxtHandle phContext, // Existing context (OPT) - LPSTR pszTargetName, // Name of target - unsigned long fContextReq, // Context Requirements - unsigned long Reserved1, // Reserved, MBZ - unsigned long TargetDataRep, // Data rep of target - PSecBufferDesc pInput, // Input Buffers - unsigned long Reserved2, // Reserved, MBZ - PCtxtHandle phNewContext, // (out) New Context handle - PSecBufferDesc pOutput, // (inout) Output Buffers - unsigned long * pfContextAttr, // (out) Context attrs - PTimeStamp ptsExpiry // (out) Life span (OPT) -); - -typedef DWORD (WINAPI *initializeSecurityContext_fn)( - PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); - -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, // Context to query - unsigned long ulAttribute, // Attribute to query - void * pBuffer // Buffer for attributes -); - -typedef DWORD (WINAPI *queryContextAttributes_fn)( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface(); - -typedef DWORD (WINAPI *initSecurityInterface_fn) (); - -/** - * Load security.dll dynamically - */ -int load_library(); - -#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc deleted file mode 100644 index e7a472f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h deleted file mode 100644 index c2ccb6b..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - Nan::Callback *callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Local (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc deleted file mode 100644 index fdf8e49..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc +++ /dev/null @@ -1,101 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_buffer.h" - -using namespace node; - -Nan::Persistent SecurityBuffer::constructor_template; - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : Nan::ObjectWrap() { - this->size = size; - this->data = calloc(size, sizeof(char)); - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : Nan::ObjectWrap() { - this->size = size; - this->data = data; - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::~SecurityBuffer() { - free(this->data); -} - -NAN_METHOD(SecurityBuffer::New) { - SecurityBuffer *security_obj; - - if(info.Length() != 2) - return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!info[0]->IsInt32()) - return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!info[1]->IsInt32() && !Buffer::HasInstance(info[1])) - return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - // Unpack buffer type - uint32_t buffer_type = info[0]->ToUint32()->Value(); - - // If we have an integer - if(info[1]->IsInt32()) { - security_obj = new SecurityBuffer(buffer_type, info[1]->ToUint32()->Value()); - } else { - // Get the length of the Buffer - size_t length = Buffer::Length(info[1]->ToObject()); - // Allocate space for the internal void data pointer - void *data = calloc(length, sizeof(char)); - // Write the data to out of V8 heap space - memcpy(data, Buffer::Data(info[1]->ToObject()), length); - // Create new SecurityBuffer - security_obj = new SecurityBuffer(buffer_type, length, data); - } - - // Wrap it - security_obj->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -NAN_METHOD(SecurityBuffer::ToBuffer) { - // Unpack the Security Buffer object - SecurityBuffer *security_obj = Nan::ObjectWrap::Unwrap(info.This()); - // Create a Buffer - Local buffer = Nan::CopyBuffer((char *)security_obj->data, (uint32_t)security_obj->size).ToLocalChecked(); - // Return the buffer - info.GetReturnValue().Set(buffer); -} - -void SecurityBuffer::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("SecurityBuffer").ToLocalChecked()); - - // Class methods - Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer); - - // Set persistent - constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("SecurityBuffer").ToLocalChecked(), t->GetFunction()); -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h deleted file mode 100644 index 0c97d56..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef SECURITY_BUFFER_H -#define SECURITY_BUFFER_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBuffer : public Nan::ObjectWrap { - public: - SecurityBuffer(uint32_t security_type, size_t size); - SecurityBuffer(uint32_t security_type, size_t size, void *data); - ~SecurityBuffer(); - - // Internal values - void *data; - size_t size; - uint32_t security_type; - SecBuffer sec_buffer; - - // Has instance check - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - static NAN_METHOD(ToBuffer); - - // Constructor used for creating new Long objects from C++ - static Nan::Persistent constructor_template; - - private: - static NAN_METHOD(New); -}; - -#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js deleted file mode 100644 index 4996163..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js +++ /dev/null @@ -1,12 +0,0 @@ -var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; - -// Add some attributes -SecurityBufferNative.VERSION = 0; -SecurityBufferNative.EMPTY = 0; -SecurityBufferNative.DATA = 1; -SecurityBufferNative.TOKEN = 2; -SecurityBufferNative.PADDING = 9; -SecurityBufferNative.STREAM = 10; - -// Export the modified class -exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc deleted file mode 100644 index fce0d81..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc +++ /dev/null @@ -1,182 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include "security_buffer_descriptor.h" -#include "security_buffer.h" - -Nan::Persistent SecurityBufferDescriptor::constructor_template; - -SecurityBufferDescriptor::SecurityBufferDescriptor() : Nan::ObjectWrap() { -} - -SecurityBufferDescriptor::SecurityBufferDescriptor(const Nan::Persistent& arrayObjectPersistent) : Nan::ObjectWrap() { - SecurityBuffer *security_obj = NULL; - // Get the Local value - Local arrayObject = Nan::New(arrayObjectPersistent); - - // Safe reference to array - this->arrayObject = arrayObject; - - // Unpack the array and ensure we have a valid descriptor - this->secBufferDesc.cBuffers = arrayObject->Length(); - this->secBufferDesc.ulVersion = SECBUFFER_VERSION; - - if(arrayObject->Length() == 1) { - // Unwrap the buffer - security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - // Assign the buffer - this->secBufferDesc.pBuffers = &security_obj->sec_buffer; - } else { - this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; - this->secBufferDesc.cBuffers = arrayObject->Length(); - - // Assign the buffers - for(uint32_t i = 0; i < arrayObject->Length(); i++) { - security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); - this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; - this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; - this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; - } - } -} - -SecurityBufferDescriptor::~SecurityBufferDescriptor() { -} - -size_t SecurityBufferDescriptor::bufferSize() { - SecurityBuffer *security_obj = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - return security_obj->size; - } else { - int bytesToAllocate = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return total size - return bytesToAllocate; - } -} - -char *SecurityBufferDescriptor::toBuffer() { - SecurityBuffer *security_obj = NULL; - char *data = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - data = (char *)malloc(security_obj->size * sizeof(char)); - memcpy(data, security_obj->data, security_obj->size); - } else { - size_t bytesToAllocate = this->bufferSize(); - char *data = (char *)calloc(bytesToAllocate, sizeof(char)); - int offset = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); - offset +=this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return the data - return data; - } - - return data; -} - -NAN_METHOD(SecurityBufferDescriptor::New) { - SecurityBufferDescriptor *security_obj; - Nan::Persistent arrayObject; - - if(info.Length() != 1) - return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(!info[0]->IsInt32() && !info[0]->IsArray()) - return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(info[0]->IsArray()) { - Local array = Local::Cast(info[0]); - // Iterate over all items and ensure we the right type - for(uint32_t i = 0; i < array->Length(); i++) { - if(!SecurityBuffer::HasInstance(array->Get(i))) { - return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - } - } - } - - // We have a single integer - if(info[0]->IsInt32()) { - // Create new SecurityBuffer instance - Local argv[] = {Nan::New(0x02), info[0]}; - Local security_buffer = Nan::New(SecurityBuffer::constructor_template)->GetFunction()->NewInstance(2, argv); - // Create a new array - Local array = Nan::New(1); - // Set the first value - array->Set(0, security_buffer); - - // Create persistent handle - Nan::Persistent persistenHandler; - persistenHandler.Reset(array); - - // Create descriptor - security_obj = new SecurityBufferDescriptor(persistenHandler); - } else { - // Create a persistent handler - Nan::Persistent persistenHandler; - persistenHandler.Reset(Local::Cast(info[0])); - // Create a descriptor - security_obj = new SecurityBufferDescriptor(persistenHandler); - } - - // Wrap it - security_obj->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -NAN_METHOD(SecurityBufferDescriptor::ToBuffer) { - // Unpack the Security Buffer object - SecurityBufferDescriptor *security_obj = Nan::ObjectWrap::Unwrap(info.This()); - - // Get the buffer - char *buffer_data = security_obj->toBuffer(); - size_t buffer_size = security_obj->bufferSize(); - - // Create a Buffer - Local buffer = Nan::CopyBuffer(buffer_data, (uint32_t)buffer_size).ToLocalChecked(); - - // Return the buffer - info.GetReturnValue().Set(buffer); -} - -void SecurityBufferDescriptor::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("SecurityBufferDescriptor").ToLocalChecked()); - - // Class methods - Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer); - - // Set persistent - constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("SecurityBufferDescriptor").ToLocalChecked(), t->GetFunction()); -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h deleted file mode 100644 index dc28f7e..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SECURITY_BUFFER_DESCRIPTOR_H -#define SECURITY_BUFFER_DESCRIPTOR_H - -#include -#include -#include - -#include -#include -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBufferDescriptor : public Nan::ObjectWrap { - public: - Local arrayObject; - SecBufferDesc secBufferDesc; - - SecurityBufferDescriptor(); - SecurityBufferDescriptor(const Nan::Persistent& arrayObjectPersistent); - ~SecurityBufferDescriptor(); - - // Has instance check - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - char *toBuffer(); - size_t bufferSize(); - - // Functions available from V8 - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - static NAN_METHOD(ToBuffer); - - // Constructor used for creating new Long objects from C++ - static Nan::Persistent constructor_template; - - private: - static NAN_METHOD(New); -}; - -#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js deleted file mode 100644 index 9421392..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; -// Export the modified class -exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc deleted file mode 100644 index 5d7ad54..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc +++ /dev/null @@ -1,856 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_context.h" -#include "security_buffer_descriptor.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -static void After(uv_work_t* work_req) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); - Local obj = err->ToObject(); - obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); - Local info[2] = { err, Nan::Null() }; - // Execute the error - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } else { - // // Map the data - Local result = worker->mapper(worker); - // Set up the callback with a null first - Local info[2] = { Nan::Null(), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } - - // Clean up the memory - delete worker->callback; - delete worker; -} - -Nan::Persistent SecurityContext::constructor_template; - -SecurityContext::SecurityContext() : Nan::ObjectWrap() { -} - -SecurityContext::~SecurityContext() { - if(this->hasContext) { - _sspi_DeleteSecurityContext(&this->m_Context); - } -} - -NAN_METHOD(SecurityContext::New) { - PSecurityFunctionTable pSecurityInterface = NULL; - DWORD dwNumOfPkgs; - SECURITY_STATUS status; - - // Create code object - SecurityContext *security_obj = new SecurityContext(); - // Get security table interface - pSecurityInterface = _ssip_InitSecurityInterface(); - // Call the security interface - status = (*pSecurityInterface->EnumerateSecurityPackages)( - &dwNumOfPkgs, - &security_obj->m_PkgInfo); - if(status != SEC_E_OK) { - printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); - return Nan::ThrowError("Failed in retrieving security packages"); - } - - // Wrap it - security_obj->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -// -// Async InitializeContext -// -typedef struct SecurityContextStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStaticInitializeCall; - -static void _initializeContext(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - BYTE *out_bound_data_str = NULL; - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &call->context->security_credentials->m_Credentials - , NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length > 0 ? &ibd : NULL - , 0 - , &call->context->m_Context - , &obd - , &call->context->CtxtAttr - , &call->context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - call->context->hasContext = true; - call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - - // Set the context - worker->return_code = status; - worker->return_value = call->context; - } else if(status == SEC_E_INSUFFICIENT_MEMORY) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INSUFFICIENT_MEMORY There is not enough memory available to complete the requested action."; - } else if(status == SEC_E_INTERNAL_ERROR) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INTERNAL_ERROR An error occurred that did not map to an SSPI error code."; - } else if(status == SEC_E_INVALID_HANDLE) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INVALID_HANDLE The handle passed to the function is not valid."; - } else if(status == SEC_E_INVALID_TOKEN) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INVALID_TOKEN The error is due to a malformed input token, such as a token corrupted in transit, a token of incorrect size, or a token passed into the wrong security package. Passing a token to the wrong package can happen if the client and server did not negotiate the proper security package."; - } else if(status == SEC_E_LOGON_DENIED) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_LOGON_DENIED The logon failed."; - } else if(status == SEC_E_NO_AUTHENTICATING_AUTHORITY) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_NO_AUTHENTICATING_AUTHORITY No authority could be contacted for authentication. The domain name of the authenticating party could be wrong, the domain could be unreachable, or there might have been a trust relationship failure."; - } else if(status == SEC_E_NO_CREDENTIALS) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_NO_CREDENTIALS No credentials are available in the security package."; - } else if(status == SEC_E_TARGET_UNKNOWN) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_TARGET_UNKNOWN The target was not recognized."; - } else if(status == SEC_E_UNSUPPORTED_FUNCTION) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_UNSUPPORTED_FUNCTION A context attribute flag that is not valid (ISC_REQ_DELEGATE or ISC_REQ_PROMPT_FOR_CREDS) was specified in the fContextReq parameter."; - } else if(status == SEC_E_WRONG_PRINCIPAL) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_WRONG_PRINCIPAL The principal that received the authentication request is not the same as the one passed into the pszTargetName parameter. This indicates a failure in mutual authentication."; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Local _map_initializeContext(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return context->handle(); -} - -NAN_METHOD(SecurityContext::InitializeContext) { - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - - // We need 3 parameters - if(info.Length() != 4) - return Nan::ThrowError("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(info[0])) - return Nan::ThrowError("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!info[1]->IsString()) - return Nan::ThrowError("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!info[2]->IsString()) - return Nan::ThrowError("Second parameter for Initialize must be a string"); - - // Third parameter must be a callback - if(!info[3]->IsFunction()) - return Nan::ThrowError("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = info[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = info[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free original allocation - free(input_str); - } - - // Unpack the Security credentials - security_credentials = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); - // Create Security context instance - Local security_context_value = Nan::New(constructor_template)->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Build the call function - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(info[3]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _initializeContext; - worker->mapper = _map_initializeContext; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -NAN_GETTER(SecurityContext::PayloadGetter) { - // Unpack the context object - SecurityContext *context = Nan::ObjectWrap::Unwrap(info.This()); - // Return the low bits - info.GetReturnValue().Set(Nan::New(context->payload).ToLocalChecked()); -} - -NAN_GETTER(SecurityContext::HasContextGetter) { - // Unpack the context object - SecurityContext *context = Nan::ObjectWrap::Unwrap(info.This()); - // Return the low bits - info.GetReturnValue().Set(Nan::New(context->hasContext)); -} - -// -// Async InitializeContextStep -// -typedef struct SecurityContextStepStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStepStaticInitializeCall; - -static void _initializeContextStep(Worker *worker) { - // Outbound data array - BYTE *out_bound_data_str = NULL; - // Status of operation - SECURITY_STATUS status; - // Unpack data - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; - SecurityContext *context = call->context; - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &context->security_credentials->m_Credentials - , context->hasContext == true ? &context->m_Context : NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length ? &ibd : NULL - , 0 - , &context->m_Context - , &obd - , &context->CtxtAttr - , &context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(context->payload != NULL) free(context->payload); - context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Local _map_initializeContextStep(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return context->handle(); -} - -NAN_METHOD(SecurityContext::InitalizeStep) { - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - - // We need 3 parameters - if(info.Length() != 3) - return Nan::ThrowError("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); - - // Second parameter must be a string - if(!info[0]->IsString()) - return Nan::ThrowError("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!info[1]->IsString()) - return Nan::ThrowError("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!info[2]->IsFunction()) - return Nan::ThrowError("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = info[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = info[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free input string - free(input_str); - } - - // Unwrap the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); - - // Create call structure - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(info[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _initializeContextStep; - worker->mapper = _map_initializeContextStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// -// Async EncryptMessage -// -typedef struct SecurityContextEncryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; - unsigned long flags; -} SecurityContextEncryptMessageCall; - -static void _encryptMessage(Worker *worker) { - SECURITY_STATUS status; - // Unpack call - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; - // Unpack the security context - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_EncryptMessage( - &context->m_Context - , call->flags - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set result - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Local _map_encryptMessage(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return context->handle(); -} - -NAN_METHOD(SecurityContext::EncryptMessage) { - if(info.Length() != 3) - return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(info[0])) - return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!info[1]->IsUint32()) - return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!info[2]->IsFunction()) - return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - - // Unpack the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); - - // Create call structure - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - call->flags = (unsigned long)info[1]->ToInteger()->Value(); - - // Callback - Local callback = Local::Cast(info[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _encryptMessage; - worker->mapper = _map_encryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// -// Async DecryptMessage -// -typedef struct SecurityContextDecryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; -} SecurityContextDecryptMessageCall; - -static void _decryptMessage(Worker *worker) { - unsigned long quality = 0; - SECURITY_STATUS status; - - // Unpack parameters - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_DecryptMessage( - &context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set return values - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Local _map_decryptMessage(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return context->handle(); -} - -NAN_METHOD(SecurityContext::DecryptMessage) { - if(info.Length() != 2) - return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(info[0])) - return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!info[1]->IsFunction()) - return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - - // Unpack the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); - // Create call structure - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - - // Callback - Local callback = Local::Cast(info[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _decryptMessage; - worker->mapper = _map_decryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// -// Async QueryContextAttributes -// -typedef struct SecurityContextQueryContextAttributesCall { - SecurityContext *context; - uint32_t attribute; -} SecurityContextQueryContextAttributesCall; - -static void _queryContextAttributes(Worker *worker) { - SECURITY_STATUS status; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - - // Allocate some space - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &call->context->m_Context, - call->attribute, - sizes - ); - - if(status == SEC_E_OK) { - worker->return_code = status; - worker->return_value = sizes; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Local _map_queryContextAttributes(Worker *worker) { - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - // Unpack the attribute - uint32_t attribute = call->attribute; - - // Convert data - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; - // Create object - Local value = Nan::New(); - value->Set(Nan::New("maxToken").ToLocalChecked(), Nan::New(uint32_t(sizes->cbMaxToken))); - value->Set(Nan::New("maxSignature").ToLocalChecked(), Nan::New(uint32_t(sizes->cbMaxSignature))); - value->Set(Nan::New("blockSize").ToLocalChecked(), Nan::New(uint32_t(sizes->cbBlockSize))); - value->Set(Nan::New("securityTrailer").ToLocalChecked(), Nan::New(uint32_t(sizes->cbSecurityTrailer))); - return value; - } - - // Return the value - return Nan::Null(); -} - -NAN_METHOD(SecurityContext::QueryContextAttributes) { - if(info.Length() != 2) - return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!info[0]->IsInt32()) - return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!info[1]->IsFunction()) - return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - - // Unpack the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); - - // Unpack the int value - uint32_t attribute = info[0]->ToInt32()->Value(); - - // Check that we have a supported attribute - if(attribute != SECPKG_ATTR_SIZES) - return Nan::ThrowError("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Create call structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); - call->attribute = attribute; - call->context = security_context; - - // Callback - Local callback = Local::Cast(info[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _queryContextAttributes; - worker->mapper = _map_queryContextAttributes; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -void SecurityContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(static_cast(SecurityContext::New)); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("SecurityContext").ToLocalChecked()); - - // Class methods - Nan::SetMethod(t, "initialize", SecurityContext::InitializeContext); - - // Set up method for the instance - Nan::SetPrototypeMethod(t, "initialize", SecurityContext::InitalizeStep); - Nan::SetPrototypeMethod(t, "decryptMessage", SecurityContext::DecryptMessage); - Nan::SetPrototypeMethod(t, "queryContextAttributes", SecurityContext::QueryContextAttributes); - Nan::SetPrototypeMethod(t, "encryptMessage", SecurityContext::EncryptMessage); - - // Get prototype - Local proto = t->PrototypeTemplate(); - - // Getter for the response - Nan::SetAccessor(proto, Nan::New("payload").ToLocalChecked(), SecurityContext::PayloadGetter); - Nan::SetAccessor(proto, Nan::New("hasContext").ToLocalChecked(), SecurityContext::HasContextGetter); - - // Set persistent - SecurityContext::constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("SecurityContext").ToLocalChecked(), t->GetFunction()); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - } - - return pszName; -} - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h deleted file mode 100644 index 1d9387d..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef SECURITY_CONTEXT_H -#define SECURITY_CONTEXT_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include -#include "security_credentials.h" -#include "../worker.h" -#include - -extern "C" { - #include "../kerberos_sspi.h" - #include "../base64.h" -} - -using namespace v8; -using namespace node; - -class SecurityContext : public Nan::ObjectWrap { - public: - SecurityContext(); - ~SecurityContext(); - - // Security info package - PSecPkgInfo m_PkgInfo; - // Do we have a context - bool hasContext; - // Reference to security credentials - SecurityCredentials *security_credentials; - // Security context - CtxtHandle m_Context; - // Attributes - DWORD CtxtAttr; - // Expiry time for ticket - TimeStamp Expiration; - // Payload - char *payload; - - // Has instance check - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - static NAN_METHOD(InitializeContext); - static NAN_METHOD(InitalizeStep); - static NAN_METHOD(DecryptMessage); - static NAN_METHOD(QueryContextAttributes); - static NAN_METHOD(EncryptMessage); - - // Payload getter - static NAN_GETTER(PayloadGetter); - // hasContext getter - static NAN_GETTER(HasContextGetter); - - // Constructor used for creating new Long objects from C++ - static Nan::Persistent constructor_template; - - // private: - // Create a new instance - static NAN_METHOD(New); -}; - -#endif diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js deleted file mode 100644 index ef04e92..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; -// Export the modified class -exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc deleted file mode 100644 index 732af3f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc +++ /dev/null @@ -1,348 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_credentials.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -Nan::Persistent SecurityCredentials::constructor_template; - -SecurityCredentials::SecurityCredentials() : Nan::ObjectWrap() { -} - -SecurityCredentials::~SecurityCredentials() { -} - -NAN_METHOD(SecurityCredentials::New) { - // Create security credentials instance - SecurityCredentials *security_credentials = new SecurityCredentials(); - // Wrap it - security_credentials->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -// Call structs -typedef struct SecurityCredentialCall { - char *package_str; - char *username_str; - char *password_str; - char *domain_str; - SecurityCredentials *credentials; -} SecurityCredentialCall; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authSSPIAquire(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - - // Unpack data - SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; - - // // Unwrap the credentials - // SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; - SecurityCredentials *security_credentials = new SecurityCredentials(); - - // If we have domain string - if(call->domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); - - // If we have a password string - if(call->password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - call->package_str, - SECPKG_CRED_OUTBOUND, - NULL, - call->password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } else { - worker->return_code = status; - worker->return_value = security_credentials; - } - - // Free up parameter structure - if(call->package_str != NULL) free(call->package_str); - if(call->domain_str != NULL) free(call->domain_str); - if(call->password_str != NULL) free(call->password_str); - if(call->username_str != NULL) free(call->username_str); - free(call); -} - -static Local _map_authSSPIAquire(Worker *worker) { - return Nan::Null(); -} - -NAN_METHOD(SecurityCredentials::Aquire) { - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Unpack the variables - if(info.Length() != 2 && info.Length() != 3 && info.Length() != 4 && info.Length() != 5) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!info[0]->IsString()) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!info[1]->IsString()) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(info.Length() == 3 && (!info[2]->IsString() && !info[2]->IsFunction())) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(info.Length() == 4 && (!info[3]->IsString() && !info[3]->IsUndefined() && !info[3]->IsNull()) && !info[3]->IsFunction()) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(info.Length() == 5 && !info[4]->IsFunction()) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - Local callbackHandle; - - // Figure out which parameter is the callback - if(info.Length() == 5) { - callbackHandle = Local::Cast(info[4]); - } else if(info.Length() == 4) { - callbackHandle = Local::Cast(info[3]); - } else if(info.Length() == 3) { - callbackHandle = Local::Cast(info[2]); - } - - // Unpack the package - Local package = info[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = info[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(info.Length() == 3 || info.Length() == 4 || info.Length() == 5) { - Local password = info[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if((info.Length() == 4 || info.Length() == 5) && info[3]->IsString()) { - Local domain = info[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Allocate call structure - SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); - call->domain_str = domain_str; - call->package_str = package_str; - call->password_str = password_str; - call->username_str = username_str; - - // Unpack the callback - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authSSPIAquire; - worker->mapper = _map_authSSPIAquire; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -void SecurityCredentials::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("SecurityCredentials").ToLocalChecked()); - - // Class methods - Nan::SetMethod(t, "aquire", Aquire); - - // Set persistent - constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("SecurityCredentials").ToLocalChecked(), t->GetFunction()); - - // Attempt to load the security.dll library - load_library(); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - - } - - return pszName; -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void SecurityCredentials::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void SecurityCredentials::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); - Local obj = err->ToObject(); - obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); - Local info[2] = { err, Nan::Null() }; - // Execute the error - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } else { - SecurityCredentials *return_value = (SecurityCredentials *)worker->return_value; - // Create a new instance - Local result = Nan::New(constructor_template)->GetFunction()->NewInstance(); - // Unwrap the credentials - SecurityCredentials *security_credentials = Nan::ObjectWrap::Unwrap(result); - // Set the values - security_credentials->m_Identity = return_value->m_Identity; - security_credentials->m_Credentials = return_value->m_Credentials; - security_credentials->Expiration = return_value->Expiration; - // Set up the callback with a null first - Local info[2] = { Nan::Null(), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } - - // Clean up the memory - delete worker->callback; - delete worker; -} - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h deleted file mode 100644 index 71751a0..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef SECURITY_CREDENTIALS_H -#define SECURITY_CREDENTIALS_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include -#include -#include "../worker.h" -#include - -extern "C" { - #include "../kerberos_sspi.h" -} - -// SEC_WINNT_AUTH_IDENTITY makes it unusually hard -// to compile for both Unicode and ansi, so I use this macro: -#ifdef _UNICODE -#define USTR(str) (str) -#else -#define USTR(str) ((unsigned char*)(str)) -#endif - -using namespace v8; -using namespace node; - -class SecurityCredentials : public Nan::ObjectWrap { - public: - SecurityCredentials(); - ~SecurityCredentials(); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - - // Has instance check - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - static NAN_METHOD(Aquire); - - // Constructor used for creating new Long objects from C++ - static Nan::Persistent constructor_template; - - private: - // Create a new instance - static NAN_METHOD(New); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js deleted file mode 100644 index 4215c92..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js +++ /dev/null @@ -1,22 +0,0 @@ -var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; - -// Add simple kebros helper -SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { - if(typeof password == 'function') { - callback = password; - password = null; - } else if(typeof domain == 'function') { - callback = domain; - domain = null; - } - - // We are going to use the async version - if(typeof callback == 'function') { - return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); - } else { - return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); - } -} - -// Export the modified class -exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc deleted file mode 100644 index e7a472f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h deleted file mode 100644 index 1b0dced..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - Nan::Callback *callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Local (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc deleted file mode 100644 index 47971da..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc +++ /dev/null @@ -1,30 +0,0 @@ -## DNT config file -## see https://github.com/rvagg/dnt - -NODE_VERSIONS="\ - master \ - v0.11.13 \ - v0.10.30 \ - v0.10.29 \ - v0.10.28 \ - v0.10.26 \ - v0.10.25 \ - v0.10.24 \ - v0.10.23 \ - v0.10.22 \ - v0.10.21 \ - v0.10.20 \ - v0.10.19 \ - v0.8.28 \ - v0.8.27 \ - v0.8.26 \ - v0.8.24 \ -" -OUTPUT_PREFIX="nan-" -TEST_CMD=" \ - cd /dnt/ && \ - npm install && \ - node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ - node_modules/.bin/tap --gc test/js/*-test.js \ -" - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md deleted file mode 100644 index 457e7c4..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md +++ /dev/null @@ -1,374 +0,0 @@ -# NAN ChangeLog - -**Version 2.0.9: current Node 4.0.0, Node 12: 0.12.7, Node 10: 0.10.40, iojs: 3.2.0** - -### 2.0.9 Sep 8 2015 - - - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7 - -### 2.0.8 Aug 28 2015 - - - Work around duplicate linking bug in clang 11902da - -### 2.0.7 Aug 26 2015 - - - Build: Repackage - -### 2.0.6 Aug 26 2015 - - - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1 - - Bugfix: Remove unused static std::map instances 525bddc - - Bugfix: Make better use of maybe versions of APIs bfba85b - - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d - -### 2.0.5 Aug 10 2015 - - - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1 - - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d - -### 2.0.4 Aug 6 2015 - - - Build: Repackage - -### 2.0.3 Aug 6 2015 - - - Bugfix: Don't use clang++ / g++ syntax extension. 231450e - -### 2.0.2 Aug 6 2015 - - - Build: Repackage - -### 2.0.1 Aug 6 2015 - - - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687 - - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601 - - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f - - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed - -### 2.0.0 Jul 31 2015 - - - Change: Renamed identifiers with leading underscores b5932b4 - - Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1 - - Change: Replace NanScope and NanEscpableScope macros with classes 47751c4 - - Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99 - - Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5 - - Change: Rename NanNewBuffer to NanCopyBuffer d6af78d - - Change: Remove Nan prefix from all names 72d1f67 - - Change: Update Buffer API for new upstream changes d5d3291 - - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a - - Change: Get rid of Handles e6c0daf - - Feature: Support io.js 3 with V8 4.4 - - Feature: Introduce NanPersistent 7fed696 - - Feature: Introduce NanGlobal 4408da1 - - Feature: Added NanTryCatch 10f1ca4 - - Feature: Update for V8 v4.3 4b6404a - - Feature: Introduce NanNewOneByteString c543d32 - - Feature: Introduce namespace Nan 67ed1b1 - - Removal: Remove NanLocker and NanUnlocker dd6e401 - - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9 - - Removal: Remove NanReturn* macros d90a25c - - Removal: Remove HasInstance e8f84fe - - -### 1.9.0 Jul 31 2015 - - - Feature: Added `NanFatalException` 81d4a2c - - Feature: Added more error types 4265f06 - - Feature: Added dereference and function call operators to NanCallback c4b2ed0 - - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c - - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6 - - Feature: Added NanErrnoException dd87d9e - - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130 - - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c - - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b - -### 1.8.4 Apr 26 2015 - - - Build: Repackage - -### 1.8.3 Apr 26 2015 - - - Bugfix: Include missing header 1af8648 - -### 1.8.2 Apr 23 2015 - - - Build: Repackage - -### 1.8.1 Apr 23 2015 - - - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 - -### 1.8.0 Apr 23 2015 - - - Feature: Allow primitives with NanReturnValue 2e4475e - - Feature: Added comparison operators to NanCallback 55b075e - - Feature: Backport thread local storage 15bb7fa - - Removal: Remove support for signatures with arguments 8a2069d - - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 - -### 1.7.0 Feb 28 2015 - - - Feature: Made NanCallback::Call accept optional target 8d54da7 - - Feature: Support atom-shell 0.21 0b7f1bb - -### 1.6.2 Feb 6 2015 - - - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 - -### 1.6.1 Jan 23 2015 - - - Build: version bump - -### 1.5.3 Jan 23 2015 - - - Build: repackage - -### 1.6.0 Jan 23 2015 - - - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af - - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 - - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 - -### 1.5.2 Jan 23 2015 - - - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 - - Bugfix: Readded missing String constructors 18d828f - - Bugfix: Add overload handling NanNew(..) 5ef813b - - Bugfix: Fix uv_work_cb versioning 997e4ae - - Bugfix: Add function factory and test 4eca89c - - Bugfix: Add object template factory and test cdcb951 - - Correctness: Lifted an io.js related typedef c9490be - - Correctness: Make explicit downcasts of String lengths 00074e6 - - Windows: Limit the scope of disabled warning C4530 83d7deb - -### 1.5.1 Jan 15 2015 - - - Build: version bump - -### 1.4.3 Jan 15 2015 - - - Build: version bump - -### 1.4.2 Jan 15 2015 - - - Feature: Support io.js 0dbc5e8 - -### 1.5.0 Jan 14 2015 - - - Feature: Support io.js b003843 - - Correctness: Improved NanNew internals 9cd4f6a - - Feature: Implement progress to NanAsyncWorker 8d6a160 - -### 1.4.1 Nov 8 2014 - - - Bugfix: Handle DEBUG definition correctly - - Bugfix: Accept int as Boolean - -### 1.4.0 Nov 1 2014 - - - Feature: Added NAN_GC_CALLBACK 6a5c245 - - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 - - Correctness: Added constness to references in NanHasInstance 02c61cd - - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 - - Windoze: Shut Visual Studio up when compiling 8d558c1 - - License: Switch to plain MIT from custom hacked MIT license 11de983 - - Build: Added test target to Makefile e232e46 - - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 - - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 - - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 - -### 1.3.0 Aug 2 2014 - - - Added NanNew(std::string) - - Added NanNew(std::string&) - - Added NanAsciiString helper class - - Added NanUtf8String helper class - - Added NanUcs2String helper class - - Deprecated NanRawString() - - Deprecated NanCString() - - Added NanGetIsolateData(v8::Isolate *isolate) - - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) - - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) - - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - -### 1.2.0 Jun 5 2014 - - - Add NanSetPrototypeTemplate - - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, - introduced _NanWeakCallbackDispatcher - - Removed -Wno-unused-local-typedefs from test builds - - Made test builds Windows compatible ('Sleep()') - -### 1.1.2 May 28 2014 - - - Release to fix more stuff-ups in 1.1.1 - -### 1.1.1 May 28 2014 - - - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 - -### 1.1.0 May 25 2014 - - - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead - - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), - (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, - v8::String::ExternalAsciiStringResource* - - Deprecate NanSymbol() - - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker - -### 1.0.0 May 4 2014 - - - Heavy API changes for V8 3.25 / Node 0.11.13 - - Use cpplint.py - - Removed NanInitPersistent - - Removed NanPersistentToLocal - - Removed NanFromV8String - - Removed NanMakeWeak - - Removed NanNewLocal - - Removed NAN_WEAK_CALLBACK_OBJECT - - Removed NAN_WEAK_CALLBACK_DATA - - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions - - Introduce NanUndefined, NanNull, NanTrue and NanFalse - - Introduce NanEscapableScope and NanEscapeScope - - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) - - Introduce NanMakeCallback for node::MakeCallback - - Introduce NanSetTemplate - - Introduce NanGetCurrentContext - - Introduce NanCompileScript and NanRunScript - - Introduce NanAdjustExternalMemory - - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback - - Introduce NanGetHeapStatistics - - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() - -### 0.8.0 Jan 9 2014 - - - NanDispose -> NanDisposePersistent, deprecate NanDispose - - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() - -### 0.7.1 Jan 9 2014 - - - Fixes to work against debug builds of Node - - Safer NanPersistentToLocal (avoid reinterpret_cast) - - Speed up common NanRawString case by only extracting flattened string when necessary - -### 0.7.0 Dec 17 2013 - - - New no-arg form of NanCallback() constructor. - - NanCallback#Call takes Handle rather than Local - - Removed deprecated NanCallback#Run method, use NanCallback#Call instead - - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS - - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() - - Introduce NanRawString() for char* (or appropriate void*) from v8::String - (replacement for NanFromV8String) - - Introduce NanCString() for null-terminated char* from v8::String - -### 0.6.0 Nov 21 2013 - - - Introduce NanNewLocal(v8::Handle value) for use in place of - v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 - -### 0.5.2 Nov 16 2013 - - - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public - -### 0.5.1 Nov 12 2013 - - - Use node::MakeCallback() instead of direct v8::Function::Call() - -### 0.5.0 Nov 11 2013 - - - Added @TooTallNate as collaborator - - New, much simpler, "include_dirs" for binding.gyp - - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros - -### 0.4.4 Nov 2 2013 - - - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ - -### 0.4.3 Nov 2 2013 - - - Include node_object_wrap.h, removed from node.h for Node 0.11.8. - -### 0.4.2 Nov 2 2013 - - - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for - Node 0.11.8 release. - -### 0.4.1 Sep 16 2013 - - - Added explicit `#include ` as it was removed from node.h for v0.11.8 - -### 0.4.0 Sep 2 2013 - - - Added NAN_INLINE and NAN_DEPRECATED and made use of them - - Added NanError, NanTypeError and NanRangeError - - Cleaned up code - -### 0.3.2 Aug 30 2013 - - - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent - in NanAsyncWorker - -### 0.3.1 Aug 20 2013 - - - fix "not all control paths return a value" compile warning on some platforms - -### 0.3.0 Aug 19 2013 - - - Made NAN work with NPM - - Lots of fixes to NanFromV8String, pulling in features from new Node core - - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API - - Added optional error number argument for NanThrowError() - - Added NanInitPersistent() - - Added NanReturnNull() and NanReturnEmptyString() - - Added NanLocker and NanUnlocker - - Added missing scopes - - Made sure to clear disposed Persistent handles - - Changed NanAsyncWorker to allocate error messages on the heap - - Changed NanThrowError(Local) to NanThrowError(Handle) - - Fixed leak in NanAsyncWorker when errmsg is used - -### 0.2.2 Aug 5 2013 - - - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() - -### 0.2.1 Aug 5 2013 - - - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for - NanFromV8String() - -### 0.2.0 Aug 5 2013 - - - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, - NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY - - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, - _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, - _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, - _NAN_PROPERTY_QUERY_ARGS - - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer - - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, - NAN_WEAK_CALLBACK_DATA, NanMakeWeak - - Renamed THROW_ERROR to _NAN_THROW_ERROR - - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) - - Added NanBufferUse(char*, uint32_t) - - Added NanNewContextHandle(v8::ExtensionConfiguration*, - v8::Handle, v8::Handle) - - Fixed broken NanCallback#GetFunction() - - Added optional encoding and size arguments to NanFromV8String() - - Added NanGetPointerSafe() and NanSetPointerSafe() - - Added initial test suite (to be expanded) - - Allow NanUInt32OptionValue to convert any Number object - -### 0.1.0 Jul 21 2013 - - - Added `NAN_GETTER`, `NAN_SETTER` - - Added `NanThrowError` with single Local argument - - Added `NanNewBufferHandle` with single uint32_t argument - - Added `NanHasInstance(Persistent&, Handle)` - - Added `Local NanCallback#GetFunction()` - - Added `NanCallback#Call(int, Local[])` - - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md deleted file mode 100644 index 77666cd..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2015 NAN contributors ------------------------------------ - -*NAN contributors listed at * - -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/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md deleted file mode 100644 index db3daec..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md +++ /dev/null @@ -1,367 +0,0 @@ -Native Abstractions for Node.js -=============================== - -**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.12 as well as io.js.** - -***Current version: 2.0.9*** - -*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* - -[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) - -[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](http://travis-ci.org/nodejs/nan) -[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) - -Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. - -This project also contains some helper utilities that make addon development a bit more pleasant. - - * **[News & Updates](#news)** - * **[Usage](#usage)** - * **[Example](#example)** - * **[API](#api)** - * **[Tests](#tests)** - * **[Governance & Contributing](#governance)** - - -## News & Updates - - -## Usage - -Simply add **NAN** as a dependency in the *package.json* of your Node addon: - -``` bash -$ npm install --save nan -``` - -Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: - -``` python -"include_dirs" : [ - "` when compiling your addon. - - -## Example - -Just getting started with Nan? Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. - -For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. - -For another example, see **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. - - -## API - -Additional to the NAN documentation below, please consult: - -* [The V8 Getting Started Guide](https://developers.google.com/v8/get_started) -* [The V8 Embedders Guide](https://developers.google.com/v8/embed) -* [V8 API Documentation](http://v8docs.nodesource.com/) - - - -### JavaScript-accessible methods - -A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://developers.google.com/v8/embed#templates) for further information. - -In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. - -* **Method argument types** - - Nan::FunctionCallbackInfo - - Nan::PropertyCallbackInfo - - Nan::ReturnValue -* **Method declarations** - - Method declaration - - Getter declaration - - Setter declaration - - Property getter declaration - - Property setter declaration - - Property enumerator declaration - - Property deleter declaration - - Property query declaration - - Index getter declaration - - Index setter declaration - - Index enumerator declaration - - Index deleter declaration - - Index query declaration -* Method and template helpers - - Nan::SetMethod() - - Nan::SetNamedPropertyHandler() - - Nan::SetIndexedPropertyHandler() - - Nan::SetPrototypeMethod() - - Nan::SetTemplate() - - Nan::SetPrototypeTemplate() - - Nan::SetInstanceTemplate() - -### Scopes - -A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. - -A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. - -The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. - - - Nan::HandleScope - - Nan::EscapableHandleScope - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). - -### Persistent references - -An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. - -Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. - - - Nan::PersistentBase & v8::PersistentBase - - Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits - - Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits - - Nan::Persistent - - Nan::Global - - Nan::WeakCallbackInfo - - Nan::WeakCallbackType - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). - -### New - -NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. - - - Nan::New() - - Nan::Undefined() - - Nan::Null() - - Nan::True() - - Nan::False() - - Nan::EmptyString() - - -### Converters - -NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. - - - Nan::To() - -### Maybe Types - -The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. - -* **Maybe Types** - - Nan::MaybeLocal - - Nan::Maybe - - Nan::Nothing - - Nan::Just -* **Maybe Helpers** - - Nan::ToDetailString() - - Nan::ToArrayIndex() - - Nan::Equals() - - Nan::NewInstance() - - Nan::GetFunction() - - Nan::Set() - - Nan::ForceSet() - - Nan::Get() - - Nan::GetPropertyAttributes() - - Nan::Has() - - Nan::Delete() - - Nan::GetPropertyNames() - - Nan::GetOwnPropertyNames() - - Nan::SetPrototype() - - Nan::ObjectProtoToString() - - Nan::HasOwnProperty() - - Nan::HasRealNamedProperty() - - Nan::HasRealIndexedProperty() - - Nan::HasRealNamedCallbackProperty() - - Nan::GetRealNamedPropertyInPrototypeChain() - - Nan::GetRealNamedProperty() - - Nan::CallAsFunction() - - Nan::CallAsConstructor() - - Nan::GetSourceLine() - - Nan::GetLineNumber() - - Nan::GetStartColumn() - - Nan::GetEndColumn() - - Nan::CloneElementAt() - -### Script - -NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. - - - Nan::CompileScript() - - Nan::RunScript() - - -### Errors - -NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. - -Note that an Error object is simply a specialized form of `v8::Value`. - -Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. - - - Nan::Error() - - Nan::RangeError() - - Nan::ReferenceError() - - Nan::SyntaxError() - - Nan::TypeError() - - Nan::ThrowError() - - Nan::ThrowRangeError() - - Nan::ThrowReferenceError() - - Nan::ThrowSyntaxError() - - Nan::ThrowTypeError() - - Nan::FatalException() - - Nan::ErrnoException() - - Nan::TryCatch - - -### Buffers - -NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. - - - Nan::NewBuffer() - - Nan::CopyBuffer() - - Nan::FreeCallback() - -### Nan::Callback - -`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. - - - Nan::Callback - -### Asynchronous work helpers - -`Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier. - - - Nan::AsyncWorker - - Nan::AsyncProgressWorker - - Nan::AsyncQueueWorker - -### Strings & Bytes - -Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. - - - Nan::Encoding - - Nan::Encode() - - Nan::DecodeBytes() - - Nan::DecodeWrite() - - -### V8 internals - -The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. - - - NAN_GC_CALLBACK() - - Nan::AddGCEpilogueCallback() - - Nan::RemoveGCEpilogueCallback() - - Nan::AddGCPrologueCallback() - - Nan::RemoveGCPrologueCallback() - - Nan::GetHeapStatistics() - - Nan::SetCounterFunction() - - Nan::SetCreateHistogramFunction() - - Nan::SetAddHistogramSampleFunction() - - Nan::IdleNotification() - - Nan::LowMemoryNotification() - - Nan::ContextDisposedNotification() - - Nan::GetInternalFieldPointer() - - Nan::SetInternalFieldPointer() - - Nan::AdjustExternalMemory() - - -### Miscellaneous V8 Helpers - - - Nan::Utf8String - - Nan::GetCurrentContext() - - Nan::SetIsolateData() - - Nan::GetIsolateData() - - -### Miscellaneous Node Helpers - - - Nan::MakeCallback() - - Nan::ObjectWrap - - NAN_MODULE_INIT() - - Nan::Export() - - - - - -### Tests - -To run the NAN tests do: - -``` sh -npm install -npm run-script rebuild-tests -npm test -``` - -Or just: - -``` sh -npm install -make test -``` - - -## Governance & Contributing - -NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group - -### Addon API Working Group (WG) - -The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. - -Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects. - -The WG has final authority over this project including: - -* Technical direction -* Project governance and process (including this policy) -* Contribution policy -* GitHub repository hosting -* Maintaining the list of additional Collaborators - -For the current list of WG members, see the project [README.md](./README.md#collaborators). - -Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. - -_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. - -For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). - -### Consensus Seeking Process - -The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. - -Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. - -If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. - -### Developer's Certificate of Origin 1.0 - -By making a contribution to this project, I certify that: - -* (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or -* (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or -* (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. - - -### WG Members / Collaborators - - - - - - - - - -
        Rod VaggGitHub/rvaggTwitter/@rvagg
        Benjamin ByholmGitHub/kkoopa-
        Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
        Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
        Brett LawsonGitHub/brett19Twitter/@brett19x
        Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
        David SiegelGitHub/agnat-
        - -## Licence & copyright - -Copyright (c) 2015 NAN WG Members / Collaborators (listed above). - -Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml deleted file mode 100644 index 1378d31..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml +++ /dev/null @@ -1,38 +0,0 @@ -# http://www.appveyor.com/docs/appveyor-yml - -# Test against these versions of Io.js and Node.js. -environment: - matrix: - # node.js - - nodejs_version: "0.8" - - nodejs_version: "0.10" - - nodejs_version: "0.12" - # io.js - - nodejs_version: "1" - - nodejs_version: "2" - - nodejs_version: "3" - -# Install scripts. (runs after repo cloning) -install: - # Get the latest stable version of Node 0.STABLE.latest - - ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version} - - ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)} - - IF %nodejs_version% LSS 1 npm -g install npm - - IF %nodejs_version% LSS 1 set PATH=%APPDATA%\npm;%PATH% - # Typical npm stuff. - - npm install - - IF %nodejs_version% EQU 0.8 (node node_modules\node-gyp\bin\node-gyp.js rebuild --msvs_version=2013 --directory test) ELSE (npm run rebuild-tests) - -# Post-install test scripts. -test_script: - # Output useful info for debugging. - - node --version - - npm --version - # run tests - - IF %nodejs_version% LSS 1 (npm test) ELSE (iojs node_modules\tap\bin\tap.js --gc test/js/*-test.js) - -# Don't actually build. -build: off - -# Set build version format here instead of in the admin panel. -version: "{build}" diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh deleted file mode 100755 index 75a975a..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash - -files=" \ - methods.md \ - scopes.md \ - persistent.md \ - new.md \ - converters.md \ - maybe_types.md \ - script.md \ - errors.md \ - buffers.md \ - callback.md \ - asyncworker.md \ - string_bytes.md \ - v8_internals.md \ - v8_misc.md \ - node_misc.md \ -" - -__dirname=$(dirname "${BASH_SOURCE[0]}") -head=$(perl -e 'while (<>) { if (!$en){print;} if ($_=~/ NanNew("foo").ToLocalChecked() */ - if (arguments[groups[3][0]] === 'NanNew') { - return [arguments[0], '.ToLocalChecked()'].join(''); - } - - /* insert warning for removed functions as comment on new line above */ - switch (arguments[groups[4][0]]) { - case 'GetIndexedPropertiesExternalArrayData': - case 'GetIndexedPropertiesExternalArrayDataLength': - case 'GetIndexedPropertiesExternalArrayDataType': - case 'GetIndexedPropertiesPixelData': - case 'GetIndexedPropertiesPixelDataLength': - case 'HasIndexedPropertiesInExternalArrayData': - case 'HasIndexedPropertiesInPixelData': - case 'SetIndexedPropertiesToExternalArrayData': - case 'SetIndexedPropertiesToPixelData': - return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join(''); - default: - } - - /* remove unnecessary NanScope() */ - switch (arguments[groups[5][0]]) { - case 'NAN_GETTER': - case 'NAN_METHOD': - case 'NAN_SETTER': - case 'NAN_INDEX_DELETER': - case 'NAN_INDEX_ENUMERATOR': - case 'NAN_INDEX_GETTER': - case 'NAN_INDEX_QUERY': - case 'NAN_INDEX_SETTER': - case 'NAN_PROPERTY_DELETER': - case 'NAN_PROPERTY_ENUMERATOR': - case 'NAN_PROPERTY_GETTER': - case 'NAN_PROPERTY_QUERY': - case 'NAN_PROPERTY_SETTER': - return arguments[groups[5][0] - 1]; - default: - } - - /* Value converstion */ - switch (arguments[groups[6][0]]) { - case 'Boolean': - case 'Int32': - case 'Integer': - case 'Number': - case 'Object': - case 'String': - case 'Uint32': - return [arguments[groups[6][0] - 2], 'NanTo(', arguments[groups[6][0] - 1]].join(''); - default: - } - - /* other value conversion */ - switch (arguments[groups[7][0]]) { - case 'BooleanValue': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'Int32Value': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'IntegerValue': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'Uint32Value': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - default: - } - - /* NAN_WEAK_CALLBACK */ - if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') { - return ['template\nvoid ', - arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo &data)'].join(''); - } - - /* use methods on NAN classes instead */ - switch (arguments[groups[9][0]]) { - case 'NanDisposePersistent': - return [arguments[groups[9][0] + 1], '.Reset('].join(''); - case 'NanObjectWrapHandle': - return [arguments[groups[9][0] + 1], '->handle('].join(''); - default: - } - - /* use method on NanPersistent instead */ - if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') { - return arguments[groups[10][0] + 1] + '.SetWeak('; - } - - /* These return Maybes, the upper ones take no arguments */ - switch (arguments[groups[11][0]]) { - case 'GetEndColumn': - case 'GetFunction': - case 'GetLineNumber': - case 'GetOwnPropertyNames': - case 'GetPropertyNames': - case 'GetSourceLine': - case 'GetStartColumn': - case 'NewInstance': - case 'ObjectProtoToString': - case 'ToArrayIndex': - case 'ToDetailString': - return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join(''); - case 'CallAsConstructor': - case 'CallAsFunction': - case 'CloneElementAt': - case 'Delete': - case 'ForceSet': - case 'Get': - case 'GetPropertyAttributes': - case 'GetRealNamedProperty': - case 'GetRealNamedPropertyInPrototypeChain': - case 'Has': - case 'HasOwnProperty': - case 'HasRealIndexedProperty': - case 'HasRealNamedCallbackProperty': - case 'HasRealNamedProperty': - case 'Set': - case 'SetAccessor': - case 'SetIndexedPropertyHandler': - case 'SetNamedPropertyHandler': - case 'SetPrototype': - return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join(''); - default: - } - - /* Automatic ToLocalChecked(), take it or leave it */ - switch (arguments[groups[12][0]]) { - case 'Date': - case 'String': - case 'RegExp': - return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join(''); - default: - } - - /* NanEquals is now required for uniformity */ - if (arguments[groups[13][0]] === 'Equals') { - return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join(''); - } - - /* use method on replacement class instead */ - if (arguments[groups[14][0]] === 'NanAssignPersistent') { - return [arguments[groups[14][0] + 1], '.Reset('].join(''); - } - - /* args --> info */ - if (arguments[groups[15][0]] === 'args') { - return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join(''); - } - - /* ObjectWrap --> NanObjectWrap */ - if (arguments[groups[16][0]] === 'ObjectWrap') { - return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join(''); - } - - /* Persistent --> NanPersistent */ - if (arguments[groups[17][0]] === 'Persistent') { - return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join(''); - } - - /* This should not happen. A switch is probably missing a case if it does. */ - throw 'Unhandled match: ' + arguments[0]; -} - -/* reads a file, runs replacement and writes it back */ -function processFile(file) { - fs.readFile(file, {encoding: 'utf8'}, function (err, data) { - if (err) { - throw err; - } - - /* run replacement twice, might need more runs */ - fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) { - if (err) { - throw err; - } - }); - }); -} - -/* process file names from command line and process the identified files */ -for (i = 2, length = process.argv.length; i < length; i++) { - glob(process.argv[i], function (err, matches) { - if (err) { - throw err; - } - matches.forEach(processFile); - }); -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md deleted file mode 100644 index 7f07e4b..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md +++ /dev/null @@ -1,14 +0,0 @@ -1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, -false positives and missed opportunities. The input files are rewritten in place. Make sure that -you have backups. You will have to manually review the changes afterwards and do some touchups. - -```sh -$ tools/1to2.js - - Usage: 1to2 [options] - - Options: - - -h, --help output usage information - -V, --version output the version number -``` diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json deleted file mode 100644 index 2dcdd78..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "1to2", - "version": "1.0.0", - "description": "NAN 1 -> 2 Migration Script", - "main": "1to2.js", - "repository": { - "type": "git", - "url": "git://github.com/nodejs/nan.git" - }, - "contributors": [ - "Benjamin Byholm (https://github.com/kkoopa/)", - "Mathias Küsel (https://github.com/mathiask88/)" - ], - "dependencies": { - "glob": "~5.0.10", - "commander": "~2.8.1" - }, - "license": "MIT" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json deleted file mode 100644 index 9955d1f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "kerberos", - "version": "0.0.15", - "description": "Kerberos library for Node.js", - "main": "index.js", - "repository": { - "type": "git", - "url": "https://github.com/christkv/kerberos.git" - }, - "keywords": [ - "kerberos", - "security", - "authentication" - ], - "dependencies": { - "nan": "~2.0" - }, - "devDependencies": { - "nodeunit": "latest" - }, - "scripts": { - "install": "(node-gyp rebuild) || (exit 0)", - "test": "nodeunit ./test" - }, - "author": { - "name": "Christian Amor Kvalheim" - }, - "license": "Apache 2.0", - "gitHead": "035be2e4619d7f3d7ea5103da1f60a6045ef8d7c", - "bugs": { - "url": "https://github.com/christkv/kerberos/issues" - }, - "homepage": "https://github.com/christkv/kerberos", - "_id": "kerberos@0.0.15", - "_shasum": "c7dd5a2d311ce79c308c2670a9187d9bf745ed52", - "_from": "kerberos@>=0.0.0 <0.1.0", - "_npmVersion": "2.14.4", - "_nodeVersion": "4.1.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "c7dd5a2d311ce79c308c2670a9187d9bf745ed52", - "tarball": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.15.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-0.0.15.tgz" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js deleted file mode 100644 index a06c5fd..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js +++ /dev/null @@ -1,34 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos object'] = function(test) { - var Kerberos = require('../lib/kerberos.js').Kerberos; - var kerberos = new Kerberos(); - // console.dir(kerberos) - - // Initiate kerberos client - kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - console.log("===================================== authGSSClientInit") - test.equal(null, err); - test.ok(context != null && typeof context == 'object'); - // console.log("===================================== authGSSClientInit") - console.dir(err) - console.dir(context) - // console.dir(typeof result) - - // Perform the first step - kerberos.authGSSClientStep(context, function(err, result) { - console.log("===================================== authGSSClientStep") - console.dir(err) - console.dir(result) - console.dir(context) - - test.done(); - }); - }); -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js deleted file mode 100644 index c8509db..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js +++ /dev/null @@ -1,15 +0,0 @@ -if (/^win/.test(process.platform)) { - -exports['Simple initialize of Kerberos win32 object'] = function(test) { - var KerberosNative = require('../build/Release/kerberos').Kerberos; - // console.dir(KerberosNative) - var kerberos = new KerberosNative(); - console.log("=========================================== 0") - console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); - console.log("=========================================== 1") - console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); - console.log("=========================================== 2") - test.done(); -} - -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js deleted file mode 100644 index 3531b6b..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js +++ /dev/null @@ -1,41 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer Descriptor'] = function(test) { - var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // Create descriptor with single Buffer - var securityDescriptor = new SecurityBufferDescriptor(100); - try { - // Fail to work due to no valid Security Buffer - securityDescriptor = new SecurityBufferDescriptor(["hello"]); - test.ok(false); - } catch(err){} - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - // Should correctly return a buffer - var result = securityDescriptor.toBuffer(); - test.equal(100, result.length); - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - var result = securityDescriptor.toBuffer(); - test.equal("hello world", result.toString()); - - // Test passing in more than one Buffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - var result = securityDescriptor.toBuffer(); - test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js deleted file mode 100644 index b52b959..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js +++ /dev/null @@ -1,22 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer'] = function(test) { - var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - // Create empty buffer - var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - var buffer = securityBuffer.toBuffer(); - test.equal(100, buffer.length); - - // Access data passed in - var allocated_buffer = new Buffer(256); - securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); - buffer = securityBuffer.toBuffer(); - test.deepEqual(allocated_buffer, buffer); - test.done(); -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js deleted file mode 100644 index 7758180..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js +++ /dev/null @@ -1,55 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a set of security credentials'] = function(test) { - var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; - - // Aquire some credentials - try { - var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); - } catch(err) { - console.dir(err) - test.ok(false); - } - - - - // console.dir(SecurityCredentials); - - // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // // Create descriptor with single Buffer - // var securityDescriptor = new SecurityBufferDescriptor(100); - // try { - // // Fail to work due to no valid Security Buffer - // securityDescriptor = new SecurityBufferDescriptor(["hello"]); - // test.ok(false); - // } catch(err){} - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // // Should correctly return a buffer - // var result = securityDescriptor.toBuffer(); - // test.equal(100, result.length); - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello world", result.toString()); - - // // Test passing in more than one Buffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/package.json deleted file mode 100644 index f690f67..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "name": "mongodb-core", - "version": "1.2.14", - "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", - "main": "index.js", - "scripts": { - "test": "node test/runner.js -t functional" - }, - "repository": { - "type": "git", - "url": "git://github.com/christkv/mongodb-core.git" - }, - "keywords": [ - "mongodb", - "core" - ], - "dependencies": { - "bson": "~0.4", - "kerberos": "~0.0" - }, - "devDependencies": { - "integra": "0.1.8", - "optimist": "latest", - "jsdoc": "3.3.0-alpha8", - "semver": "4.1.0", - "gleak": "0.5.0", - "mongodb-tools": "~1.0", - "mkdirp": "0.5.0", - "rimraf": "2.2.6", - "mongodb-version-manager": "^0.7.1", - "co": "4.5.4" - }, - "optionalDependencies": { - "kerberos": "~0.0" - }, - "author": { - "name": "Christian Kvalheim" - }, - "license": "Apache 2.0", - "bugs": { - "url": "https://github.com/christkv/mongodb-core/issues" - }, - "homepage": "https://github.com/christkv/mongodb-core", - "gitHead": "ea4e6c9fe93e4ace4cbffb816d47ee282c1cd844", - "_id": "mongodb-core@1.2.14", - "_shasum": "0f1393778b71f1e2b86228fd160ec9ad5a8cd9a3", - "_from": "mongodb-core@1.2.14", - "_npmVersion": "2.14.4", - "_nodeVersion": "4.1.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "0f1393778b71f1e2b86228fd160ec9ad5a8cd9a3", - "tarball": "http://registry.npmjs.org/mongodb-core/-/mongodb-core-1.2.14.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-1.2.14.tgz" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat b/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat deleted file mode 100644 index 25ccf0b..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat +++ /dev/null @@ -1,11000 +0,0 @@ -1 2 -2 1 -3 0 -4 0 -5 1 -6 0 -7 0 -8 0 -9 0 -10 1 -11 0 -12 0 -13 0 -14 1 -15 0 -16 0 -17 0 -18 1 -19 0 -20 0 -21 0 -22 1 -23 0 -24 0 -25 0 -26 0 -27 1 -28 0 -29 0 -30 0 -31 1 -32 0 -33 0 -34 0 -35 0 -36 0 -37 1 -38 0 -39 0 -40 0 -41 0 -42 0 -43 1 -44 0 -45 0 -46 0 -47 0 -48 0 -49 0 -50 0 -51 0 -52 0 -53 0 -54 0 -55 0 -56 0 -57 0 -58 0 -59 1 -60 0 -61 2 -62 0 -63 0 -64 1 -65 0 -66 0 -67 0 -68 1 -69 0 -70 0 -71 0 -72 0 -73 1 -74 0 -75 0 -76 0 -77 0 -78 0 -79 1 -80 0 -81 0 -82 0 -83 0 -84 0 -85 0 -86 1 -87 0 -88 0 -89 0 -90 0 -91 0 -92 0 -93 1 -94 0 -95 0 -96 0 -97 0 -98 0 -99 0 -100 0 -101 1 -102 0 -103 0 -104 0 -105 0 -106 0 -107 0 -108 1 -109 0 -110 0 -111 0 -112 0 -113 0 -114 0 -115 1 -116 0 -117 0 -118 0 -119 1 -120 0 -121 0 -122 0 -123 0 -124 0 -125 0 -126 1 -127 0 -128 1 -129 0 -130 0 -131 0 -132 1 -133 1 -134 0 -135 0 -136 0 -137 1 -138 0 -139 0 -140 0 -141 0 -142 0 -143 0 -144 1 -145 0 -146 0 -147 0 -148 0 -149 0 -150 0 -151 0 -152 0 -153 1 -154 0 -155 0 -156 0 -157 0 -158 0 -159 0 -160 0 -161 0 -162 0 -163 0 -164 0 -165 0 -166 0 -167 0 -168 0 -169 0 -170 1 -171 0 -172 0 -173 0 -174 0 -175 0 -176 0 -177 0 -178 1 -179 0 -180 0 -181 0 -182 0 -183 0 -184 0 -185 0 -186 1 -187 0 -188 0 -189 0 -190 0 -191 0 -192 1 -193 0 -194 0 -195 0 -196 1 -197 0 -198 0 -199 0 -200 1 -201 0 -202 0 -203 0 -204 0 -205 0 -206 0 -207 1 -208 0 -209 0 -210 0 -211 0 -212 0 -213 0 -214 0 -215 1 -216 0 -217 0 -218 0 -219 0 -220 0 -221 0 -222 0 -223 1 -224 0 -225 0 -226 0 -227 0 -228 0 -229 0 -230 1 -231 0 -232 0 -233 0 -234 0 -235 0 -236 0 -237 1 -238 0 -239 0 -240 0 -241 0 -242 0 -243 0 -244 0 -245 1 -246 0 -247 0 -248 0 -249 0 -250 0 -251 0 -252 0 -253 0 -254 1 -255 0 -256 0 -257 0 -258 0 -259 1 -260 0 -261 0 -262 0 -263 0 -264 0 -265 1 -266 0 -267 0 -268 0 -269 0 -270 0 -271 0 -272 1 -273 0 -274 0 -275 0 -276 0 -277 0 -278 0 -279 0 -280 0 -281 1 -282 0 -283 1 -284 0 -285 0 -286 1 -287 0 -288 0 -289 0 -290 0 -291 1 -292 0 -293 0 -294 0 -295 0 -296 1 -297 0 -298 0 -299 0 -300 0 -301 0 -302 0 -303 1 -304 0 -305 0 -306 0 -307 0 -308 0 -309 1 -310 0 -311 0 -312 0 -313 0 -314 0 -315 0 -316 1 -317 0 -318 0 -319 0 -320 0 -321 0 -322 0 -323 0 -324 0 -325 1 -326 0 -327 0 -328 0 -329 0 -330 0 -331 0 -332 0 -333 0 -334 1 -335 0 -336 0 -337 0 -338 0 -339 0 -340 0 -341 0 -342 0 -343 1 -344 0 -345 0 -346 0 -347 0 -348 0 -349 0 -350 0 -351 0 -352 1 -353 0 -354 0 -355 0 -356 0 -357 0 -358 0 -359 0 -360 0 -361 1 -362 0 -363 0 -364 0 -365 0 -366 0 -367 0 -368 0 -369 1 -370 0 -371 0 -372 0 -373 0 -374 0 -375 0 -376 0 -377 1 -378 0 -379 0 -380 0 -381 0 -382 0 -383 0 -384 0 -385 1 -386 0 -387 0 -388 0 -389 0 -390 1 -391 0 -392 0 -393 0 -394 0 -395 0 -396 0 -397 0 -398 0 -399 0 -400 0 -401 0 -402 1 -403 0 -404 0 -405 0 -406 0 -407 0 -408 0 -409 0 -410 1 -411 0 -412 0 -413 0 -414 0 -415 0 -416 0 -417 0 -418 0 -419 1 -420 0 -421 0 -422 0 -423 0 -424 0 -425 0 -426 0 -427 1 -428 0 -429 0 -430 0 -431 0 -432 0 -433 0 -434 0 -435 1 -436 0 -437 0 -438 0 -439 0 -440 0 -441 0 -442 0 -443 1 -444 0 -445 0 -446 0 -447 0 -448 0 -449 0 -450 1 -451 0 -452 0 -453 0 -454 0 -455 0 -456 1 -457 0 -458 0 -459 0 -460 0 -461 0 -462 0 -463 0 -464 1 -465 0 -466 0 -467 0 -468 0 -469 0 -470 0 -471 0 -472 0 -473 1 -474 0 -475 0 -476 0 -477 0 -478 0 -479 0 -480 0 -481 1 -482 0 -483 0 -484 0 -485 0 -486 0 -487 0 -488 0 -489 0 -490 1 -491 0 -492 0 -493 0 -494 0 -495 0 -496 0 -497 0 -498 0 -499 0 -500 0 -501 0 -502 0 -503 0 -504 1 -505 0 -506 0 -507 0 -508 0 -509 0 -510 0 -511 0 -512 1 -513 0 -514 0 -515 0 -516 0 -517 0 -518 0 -519 4 -520 0 -521 1 -522 0 -523 0 -524 0 -525 1 -526 0 -527 0 -528 0 -529 0 -530 1 -531 0 -532 0 -533 0 -534 1 -535 0 -536 0 -537 0 -538 0 -539 1 -540 0 -541 0 -542 0 -543 0 -544 0 -545 1 -546 0 -547 0 -548 0 -549 0 -550 0 -551 1 -552 0 -553 0 -554 0 -555 0 -556 0 -557 0 -558 0 -559 1 -560 0 -561 0 -562 0 -563 0 -564 0 -565 0 -566 0 -567 1 -568 0 -569 0 -570 0 -571 0 -572 0 -573 0 -574 0 -575 0 -576 1 -577 0 -578 0 -579 0 -580 0 -581 0 -582 0 -583 0 -584 0 -585 0 -586 0 -587 0 -588 0 -589 0 -590 0 -591 0 -592 0 -593 1 -594 0 -595 0 -596 0 -597 0 -598 0 -599 0 -600 0 -601 0 -602 1 -603 0 -604 0 -605 0 -606 0 -607 0 -608 0 -609 0 -610 0 -611 1 -612 0 -613 0 -614 0 -615 0 -616 0 -617 0 -618 0 -619 0 -620 1 -621 0 -622 0 -623 0 -624 0 -625 0 -626 0 -627 0 -628 0 -629 1 -630 0 -631 0 -632 0 -633 0 -634 0 -635 0 -636 0 -637 0 -638 0 -639 1 -640 0 -641 0 -642 0 -643 0 -644 0 -645 0 -646 1 -647 0 -648 0 -649 0 -650 0 -651 0 -652 1 -653 1 -654 0 -655 0 -656 1 -657 0 -658 1 -659 0 -660 0 -661 0 -662 0 -663 0 -664 1 -665 0 -666 0 -667 0 -668 0 -669 0 -670 0 -671 0 -672 0 -673 0 -674 0 -675 0 -676 0 -677 1 -678 0 -679 0 -680 0 -681 0 -682 0 -683 0 -684 0 -685 0 -686 1 -687 0 -688 0 -689 0 -690 0 -691 0 -692 0 -693 0 -694 0 -695 1 -696 0 -697 0 -698 0 -699 0 -700 0 -701 0 -702 0 -703 1 -704 0 -705 0 -706 0 -707 0 -708 0 -709 0 -710 0 -711 0 -712 1 -713 0 -714 0 -715 0 -716 0 -717 0 -718 0 -719 0 -720 1 -721 0 -722 0 -723 0 -724 0 -725 0 -726 0 -727 0 -728 1 -729 0 -730 0 -731 0 -732 0 -733 0 -734 0 -735 0 -736 0 -737 1 -738 0 -739 0 -740 0 -741 0 -742 0 -743 0 -744 0 -745 1 -746 0 -747 0 -748 0 -749 0 -750 0 -751 0 -752 0 -753 1 -754 0 -755 0 -756 0 -757 0 -758 0 -759 0 -760 0 -761 1 -762 0 -763 0 -764 0 -765 0 -766 0 -767 0 -768 1 -769 0 -770 0 -771 0 -772 0 -773 0 -774 0 -775 0 -776 0 -777 1 -778 0 -779 0 -780 0 -781 0 -782 0 -783 0 -784 0 -785 0 -786 1 -787 0 -788 0 -789 0 -790 0 -791 0 -792 1 -793 0 -794 0 -795 0 -796 0 -797 0 -798 0 -799 0 -800 0 -801 1 -802 0 -803 0 -804 0 -805 0 -806 0 -807 0 -808 0 -809 0 -810 0 -811 0 -812 0 -813 0 -814 0 -815 0 -816 0 -817 0 -818 0 -819 0 -820 1 -821 0 -822 0 -823 0 -824 0 -825 0 -826 0 -827 0 -828 0 -829 1 -830 0 -831 0 -832 0 -833 0 -834 0 -835 0 -836 0 -837 1 -838 0 -839 0 -840 0 -841 0 -842 0 -843 0 -844 0 -845 0 -846 1 -847 0 -848 0 -849 0 -850 0 -851 0 -852 0 -853 0 -854 0 -855 2 -856 0 -857 0 -858 0 -859 0 -860 0 -861 0 -862 1 -863 0 -864 0 -865 0 -866 0 -867 0 -868 0 -869 0 -870 0 -871 1 -872 0 -873 0 -874 0 -875 0 -876 0 -877 0 -878 1 -879 0 -880 0 -881 0 -882 0 -883 0 -884 0 -885 0 -886 0 -887 0 -888 0 -889 0 -890 0 -891 0 -892 0 -893 0 -894 0 -895 0 -896 1 -897 0 -898 0 -899 0 -900 0 -901 0 -902 0 -903 0 -904 0 -905 0 -906 1 -907 0 -908 0 -909 0 -910 0 -911 0 -912 0 -913 0 -914 0 -915 1 -916 0 -917 0 -918 0 -919 0 -920 0 -921 0 -922 1 -923 0 -924 0 -925 0 -926 0 -927 0 -928 0 -929 0 -930 1 -931 0 -932 0 -933 0 -934 0 -935 0 -936 0 -937 0 -938 0 -939 1 -940 0 -941 0 -942 0 -943 0 -944 0 -945 0 -946 0 -947 0 -948 0 -949 1 -950 0 -951 0 -952 0 -953 0 -954 0 -955 0 -956 0 -957 0 -958 1 -959 0 -960 0 -961 0 -962 0 -963 0 -964 0 -965 0 -966 0 -967 0 -968 1 -969 0 -970 0 -971 0 -972 0 -973 0 -974 0 -975 0 -976 0 -977 0 -978 1 -979 0 -980 0 -981 0 -982 0 -983 0 -984 0 -985 0 -986 0 -987 0 -988 1 -989 0 -990 0 -991 0 -992 0 -993 0 -994 0 -995 0 -996 0 -997 1 -998 0 -999 0 -1000 0 -1001 0 -1002 0 -1003 0 -1004 0 -1005 1 -1006 0 -1007 0 -1008 0 -1009 0 -1010 0 -1011 0 -1012 1 -1013 0 -1014 0 -1015 0 -1016 0 -1017 0 -1018 0 -1019 0 -1020 0 -1021 0 -1022 0 -1023 0 -1024 0 -1025 0 -1026 0 -1027 0 -1028 0 -1029 0 -1030 0 -1031 1 -1032 0 -1033 0 -1034 0 -1035 0 -1036 0 -1037 0 -1038 0 -1039 0 -1040 0 -1041 0 -1042 1 -1043 0 -1044 0 -1045 0 -1046 0 -1047 0 -1048 0 -1049 0 -1050 1 -1051 0 -1052 0 -1053 0 -1054 0 -1055 0 -1056 0 -1057 1 -1058 0 -1059 0 -1060 0 -1061 0 -1062 0 -1063 0 -1064 0 -1065 0 -1066 0 -1067 1 -1068 0 -1069 0 -1070 0 -1071 0 -1072 0 -1073 0 -1074 0 -1075 0 -1076 0 -1077 1 -1078 0 -1079 0 -1080 0 -1081 0 -1082 0 -1083 0 -1084 0 -1085 0 -1086 0 -1087 1 -1088 0 -1089 0 -1090 0 -1091 0 -1092 0 -1093 0 -1094 1 -1095 0 -1096 0 -1097 0 -1098 0 -1099 0 -1100 0 -1101 0 -1102 1 -1103 0 -1104 0 -1105 0 -1106 0 -1107 0 -1108 0 -1109 0 -1110 0 -1111 1 -1112 0 -1113 0 -1114 0 -1115 0 -1116 0 -1117 0 -1118 0 -1119 0 -1120 1 -1121 0 -1122 0 -1123 0 -1124 0 -1125 0 -1126 0 -1127 0 -1128 0 -1129 0 -1130 1 -1131 0 -1132 0 -1133 0 -1134 0 -1135 0 -1136 0 -1137 0 -1138 0 -1139 0 -1140 1 -1141 0 -1142 0 -1143 0 -1144 0 -1145 0 -1146 0 -1147 0 -1148 0 -1149 0 -1150 0 -1151 1 -1152 0 -1153 0 -1154 0 -1155 0 -1156 0 -1157 0 -1158 0 -1159 0 -1160 1 -1161 0 -1162 0 -1163 0 -1164 0 -1165 0 -1166 0 -1167 1 -1168 0 -1169 0 -1170 0 -1171 0 -1172 0 -1173 0 -1174 0 -1175 0 -1176 1 -1177 0 -1178 0 -1179 0 -1180 0 -1181 0 -1182 1 -1183 0 -1184 0 -1185 0 -1186 0 -1187 0 -1188 0 -1189 0 -1190 1 -1191 0 -1192 0 -1193 0 -1194 0 -1195 0 -1196 0 -1197 0 -1198 1 -1199 0 -1200 0 -1201 0 -1202 0 -1203 0 -1204 0 -1205 0 -1206 1 -1207 0 -1208 0 -1209 0 -1210 0 -1211 0 -1212 0 -1213 0 -1214 0 -1215 0 -1216 1 -1217 0 -1218 0 -1219 0 -1220 0 -1221 0 -1222 0 -1223 0 -1224 0 -1225 0 -1226 1 -1227 0 -1228 0 -1229 0 -1230 0 -1231 0 -1232 0 -1233 0 -1234 0 -1235 0 -1236 0 -1237 0 -1238 0 -1239 1 -1240 0 -1241 0 -1242 0 -1243 0 -1244 0 -1245 0 -1246 0 -1247 0 -1248 1 -1249 0 -1250 0 -1251 0 -1252 0 -1253 0 -1254 0 -1255 0 -1256 0 -1257 1 -1258 0 -1259 0 -1260 0 -1261 0 -1262 0 -1263 0 -1264 0 -1265 0 -1266 1 -1267 0 -1268 0 -1269 0 -1270 0 -1271 0 -1272 0 -1273 0 -1274 0 -1275 1 -1276 0 -1277 0 -1278 0 -1279 0 -1280 0 -1281 0 -1282 0 -1283 0 -1284 0 -1285 0 -1286 0 -1287 0 -1288 0 -1289 0 -1290 0 -1291 0 -1292 0 -1293 1 -1294 0 -1295 0 -1296 0 -1297 0 -1298 0 -1299 0 -1300 0 -1301 0 -1302 0 -1303 0 -1304 0 -1305 0 -1306 0 -1307 0 -1308 0 -1309 0 -1310 1 -1311 0 -1312 0 -1313 0 -1314 0 -1315 0 -1316 0 -1317 0 -1318 1 -1319 0 -1320 0 -1321 0 -1322 0 -1323 0 -1324 0 -1325 0 -1326 0 -1327 1 -1328 0 -1329 0 -1330 0 -1331 0 -1332 0 -1333 0 -1334 0 -1335 0 -1336 1 -1337 0 -1338 0 -1339 0 -1340 0 -1341 0 -1342 0 -1343 0 -1344 0 -1345 0 -1346 1 -1347 0 -1348 0 -1349 0 -1350 0 -1351 0 -1352 0 -1353 0 -1354 0 -1355 0 -1356 1 -1357 0 -1358 0 -1359 0 -1360 0 -1361 0 -1362 0 -1363 0 -1364 0 -1365 1 -1366 0 -1367 0 -1368 0 -1369 0 -1370 0 -1371 0 -1372 0 -1373 1 -1374 0 -1375 0 -1376 0 -1377 0 -1378 0 -1379 0 -1380 0 -1381 0 -1382 0 -1383 1 -1384 0 -1385 0 -1386 0 -1387 0 -1388 0 -1389 0 -1390 0 -1391 0 -1392 1 -1393 0 -1394 0 -1395 0 -1396 0 -1397 0 -1398 0 -1399 0 -1400 1 -1401 0 -1402 0 -1403 0 -1404 0 -1405 0 -1406 0 -1407 0 -1408 0 -1409 0 -1410 1 -1411 0 -1412 0 -1413 0 -1414 0 -1415 0 -1416 0 -1417 0 -1418 0 -1419 0 -1420 1 -1421 0 -1422 0 -1423 0 -1424 0 -1425 0 -1426 0 -1427 0 -1428 0 -1429 0 -1430 0 -1431 1 -1432 0 -1433 0 -1434 0 -1435 0 -1436 0 -1437 0 -1438 0 -1439 0 -1440 0 -1441 1 -1442 0 -1443 0 -1444 0 -1445 0 -1446 0 -1447 2 -1448 0 -1449 0 -1450 0 -1451 0 -1452 0 -1453 0 -1454 0 -1455 1 -1456 0 -1457 0 -1458 0 -1459 0 -1460 0 -1461 0 -1462 0 -1463 0 -1464 0 -1465 1 -1466 0 -1467 0 -1468 0 -1469 0 -1470 0 -1471 0 -1472 0 -1473 0 -1474 0 -1475 1 -1476 0 -1477 0 -1478 0 -1479 0 -1480 0 -1481 0 -1482 0 -1483 0 -1484 0 -1485 1 -1486 0 -1487 0 -1488 0 -1489 0 -1490 0 -1491 0 -1492 0 -1493 0 -1494 1 -1495 0 -1496 0 -1497 0 -1498 0 -1499 0 -1500 0 -1501 0 -1502 0 -1503 1 -1504 0 -1505 0 -1506 0 -1507 0 -1508 0 -1509 0 -1510 0 -1511 0 -1512 0 -1513 0 -1514 0 -1515 0 -1516 0 -1517 0 -1518 0 -1519 0 -1520 1 -1521 0 -1522 0 -1523 0 -1524 0 -1525 0 -1526 0 -1527 0 -1528 0 -1529 1 -1530 0 -1531 0 -1532 0 -1533 0 -1534 0 -1535 0 -1536 0 -1537 0 -1538 0 -1539 1 -1540 0 -1541 0 -1542 0 -1543 0 -1544 0 -1545 0 -1546 0 -1547 0 -1548 1 -1549 0 -1550 0 -1551 0 -1552 0 -1553 0 -1554 0 -1555 0 -1556 0 -1557 1 -1558 0 -1559 0 -1560 0 -1561 0 -1562 0 -1563 0 -1564 0 -1565 0 -1566 0 -1567 1 -1568 0 -1569 0 -1570 0 -1571 0 -1572 0 -1573 0 -1574 0 -1575 1 -1576 0 -1577 0 -1578 0 -1579 0 -1580 0 -1581 0 -1582 0 -1583 0 -1584 1 -1585 0 -1586 0 -1587 0 -1588 0 -1589 0 -1590 0 -1591 0 -1592 0 -1593 1 -1594 0 -1595 0 -1596 0 -1597 0 -1598 0 -1599 0 -1600 0 -1601 0 -1602 1 -1603 0 -1604 0 -1605 0 -1606 0 -1607 0 -1608 0 -1609 0 -1610 0 -1611 1 -1612 0 -1613 0 -1614 0 -1615 0 -1616 0 -1617 0 -1618 0 -1619 0 -1620 0 -1621 1 -1622 0 -1623 0 -1624 0 -1625 0 -1626 0 -1627 0 -1628 0 -1629 0 -1630 0 -1631 1 -1632 0 -1633 0 -1634 0 -1635 0 -1636 0 -1637 0 -1638 0 -1639 0 -1640 1 -1641 0 -1642 0 -1643 0 -1644 0 -1645 0 -1646 0 -1647 0 -1648 0 -1649 0 -1650 1 -1651 0 -1652 0 -1653 0 -1654 0 -1655 0 -1656 0 -1657 0 -1658 0 -1659 0 -1660 1 -1661 0 -1662 0 -1663 0 -1664 0 -1665 0 -1666 0 -1667 0 -1668 0 -1669 0 -1670 1 -1671 0 -1672 0 -1673 0 -1674 0 -1675 0 -1676 0 -1677 0 -1678 0 -1679 0 -1680 1 -1681 0 -1682 0 -1683 0 -1684 0 -1685 0 -1686 0 -1687 0 -1688 0 -1689 0 -1690 1 -1691 0 -1692 0 -1693 0 -1694 0 -1695 0 -1696 0 -1697 0 -1698 0 -1699 0 -1700 0 -1701 1 -1702 0 -1703 0 -1704 0 -1705 0 -1706 0 -1707 0 -1708 1 -1709 0 -1710 0 -1711 0 -1712 0 -1713 0 -1714 0 -1715 0 -1716 1 -1717 0 -1718 0 -1719 0 -1720 0 -1721 0 -1722 0 -1723 0 -1724 0 -1725 0 -1726 0 -1727 0 -1728 0 -1729 0 -1730 0 -1731 0 -1732 0 -1733 0 -1734 1 -1735 0 -1736 0 -1737 0 -1738 0 -1739 0 -1740 0 -1741 0 -1742 0 -1743 1 -1744 0 -1745 0 -1746 0 -1747 0 -1748 0 -1749 0 -1750 0 -1751 0 -1752 0 -1753 1 -1754 0 -1755 0 -1756 0 -1757 0 -1758 0 -1759 0 -1760 0 -1761 0 -1762 0 -1763 1 -1764 0 -1765 0 -1766 0 -1767 0 -1768 0 -1769 0 -1770 0 -1771 0 -1772 0 -1773 1 -1774 0 -1775 0 -1776 0 -1777 0 -1778 0 -1779 0 -1780 0 -1781 0 -1782 0 -1783 1 -1784 0 -1785 0 -1786 0 -1787 0 -1788 0 -1789 0 -1790 0 -1791 0 -1792 0 -1793 1 -1794 0 -1795 0 -1796 0 -1797 0 -1798 0 -1799 0 -1800 0 -1801 0 -1802 0 -1803 1 -1804 0 -1805 0 -1806 0 -1807 0 -1808 0 -1809 0 -1810 0 -1811 0 -1812 0 -1813 1 -1814 0 -1815 0 -1816 0 -1817 0 -1818 0 -1819 0 -1820 0 -1821 0 -1822 1 -1823 0 -1824 0 -1825 0 -1826 0 -1827 0 -1828 0 -1829 1 -1830 0 -1831 0 -1832 0 -1833 0 -1834 0 -1835 0 -1836 0 -1837 0 -1838 0 -1839 1 -1840 0 -1841 0 -1842 0 -1843 0 -1844 0 -1845 0 -1846 0 -1847 0 -1848 0 -1849 1 -1850 0 -1851 0 -1852 0 -1853 0 -1854 0 -1855 0 -1856 0 -1857 0 -1858 0 -1859 1 -1860 0 -1861 0 -1862 0 -1863 0 -1864 0 -1865 0 -1866 0 -1867 0 -1868 0 -1869 1 -1870 0 -1871 0 -1872 0 -1873 0 -1874 0 -1875 0 -1876 0 -1877 0 -1878 0 -1879 1 -1880 0 -1881 0 -1882 0 -1883 0 -1884 0 -1885 0 -1886 0 -1887 0 -1888 0 -1889 1 -1890 0 -1891 0 -1892 0 -1893 0 -1894 0 -1895 0 -1896 0 -1897 0 -1898 0 -1899 0 -1900 0 -1901 0 -1902 0 -1903 0 -1904 0 -1905 0 -1906 0 -1907 0 -1908 0 -1909 0 -1910 1 -1911 0 -1912 0 -1913 0 -1914 0 -1915 0 -1916 0 -1917 0 -1918 0 -1919 0 -1920 0 -1921 0 -1922 0 -1923 0 -1924 0 -1925 0 -1926 0 -1927 0 -1928 0 -1929 0 -1930 1 -1931 0 -1932 0 -1933 0 -1934 0 -1935 0 -1936 0 -1937 0 -1938 0 -1939 1 -1940 0 -1941 0 -1942 0 -1943 0 -1944 0 -1945 0 -1946 0 -1947 0 -1948 0 -1949 1 -1950 0 -1951 0 -1952 0 -1953 0 -1954 0 -1955 0 -1956 0 -1957 0 -1958 1 -1959 0 -1960 0 -1961 0 -1962 0 -1963 0 -1964 0 -1965 0 -1966 0 -1967 0 -1968 1 -1969 0 -1970 0 -1971 0 -1972 0 -1973 0 -1974 0 -1975 0 -1976 0 -1977 0 -1978 1 -1979 0 -1980 0 -1981 0 -1982 0 -1983 0 -1984 0 -1985 0 -1986 0 -1987 0 -1988 1 -1989 0 -1990 0 -1991 0 -1992 0 -1993 0 -1994 0 -1995 0 -1996 1 -1997 0 -1998 0 -1999 0 -2000 0 -2001 0 -2002 0 -2003 0 -2004 1 -2005 0 -2006 0 -2007 0 -2008 0 -2009 0 -2010 0 -2011 0 -2012 0 -2013 0 -2014 1 -2015 0 -2016 0 -2017 0 -2018 0 -2019 0 -2020 0 -2021 0 -2022 0 -2023 0 -2024 1 -2025 0 -2026 0 -2027 0 -2028 0 -2029 0 -2030 0 -2031 0 -2032 0 -2033 1 -2034 0 -2035 0 -2036 0 -2037 0 -2038 0 -2039 0 -2040 0 -2041 2 -2042 0 -2043 0 -2044 0 -2045 0 -2046 0 -2047 0 -2048 0 -2049 1 -2050 0 -2051 0 -2052 0 -2053 0 -2054 0 -2055 0 -2056 0 -2057 0 -2058 0 -2059 0 -2060 0 -2061 0 -2062 0 -2063 0 -2064 0 -2065 0 -2066 0 -2067 1 -2068 0 -2069 0 -2070 0 -2071 0 -2072 0 -2073 0 -2074 0 -2075 0 -2076 1 -2077 0 -2078 0 -2079 0 -2080 0 -2081 0 -2082 0 -2083 0 -2084 0 -2085 0 -2086 1 -2087 0 -2088 0 -2089 0 -2090 0 -2091 0 -2092 0 -2093 0 -2094 0 -2095 0 -2096 1 -2097 0 -2098 0 -2099 0 -2100 0 -2101 0 -2102 0 -2103 0 -2104 0 -2105 1 -2106 0 -2107 0 -2108 0 -2109 0 -2110 0 -2111 0 -2112 0 -2113 0 -2114 0 -2115 0 -2116 1 -2117 0 -2118 0 -2119 0 -2120 0 -2121 0 -2122 0 -2123 0 -2124 0 -2125 1 -2126 0 -2127 0 -2128 0 -2129 0 -2130 0 -2131 0 -2132 0 -2133 1 -2134 0 -2135 0 -2136 0 -2137 0 -2138 0 -2139 0 -2140 0 -2141 1 -2142 0 -2143 0 -2144 0 -2145 0 -2146 0 -2147 0 -2148 0 -2149 0 -2150 1 -2151 0 -2152 0 -2153 0 -2154 0 -2155 0 -2156 0 -2157 0 -2158 0 -2159 1 -2160 0 -2161 0 -2162 0 -2163 0 -2164 0 -2165 0 -2166 0 -2167 0 -2168 0 -2169 1 -2170 0 -2171 0 -2172 0 -2173 0 -2174 0 -2175 0 -2176 0 -2177 1 -2178 0 -2179 0 -2180 0 -2181 0 -2182 0 -2183 0 -2184 0 -2185 0 -2186 0 -2187 1 -2188 0 -2189 0 -2190 0 -2191 0 -2192 0 -2193 0 -2194 0 -2195 0 -2196 1 -2197 0 -2198 0 -2199 0 -2200 0 -2201 0 -2202 0 -2203 0 -2204 1 -2205 0 -2206 0 -2207 0 -2208 0 -2209 0 -2210 0 -2211 0 -2212 0 -2213 0 -2214 1 -2215 0 -2216 0 -2217 0 -2218 0 -2219 0 -2220 0 -2221 0 -2222 0 -2223 0 -2224 1 -2225 0 -2226 0 -2227 0 -2228 0 -2229 0 -2230 0 -2231 0 -2232 0 -2233 1 -2234 0 -2235 0 -2236 0 -2237 0 -2238 0 -2239 0 -2240 0 -2241 0 -2242 1 -2243 0 -2244 0 -2245 0 -2246 0 -2247 0 -2248 0 -2249 0 -2250 1 -2251 0 -2252 0 -2253 0 -2254 0 -2255 0 -2256 0 -2257 0 -2258 0 -2259 0 -2260 1 -2261 0 -2262 0 -2263 0 -2264 0 -2265 0 -2266 0 -2267 0 -2268 0 -2269 0 -2270 1 -2271 0 -2272 0 -2273 0 -2274 0 -2275 0 -2276 0 -2277 0 -2278 0 -2279 0 -2280 1 -2281 0 -2282 0 -2283 0 -2284 0 -2285 0 -2286 0 -2287 0 -2288 0 -2289 0 -2290 1 -2291 0 -2292 0 -2293 0 -2294 0 -2295 0 -2296 0 -2297 0 -2298 1 -2299 0 -2300 0 -2301 0 -2302 0 -2303 0 -2304 0 -2305 0 -2306 1 -2307 0 -2308 0 -2309 0 -2310 0 -2311 0 -2312 0 -2313 0 -2314 0 -2315 1 -2316 0 -2317 0 -2318 0 -2319 0 -2320 0 -2321 0 -2322 0 -2323 0 -2324 0 -2325 1 -2326 0 -2327 0 -2328 0 -2329 0 -2330 0 -2331 0 -2332 0 -2333 0 -2334 0 -2335 1 -2336 0 -2337 0 -2338 0 -2339 0 -2340 0 -2341 0 -2342 0 -2343 0 -2344 0 -2345 1 -2346 0 -2347 0 -2348 0 -2349 0 -2350 0 -2351 0 -2352 0 -2353 1 -2354 0 -2355 0 -2356 0 -2357 0 -2358 0 -2359 0 -2360 0 -2361 1 -2362 0 -2363 0 -2364 0 -2365 0 -2366 0 -2367 0 -2368 0 -2369 0 -2370 0 -2371 1 -2372 0 -2373 0 -2374 0 -2375 0 -2376 0 -2377 0 -2378 0 -2379 0 -2380 0 -2381 1 -2382 0 -2383 0 -2384 0 -2385 0 -2386 0 -2387 0 -2388 0 -2389 0 -2390 1 -2391 0 -2392 0 -2393 0 -2394 0 -2395 0 -2396 0 -2397 0 -2398 0 -2399 0 -2400 0 -2401 0 -2402 0 -2403 0 -2404 0 -2405 0 -2406 0 -2407 0 -2408 0 -2409 0 -2410 0 -2411 1 -2412 0 -2413 0 -2414 0 -2415 0 -2416 0 -2417 0 -2418 0 -2419 0 -2420 0 -2421 1 -2422 0 -2423 0 -2424 0 -2425 0 -2426 0 -2427 0 -2428 0 -2429 0 -2430 0 -2431 0 -2432 0 -2433 0 -2434 0 -2435 0 -2436 0 -2437 0 -2438 0 -2439 0 -2440 1 -2441 0 -2442 0 -2443 0 -2444 0 -2445 0 -2446 0 -2447 0 -2448 0 -2449 0 -2450 0 -2451 1 -2452 0 -2453 0 -2454 0 -2455 0 -2456 0 -2457 0 -2458 0 -2459 0 -2460 0 -2461 1 -2462 0 -2463 0 -2464 0 -2465 0 -2466 0 -2467 0 -2468 0 -2469 1 -2470 0 -2471 0 -2472 0 -2473 0 -2474 0 -2475 0 -2476 0 -2477 1 -2478 0 -2479 0 -2480 0 -2481 0 -2482 0 -2483 0 -2484 0 -2485 0 -2486 1 -2487 0 -2488 0 -2489 0 -2490 0 -2491 0 -2492 0 -2493 0 -2494 0 -2495 0 -2496 1 -2497 0 -2498 0 -2499 0 -2500 0 -2501 0 -2502 0 -2503 0 -2504 0 -2505 0 -2506 1 -2507 0 -2508 0 -2509 0 -2510 0 -2511 0 -2512 0 -2513 0 -2514 0 -2515 0 -2516 1 -2517 0 -2518 0 -2519 0 -2520 0 -2521 0 -2522 0 -2523 0 -2524 0 -2525 0 -2526 0 -2527 1 -2528 0 -2529 0 -2530 0 -2531 0 -2532 0 -2533 0 -2534 0 -2535 0 -2536 0 -2537 1 -2538 0 -2539 0 -2540 0 -2541 0 -2542 0 -2543 0 -2544 0 -2545 0 -2546 0 -2547 0 -2548 0 -2549 0 -2550 0 -2551 0 -2552 0 -2553 0 -2554 0 -2555 0 -2556 0 -2557 1 -2558 0 -2559 0 -2560 0 -2561 0 -2562 0 -2563 0 -2564 0 -2565 0 -2566 1 -2567 0 -2568 0 -2569 0 -2570 0 -2571 0 -2572 0 -2573 0 -2574 0 -2575 1 -2576 0 -2577 0 -2578 0 -2579 0 -2580 0 -2581 0 -2582 0 -2583 0 -2584 1 -2585 0 -2586 0 -2587 0 -2588 0 -2589 0 -2590 0 -2591 0 -2592 0 -2593 0 -2594 0 -2595 1 -2596 0 -2597 0 -2598 0 -2599 0 -2600 0 -2601 0 -2602 0 -2603 0 -2604 0 -2605 1 -2606 0 -2607 0 -2608 0 -2609 0 -2610 0 -2611 0 -2612 0 -2613 0 -2614 0 -2615 0 -2616 0 -2617 0 -2618 0 -2619 0 -2620 0 -2621 0 -2622 0 -2623 0 -2624 0 -2625 1 -2626 0 -2627 0 -2628 0 -2629 0 -2630 0 -2631 0 -2632 0 -2633 0 -2634 0 -2635 1 -2636 0 -2637 0 -2638 0 -2639 1 -2640 0 -2641 0 -2642 0 -2643 1 -2644 0 -2645 0 -2646 0 -2647 0 -2648 0 -2649 0 -2650 0 -2651 0 -2652 0 -2653 1 -2654 0 -2655 0 -2656 0 -2657 0 -2658 0 -2659 0 -2660 0 -2661 0 -2662 0 -2663 1 -2664 0 -2665 0 -2666 0 -2667 0 -2668 0 -2669 0 -2670 0 -2671 1 -2672 0 -2673 0 -2674 0 -2675 0 -2676 0 -2677 0 -2678 0 -2679 1 -2680 0 -2681 0 -2682 0 -2683 0 -2684 0 -2685 0 -2686 0 -2687 0 -2688 0 -2689 1 -2690 0 -2691 0 -2692 0 -2693 0 -2694 0 -2695 0 -2696 0 -2697 0 -2698 0 -2699 1 -2700 0 -2701 0 -2702 0 -2703 0 -2704 0 -2705 0 -2706 0 -2707 0 -2708 0 -2709 1 -2710 0 -2711 0 -2712 0 -2713 0 -2714 0 -2715 0 -2716 1 -2717 0 -2718 0 -2719 0 -2720 0 -2721 0 -2722 0 -2723 0 -2724 1 -2725 0 -2726 0 -2727 0 -2728 0 -2729 0 -2730 0 -2731 0 -2732 0 -2733 0 -2734 1 -2735 0 -2736 0 -2737 0 -2738 0 -2739 0 -2740 0 -2741 0 -2742 0 -2743 0 -2744 1 -2745 0 -2746 0 -2747 0 -2748 0 -2749 0 -2750 0 -2751 0 -2752 0 -2753 1 -2754 0 -2755 0 -2756 0 -2757 0 -2758 0 -2759 0 -2760 0 -2761 0 -2762 0 -2763 1 -2764 0 -2765 0 -2766 0 -2767 0 -2768 0 -2769 0 -2770 0 -2771 0 -2772 0 -2773 1 -2774 0 -2775 0 -2776 0 -2777 0 -2778 0 -2779 0 -2780 0 -2781 0 -2782 0 -2783 1 -2784 0 -2785 0 -2786 0 -2787 0 -2788 0 -2789 0 -2790 0 -2791 0 -2792 1 -2793 0 -2794 0 -2795 0 -2796 0 -2797 0 -2798 0 -2799 0 -2800 0 -2801 0 -2802 0 -2803 0 -2804 0 -2805 0 -2806 0 -2807 0 -2808 0 -2809 0 -2810 0 -2811 0 -2812 0 -2813 0 -2814 0 -2815 0 -2816 0 -2817 0 -2818 0 -2819 0 -2820 0 -2821 1 -2822 0 -2823 0 -2824 0 -2825 0 -2826 0 -2827 0 -2828 0 -2829 0 -2830 0 -2831 1 -2832 0 -2833 0 -2834 0 -2835 0 -2836 0 -2837 0 -2838 0 -2839 0 -2840 0 -2841 1 -2842 0 -2843 0 -2844 0 -2845 0 -2846 0 -2847 0 -2848 0 -2849 0 -2850 0 -2851 1 -2852 0 -2853 0 -2854 0 -2855 0 -2856 0 -2857 0 -2858 0 -2859 0 -2860 0 -2861 1 -2862 0 -2863 0 -2864 0 -2865 0 -2866 0 -2867 0 -2868 0 -2869 0 -2870 0 -2871 1 -2872 0 -2873 0 -2874 0 -2875 0 -2876 0 -2877 0 -2878 0 -2879 0 -2880 1 -2881 0 -2882 0 -2883 0 -2884 0 -2885 0 -2886 0 -2887 0 -2888 1 -2889 0 -2890 0 -2891 0 -2892 0 -2893 0 -2894 0 -2895 0 -2896 0 -2897 1 -2898 0 -2899 0 -2900 0 -2901 0 -2902 0 -2903 0 -2904 0 -2905 0 -2906 1 -2907 0 -2908 0 -2909 0 -2910 0 -2911 0 -2912 0 -2913 0 -2914 1 -2915 0 -2916 0 -2917 0 -2918 0 -2919 0 -2920 0 -2921 0 -2922 1 -2923 0 -2924 0 -2925 0 -2926 0 -2927 0 -2928 0 -2929 0 -2930 0 -2931 0 -2932 0 -2933 0 -2934 0 -2935 0 -2936 0 -2937 0 -2938 1 -2939 0 -2940 0 -2941 0 -2942 0 -2943 0 -2944 0 -2945 0 -2946 0 -2947 0 -2948 0 -2949 1 -2950 0 -2951 0 -2952 0 -2953 0 -2954 0 -2955 0 -2956 0 -2957 0 -2958 0 -2959 1 -2960 0 -2961 0 -2962 0 -2963 0 -2964 0 -2965 0 -2966 0 -2967 0 -2968 1 -2969 0 -2970 0 -2971 0 -2972 0 -2973 0 -2974 0 -2975 0 -2976 0 -2977 1 -2978 0 -2979 0 -2980 0 -2981 0 -2982 0 -2983 0 -2984 0 -2985 0 -2986 0 -2987 1 -2988 0 -2989 0 -2990 0 -2991 0 -2992 0 -2993 0 -2994 0 -2995 0 -2996 0 -2997 1 -2998 0 -2999 0 -3000 0 -3001 0 -3002 0 -3003 0 -3004 0 -3005 0 -3006 0 -3007 0 -3008 0 -3009 0 -3010 0 -3011 0 -3012 0 -3013 0 -3014 0 -3015 1 -3016 0 -3017 0 -3018 0 -3019 0 -3020 0 -3021 0 -3022 0 -3023 0 -3024 0 -3025 1 -3026 0 -3027 0 -3028 0 -3029 0 -3030 0 -3031 0 -3032 0 -3033 0 -3034 1 -3035 0 -3036 0 -3037 0 -3038 0 -3039 0 -3040 0 -3041 0 -3042 1 -3043 0 -3044 0 -3045 0 -3046 0 -3047 0 -3048 0 -3049 0 -3050 0 -3051 0 -3052 1 -3053 0 -3054 0 -3055 0 -3056 0 -3057 0 -3058 0 -3059 0 -3060 0 -3061 0 -3062 1 -3063 0 -3064 0 -3065 0 -3066 0 -3067 0 -3068 0 -3069 0 -3070 0 -3071 0 -3072 1 -3073 0 -3074 0 -3075 0 -3076 0 -3077 0 -3078 0 -3079 0 -3080 0 -3081 0 -3082 1 -3083 0 -3084 0 -3085 0 -3086 0 -3087 0 -3088 0 -3089 0 -3090 0 -3091 0 -3092 1 -3093 0 -3094 0 -3095 0 -3096 0 -3097 0 -3098 0 -3099 0 -3100 0 -3101 0 -3102 1 -3103 0 -3104 0 -3105 0 -3106 0 -3107 0 -3108 0 -3109 0 -3110 0 -3111 0 -3112 1 -3113 0 -3114 0 -3115 0 -3116 0 -3117 0 -3118 0 -3119 0 -3120 1 -3121 0 -3122 0 -3123 0 -3124 0 -3125 0 -3126 0 -3127 0 -3128 0 -3129 1 -3130 0 -3131 0 -3132 0 -3133 0 -3134 0 -3135 0 -3136 0 -3137 0 -3138 0 -3139 1 -3140 0 -3141 0 -3142 0 -3143 0 -3144 0 -3145 0 -3146 0 -3147 0 -3148 0 -3149 1 -3150 0 -3151 0 -3152 0 -3153 0 -3154 0 -3155 0 -3156 0 -3157 1 -3158 0 -3159 0 -3160 0 -3161 0 -3162 0 -3163 0 -3164 0 -3165 1 -3166 0 -3167 0 -3168 0 -3169 0 -3170 0 -3171 0 -3172 0 -3173 0 -3174 0 -3175 1 -3176 0 -3177 0 -3178 0 -3179 0 -3180 0 -3181 0 -3182 0 -3183 0 -3184 0 -3185 1 -3186 0 -3187 0 -3188 0 -3189 0 -3190 0 -3191 0 -3192 0 -3193 0 -3194 0 -3195 0 -3196 1 -3197 0 -3198 0 -3199 0 -3200 0 -3201 0 -3202 0 -3203 0 -3204 0 -3205 0 -3206 0 -3207 1 -3208 0 -3209 0 -3210 0 -3211 0 -3212 0 -3213 0 -3214 0 -3215 1 -3216 0 -3217 0 -3218 0 -3219 0 -3220 0 -3221 0 -3222 0 -3223 1 -3224 0 -3225 0 -3226 0 -3227 0 -3228 0 -3229 0 -3230 0 -3231 0 -3232 1 -3233 0 -3234 1 -3235 0 -3236 0 -3237 0 -3238 0 -3239 1 -3240 0 -3241 0 -3242 0 -3243 0 -3244 0 -3245 0 -3246 0 -3247 0 -3248 1 -3249 0 -3250 0 -3251 0 -3252 0 -3253 0 -3254 0 -3255 0 -3256 0 -3257 0 -3258 1 -3259 0 -3260 0 -3261 0 -3262 0 -3263 0 -3264 0 -3265 0 -3266 0 -3267 0 -3268 0 -3269 1 -3270 0 -3271 0 -3272 0 -3273 0 -3274 0 -3275 0 -3276 0 -3277 0 -3278 1 -3279 0 -3280 0 -3281 0 -3282 0 -3283 0 -3284 0 -3285 0 -3286 0 -3287 1 -3288 0 -3289 0 -3290 0 -3291 0 -3292 0 -3293 0 -3294 0 -3295 0 -3296 0 -3297 1 -3298 0 -3299 0 -3300 0 -3301 0 -3302 0 -3303 0 -3304 0 -3305 0 -3306 0 -3307 1 -3308 0 -3309 0 -3310 0 -3311 0 -3312 0 -3313 0 -3314 0 -3315 0 -3316 0 -3317 1 -3318 0 -3319 0 -3320 0 -3321 0 -3322 0 -3323 0 -3324 0 -3325 1 -3326 0 -3327 0 -3328 0 -3329 0 -3330 0 -3331 0 -3332 0 -3333 0 -3334 0 -3335 1 -3336 0 -3337 0 -3338 0 -3339 0 -3340 0 -3341 0 -3342 0 -3343 0 -3344 1 -3345 0 -3346 0 -3347 0 -3348 0 -3349 0 -3350 0 -3351 0 -3352 0 -3353 0 -3354 1 -3355 0 -3356 0 -3357 0 -3358 0 -3359 0 -3360 0 -3361 0 -3362 0 -3363 0 -3364 0 -3365 1 -3366 0 -3367 0 -3368 0 -3369 0 -3370 0 -3371 0 -3372 0 -3373 0 -3374 0 -3375 1 -3376 0 -3377 0 -3378 0 -3379 0 -3380 0 -3381 0 -3382 0 -3383 0 -3384 0 -3385 0 -3386 1 -3387 0 -3388 0 -3389 0 -3390 0 -3391 0 -3392 0 -3393 0 -3394 0 -3395 0 -3396 0 -3397 1 -3398 0 -3399 0 -3400 0 -3401 0 -3402 0 -3403 0 -3404 0 -3405 0 -3406 0 -3407 1 -3408 0 -3409 0 -3410 0 -3411 0 -3412 0 -3413 0 -3414 0 -3415 0 -3416 0 -3417 1 -3418 0 -3419 0 -3420 0 -3421 0 -3422 0 -3423 0 -3424 0 -3425 0 -3426 0 -3427 0 -3428 1 -3429 0 -3430 0 -3431 0 -3432 0 -3433 0 -3434 0 -3435 0 -3436 0 -3437 1 -3438 0 -3439 0 -3440 0 -3441 0 -3442 0 -3443 0 -3444 0 -3445 1 -3446 0 -3447 0 -3448 0 -3449 0 -3450 0 -3451 0 -3452 0 -3453 0 -3454 1 -3455 0 -3456 0 -3457 0 -3458 0 -3459 0 -3460 0 -3461 0 -3462 0 -3463 0 -3464 1 -3465 0 -3466 0 -3467 0 -3468 0 -3469 0 -3470 0 -3471 0 -3472 0 -3473 0 -3474 1 -3475 0 -3476 0 -3477 0 -3478 0 -3479 0 -3480 0 -3481 0 -3482 0 -3483 0 -3484 1 -3485 0 -3486 0 -3487 0 -3488 0 -3489 0 -3490 0 -3491 0 -3492 0 -3493 0 -3494 1 -3495 0 -3496 0 -3497 0 -3498 0 -3499 0 -3500 0 -3501 0 -3502 0 -3503 0 -3504 1 -3505 0 -3506 0 -3507 0 -3508 0 -3509 0 -3510 0 -3511 0 -3512 0 -3513 0 -3514 1 -3515 0 -3516 0 -3517 0 -3518 0 -3519 0 -3520 0 -3521 0 -3522 0 -3523 0 -3524 1 -3525 0 -3526 0 -3527 0 -3528 0 -3529 0 -3530 0 -3531 0 -3532 0 -3533 1 -3534 0 -3535 0 -3536 0 -3537 0 -3538 0 -3539 0 -3540 0 -3541 0 -3542 0 -3543 0 -3544 0 -3545 0 -3546 0 -3547 0 -3548 0 -3549 0 -3550 0 -3551 1 -3552 0 -3553 0 -3554 0 -3555 0 -3556 0 -3557 0 -3558 0 -3559 0 -3560 0 -3561 1 -3562 0 -3563 0 -3564 0 -3565 0 -3566 0 -3567 0 -3568 0 -3569 0 -3570 1 -3571 0 -3572 0 -3573 0 -3574 0 -3575 0 -3576 0 -3577 0 -3578 0 -3579 0 -3580 1 -3581 0 -3582 0 -3583 0 -3584 0 -3585 0 -3586 0 -3587 0 -3588 0 -3589 0 -3590 1 -3591 0 -3592 0 -3593 0 -3594 0 -3595 0 -3596 0 -3597 0 -3598 0 -3599 1 -3600 0 -3601 0 -3602 0 -3603 0 -3604 0 -3605 0 -3606 0 -3607 0 -3608 0 -3609 1 -3610 0 -3611 0 -3612 0 -3613 0 -3614 0 -3615 0 -3616 0 -3617 0 -3618 0 -3619 0 -3620 1 -3621 0 -3622 0 -3623 0 -3624 0 -3625 0 -3626 0 -3627 0 -3628 0 -3629 0 -3630 1 -3631 0 -3632 0 -3633 0 -3634 0 -3635 0 -3636 0 -3637 0 -3638 0 -3639 1 -3640 0 -3641 0 -3642 0 -3643 0 -3644 0 -3645 1 -3646 0 -3647 0 -3648 0 -3649 0 -3650 0 -3651 1 -3652 0 -3653 0 -3654 0 -3655 0 -3656 0 -3657 0 -3658 1 -3659 0 -3660 0 -3661 0 -3662 0 -3663 0 -3664 0 -3665 0 -3666 1 -3667 0 -3668 0 -3669 0 -3670 0 -3671 0 -3672 0 -3673 0 -3674 0 -3675 0 -3676 1 -3677 0 -3678 0 -3679 0 -3680 0 -3681 0 -3682 0 -3683 0 -3684 0 -3685 1 -3686 0 -3687 0 -3688 0 -3689 0 -3690 0 -3691 0 -3692 0 -3693 0 -3694 0 -3695 1 -3696 0 -3697 0 -3698 0 -3699 0 -3700 0 -3701 0 -3702 0 -3703 0 -3704 0 -3705 0 -3706 1 -3707 0 -3708 0 -3709 0 -3710 0 -3711 0 -3712 0 -3713 0 -3714 0 -3715 0 -3716 1 -3717 0 -3718 0 -3719 0 -3720 0 -3721 0 -3722 0 -3723 0 -3724 0 -3725 0 -3726 0 -3727 0 -3728 0 -3729 0 -3730 0 -3731 0 -3732 0 -3733 0 -3734 0 -3735 0 -3736 1 -3737 0 -3738 0 -3739 0 -3740 0 -3741 0 -3742 0 -3743 0 -3744 0 -3745 0 -3746 1 -3747 0 -3748 0 -3749 0 -3750 0 -3751 0 -3752 0 -3753 0 -3754 0 -3755 0 -3756 1 -3757 0 -3758 0 -3759 0 -3760 0 -3761 0 -3762 0 -3763 1 -3764 0 -3765 0 -3766 0 -3767 0 -3768 0 -3769 0 -3770 0 -3771 1 -3772 0 -3773 0 -3774 0 -3775 0 -3776 0 -3777 0 -3778 1 -3779 0 -3780 0 -3781 0 -3782 0 -3783 0 -3784 0 -3785 0 -3786 0 -3787 0 -3788 0 -3789 0 -3790 0 -3791 0 -3792 0 -3793 0 -3794 0 -3795 0 -3796 0 -3797 1 -3798 0 -3799 0 -3800 0 -3801 0 -3802 0 -3803 0 -3804 0 -3805 0 -3806 1 -3807 0 -3808 0 -3809 0 -3810 0 -3811 0 -3812 0 -3813 0 -3814 0 -3815 0 -3816 0 -3817 1 -3818 0 -3819 0 -3820 0 -3821 0 -3822 0 -3823 0 -3824 0 -3825 0 -3826 0 -3827 1 -3828 0 -3829 1 -3830 0 -3831 0 -3832 0 -3833 0 -3834 1 -3835 0 -3836 0 -3837 0 -3838 0 -3839 0 -3840 0 -3841 0 -3842 0 -3843 0 -3844 0 -3845 1 -3846 0 -3847 0 -3848 0 -3849 0 -3850 0 -3851 0 -3852 0 -3853 0 -3854 0 -3855 1 -3856 0 -3857 0 -3858 0 -3859 0 -3860 0 -3861 0 -3862 0 -3863 1 -3864 0 -3865 0 -3866 0 -3867 0 -3868 0 -3869 0 -3870 0 -3871 0 -3872 0 -3873 1 -3874 0 -3875 0 -3876 0 -3877 0 -3878 0 -3879 0 -3880 0 -3881 0 -3882 0 -3883 1 -3884 0 -3885 0 -3886 0 -3887 0 -3888 0 -3889 0 -3890 0 -3891 0 -3892 0 -3893 0 -3894 1 -3895 0 -3896 0 -3897 0 -3898 0 -3899 0 -3900 0 -3901 0 -3902 0 -3903 0 -3904 0 -3905 1 -3906 0 -3907 0 -3908 0 -3909 0 -3910 0 -3911 0 -3912 0 -3913 0 -3914 1 -3915 0 -3916 0 -3917 0 -3918 0 -3919 0 -3920 0 -3921 0 -3922 0 -3923 0 -3924 0 -3925 1 -3926 0 -3927 0 -3928 0 -3929 0 -3930 0 -3931 0 -3932 0 -3933 0 -3934 1 -3935 0 -3936 0 -3937 0 -3938 0 -3939 0 -3940 0 -3941 0 -3942 0 -3943 0 -3944 0 -3945 1 -3946 0 -3947 0 -3948 0 -3949 0 -3950 0 -3951 0 -3952 0 -3953 0 -3954 0 -3955 1 -3956 0 -3957 0 -3958 0 -3959 0 -3960 0 -3961 0 -3962 0 -3963 0 -3964 0 -3965 0 -3966 1 -3967 0 -3968 0 -3969 0 -3970 0 -3971 0 -3972 0 -3973 0 -3974 0 -3975 1 -3976 0 -3977 0 -3978 0 -3979 0 -3980 0 -3981 0 -3982 0 -3983 0 -3984 1 -3985 0 -3986 0 -3987 0 -3988 0 -3989 0 -3990 0 -3991 0 -3992 0 -3993 0 -3994 1 -3995 0 -3996 0 -3997 0 -3998 0 -3999 0 -4000 0 -4001 0 -4002 0 -4003 0 -4004 0 -4005 0 -4006 0 -4007 0 -4008 0 -4009 0 -4010 0 -4011 0 -4012 0 -4013 0 -4014 1 -4015 0 -4016 0 -4017 0 -4018 0 -4019 0 -4020 0 -4021 0 -4022 0 -4023 0 -4024 1 -4025 0 -4026 0 -4027 0 -4028 0 -4029 0 -4030 0 -4031 0 -4032 0 -4033 0 -4034 0 -4035 1 -4036 0 -4037 0 -4038 0 -4039 0 -4040 0 -4041 0 -4042 0 -4043 0 -4044 0 -4045 1 -4046 0 -4047 0 -4048 0 -4049 0 -4050 0 -4051 0 -4052 0 -4053 0 -4054 0 -4055 0 -4056 1 -4057 0 -4058 0 -4059 0 -4060 0 -4061 0 -4062 0 -4063 0 -4064 0 -4065 0 -4066 1 -4067 0 -4068 0 -4069 0 -4070 0 -4071 0 -4072 0 -4073 0 -4074 1 -4075 0 -4076 0 -4077 0 -4078 0 -4079 0 -4080 0 -4081 0 -4082 0 -4083 0 -4084 1 -4085 0 -4086 0 -4087 0 -4088 0 -4089 0 -4090 0 -4091 0 -4092 0 -4093 1 -4094 0 -4095 0 -4096 0 -4097 0 -4098 0 -4099 0 -4100 0 -4101 0 -4102 1 -4103 0 -4104 0 -4105 0 -4106 0 -4107 0 -4108 0 -4109 0 -4110 0 -4111 0 -4112 1 -4113 0 -4114 0 -4115 0 -4116 0 -4117 0 -4118 0 -4119 0 -4120 0 -4121 0 -4122 1 -4123 0 -4124 0 -4125 0 -4126 0 -4127 0 -4128 0 -4129 0 -4130 0 -4131 0 -4132 0 -4133 1 -4134 0 -4135 0 -4136 0 -4137 0 -4138 0 -4139 0 -4140 0 -4141 0 -4142 0 -4143 0 -4144 1 -4145 0 -4146 0 -4147 0 -4148 0 -4149 0 -4150 0 -4151 0 -4152 0 -4153 0 -4154 1 -4155 0 -4156 0 -4157 0 -4158 0 -4159 0 -4160 0 -4161 0 -4162 0 -4163 0 -4164 0 -4165 1 -4166 0 -4167 0 -4168 0 -4169 0 -4170 0 -4171 0 -4172 0 -4173 0 -4174 0 -4175 0 -4176 1 -4177 0 -4178 0 -4179 0 -4180 0 -4181 0 -4182 0 -4183 0 -4184 0 -4185 1 -4186 0 -4187 0 -4188 0 -4189 0 -4190 0 -4191 0 -4192 0 -4193 0 -4194 0 -4195 1 -4196 0 -4197 0 -4198 0 -4199 0 -4200 0 -4201 0 -4202 0 -4203 0 -4204 0 -4205 0 -4206 0 -4207 0 -4208 0 -4209 0 -4210 0 -4211 0 -4212 1 -4213 0 -4214 0 -4215 0 -4216 0 -4217 0 -4218 0 -4219 0 -4220 0 -4221 1 -4222 0 -4223 0 -4224 0 -4225 0 -4226 0 -4227 0 -4228 0 -4229 0 -4230 1 -4231 0 -4232 0 -4233 0 -4234 0 -4235 0 -4236 0 -4237 0 -4238 0 -4239 1 -4240 0 -4241 0 -4242 0 -4243 0 -4244 0 -4245 0 -4246 0 -4247 0 -4248 0 -4249 1 -4250 0 -4251 0 -4252 0 -4253 0 -4254 0 -4255 0 -4256 0 -4257 0 -4258 1 -4259 0 -4260 0 -4261 0 -4262 0 -4263 0 -4264 0 -4265 0 -4266 0 -4267 0 -4268 1 -4269 0 -4270 0 -4271 0 -4272 0 -4273 0 -4274 0 -4275 0 -4276 0 -4277 0 -4278 1 -4279 0 -4280 0 -4281 0 -4282 0 -4283 0 -4284 0 -4285 0 -4286 0 -4287 0 -4288 0 -4289 1 -4290 0 -4291 0 -4292 0 -4293 0 -4294 0 -4295 0 -4296 0 -4297 0 -4298 0 -4299 1 -4300 0 -4301 0 -4302 0 -4303 0 -4304 0 -4305 0 -4306 0 -4307 0 -4308 0 -4309 1 -4310 0 -4311 0 -4312 0 -4313 0 -4314 0 -4315 0 -4316 0 -4317 0 -4318 1 -4319 0 -4320 0 -4321 0 -4322 0 -4323 0 -4324 0 -4325 0 -4326 0 -4327 1 -4328 0 -4329 0 -4330 0 -4331 0 -4332 0 -4333 0 -4334 0 -4335 0 -4336 0 -4337 1 -4338 0 -4339 0 -4340 0 -4341 0 -4342 0 -4343 0 -4344 0 -4345 0 -4346 0 -4347 1 -4348 0 -4349 0 -4350 0 -4351 0 -4352 0 -4353 0 -4354 0 -4355 1 -4356 0 -4357 0 -4358 0 -4359 0 -4360 0 -4361 0 -4362 0 -4363 0 -4364 0 -4365 0 -4366 0 -4367 0 -4368 0 -4369 0 -4370 0 -4371 0 -4372 0 -4373 0 -4374 1 -4375 0 -4376 0 -4377 0 -4378 0 -4379 0 -4380 0 -4381 0 -4382 0 -4383 0 -4384 1 -4385 0 -4386 0 -4387 0 -4388 0 -4389 0 -4390 0 -4391 0 -4392 0 -4393 1 -4394 0 -4395 0 -4396 0 -4397 0 -4398 0 -4399 0 -4400 0 -4401 0 -4402 0 -4403 1 -4404 0 -4405 0 -4406 0 -4407 0 -4408 0 -4409 0 -4410 0 -4411 0 -4412 1 -4413 0 -4414 0 -4415 0 -4416 0 -4417 0 -4418 0 -4419 0 -4420 0 -4421 0 -4422 0 -4423 1 -4424 0 -4425 0 -4426 0 -4427 0 -4428 0 -4429 0 -4430 2 -4431 0 -4432 0 -4433 0 -4434 0 -4435 0 -4436 0 -4437 1 -4438 0 -4439 0 -4440 0 -4441 0 -4442 0 -4443 0 -4444 0 -4445 1 -4446 0 -4447 0 -4448 0 -4449 0 -4450 0 -4451 0 -4452 0 -4453 0 -4454 1 -4455 0 -4456 0 -4457 0 -4458 0 -4459 0 -4460 0 -4461 0 -4462 1 -4463 0 -4464 0 -4465 0 -4466 0 -4467 0 -4468 0 -4469 0 -4470 0 -4471 1 -4472 0 -4473 0 -4474 0 -4475 0 -4476 0 -4477 0 -4478 0 -4479 0 -4480 1 -4481 0 -4482 0 -4483 0 -4484 0 -4485 0 -4486 0 -4487 0 -4488 1 -4489 0 -4490 0 -4491 0 -4492 0 -4493 0 -4494 0 -4495 0 -4496 0 -4497 1 -4498 0 -4499 0 -4500 0 -4501 0 -4502 0 -4503 0 -4504 0 -4505 1 -4506 0 -4507 0 -4508 0 -4509 0 -4510 0 -4511 0 -4512 0 -4513 1 -4514 0 -4515 0 -4516 0 -4517 0 -4518 0 -4519 0 -4520 1 -4521 0 -4522 0 -4523 0 -4524 0 -4525 0 -4526 0 -4527 0 -4528 0 -4529 1 -4530 0 -4531 0 -4532 0 -4533 0 -4534 0 -4535 0 -4536 0 -4537 0 -4538 1 -4539 0 -4540 0 -4541 0 -4542 0 -4543 0 -4544 0 -4545 0 -4546 1 -4547 0 -4548 0 -4549 0 -4550 0 -4551 0 -4552 1 -4553 0 -4554 0 -4555 0 -4556 0 -4557 0 -4558 0 -4559 1 -4560 0 -4561 0 -4562 0 -4563 0 -4564 0 -4565 0 -4566 0 -4567 1 -4568 0 -4569 0 -4570 0 -4571 0 -4572 0 -4573 0 -4574 0 -4575 1 -4576 0 -4577 0 -4578 0 -4579 0 -4580 0 -4581 0 -4582 0 -4583 1 -4584 0 -4585 0 -4586 0 -4587 0 -4588 0 -4589 0 -4590 0 -4591 1 -4592 0 -4593 0 -4594 0 -4595 0 -4596 0 -4597 0 -4598 0 -4599 0 -4600 1 -4601 0 -4602 0 -4603 0 -4604 0 -4605 0 -4606 0 -4607 1 -4608 0 -4609 0 -4610 0 -4611 0 -4612 0 -4613 0 -4614 0 -4615 0 -4616 1 -4617 0 -4618 0 -4619 0 -4620 0 -4621 0 -4622 0 -4623 0 -4624 0 -4625 1 -4626 0 -4627 0 -4628 0 -4629 0 -4630 0 -4631 0 -4632 0 -4633 0 -4634 1 -4635 0 -4636 0 -4637 0 -4638 0 -4639 0 -4640 0 -4641 0 -4642 0 -4643 0 -4644 0 -4645 0 -4646 0 -4647 0 -4648 0 -4649 0 -4650 0 -4651 0 -4652 1 -4653 0 -4654 0 -4655 0 -4656 0 -4657 0 -4658 0 -4659 0 -4660 0 -4661 1 -4662 0 -4663 0 -4664 0 -4665 1 -4666 0 -4667 0 -4668 0 -4669 0 -4670 0 -4671 0 -4672 1 -4673 0 -4674 0 -4675 0 -4676 0 -4677 0 -4678 1 -4679 0 -4680 0 -4681 0 -4682 0 -4683 0 -4684 0 -4685 0 -4686 1 -4687 0 -4688 0 -4689 0 -4690 0 -4691 0 -4692 0 -4693 0 -4694 1 -4695 0 -4696 0 -4697 0 -4698 0 -4699 0 -4700 0 -4701 0 -4702 1 -4703 0 -4704 0 -4705 0 -4706 0 -4707 0 -4708 0 -4709 1 -4710 0 -4711 0 -4712 0 -4713 0 -4714 0 -4715 0 -4716 0 -4717 1 -4718 0 -4719 0 -4720 0 -4721 0 -4722 0 -4723 0 -4724 0 -4725 1 -4726 0 -4727 0 -4728 0 -4729 0 -4730 0 -4731 0 -4732 0 -4733 0 -4734 1 -4735 0 -4736 0 -4737 0 -4738 0 -4739 0 -4740 0 -4741 0 -4742 0 -4743 0 -4744 1 -4745 0 -4746 0 -4747 0 -4748 0 -4749 0 -4750 0 -4751 0 -4752 1 -4753 0 -4754 0 -4755 0 -4756 0 -4757 0 -4758 0 -4759 0 -4760 1 -4761 0 -4762 0 -4763 0 -4764 0 -4765 0 -4766 0 -4767 0 -4768 0 -4769 1 -4770 0 -4771 0 -4772 0 -4773 0 -4774 0 -4775 0 -4776 0 -4777 0 -4778 1 -4779 0 -4780 0 -4781 0 -4782 0 -4783 0 -4784 0 -4785 0 -4786 1 -4787 0 -4788 0 -4789 0 -4790 0 -4791 0 -4792 0 -4793 0 -4794 0 -4795 0 -4796 1 -4797 0 -4798 0 -4799 0 -4800 0 -4801 0 -4802 0 -4803 0 -4804 1 -4805 0 -4806 0 -4807 0 -4808 0 -4809 0 -4810 0 -4811 0 -4812 0 -4813 1 -4814 0 -4815 0 -4816 0 -4817 0 -4818 0 -4819 0 -4820 0 -4821 0 -4822 1 -4823 0 -4824 0 -4825 0 -4826 0 -4827 0 -4828 0 -4829 0 -4830 0 -4831 1 -4832 0 -4833 0 -4834 0 -4835 0 -4836 0 -4837 0 -4838 0 -4839 0 -4840 0 -4841 0 -4842 0 -4843 0 -4844 0 -4845 0 -4846 0 -4847 0 -4848 0 -4849 0 -4850 0 -4851 0 -4852 0 -4853 0 -4854 0 -4855 0 -4856 0 -4857 0 -4858 0 -4859 0 -4860 0 -4861 0 -4862 0 -4863 0 -4864 0 -4865 1 -4866 0 -4867 0 -4868 0 -4869 0 -4870 0 -4871 0 -4872 1 -4873 0 -4874 0 -4875 0 -4876 0 -4877 0 -4878 0 -4879 0 -4880 1 -4881 0 -4882 0 -4883 0 -4884 0 -4885 0 -4886 0 -4887 0 -4888 0 -4889 0 -4890 1 -4891 0 -4892 0 -4893 0 -4894 0 -4895 0 -4896 0 -4897 0 -4898 1 -4899 0 -4900 0 -4901 0 -4902 0 -4903 0 -4904 0 -4905 1 -4906 0 -4907 0 -4908 0 -4909 0 -4910 0 -4911 0 -4912 0 -4913 1 -4914 0 -4915 0 -4916 0 -4917 0 -4918 0 -4919 0 -4920 0 -4921 0 -4922 0 -4923 1 -4924 0 -4925 0 -4926 0 -4927 0 -4928 0 -4929 0 -4930 0 -4931 0 -4932 0 -4933 1 -4934 0 -4935 0 -4936 0 -4937 0 -4938 0 -4939 0 -4940 0 -4941 0 -4942 0 -4943 0 -4944 0 -4945 0 -4946 0 -4947 0 -4948 1 -4949 0 -4950 0 -4951 0 -4952 0 -4953 0 -4954 0 -4955 0 -4956 1 -4957 0 -4958 0 -4959 0 -4960 0 -4961 0 -4962 0 -4963 0 -4964 1 -4965 0 -4966 0 -4967 0 -4968 0 -4969 0 -4970 0 -4971 0 -4972 1 -4973 0 -4974 0 -4975 0 -4976 0 -4977 0 -4978 0 -4979 1 -4980 0 -4981 0 -4982 0 -4983 0 -4984 0 -4985 0 -4986 0 -4987 1 -4988 0 -4989 0 -4990 0 -4991 0 -4992 0 -4993 0 -4994 1 -4995 0 -4996 0 -4997 0 -4998 0 -4999 0 -5000 0 -5001 0 -5002 0 -5003 1 -5004 0 -5005 0 -5006 0 -5007 0 -5008 0 -5009 0 -5010 0 -5011 0 -5012 1 -5013 0 -5014 0 -5015 0 -5016 0 -5017 0 -5018 0 -5019 0 -5020 1 -5021 0 -5022 0 -5023 0 -5024 0 -5025 0 -5026 0 -5027 0 -5028 0 -5029 1 -5030 0 -5031 0 -5032 0 -5033 0 -5034 0 -5035 0 -5036 0 -5037 1 -5038 0 -5039 0 -5040 0 -5041 0 -5042 0 -5043 0 -5044 0 -5045 1 -5046 0 -5047 0 -5048 0 -5049 0 -5050 0 -5051 0 -5052 0 -5053 1 -5054 0 -5055 0 -5056 0 -5057 0 -5058 0 -5059 0 -5060 0 -5061 0 -5062 1 -5063 0 -5064 0 -5065 0 -5066 0 -5067 0 -5068 0 -5069 0 -5070 0 -5071 0 -5072 0 -5073 0 -5074 0 -5075 0 -5076 0 -5077 0 -5078 0 -5079 1 -5080 0 -5081 0 -5082 0 -5083 0 -5084 0 -5085 0 -5086 1 -5087 0 -5088 0 -5089 0 -5090 0 -5091 0 -5092 0 -5093 0 -5094 1 -5095 0 -5096 0 -5097 0 -5098 0 -5099 0 -5100 0 -5101 0 -5102 0 -5103 1 -5104 0 -5105 0 -5106 0 -5107 0 -5108 0 -5109 0 -5110 1 -5111 0 -5112 0 -5113 0 -5114 0 -5115 0 -5116 0 -5117 0 -5118 1 -5119 0 -5120 0 -5121 0 -5122 0 -5123 0 -5124 0 -5125 0 -5126 0 -5127 1 -5128 0 -5129 0 -5130 0 -5131 0 -5132 0 -5133 0 -5134 1 -5135 0 -5136 0 -5137 0 -5138 0 -5139 0 -5140 0 -5141 1 -5142 0 -5143 0 -5144 0 -5145 0 -5146 0 -5147 0 -5148 0 -5149 1 -5150 0 -5151 0 -5152 0 -5153 0 -5154 0 -5155 0 -5156 0 -5157 0 -5158 1 -5159 0 -5160 0 -5161 0 -5162 0 -5163 0 -5164 0 -5165 0 -5166 0 -5167 1 -5168 0 -5169 0 -5170 0 -5171 0 -5172 0 -5173 0 -5174 0 -5175 1 -5176 0 -5177 0 -5178 0 -5179 0 -5180 0 -5181 0 -5182 1 -5183 0 -5184 0 -5185 0 -5186 0 -5187 0 -5188 0 -5189 0 -5190 1 -5191 0 -5192 0 -5193 0 -5194 0 -5195 0 -5196 0 -5197 0 -5198 0 -5199 1 -5200 0 -5201 0 -5202 0 -5203 0 -5204 0 -5205 0 -5206 0 -5207 0 -5208 1 -5209 0 -5210 0 -5211 0 -5212 0 -5213 0 -5214 0 -5215 0 -5216 0 -5217 0 -5218 1 -5219 0 -5220 0 -5221 0 -5222 0 -5223 0 -5224 0 -5225 0 -5226 1 -5227 0 -5228 0 -5229 0 -5230 0 -5231 0 -5232 0 -5233 0 -5234 1 -5235 0 -5236 0 -5237 0 -5238 0 -5239 0 -5240 0 -5241 0 -5242 1 -5243 0 -5244 0 -5245 0 -5246 0 -5247 0 -5248 0 -5249 0 -5250 0 -5251 1 -5252 0 -5253 0 -5254 0 -5255 0 -5256 0 -5257 0 -5258 0 -5259 0 -5260 0 -5261 0 -5262 0 -5263 0 -5264 0 -5265 0 -5266 0 -5267 0 -5268 1 -5269 0 -5270 0 -5271 0 -5272 0 -5273 0 -5274 0 -5275 0 -5276 1 -5277 0 -5278 0 -5279 0 -5280 0 -5281 0 -5282 0 -5283 1 -5284 0 -5285 0 -5286 0 -5287 0 -5288 0 -5289 0 -5290 0 -5291 0 -5292 0 -5293 1 -5294 0 -5295 0 -5296 0 -5297 0 -5298 0 -5299 0 -5300 0 -5301 1 -5302 0 -5303 0 -5304 0 -5305 0 -5306 0 -5307 0 -5308 0 -5309 0 -5310 1 -5311 0 -5312 0 -5313 0 -5314 0 -5315 0 -5316 0 -5317 0 -5318 1 -5319 0 -5320 0 -5321 0 -5322 0 -5323 0 -5324 0 -5325 1 -5326 0 -5327 0 -5328 0 -5329 0 -5330 0 -5331 0 -5332 0 -5333 0 -5334 0 -5335 0 -5336 0 -5337 0 -5338 0 -5339 0 -5340 0 -5341 0 -5342 1 -5343 0 -5344 0 -5345 0 -5346 0 -5347 0 -5348 0 -5349 1 -5350 0 -5351 0 -5352 0 -5353 0 -5354 0 -5355 0 -5356 0 -5357 0 -5358 1 -5359 0 -5360 0 -5361 0 -5362 0 -5363 0 -5364 0 -5365 0 -5366 1 -5367 0 -5368 0 -5369 0 -5370 0 -5371 0 -5372 0 -5373 1 -5374 0 -5375 0 -5376 0 -5377 0 -5378 0 -5379 0 -5380 0 -5381 1 -5382 0 -5383 0 -5384 0 -5385 0 -5386 0 -5387 0 -5388 0 -5389 0 -5390 1 -5391 0 -5392 0 -5393 0 -5394 0 -5395 0 -5396 0 -5397 0 -5398 1 -5399 0 -5400 0 -5401 0 -5402 0 -5403 0 -5404 0 -5405 0 -5406 1 -5407 0 -5408 0 -5409 0 -5410 0 -5411 0 -5412 0 -5413 0 -5414 1 -5415 0 -5416 0 -5417 0 -5418 0 -5419 0 -5420 0 -5421 0 -5422 1 -5423 0 -5424 0 -5425 0 -5426 0 -5427 0 -5428 0 -5429 0 -5430 0 -5431 0 -5432 0 -5433 0 -5434 0 -5435 0 -5436 0 -5437 0 -5438 1 -5439 0 -5440 0 -5441 0 -5442 0 -5443 0 -5444 0 -5445 0 -5446 0 -5447 1 -5448 0 -5449 0 -5450 0 -5451 0 -5452 0 -5453 0 -5454 0 -5455 0 -5456 1 -5457 0 -5458 0 -5459 0 -5460 0 -5461 0 -5462 0 -5463 0 -5464 1 -5465 0 -5466 0 -5467 0 -5468 0 -5469 0 -5470 0 -5471 0 -5472 1 -5473 0 -5474 0 -5475 0 -5476 0 -5477 0 -5478 0 -5479 0 -5480 0 -5481 1 -5482 0 -5483 0 -5484 0 -5485 0 -5486 0 -5487 0 -5488 0 -5489 1 -5490 0 -5491 0 -5492 0 -5493 0 -5494 0 -5495 0 -5496 0 -5497 0 -5498 1 -5499 0 -5500 0 -5501 0 -5502 0 -5503 0 -5504 0 -5505 0 -5506 1 -5507 0 -5508 0 -5509 0 -5510 0 -5511 0 -5512 0 -5513 0 -5514 1 -5515 0 -5516 0 -5517 0 -5518 0 -5519 0 -5520 0 -5521 0 -5522 0 -5523 1 -5524 0 -5525 0 -5526 0 -5527 0 -5528 0 -5529 0 -5530 0 -5531 1 -5532 0 -5533 0 -5534 0 -5535 0 -5536 0 -5537 0 -5538 0 -5539 0 -5540 1 -5541 0 -5542 0 -5543 0 -5544 0 -5545 0 -5546 0 -5547 0 -5548 0 -5549 1 -5550 0 -5551 0 -5552 0 -5553 0 -5554 0 -5555 0 -5556 0 -5557 0 -5558 0 -5559 0 -5560 0 -5561 0 -5562 0 -5563 0 -5564 0 -5565 1 -5566 0 -5567 0 -5568 0 -5569 0 -5570 0 -5571 1 -5572 0 -5573 0 -5574 0 -5575 0 -5576 0 -5577 0 -5578 0 -5579 1 -5580 0 -5581 0 -5582 0 -5583 0 -5584 0 -5585 0 -5586 0 -5587 0 -5588 1 -5589 0 -5590 0 -5591 0 -5592 0 -5593 0 -5594 0 -5595 0 -5596 1 -5597 0 -5598 0 -5599 0 -5600 0 -5601 0 -5602 0 -5603 0 -5604 0 -5605 0 -5606 1 -5607 0 -5608 0 -5609 0 -5610 0 -5611 0 -5612 0 -5613 0 -5614 1 -5615 0 -5616 0 -5617 0 -5618 0 -5619 0 -5620 0 -5621 0 -5622 1 -5623 0 -5624 0 -5625 0 -5626 0 -5627 0 -5628 0 -5629 0 -5630 0 -5631 0 -5632 0 -5633 0 -5634 0 -5635 0 -5636 0 -5637 0 -5638 1 -5639 0 -5640 0 -5641 0 -5642 0 -5643 0 -5644 0 -5645 0 -5646 0 -5647 1 -5648 0 -5649 0 -5650 0 -5651 0 -5652 0 -5653 0 -5654 1 -5655 0 -5656 0 -5657 0 -5658 0 -5659 0 -5660 0 -5661 0 -5662 1 -5663 0 -5664 0 -5665 0 -5666 0 -5667 0 -5668 0 -5669 0 -5670 1 -5671 0 -5672 0 -5673 0 -5674 0 -5675 0 -5676 0 -5677 0 -5678 0 -5679 1 -5680 2 -5681 1 -5682 0 -5683 0 -5684 0 -5685 0 -5686 0 -5687 1 -5688 0 -5689 0 -5690 0 -5691 0 -5692 1 -5693 0 -5694 0 -5695 0 -5696 0 -5697 1 -5698 0 -5699 0 -5700 0 -5701 0 -5702 0 -5703 0 -5704 0 -5705 1 -5706 0 -5707 0 -5708 0 -5709 0 -5710 0 -5711 1 -5712 0 -5713 0 -5714 0 -5715 0 -5716 0 -5717 0 -5718 0 -5719 0 -5720 0 -5721 0 -5722 0 -5723 0 -5724 0 -5725 0 -5726 1 -5727 0 -5728 0 -5729 0 -5730 0 -5731 0 -5732 0 -5733 0 -5734 1 -5735 0 -5736 0 -5737 0 -5738 0 -5739 0 -5740 0 -5741 0 -5742 1 -5743 0 -5744 0 -5745 0 -5746 0 -5747 0 -5748 0 -5749 0 -5750 0 -5751 1 -5752 0 -5753 0 -5754 0 -5755 0 -5756 0 -5757 0 -5758 0 -5759 1 -5760 0 -5761 0 -5762 0 -5763 0 -5764 0 -5765 0 -5766 1 -5767 0 -5768 0 -5769 0 -5770 0 -5771 0 -5772 0 -5773 0 -5774 1 -5775 0 -5776 0 -5777 0 -5778 0 -5779 0 -5780 0 -5781 0 -5782 1 -5783 0 -5784 0 -5785 0 -5786 0 -5787 0 -5788 0 -5789 0 -5790 0 -5791 1 -5792 0 -5793 0 -5794 0 -5795 0 -5796 0 -5797 0 -5798 0 -5799 0 -5800 1 -5801 0 -5802 0 -5803 0 -5804 0 -5805 0 -5806 0 -5807 0 -5808 0 -5809 1 -5810 0 -5811 0 -5812 0 -5813 0 -5814 0 -5815 0 -5816 1 -5817 0 -5818 0 -5819 0 -5820 0 -5821 0 -5822 0 -5823 0 -5824 0 -5825 1 -5826 0 -5827 0 -5828 0 -5829 0 -5830 0 -5831 0 -5832 0 -5833 0 -5834 1 -5835 0 -5836 0 -5837 0 -5838 0 -5839 0 -5840 0 -5841 0 -5842 1 -5843 0 -5844 0 -5845 0 -5846 0 -5847 0 -5848 0 -5849 0 -5850 1 -5851 0 -5852 0 -5853 0 -5854 0 -5855 0 -5856 0 -5857 0 -5858 1 -5859 0 -5860 0 -5861 0 -5862 0 -5863 0 -5864 0 -5865 0 -5866 0 -5867 1 -5868 0 -5869 0 -5870 0 -5871 0 -5872 0 -5873 0 -5874 0 -5875 1 -5876 0 -5877 0 -5878 0 -5879 0 -5880 0 -5881 0 -5882 0 -5883 0 -5884 1 -5885 0 -5886 0 -5887 0 -5888 0 -5889 0 -5890 0 -5891 1 -5892 0 -5893 0 -5894 0 -5895 0 -5896 0 -5897 0 -5898 0 -5899 0 -5900 1 -5901 0 -5902 0 -5903 0 -5904 0 -5905 0 -5906 0 -5907 0 -5908 0 -5909 1 -5910 0 -5911 0 -5912 0 -5913 0 -5914 0 -5915 0 -5916 0 -5917 1 -5918 0 -5919 0 -5920 0 -5921 0 -5922 0 -5923 0 -5924 0 -5925 0 -5926 1 -5927 0 -5928 0 -5929 0 -5930 0 -5931 0 -5932 0 -5933 0 -5934 1 -5935 0 -5936 0 -5937 0 -5938 0 -5939 0 -5940 0 -5941 0 -5942 0 -5943 0 -5944 1 -5945 0 -5946 0 -5947 0 -5948 0 -5949 0 -5950 0 -5951 0 -5952 0 -5953 0 -5954 0 -5955 0 -5956 0 -5957 0 -5958 0 -5959 0 -5960 0 -5961 0 -5962 0 -5963 0 -5964 0 -5965 0 -5966 0 -5967 0 -5968 0 -5969 0 -5970 1 -5971 0 -5972 0 -5973 0 -5974 0 -5975 0 -5976 0 -5977 0 -5978 1 -5979 0 -5980 0 -5981 0 -5982 0 -5983 0 -5984 0 -5985 0 -5986 0 -5987 1 -5988 0 -5989 0 -5990 0 -5991 0 -5992 0 -5993 0 -5994 0 -5995 0 -5996 1 -5997 0 -5998 0 -5999 0 -6000 0 -6001 0 -6002 0 -6003 0 -6004 0 -6005 0 -6006 1 -6007 0 -6008 0 -6009 0 -6010 0 -6011 0 -6012 0 -6013 0 -6014 1 -6015 0 -6016 0 -6017 0 -6018 0 -6019 0 -6020 0 -6021 0 -6022 0 -6023 1 -6024 0 -6025 0 -6026 0 -6027 0 -6028 0 -6029 0 -6030 0 -6031 1 -6032 0 -6033 0 -6034 0 -6035 0 -6036 0 -6037 0 -6038 1 -6039 0 -6040 0 -6041 0 -6042 0 -6043 0 -6044 0 -6045 0 -6046 0 -6047 0 -6048 1 -6049 0 -6050 0 -6051 0 -6052 0 -6053 0 -6054 0 -6055 1 -6056 0 -6057 0 -6058 0 -6059 0 -6060 0 -6061 1 -6062 0 -6063 0 -6064 0 -6065 0 -6066 0 -6067 0 -6068 1 -6069 0 -6070 0 -6071 0 -6072 0 -6073 0 -6074 0 -6075 0 -6076 1 -6077 0 -6078 0 -6079 0 -6080 0 -6081 0 -6082 0 -6083 0 -6084 0 -6085 1 -6086 0 -6087 0 -6088 0 -6089 0 -6090 0 -6091 0 -6092 0 -6093 0 -6094 0 -6095 1 -6096 0 -6097 0 -6098 0 -6099 0 -6100 0 -6101 0 -6102 0 -6103 0 -6104 1 -6105 0 -6106 0 -6107 0 -6108 0 -6109 0 -6110 0 -6111 0 -6112 1 -6113 0 -6114 0 -6115 0 -6116 0 -6117 0 -6118 0 -6119 0 -6120 0 -6121 0 -6122 0 -6123 0 -6124 0 -6125 1 -6126 0 -6127 0 -6128 0 -6129 0 -6130 0 -6131 0 -6132 0 -6133 0 -6134 0 -6135 0 -6136 0 -6137 0 -6138 0 -6139 0 -6140 0 -6141 0 -6142 1 -6143 0 -6144 0 -6145 0 -6146 0 -6147 0 -6148 0 -6149 0 -6150 1 -6151 0 -6152 0 -6153 0 -6154 0 -6155 0 -6156 0 -6157 0 -6158 0 -6159 1 -6160 0 -6161 0 -6162 0 -6163 0 -6164 0 -6165 0 -6166 0 -6167 1 -6168 0 -6169 0 -6170 0 -6171 0 -6172 0 -6173 0 -6174 0 -6175 1 -6176 0 -6177 0 -6178 0 -6179 0 -6180 0 -6181 0 -6182 0 -6183 1 -6184 0 -6185 0 -6186 0 -6187 0 -6188 0 -6189 0 -6190 0 -6191 0 -6192 1 -6193 0 -6194 0 -6195 0 -6196 0 -6197 0 -6198 0 -6199 0 -6200 0 -6201 1 -6202 0 -6203 0 -6204 0 -6205 0 -6206 0 -6207 0 -6208 0 -6209 0 -6210 1 -6211 0 -6212 0 -6213 0 -6214 0 -6215 0 -6216 0 -6217 1 -6218 0 -6219 0 -6220 0 -6221 0 -6222 0 -6223 0 -6224 0 -6225 1 -6226 0 -6227 0 -6228 0 -6229 0 -6230 0 -6231 0 -6232 0 -6233 0 -6234 1 -6235 0 -6236 0 -6237 0 -6238 0 -6239 0 -6240 0 -6241 1 -6242 0 -6243 0 -6244 0 -6245 0 -6246 0 -6247 0 -6248 0 -6249 0 -6250 1 -6251 0 -6252 0 -6253 0 -6254 0 -6255 0 -6256 0 -6257 0 -6258 1 -6259 0 -6260 0 -6261 0 -6262 0 -6263 0 -6264 0 -6265 0 -6266 0 -6267 0 -6268 1 -6269 0 -6270 0 -6271 0 -6272 0 -6273 0 -6274 0 -6275 0 -6276 0 -6277 1 -6278 0 -6279 0 -6280 0 -6281 0 -6282 0 -6283 0 -6284 0 -6285 1 -6286 0 -6287 0 -6288 0 -6289 0 -6290 0 -6291 0 -6292 1 -6293 0 -6294 0 -6295 0 -6296 0 -6297 0 -6298 0 -6299 1 -6300 0 -6301 0 -6302 0 -6303 0 -6304 0 -6305 0 -6306 0 -6307 1 -6308 0 -6309 0 -6310 0 -6311 0 -6312 0 -6313 0 -6314 0 -6315 1 -6316 0 -6317 0 -6318 0 -6319 0 -6320 0 -6321 0 -6322 0 -6323 0 -6324 1 -6325 0 -6326 0 -6327 0 -6328 0 -6329 0 -6330 0 -6331 0 -6332 1 -6333 0 -6334 0 -6335 0 -6336 0 -6337 0 -6338 0 -6339 0 -6340 0 -6341 1 -6342 0 -6343 0 -6344 0 -6345 0 -6346 0 -6347 0 -6348 0 -6349 0 -6350 1 -6351 0 -6352 0 -6353 0 -6354 0 -6355 0 -6356 0 -6357 0 -6358 1 -6359 0 -6360 0 -6361 0 -6362 0 -6363 0 -6364 0 -6365 0 -6366 1 -6367 0 -6368 0 -6369 0 -6370 0 -6371 0 -6372 0 -6373 0 -6374 0 -6375 1 -6376 0 -6377 0 -6378 0 -6379 0 -6380 0 -6381 0 -6382 0 -6383 1 -6384 0 -6385 0 -6386 0 -6387 0 -6388 0 -6389 0 -6390 0 -6391 4 -6392 0 -6393 1 -6394 0 -6395 0 -6396 0 -6397 1 -6398 0 -6399 0 -6400 0 -6401 0 -6402 1 -6403 0 -6404 0 -6405 0 -6406 0 -6407 1 -6408 0 -6409 0 -6410 0 -6411 0 -6412 1 -6413 0 -6414 0 -6415 0 -6416 0 -6417 0 -6418 1 -6419 0 -6420 0 -6421 0 -6422 0 -6423 0 -6424 0 -6425 1 -6426 0 -6427 0 -6428 0 -6429 0 -6430 0 -6431 0 -6432 0 -6433 0 -6434 1 -6435 0 -6436 0 -6437 0 -6438 0 -6439 0 -6440 0 -6441 0 -6442 0 -6443 1 -6444 0 -6445 0 -6446 0 -6447 0 -6448 0 -6449 0 -6450 0 -6451 0 -6452 1 -6453 0 -6454 0 -6455 0 -6456 0 -6457 0 -6458 0 -6459 0 -6460 0 -6461 0 -6462 0 -6463 1 -6464 0 -6465 0 -6466 0 -6467 0 -6468 0 -6469 0 -6470 0 -6471 0 -6472 1 -6473 0 -6474 0 -6475 0 -6476 0 -6477 0 -6478 0 -6479 0 -6480 0 -6481 0 -6482 1 -6483 0 -6484 0 -6485 0 -6486 0 -6487 0 -6488 0 -6489 0 -6490 0 -6491 0 -6492 1 -6493 0 -6494 0 -6495 0 -6496 0 -6497 0 -6498 0 -6499 0 -6500 0 -6501 0 -6502 0 -6503 0 -6504 0 -6505 0 -6506 0 -6507 0 -6508 0 -6509 0 -6510 0 -6511 0 -6512 1 -6513 0 -6514 0 -6515 0 -6516 0 -6517 0 -6518 0 -6519 0 -6520 0 -6521 1 -6522 0 -6523 0 -6524 0 -6525 0 -6526 0 -6527 0 -6528 0 -6529 0 -6530 0 -6531 1 -6532 0 -6533 0 -6534 0 -6535 0 -6536 0 -6537 0 -6538 0 -6539 0 -6540 1 -6541 0 -6542 0 -6543 0 -6544 0 -6545 0 -6546 0 -6547 0 -6548 0 -6549 0 -6550 1 -6551 0 -6552 0 -6553 0 -6554 0 -6555 0 -6556 0 -6557 0 -6558 0 -6559 0 -6560 1 -6561 0 -6562 0 -6563 0 -6564 0 -6565 0 -6566 0 -6567 0 -6568 0 -6569 1 -6570 0 -6571 0 -6572 0 -6573 0 -6574 0 -6575 0 -6576 0 -6577 1 -6578 0 -6579 0 -6580 0 -6581 0 -6582 0 -6583 0 -6584 0 -6585 0 -6586 1 -6587 0 -6588 0 -6589 0 -6590 0 -6591 0 -6592 0 -6593 0 -6594 0 -6595 1 -6596 0 -6597 0 -6598 0 -6599 0 -6600 0 -6601 0 -6602 0 -6603 0 -6604 1 -6605 0 -6606 0 -6607 0 -6608 0 -6609 0 -6610 0 -6611 0 -6612 0 -6613 1 -6614 0 -6615 0 -6616 0 -6617 0 -6618 0 -6619 0 -6620 0 -6621 0 -6622 1 -6623 0 -6624 0 -6625 0 -6626 0 -6627 0 -6628 0 -6629 0 -6630 0 -6631 1 -6632 0 -6633 0 -6634 0 -6635 0 -6636 0 -6637 0 -6638 0 -6639 0 -6640 1 -6641 0 -6642 0 -6643 0 -6644 0 -6645 0 -6646 0 -6647 0 -6648 0 -6649 0 -6650 1 -6651 0 -6652 0 -6653 0 -6654 0 -6655 0 -6656 0 -6657 0 -6658 0 -6659 0 -6660 1 -6661 0 -6662 0 -6663 0 -6664 0 -6665 0 -6666 0 -6667 0 -6668 0 -6669 1 -6670 0 -6671 0 -6672 0 -6673 0 -6674 0 -6675 0 -6676 0 -6677 0 -6678 0 -6679 1 -6680 0 -6681 0 -6682 0 -6683 0 -6684 0 -6685 0 -6686 0 -6687 0 -6688 1 -6689 0 -6690 0 -6691 0 -6692 0 -6693 0 -6694 0 -6695 0 -6696 0 -6697 0 -6698 1 -6699 0 -6700 0 -6701 0 -6702 0 -6703 0 -6704 0 -6705 0 -6706 1 -6707 0 -6708 0 -6709 0 -6710 0 -6711 0 -6712 0 -6713 0 -6714 0 -6715 0 -6716 1 -6717 0 -6718 0 -6719 0 -6720 0 -6721 0 -6722 0 -6723 0 -6724 0 -6725 0 -6726 1 -6727 0 -6728 0 -6729 0 -6730 0 -6731 0 -6732 0 -6733 0 -6734 0 -6735 0 -6736 0 -6737 1 -6738 0 -6739 0 -6740 0 -6741 0 -6742 0 -6743 0 -6744 0 -6745 0 -6746 1 -6747 0 -6748 0 -6749 0 -6750 0 -6751 0 -6752 0 -6753 0 -6754 0 -6755 0 -6756 1 -6757 0 -6758 0 -6759 0 -6760 0 -6761 0 -6762 0 -6763 0 -6764 0 -6765 0 -6766 1 -6767 0 -6768 0 -6769 0 -6770 0 -6771 0 -6772 0 -6773 0 -6774 0 -6775 1 -6776 0 -6777 0 -6778 0 -6779 0 -6780 0 -6781 0 -6782 0 -6783 0 -6784 1 -6785 0 -6786 0 -6787 0 -6788 0 -6789 0 -6790 0 -6791 0 -6792 0 -6793 0 -6794 1 -6795 0 -6796 0 -6797 0 -6798 0 -6799 0 -6800 0 -6801 0 -6802 0 -6803 1 -6804 0 -6805 0 -6806 0 -6807 0 -6808 0 -6809 0 -6810 0 -6811 0 -6812 0 -6813 1 -6814 0 -6815 0 -6816 0 -6817 0 -6818 0 -6819 0 -6820 0 -6821 0 -6822 0 -6823 0 -6824 1 -6825 0 -6826 0 -6827 0 -6828 0 -6829 0 -6830 0 -6831 0 -6832 1 -6833 0 -6834 0 -6835 0 -6836 0 -6837 0 -6838 0 -6839 0 -6840 0 -6841 0 -6842 1 -6843 0 -6844 0 -6845 0 -6846 0 -6847 0 -6848 0 -6849 0 -6850 0 -6851 1 -6852 0 -6853 0 -6854 0 -6855 0 -6856 0 -6857 0 -6858 0 -6859 0 -6860 0 -6861 0 -6862 1 -6863 0 -6864 0 -6865 0 -6866 0 -6867 0 -6868 0 -6869 0 -6870 0 -6871 1 -6872 0 -6873 0 -6874 0 -6875 0 -6876 0 -6877 0 -6878 0 -6879 1 -6880 0 -6881 0 -6882 0 -6883 0 -6884 0 -6885 0 -6886 1 -6887 0 -6888 0 -6889 0 -6890 0 -6891 0 -6892 0 -6893 0 -6894 0 -6895 1 -6896 0 -6897 0 -6898 0 -6899 0 -6900 0 -6901 0 -6902 0 -6903 0 -6904 0 -6905 0 -6906 0 -6907 0 -6908 0 -6909 0 -6910 0 -6911 0 -6912 0 -6913 0 -6914 1 -6915 0 -6916 0 -6917 0 -6918 0 -6919 0 -6920 0 -6921 0 -6922 0 -6923 1 -6924 0 -6925 0 -6926 0 -6927 0 -6928 0 -6929 0 -6930 0 -6931 0 -6932 0 -6933 0 -6934 1 -6935 0 -6936 0 -6937 0 -6938 0 -6939 0 -6940 0 -6941 0 -6942 0 -6943 0 -6944 1 -6945 0 -6946 0 -6947 0 -6948 0 -6949 0 -6950 0 -6951 0 -6952 0 -6953 0 -6954 1 -6955 0 -6956 0 -6957 0 -6958 0 -6959 0 -6960 0 -6961 0 -6962 0 -6963 0 -6964 1 -6965 0 -6966 0 -6967 0 -6968 0 -6969 0 -6970 0 -6971 0 -6972 0 -6973 0 -6974 1 -6975 0 -6976 0 -6977 0 -6978 0 -6979 0 -6980 0 -6981 0 -6982 0 -6983 1 -6984 0 -6985 0 -6986 0 -6987 0 -6988 0 -6989 0 -6990 0 -6991 0 -6992 1 -6993 0 -6994 0 -6995 0 -6996 0 -6997 0 -6998 0 -6999 0 -7000 0 -7001 1 -7002 0 -7003 0 -7004 0 -7005 0 -7006 0 -7007 0 -7008 0 -7009 0 -7010 1 -7011 0 -7012 0 -7013 0 -7014 0 -7015 0 -7016 0 -7017 0 -7018 0 -7019 0 -7020 1 -7021 0 -7022 0 -7023 0 -7024 0 -7025 0 -7026 0 -7027 0 -7028 0 -7029 0 -7030 1 -7031 0 -7032 0 -7033 0 -7034 0 -7035 0 -7036 0 -7037 0 -7038 0 -7039 1 -7040 0 -7041 0 -7042 0 -7043 0 -7044 0 -7045 0 -7046 0 -7047 0 -7048 1 -7049 0 -7050 0 -7051 0 -7052 0 -7053 0 -7054 0 -7055 0 -7056 0 -7057 0 -7058 0 -7059 1 -7060 0 -7061 0 -7062 0 -7063 0 -7064 0 -7065 0 -7066 0 -7067 0 -7068 0 -7069 1 -7070 0 -7071 0 -7072 0 -7073 0 -7074 0 -7075 0 -7076 0 -7077 0 -7078 0 -7079 1 -7080 0 -7081 0 -7082 0 -7083 0 -7084 0 -7085 0 -7086 0 -7087 1 -7088 0 -7089 0 -7090 0 -7091 0 -7092 0 -7093 0 -7094 0 -7095 0 -7096 0 -7097 1 -7098 0 -7099 0 -7100 0 -7101 0 -7102 0 -7103 0 -7104 0 -7105 1 -7106 0 -7107 0 -7108 0 -7109 0 -7110 0 -7111 0 -7112 0 -7113 0 -7114 1 -7115 0 -7116 0 -7117 0 -7118 0 -7119 0 -7120 0 -7121 0 -7122 0 -7123 0 -7124 1 -7125 0 -7126 0 -7127 0 -7128 0 -7129 0 -7130 0 -7131 0 -7132 0 -7133 0 -7134 1 -7135 0 -7136 0 -7137 0 -7138 0 -7139 0 -7140 0 -7141 0 -7142 0 -7143 1 -7144 0 -7145 0 -7146 0 -7147 0 -7148 0 -7149 0 -7150 0 -7151 0 -7152 1 -7153 0 -7154 0 -7155 0 -7156 0 -7157 0 -7158 0 -7159 0 -7160 0 -7161 0 -7162 1 -7163 0 -7164 0 -7165 0 -7166 0 -7167 0 -7168 0 -7169 0 -7170 0 -7171 0 -7172 1 -7173 0 -7174 0 -7175 0 -7176 0 -7177 0 -7178 0 -7179 0 -7180 0 -7181 0 -7182 1 -7183 0 -7184 0 -7185 0 -7186 0 -7187 0 -7188 0 -7189 0 -7190 0 -7191 0 -7192 0 -7193 1 -7194 0 -7195 0 -7196 0 -7197 0 -7198 0 -7199 0 -7200 0 -7201 0 -7202 0 -7203 1 -7204 0 -7205 0 -7206 0 -7207 0 -7208 0 -7209 0 -7210 0 -7211 0 -7212 0 -7213 0 -7214 0 -7215 0 -7216 0 -7217 0 -7218 0 -7219 0 -7220 0 -7221 0 -7222 1 -7223 0 -7224 0 -7225 0 -7226 0 -7227 0 -7228 0 -7229 0 -7230 0 -7231 0 -7232 1 -7233 0 -7234 0 -7235 0 -7236 0 -7237 0 -7238 0 -7239 0 -7240 0 -7241 0 -7242 0 -7243 1 -7244 0 -7245 0 -7246 0 -7247 0 -7248 0 -7249 0 -7250 0 -7251 0 -7252 0 -7253 1 -7254 0 -7255 0 -7256 0 -7257 0 -7258 0 -7259 0 -7260 0 -7261 0 -7262 0 -7263 0 -7264 1 -7265 0 -7266 0 -7267 0 -7268 0 -7269 0 -7270 0 -7271 0 -7272 0 -7273 0 -7274 1 -7275 0 -7276 0 -7277 0 -7278 0 -7279 0 -7280 0 -7281 0 -7282 0 -7283 0 -7284 0 -7285 1 -7286 0 -7287 0 -7288 0 -7289 0 -7290 0 -7291 0 -7292 0 -7293 0 -7294 0 -7295 0 -7296 0 -7297 0 -7298 0 -7299 0 -7300 0 -7301 0 -7302 0 -7303 0 -7304 1 -7305 0 -7306 0 -7307 0 -7308 0 -7309 0 -7310 0 -7311 0 -7312 0 -7313 0 -7314 0 -7315 1 -7316 0 -7317 0 -7318 0 -7319 0 -7320 0 -7321 0 -7322 0 -7323 0 -7324 1 -7325 0 -7326 0 -7327 0 -7328 0 -7329 0 -7330 0 -7331 0 -7332 0 -7333 1 -7334 0 -7335 0 -7336 0 -7337 0 -7338 0 -7339 0 -7340 0 -7341 0 -7342 1 -7343 0 -7344 0 -7345 0 -7346 0 -7347 0 -7348 0 -7349 0 -7350 0 -7351 0 -7352 1 -7353 0 -7354 0 -7355 0 -7356 0 -7357 0 -7358 0 -7359 0 -7360 0 -7361 0 -7362 0 -7363 1 -7364 0 -7365 0 -7366 0 -7367 0 -7368 0 -7369 0 -7370 0 -7371 0 -7372 1 -7373 0 -7374 0 -7375 0 -7376 0 -7377 0 -7378 0 -7379 0 -7380 0 -7381 0 -7382 1 -7383 0 -7384 0 -7385 0 -7386 0 -7387 0 -7388 0 -7389 0 -7390 0 -7391 1 -7392 0 -7393 0 -7394 0 -7395 0 -7396 0 -7397 0 -7398 0 -7399 0 -7400 0 -7401 1 -7402 0 -7403 0 -7404 0 -7405 0 -7406 0 -7407 0 -7408 0 -7409 0 -7410 0 -7411 0 -7412 1 -7413 0 -7414 0 -7415 0 -7416 0 -7417 0 -7418 0 -7419 0 -7420 0 -7421 0 -7422 1 -7423 0 -7424 0 -7425 0 -7426 0 -7427 0 -7428 0 -7429 0 -7430 0 -7431 0 -7432 1 -7433 0 -7434 0 -7435 0 -7436 0 -7437 0 -7438 0 -7439 0 -7440 0 -7441 1 -7442 0 -7443 0 -7444 0 -7445 0 -7446 0 -7447 0 -7448 0 -7449 1 -7450 0 -7451 0 -7452 0 -7453 0 -7454 0 -7455 0 -7456 0 -7457 0 -7458 0 -7459 0 -7460 1 -7461 0 -7462 0 -7463 0 -7464 0 -7465 0 -7466 0 -7467 0 -7468 0 -7469 1 -7470 0 -7471 0 -7472 0 -7473 0 -7474 0 -7475 0 -7476 0 -7477 0 -7478 1 -7479 0 -7480 0 -7481 0 -7482 0 -7483 0 -7484 0 -7485 0 -7486 0 -7487 1 -7488 0 -7489 0 -7490 0 -7491 0 -7492 0 -7493 0 -7494 0 -7495 0 -7496 0 -7497 1 -7498 0 -7499 0 -7500 0 -7501 0 -7502 0 -7503 0 -7504 0 -7505 0 -7506 0 -7507 0 -7508 1 -7509 0 -7510 0 -7511 0 -7512 0 -7513 0 -7514 0 -7515 0 -7516 0 -7517 0 -7518 1 -7519 0 -7520 0 -7521 0 -7522 0 -7523 0 -7524 0 -7525 0 -7526 0 -7527 0 -7528 0 -7529 0 -7530 0 -7531 0 -7532 0 -7533 0 -7534 0 -7535 0 -7536 0 -7537 0 -7538 0 -7539 1 -7540 0 -7541 0 -7542 0 -7543 0 -7544 0 -7545 0 -7546 0 -7547 0 -7548 0 -7549 2 -7550 0 -7551 0 -7552 0 -7553 0 -7554 0 -7555 0 -7556 0 -7557 1 -7558 0 -7559 0 -7560 0 -7561 0 -7562 0 -7563 0 -7564 0 -7565 0 -7566 0 -7567 0 -7568 1 -7569 0 -7570 0 -7571 0 -7572 0 -7573 0 -7574 0 -7575 0 -7576 0 -7577 0 -7578 0 -7579 0 -7580 0 -7581 0 -7582 0 -7583 0 -7584 0 -7585 0 -7586 0 -7587 0 -7588 1 -7589 0 -7590 0 -7591 0 -7592 0 -7593 0 -7594 0 -7595 0 -7596 0 -7597 0 -7598 0 -7599 1 -7600 0 -7601 0 -7602 0 -7603 0 -7604 0 -7605 0 -7606 0 -7607 0 -7608 0 -7609 0 -7610 1 -7611 0 -7612 0 -7613 0 -7614 0 -7615 0 -7616 0 -7617 0 -7618 0 -7619 0 -7620 0 -7621 1 -7622 0 -7623 0 -7624 0 -7625 0 -7626 0 -7627 1 -7628 0 -7629 0 -7630 0 -7631 0 -7632 0 -7633 0 -7634 1 -7635 0 -7636 0 -7637 0 -7638 0 -7639 0 -7640 0 -7641 1 -7642 0 -7643 0 -7644 0 -7645 0 -7646 0 -7647 0 -7648 0 -7649 1 -7650 0 -7651 0 -7652 0 -7653 0 -7654 0 -7655 0 -7656 0 -7657 0 -7658 0 -7659 0 -7660 1 -7661 0 -7662 0 -7663 0 -7664 0 -7665 0 -7666 0 -7667 0 -7668 0 -7669 0 -7670 1 -7671 0 -7672 0 -7673 0 -7674 0 -7675 0 -7676 0 -7677 0 -7678 0 -7679 0 -7680 0 -7681 1 -7682 0 -7683 0 -7684 0 -7685 0 -7686 0 -7687 0 -7688 0 -7689 0 -7690 0 -7691 1 -7692 0 -7693 0 -7694 0 -7695 0 -7696 0 -7697 0 -7698 0 -7699 0 -7700 0 -7701 0 -7702 1 -7703 0 -7704 0 -7705 0 -7706 0 -7707 0 -7708 0 -7709 0 -7710 0 -7711 0 -7712 1 -7713 0 -7714 0 -7715 0 -7716 0 -7717 0 -7718 0 -7719 0 -7720 0 -7721 0 -7722 1 -7723 0 -7724 0 -7725 0 -7726 0 -7727 0 -7728 0 -7729 0 -7730 0 -7731 0 -7732 1 -7733 0 -7734 0 -7735 0 -7736 0 -7737 0 -7738 0 -7739 0 -7740 0 -7741 0 -7742 1 -7743 0 -7744 0 -7745 0 -7746 0 -7747 0 -7748 0 -7749 0 -7750 0 -7751 0 -7752 1 -7753 0 -7754 0 -7755 0 -7756 0 -7757 0 -7758 0 -7759 0 -7760 0 -7761 1 -7762 0 -7763 0 -7764 0 -7765 0 -7766 0 -7767 0 -7768 0 -7769 0 -7770 1 -7771 0 -7772 0 -7773 0 -7774 0 -7775 0 -7776 0 -7777 0 -7778 0 -7779 1 -7780 0 -7781 0 -7782 0 -7783 0 -7784 0 -7785 0 -7786 0 -7787 0 -7788 0 -7789 1 -7790 0 -7791 0 -7792 0 -7793 0 -7794 0 -7795 0 -7796 0 -7797 0 -7798 0 -7799 1 -7800 0 -7801 0 -7802 0 -7803 0 -7804 0 -7805 0 -7806 0 -7807 0 -7808 0 -7809 0 -7810 1 -7811 0 -7812 0 -7813 0 -7814 0 -7815 0 -7816 0 -7817 0 -7818 0 -7819 1 -7820 0 -7821 0 -7822 0 -7823 0 -7824 0 -7825 0 -7826 0 -7827 0 -7828 1 -7829 0 -7830 0 -7831 0 -7832 0 -7833 0 -7834 0 -7835 0 -7836 0 -7837 0 -7838 0 -7839 1 -7840 0 -7841 0 -7842 0 -7843 0 -7844 0 -7845 0 -7846 0 -7847 0 -7848 0 -7849 1 -7850 0 -7851 0 -7852 0 -7853 0 -7854 0 -7855 0 -7856 0 -7857 0 -7858 1 -7859 0 -7860 0 -7861 0 -7862 0 -7863 0 -7864 0 -7865 0 -7866 0 -7867 0 -7868 1 -7869 0 -7870 0 -7871 0 -7872 0 -7873 0 -7874 0 -7875 0 -7876 0 -7877 0 -7878 0 -7879 0 -7880 0 -7881 0 -7882 0 -7883 0 -7884 0 -7885 0 -7886 0 -7887 1 -7888 0 -7889 0 -7890 0 -7891 0 -7892 0 -7893 0 -7894 0 -7895 0 -7896 0 -7897 0 -7898 1 -7899 0 -7900 0 -7901 0 -7902 0 -7903 0 -7904 0 -7905 0 -7906 0 -7907 0 -7908 1 -7909 0 -7910 0 -7911 0 -7912 0 -7913 0 -7914 0 -7915 0 -7916 0 -7917 0 -7918 1 -7919 0 -7920 0 -7921 0 -7922 0 -7923 0 -7924 0 -7925 0 -7926 0 -7927 0 -7928 1 -7929 0 -7930 0 -7931 0 -7932 0 -7933 0 -7934 0 -7935 0 -7936 0 -7937 0 -7938 1 -7939 0 -7940 0 -7941 0 -7942 0 -7943 0 -7944 0 -7945 0 -7946 0 -7947 0 -7948 1 -7949 0 -7950 0 -7951 0 -7952 0 -7953 0 -7954 0 -7955 0 -7956 0 -7957 0 -7958 1 -7959 0 -7960 0 -7961 0 -7962 0 -7963 0 -7964 0 -7965 0 -7966 0 -7967 0 -7968 1 -7969 0 -7970 0 -7971 0 -7972 0 -7973 0 -7974 0 -7975 0 -7976 0 -7977 0 -7978 1 -7979 0 -7980 0 -7981 0 -7982 0 -7983 0 -7984 0 -7985 1 -7986 0 -7987 0 -7988 0 -7989 0 -7990 0 -7991 0 -7992 0 -7993 0 -7994 0 -7995 1 -7996 0 -7997 0 -7998 0 -7999 0 -8000 0 -8001 0 -8002 0 -8003 0 -8004 0 -8005 0 -8006 1 -8007 0 -8008 0 -8009 0 -8010 0 -8011 0 -8012 0 -8013 0 -8014 0 -8015 1 -8016 0 -8017 0 -8018 0 -8019 0 -8020 0 -8021 0 -8022 0 -8023 0 -8024 0 -8025 1 -8026 0 -8027 0 -8028 0 -8029 0 -8030 0 -8031 0 -8032 0 -8033 0 -8034 0 -8035 0 -8036 1 -8037 0 -8038 0 -8039 0 -8040 0 -8041 0 -8042 0 -8043 0 -8044 0 -8045 0 -8046 1 -8047 0 -8048 0 -8049 0 -8050 0 -8051 0 -8052 0 -8053 0 -8054 0 -8055 0 -8056 0 -8057 1 -8058 0 -8059 0 -8060 0 -8061 0 -8062 0 -8063 0 -8064 0 -8065 0 -8066 0 -8067 1 -8068 0 -8069 0 -8070 0 -8071 0 -8072 0 -8073 0 -8074 0 -8075 0 -8076 0 -8077 0 -8078 1 -8079 0 -8080 0 -8081 0 -8082 0 -8083 0 -8084 0 -8085 0 -8086 0 -8087 0 -8088 1 -8089 0 -8090 0 -8091 0 -8092 0 -8093 0 -8094 0 -8095 0 -8096 0 -8097 0 -8098 1 -8099 0 -8100 0 -8101 0 -8102 0 -8103 0 -8104 0 -8105 1 -8106 0 -8107 0 -8108 0 -8109 0 -8110 0 -8111 0 -8112 0 -8113 0 -8114 0 -8115 1 -8116 0 -8117 0 -8118 0 -8119 0 -8120 0 -8121 0 -8122 0 -8123 0 -8124 0 -8125 1 -8126 0 -8127 0 -8128 0 -8129 0 -8130 0 -8131 0 -8132 0 -8133 0 -8134 1 -8135 0 -8136 0 -8137 0 -8138 0 -8139 0 -8140 0 -8141 0 -8142 0 -8143 0 -8144 0 -8145 1 -8146 0 -8147 0 -8148 0 -8149 0 -8150 0 -8151 0 -8152 0 -8153 0 -8154 0 -8155 0 -8156 1 -8157 0 -8158 0 -8159 0 -8160 0 -8161 0 -8162 0 -8163 0 -8164 0 -8165 0 -8166 1 -8167 0 -8168 0 -8169 0 -8170 0 -8171 0 -8172 0 -8173 0 -8174 0 -8175 0 -8176 1 -8177 0 -8178 0 -8179 0 -8180 0 -8181 0 -8182 0 -8183 0 -8184 0 -8185 0 -8186 1 -8187 0 -8188 0 -8189 0 -8190 0 -8191 0 -8192 0 -8193 0 -8194 0 -8195 0 -8196 0 -8197 1 -8198 0 -8199 0 -8200 0 -8201 0 -8202 0 -8203 0 -8204 0 -8205 0 -8206 0 -8207 1 -8208 0 -8209 0 -8210 0 -8211 0 -8212 0 -8213 0 -8214 0 -8215 0 -8216 1 -8217 0 -8218 0 -8219 0 -8220 0 -8221 0 -8222 0 -8223 0 -8224 0 -8225 1 -8226 0 -8227 0 -8228 0 -8229 0 -8230 0 -8231 0 -8232 0 -8233 0 -8234 0 -8235 1 -8236 0 -8237 0 -8238 0 -8239 0 -8240 0 -8241 0 -8242 0 -8243 0 -8244 1 -8245 0 -8246 0 -8247 0 -8248 0 -8249 0 -8250 0 -8251 0 -8252 0 -8253 0 -8254 1 -8255 0 -8256 0 -8257 0 -8258 0 -8259 0 -8260 0 -8261 0 -8262 0 -8263 0 -8264 0 -8265 1 -8266 0 -8267 0 -8268 0 -8269 0 -8270 0 -8271 0 -8272 0 -8273 0 -8274 0 -8275 1 -8276 0 -8277 0 -8278 0 -8279 0 -8280 0 -8281 0 -8282 0 -8283 0 -8284 0 -8285 0 -8286 1 -8287 0 -8288 0 -8289 0 -8290 0 -8291 0 -8292 0 -8293 0 -8294 0 -8295 0 -8296 1 -8297 0 -8298 0 -8299 0 -8300 0 -8301 0 -8302 0 -8303 0 -8304 1 -8305 0 -8306 0 -8307 0 -8308 0 -8309 0 -8310 0 -8311 0 -8312 0 -8313 0 -8314 1 -8315 0 -8316 0 -8317 0 -8318 0 -8319 0 -8320 0 -8321 0 -8322 0 -8323 0 -8324 1 -8325 0 -8326 0 -8327 0 -8328 0 -8329 0 -8330 0 -8331 0 -8332 0 -8333 0 -8334 0 -8335 0 -8336 0 -8337 0 -8338 0 -8339 0 -8340 0 -8341 0 -8342 1 -8343 0 -8344 0 -8345 0 -8346 0 -8347 0 -8348 0 -8349 0 -8350 0 -8351 1 -8352 0 -8353 0 -8354 0 -8355 0 -8356 0 -8357 0 -8358 0 -8359 0 -8360 0 -8361 1 -8362 0 -8363 0 -8364 0 -8365 0 -8366 0 -8367 0 -8368 0 -8369 0 -8370 0 -8371 1 -8372 0 -8373 0 -8374 0 -8375 0 -8376 0 -8377 0 -8378 0 -8379 0 -8380 1 -8381 0 -8382 0 -8383 0 -8384 0 -8385 0 -8386 0 -8387 0 -8388 0 -8389 1 -8390 0 -8391 0 -8392 0 -8393 0 -8394 0 -8395 0 -8396 0 -8397 0 -8398 0 -8399 1 -8400 0 -8401 0 -8402 0 -8403 0 -8404 0 -8405 0 -8406 0 -8407 0 -8408 0 -8409 1 -8410 0 -8411 0 -8412 0 -8413 0 -8414 0 -8415 0 -8416 0 -8417 0 -8418 0 -8419 1 -8420 0 -8421 0 -8422 0 -8423 0 -8424 0 -8425 0 -8426 0 -8427 0 -8428 0 -8429 0 -8430 1 -8431 0 -8432 0 -8433 0 -8434 0 -8435 0 -8436 0 -8437 0 -8438 1 -8439 0 -8440 0 -8441 0 -8442 0 -8443 0 -8444 0 -8445 0 -8446 0 -8447 1 -8448 0 -8449 0 -8450 0 -8451 0 -8452 0 -8453 0 -8454 0 -8455 0 -8456 0 -8457 1 -8458 0 -8459 0 -8460 0 -8461 0 -8462 0 -8463 0 -8464 0 -8465 0 -8466 0 -8467 1 -8468 0 -8469 0 -8470 0 -8471 0 -8472 0 -8473 0 -8474 0 -8475 0 -8476 0 -8477 1 -8478 0 -8479 0 -8480 0 -8481 0 -8482 0 -8483 0 -8484 0 -8485 0 -8486 1 -8487 0 -8488 0 -8489 0 -8490 0 -8491 0 -8492 0 -8493 0 -8494 0 -8495 0 -8496 0 -8497 0 -8498 0 -8499 0 -8500 0 -8501 0 -8502 0 -8503 0 -8504 0 -8505 0 -8506 1 -8507 0 -8508 0 -8509 0 -8510 0 -8511 0 -8512 0 -8513 0 -8514 0 -8515 0 -8516 0 -8517 0 -8518 0 -8519 0 -8520 0 -8521 0 -8522 0 -8523 1 -8524 0 -8525 0 -8526 0 -8527 0 -8528 0 -8529 0 -8530 0 -8531 0 -8532 1 -8533 0 -8534 0 -8535 0 -8536 0 -8537 0 -8538 0 -8539 0 -8540 0 -8541 1 -8542 0 -8543 0 -8544 0 -8545 0 -8546 0 -8547 0 -8548 0 -8549 1 -8550 0 -8551 0 -8552 0 -8553 0 -8554 0 -8555 0 -8556 0 -8557 0 -8558 0 -8559 1 -8560 0 -8561 0 -8562 0 -8563 0 -8564 0 -8565 0 -8566 0 -8567 0 -8568 1 -8569 0 -8570 0 -8571 0 -8572 0 -8573 0 -8574 0 -8575 0 -8576 0 -8577 1 -8578 0 -8579 0 -8580 0 -8581 0 -8582 0 -8583 0 -8584 0 -8585 0 -8586 1 -8587 0 -8588 0 -8589 0 -8590 0 -8591 0 -8592 0 -8593 0 -8594 0 -8595 0 -8596 1 -8597 0 -8598 0 -8599 0 -8600 0 -8601 0 -8602 0 -8603 0 -8604 0 -8605 0 -8606 1 -8607 0 -8608 0 -8609 0 -8610 0 -8611 0 -8612 0 -8613 0 -8614 0 -8615 0 -8616 1 -8617 0 -8618 0 -8619 0 -8620 0 -8621 0 -8622 0 -8623 0 -8624 0 -8625 1 -8626 0 -8627 0 -8628 0 -8629 0 -8630 0 -8631 0 -8632 0 -8633 1 -8634 0 -8635 0 -8636 0 -8637 0 -8638 0 -8639 0 -8640 0 -8641 0 -8642 0 -8643 1 -8644 0 -8645 0 -8646 0 -8647 0 -8648 0 -8649 0 -8650 0 -8651 1 -8652 0 -8653 0 -8654 0 -8655 0 -8656 0 -8657 0 -8658 0 -8659 0 -8660 1 -8661 0 -8662 0 -8663 0 -8664 0 -8665 0 -8666 0 -8667 0 -8668 0 -8669 1 -8670 0 -8671 0 -8672 0 -8673 0 -8674 0 -8675 0 -8676 0 -8677 1 -8678 0 -8679 0 -8680 0 -8681 0 -8682 0 -8683 0 -8684 0 -8685 0 -8686 1 -8687 0 -8688 0 -8689 0 -8690 0 -8691 0 -8692 0 -8693 0 -8694 0 -8695 0 -8696 1 -8697 0 -8698 0 -8699 0 -8700 0 -8701 0 -8702 0 -8703 0 -8704 0 -8705 1 -8706 0 -8707 0 -8708 0 -8709 0 -8710 0 -8711 0 -8712 0 -8713 0 -8714 0 -8715 1 -8716 0 -8717 0 -8718 0 -8719 0 -8720 0 -8721 0 -8722 0 -8723 0 -8724 0 -8725 1 -8726 0 -8727 0 -8728 0 -8729 0 -8730 0 -8731 0 -8732 0 -8733 0 -8734 0 -8735 1 -8736 0 -8737 0 -8738 0 -8739 0 -8740 0 -8741 0 -8742 0 -8743 0 -8744 0 -8745 1 -8746 0 -8747 0 -8748 0 -8749 0 -8750 0 -8751 0 -8752 0 -8753 0 -8754 0 -8755 1 -8756 0 -8757 0 -8758 0 -8759 0 -8760 0 -8761 0 -8762 0 -8763 1 -8764 0 -8765 0 -8766 0 -8767 0 -8768 0 -8769 0 -8770 1 -8771 0 -8772 0 -8773 0 -8774 0 -8775 0 -8776 0 -8777 0 -8778 0 -8779 0 -8780 1 -8781 0 -8782 0 -8783 0 -8784 0 -8785 0 -8786 0 -8787 0 -8788 0 -8789 1 -8790 0 -8791 0 -8792 0 -8793 0 -8794 0 -8795 0 -8796 0 -8797 0 -8798 1 -8799 0 -8800 0 -8801 0 -8802 0 -8803 0 -8804 0 -8805 0 -8806 0 -8807 3 -8808 0 -8809 0 -8810 1 -8811 0 -8812 0 -8813 0 -8814 0 -8815 1 -8816 0 -8817 0 -8818 0 -8819 0 -8820 1 -8821 0 -8822 0 -8823 0 -8824 1 -8825 0 -8826 0 -8827 0 -8828 0 -8829 0 -8830 1 -8831 0 -8832 0 -8833 0 -8834 0 -8835 0 -8836 0 -8837 1 -8838 0 -8839 0 -8840 0 -8841 0 -8842 0 -8843 0 -8844 0 -8845 1 -8846 0 -8847 0 -8848 0 -8849 0 -8850 0 -8851 0 -8852 0 -8853 0 -8854 0 -8855 1 -8856 0 -8857 0 -8858 0 -8859 0 -8860 0 -8861 0 -8862 0 -8863 0 -8864 0 -8865 1 -8866 0 -8867 0 -8868 0 -8869 0 -8870 0 -8871 0 -8872 1 -8873 0 -8874 0 -8875 0 -8876 0 -8877 0 -8878 0 -8879 0 -8880 1 -8881 0 -8882 0 -8883 0 -8884 0 -8885 0 -8886 0 -8887 0 -8888 1 -8889 0 -8890 0 -8891 0 -8892 0 -8893 0 -8894 0 -8895 0 -8896 0 -8897 0 -8898 0 -8899 0 -8900 0 -8901 0 -8902 0 -8903 0 -8904 0 -8905 1 -8906 0 -8907 0 -8908 0 -8909 0 -8910 0 -8911 0 -8912 1 -8913 0 -8914 0 -8915 0 -8916 0 -8917 0 -8918 0 -8919 0 -8920 1 -8921 0 -8922 0 -8923 0 -8924 0 -8925 0 -8926 0 -8927 0 -8928 0 -8929 1 -8930 0 -8931 0 -8932 0 -8933 0 -8934 0 -8935 0 -8936 0 -8937 0 -8938 0 -8939 1 -8940 0 -8941 0 -8942 0 -8943 0 -8944 0 -8945 0 -8946 0 -8947 0 -8948 0 -8949 1 -8950 0 -8951 0 -8952 0 -8953 0 -8954 0 -8955 0 -8956 0 -8957 0 -8958 0 -8959 1 -8960 0 -8961 0 -8962 0 -8963 0 -8964 0 -8965 0 -8966 0 -8967 0 -8968 0 -8969 1 -8970 0 -8971 0 -8972 0 -8973 0 -8974 0 -8975 0 -8976 0 -8977 0 -8978 1 -8979 0 -8980 0 -8981 0 -8982 0 -8983 0 -8984 0 -8985 0 -8986 0 -8987 1 -8988 0 -8989 0 -8990 0 -8991 0 -8992 0 -8993 0 -8994 0 -8995 0 -8996 0 -8997 1 -8998 0 -8999 0 -9000 0 -9001 0 -9002 0 -9003 0 -9004 0 -9005 0 -9006 1 -9007 0 -9008 0 -9009 0 -9010 0 -9011 0 -9012 0 -9013 0 -9014 1 -9015 0 -9016 0 -9017 0 -9018 0 -9019 0 -9020 0 -9021 0 -9022 1 -9023 0 -9024 0 -9025 0 -9026 0 -9027 0 -9028 0 -9029 0 -9030 1 -9031 0 -9032 0 -9033 0 -9034 0 -9035 0 -9036 0 -9037 0 -9038 1 -9039 0 -9040 0 -9041 0 -9042 0 -9043 0 -9044 0 -9045 0 -9046 0 -9047 1 -9048 0 -9049 0 -9050 0 -9051 0 -9052 0 -9053 0 -9054 0 -9055 1 -9056 0 -9057 0 -9058 0 -9059 0 -9060 0 -9061 0 -9062 0 -9063 1 -9064 0 -9065 0 -9066 0 -9067 0 -9068 0 -9069 0 -9070 0 -9071 0 -9072 0 -9073 1 -9074 0 -9075 0 -9076 0 -9077 0 -9078 0 -9079 0 -9080 0 -9081 0 -9082 0 -9083 0 -9084 0 -9085 0 -9086 0 -9087 0 -9088 0 -9089 0 -9090 0 -9091 0 -9092 1 -9093 0 -9094 0 -9095 0 -9096 0 -9097 0 -9098 0 -9099 0 -9100 1 -9101 0 -9102 0 -9103 0 -9104 0 -9105 0 -9106 0 -9107 0 -9108 1 -9109 0 -9110 0 -9111 0 -9112 0 -9113 0 -9114 0 -9115 0 -9116 0 -9117 1 -9118 0 -9119 0 -9120 0 -9121 0 -9122 0 -9123 0 -9124 0 -9125 0 -9126 1 -9127 0 -9128 0 -9129 0 -9130 0 -9131 0 -9132 0 -9133 0 -9134 0 -9135 1 -9136 0 -9137 0 -9138 0 -9139 0 -9140 0 -9141 0 -9142 0 -9143 1 -9144 0 -9145 0 -9146 0 -9147 0 -9148 0 -9149 0 -9150 0 -9151 0 -9152 1 -9153 0 -9154 0 -9155 0 -9156 0 -9157 0 -9158 0 -9159 0 -9160 0 -9161 1 -9162 0 -9163 0 -9164 0 -9165 0 -9166 0 -9167 0 -9168 0 -9169 1 -9170 0 -9171 0 -9172 0 -9173 0 -9174 0 -9175 0 -9176 0 -9177 0 -9178 1 -9179 0 -9180 0 -9181 0 -9182 0 -9183 0 -9184 0 -9185 0 -9186 0 -9187 0 -9188 1 -9189 0 -9190 0 -9191 0 -9192 0 -9193 0 -9194 0 -9195 0 -9196 0 -9197 1 -9198 0 -9199 0 -9200 0 -9201 0 -9202 0 -9203 0 -9204 0 -9205 0 -9206 0 -9207 0 -9208 0 -9209 0 -9210 0 -9211 0 -9212 0 -9213 0 -9214 0 -9215 0 -9216 0 -9217 0 -9218 0 -9219 0 -9220 0 -9221 1 -9222 0 -9223 0 -9224 0 -9225 0 -9226 0 -9227 0 -9228 1 -9229 0 -9230 0 -9231 0 -9232 0 -9233 0 -9234 0 -9235 0 -9236 0 -9237 1 -9238 0 -9239 0 -9240 0 -9241 0 -9242 0 -9243 0 -9244 0 -9245 0 -9246 1 -9247 0 -9248 0 -9249 0 -9250 0 -9251 0 -9252 0 -9253 0 -9254 0 -9255 1 -9256 0 -9257 0 -9258 0 -9259 0 -9260 0 -9261 1 -9262 0 -9263 0 -9264 0 -9265 0 -9266 0 -9267 0 -9268 0 -9269 0 -9270 0 -9271 0 -9272 0 -9273 0 -9274 0 -9275 0 -9276 1 -9277 0 -9278 0 -9279 0 -9280 0 -9281 0 -9282 0 -9283 0 -9284 0 -9285 0 -9286 0 -9287 0 -9288 0 -9289 0 -9290 1 -9291 0 -9292 0 -9293 0 -9294 0 -9295 0 -9296 0 -9297 0 -9298 0 -9299 0 -9300 1 -9301 0 -9302 0 -9303 0 -9304 0 -9305 0 -9306 0 -9307 0 -9308 1 -9309 0 -9310 0 -9311 0 -9312 0 -9313 0 -9314 0 -9315 0 -9316 1 -9317 0 -9318 0 -9319 0 -9320 0 -9321 0 -9322 0 -9323 1 -9324 0 -9325 0 -9326 0 -9327 0 -9328 0 -9329 0 -9330 0 -9331 1 -9332 0 -9333 0 -9334 0 -9335 0 -9336 0 -9337 0 -9338 1 -9339 0 -9340 0 -9341 0 -9342 0 -9343 0 -9344 0 -9345 1 -9346 0 -9347 0 -9348 0 -9349 0 -9350 0 -9351 0 -9352 0 -9353 0 -9354 0 -9355 1 -9356 0 -9357 0 -9358 0 -9359 0 -9360 0 -9361 0 -9362 0 -9363 1 -9364 0 -9365 0 -9366 0 -9367 0 -9368 0 -9369 0 -9370 1 -9371 0 -9372 0 -9373 0 -9374 0 -9375 0 -9376 0 -9377 0 -9378 1 -9379 0 -9380 0 -9381 0 -9382 0 -9383 0 -9384 0 -9385 0 -9386 0 -9387 0 -9388 0 -9389 0 -9390 0 -9391 0 -9392 0 -9393 0 -9394 0 -9395 1 -9396 0 -9397 0 -9398 0 -9399 0 -9400 0 -9401 0 -9402 0 -9403 1 -9404 0 -9405 0 -9406 0 -9407 0 -9408 0 -9409 0 -9410 0 -9411 0 -9412 1 -9413 0 -9414 0 -9415 0 -9416 0 -9417 0 -9418 0 -9419 0 -9420 1 -9421 0 -9422 0 -9423 0 -9424 0 -9425 0 -9426 0 -9427 0 -9428 0 -9429 1 -9430 0 -9431 0 -9432 0 -9433 0 -9434 0 -9435 0 -9436 0 -9437 0 -9438 0 -9439 1 -9440 0 -9441 0 -9442 0 -9443 0 -9444 0 -9445 0 -9446 0 -9447 0 -9448 0 -9449 1 -9450 0 -9451 0 -9452 0 -9453 0 -9454 0 -9455 0 -9456 0 -9457 1 -9458 0 -9459 0 -9460 0 -9461 0 -9462 0 -9463 0 -9464 1 -9465 0 -9466 0 -9467 0 -9468 0 -9469 0 -9470 0 -9471 0 -9472 0 -9473 1 -9474 0 -9475 0 -9476 0 -9477 0 -9478 0 -9479 0 -9480 0 -9481 1 -9482 0 -9483 0 -9484 0 -9485 0 -9486 0 -9487 0 -9488 1 -9489 0 -9490 0 -9491 0 -9492 0 -9493 0 -9494 0 -9495 0 -9496 0 -9497 1 -9498 0 -9499 0 -9500 0 -9501 0 -9502 0 -9503 0 -9504 0 -9505 0 -9506 0 -9507 0 -9508 0 -9509 0 -9510 0 -9511 0 -9512 0 -9513 0 -9514 1 -9515 0 -9516 0 -9517 0 -9518 0 -9519 0 -9520 0 -9521 0 -9522 1 -9523 0 -9524 0 -9525 0 -9526 0 -9527 0 -9528 0 -9529 0 -9530 1 -9531 0 -9532 0 -9533 0 -9534 0 -9535 0 -9536 0 -9537 0 -9538 1 -9539 0 -9540 0 -9541 0 -9542 0 -9543 0 -9544 0 -9545 0 -9546 0 -9547 1 -9548 0 -9549 0 -9550 0 -9551 0 -9552 0 -9553 0 -9554 0 -9555 1 -9556 0 -9557 0 -9558 0 -9559 0 -9560 0 -9561 0 -9562 0 -9563 1 -9564 0 -9565 0 -9566 0 -9567 0 -9568 0 -9569 0 -9570 0 -9571 0 -9572 1 -9573 0 -9574 0 -9575 0 -9576 0 -9577 0 -9578 0 -9579 0 -9580 1 -9581 0 -9582 0 -9583 0 -9584 0 -9585 0 -9586 0 -9587 0 -9588 0 -9589 1 -9590 0 -9591 0 -9592 0 -9593 0 -9594 0 -9595 0 -9596 0 -9597 0 -9598 0 -9599 0 -9600 0 -9601 0 -9602 0 -9603 0 -9604 0 -9605 0 -9606 0 -9607 0 -9608 1 -9609 0 -9610 0 -9611 0 -9612 0 -9613 0 -9614 0 -9615 1 -9616 0 -9617 0 -9618 0 -9619 0 -9620 0 -9621 0 -9622 1 -9623 0 -9624 0 -9625 0 -9626 0 -9627 0 -9628 0 -9629 0 -9630 1 -9631 0 -9632 0 -9633 0 -9634 0 -9635 0 -9636 0 -9637 0 -9638 0 -9639 1 -9640 0 -9641 0 -9642 0 -9643 0 -9644 0 -9645 0 -9646 0 -9647 0 -9648 1 -9649 0 -9650 0 -9651 0 -9652 0 -9653 0 -9654 0 -9655 0 -9656 1 -9657 0 -9658 0 -9659 0 -9660 0 -9661 0 -9662 0 -9663 1 -9664 0 -9665 0 -9666 0 -9667 0 -9668 0 -9669 0 -9670 0 -9671 0 -9672 0 -9673 1 -9674 0 -9675 0 -9676 0 -9677 0 -9678 0 -9679 0 -9680 0 -9681 1 -9682 0 -9683 0 -9684 0 -9685 0 -9686 0 -9687 0 -9688 0 -9689 1 -9690 0 -9691 0 -9692 0 -9693 0 -9694 0 -9695 0 -9696 1 -9697 0 -9698 0 -9699 0 -9700 0 -9701 0 -9702 0 -9703 0 -9704 1 -9705 0 -9706 0 -9707 0 -9708 0 -9709 0 -9710 0 -9711 0 -9712 1 -9713 0 -9714 0 -9715 0 -9716 0 -9717 0 -9718 0 -9719 0 -9720 0 -9721 0 -9722 1 -9723 0 -9724 0 -9725 0 -9726 0 -9727 0 -9728 0 -9729 0 -9730 0 -9731 1 -9732 0 -9733 0 -9734 0 -9735 0 -9736 0 -9737 0 -9738 0 -9739 0 -9740 1 -9741 0 -9742 0 -9743 0 -9744 0 -9745 0 -9746 0 -9747 0 -9748 0 -9749 1 -9750 0 -9751 0 -9752 0 -9753 0 -9754 0 -9755 0 -9756 1 -9757 0 -9758 0 -9759 0 -9760 0 -9761 0 -9762 0 -9763 0 -9764 0 -9765 0 -9766 0 -9767 0 -9768 0 -9769 0 -9770 0 -9771 0 -9772 0 -9773 1 -9774 0 -9775 0 -9776 0 -9777 0 -9778 0 -9779 0 -9780 1 -9781 0 -9782 0 -9783 0 -9784 0 -9785 0 -9786 0 -9787 0 -9788 1 -9789 0 -9790 0 -9791 0 -9792 0 -9793 0 -9794 0 -9795 0 -9796 0 -9797 0 -9798 0 -9799 0 -9800 0 -9801 0 -9802 0 -9803 1 -9804 0 -9805 0 -9806 0 -9807 0 -9808 0 -9809 0 -9810 0 -9811 0 -9812 1 -9813 0 -9814 0 -9815 0 -9816 0 -9817 0 -9818 0 -9819 0 -9820 1 -9821 0 -9822 0 -9823 0 -9824 0 -9825 0 -9826 0 -9827 0 -9828 0 -9829 1 -9830 0 -9831 0 -9832 0 -9833 0 -9834 0 -9835 0 -9836 0 -9837 0 -9838 1 -9839 0 -9840 0 -9841 0 -9842 0 -9843 0 -9844 0 -9845 0 -9846 0 -9847 0 -9848 1 -9849 0 -9850 0 -9851 0 -9852 0 -9853 0 -9854 4 -9855 0 -9856 0 -9857 1 -9858 0 -9859 0 -9860 0 -9861 0 -9862 1 -9863 0 -9864 0 -9865 0 -9866 0 -9867 0 -9868 1 -9869 0 -9870 0 -9871 0 -9872 0 -9873 1 -9874 0 -9875 0 -9876 0 -9877 0 -9878 1 -9879 0 -9880 0 -9881 0 -9882 0 -9883 0 -9884 0 -9885 0 -9886 1 -9887 0 -9888 0 -9889 0 -9890 0 -9891 0 -9892 0 -9893 0 -9894 0 -9895 1 -9896 0 -9897 0 -9898 0 -9899 0 -9900 0 -9901 0 -9902 0 -9903 0 -9904 1 -9905 0 -9906 0 -9907 0 -9908 0 -9909 0 -9910 0 -9911 0 -9912 0 -9913 0 -9914 0 -9915 0 -9916 0 -9917 0 -9918 0 -9919 0 -9920 0 -9921 0 -9922 0 -9923 0 -9924 1 -9925 0 -9926 0 -9927 0 -9928 0 -9929 0 -9930 0 -9931 0 -9932 0 -9933 0 -9934 1 -9935 0 -9936 0 -9937 0 -9938 0 -9939 0 -9940 0 -9941 0 -9942 0 -9943 0 -9944 1 -9945 0 -9946 0 -9947 0 -9948 0 -9949 0 -9950 0 -9951 0 -9952 0 -9953 0 -9954 1 -9955 0 -9956 0 -9957 0 -9958 0 -9959 0 -9960 0 -9961 0 -9962 0 -9963 1 -9964 0 -9965 0 -9966 0 -9967 0 -9968 0 -9969 0 -9970 0 -9971 0 -9972 1 -9973 0 -9974 0 -9975 0 -9976 0 -9977 0 -9978 0 -9979 0 -9980 0 -9981 0 -9982 0 -9983 1 -9984 0 -9985 0 -9986 0 -9987 0 -9988 0 -9989 0 -9990 0 -9991 0 -9992 0 -9993 1 -9994 0 -9995 0 -9996 0 -9997 0 -9998 0 -9999 0 -10000 0 -10001 0 -10002 0 -10003 0 -10004 1 -10005 0 -10006 0 -10007 0 -10008 0 -10009 0 -10010 0 -10011 0 -10012 0 -10013 1 -10014 0 -10015 0 -10016 0 -10017 0 -10018 0 -10019 0 -10020 0 -10021 0 -10022 0 -10023 1 -10024 0 -10025 0 -10026 0 -10027 0 -10028 0 -10029 0 -10030 0 -10031 1 -10032 0 -10033 0 -10034 0 -10035 0 -10036 0 -10037 0 -10038 0 -10039 0 -10040 0 -10041 1 -10042 0 -10043 0 -10044 0 -10045 0 -10046 0 -10047 0 -10048 0 -10049 0 -10050 0 -10051 1 -10052 0 -10053 0 -10054 0 -10055 0 -10056 0 -10057 0 -10058 0 -10059 0 -10060 1 -10061 0 -10062 0 -10063 0 -10064 0 -10065 0 -10066 0 -10067 0 -10068 0 -10069 1 -10070 0 -10071 0 -10072 0 -10073 0 -10074 0 -10075 0 -10076 0 -10077 0 -10078 1 -10079 0 -10080 0 -10081 0 -10082 0 -10083 0 -10084 0 -10085 0 -10086 0 -10087 1 -10088 0 -10089 0 -10090 0 -10091 0 -10092 0 -10093 0 -10094 0 -10095 0 -10096 0 -10097 1 -10098 0 -10099 0 -10100 0 -10101 0 -10102 0 -10103 0 -10104 0 -10105 0 -10106 0 -10107 0 -10108 1 -10109 0 -10110 0 -10111 0 -10112 0 -10113 0 -10114 0 -10115 0 -10116 0 -10117 0 -10118 1 -10119 0 -10120 0 -10121 0 -10122 0 -10123 0 -10124 0 -10125 0 -10126 0 -10127 1 -10128 0 -10129 0 -10130 0 -10131 0 -10132 0 -10133 0 -10134 0 -10135 0 -10136 0 -10137 1 -10138 0 -10139 0 -10140 0 -10141 0 -10142 0 -10143 0 -10144 0 -10145 0 -10146 0 -10147 1 -10148 0 -10149 0 -10150 0 -10151 0 -10152 0 -10153 0 -10154 0 -10155 0 -10156 0 -10157 1 -10158 0 -10159 0 -10160 0 -10161 0 -10162 0 -10163 0 -10164 0 -10165 0 -10166 0 -10167 1 -10168 0 -10169 0 -10170 0 -10171 0 -10172 0 -10173 0 -10174 0 -10175 0 -10176 1 -10177 0 -10178 0 -10179 0 -10180 0 -10181 0 -10182 0 -10183 0 -10184 0 -10185 1 -10186 0 -10187 0 -10188 0 -10189 0 -10190 0 -10191 0 -10192 0 -10193 1 -10194 0 -10195 0 -10196 0 -10197 0 -10198 0 -10199 0 -10200 0 -10201 1 -10202 0 -10203 0 -10204 0 -10205 0 -10206 0 -10207 0 -10208 0 -10209 0 -10210 0 -10211 1 -10212 0 -10213 0 -10214 0 -10215 0 -10216 0 -10217 0 -10218 0 -10219 0 -10220 1 -10221 0 -10222 0 -10223 0 -10224 0 -10225 0 -10226 0 -10227 0 -10228 0 -10229 0 -10230 1 -10231 0 -10232 0 -10233 0 -10234 0 -10235 0 -10236 0 -10237 0 -10238 0 -10239 0 -10240 1 -10241 0 -10242 0 -10243 0 -10244 0 -10245 0 -10246 0 -10247 0 -10248 0 -10249 0 -10250 1 -10251 0 -10252 0 -10253 0 -10254 0 -10255 0 -10256 0 -10257 0 -10258 0 -10259 0 -10260 1 -10261 0 -10262 0 -10263 0 -10264 1 -10265 0 -10266 0 -10267 0 -10268 0 -10269 0 -10270 1 -10271 0 -10272 0 -10273 0 -10274 0 -10275 0 -10276 0 -10277 0 -10278 1 -10279 0 -10280 0 -10281 0 -10282 0 -10283 0 -10284 0 -10285 0 -10286 1 -10287 0 -10288 0 -10289 0 -10290 0 -10291 0 -10292 0 -10293 0 -10294 0 -10295 0 -10296 1 -10297 0 -10298 0 -10299 0 -10300 0 -10301 0 -10302 0 -10303 0 -10304 0 -10305 1 -10306 0 -10307 0 -10308 0 -10309 0 -10310 0 -10311 0 -10312 0 -10313 0 -10314 1 -10315 0 -10316 0 -10317 0 -10318 0 -10319 0 -10320 0 -10321 0 -10322 0 -10323 1 -10324 0 -10325 0 -10326 0 -10327 0 -10328 0 -10329 0 -10330 0 -10331 0 -10332 0 -10333 1 -10334 0 -10335 0 -10336 0 -10337 0 -10338 0 -10339 0 -10340 0 -10341 0 -10342 0 -10343 0 -10344 0 -10345 0 -10346 0 -10347 0 -10348 0 -10349 0 -10350 0 -10351 1 -10352 0 -10353 0 -10354 0 -10355 0 -10356 0 -10357 0 -10358 0 -10359 0 -10360 1 -10361 0 -10362 0 -10363 0 -10364 0 -10365 0 -10366 0 -10367 0 -10368 0 -10369 0 -10370 1 -10371 0 -10372 0 -10373 0 -10374 0 -10375 0 -10376 0 -10377 0 -10378 0 -10379 0 -10380 1 -10381 0 -10382 0 -10383 0 -10384 0 -10385 0 -10386 0 -10387 1 -10388 0 -10389 0 -10390 0 -10391 0 -10392 0 -10393 0 -10394 0 -10395 1 -10396 0 -10397 0 -10398 0 -10399 0 -10400 0 -10401 0 -10402 0 -10403 0 -10404 1 -10405 0 -10406 0 -10407 0 -10408 0 -10409 0 -10410 0 -10411 0 -10412 0 -10413 0 -10414 1 -10415 0 -10416 0 -10417 0 -10418 0 -10419 0 -10420 0 -10421 0 -10422 0 -10423 1 -10424 0 -10425 0 -10426 0 -10427 0 -10428 0 -10429 0 -10430 0 -10431 0 -10432 0 -10433 1 -10434 0 -10435 0 -10436 0 -10437 0 -10438 0 -10439 0 -10440 0 -10441 0 -10442 0 -10443 1 -10444 0 -10445 0 -10446 0 -10447 0 -10448 0 -10449 0 -10450 0 -10451 0 -10452 1 -10453 0 -10454 0 -10455 0 -10456 0 -10457 0 -10458 0 -10459 0 -10460 1 -10461 0 -10462 0 -10463 0 -10464 0 -10465 0 -10466 0 -10467 0 -10468 0 -10469 1 -10470 0 -10471 0 -10472 0 -10473 0 -10474 0 -10475 0 -10476 0 -10477 0 -10478 0 -10479 1 -10480 0 -10481 0 -10482 0 -10483 0 -10484 0 -10485 0 -10486 0 -10487 0 -10488 0 -10489 1 -10490 0 -10491 0 -10492 0 -10493 0 -10494 0 -10495 0 -10496 0 -10497 0 -10498 1 -10499 0 -10500 0 -10501 0 -10502 0 -10503 0 -10504 0 -10505 0 -10506 1 -10507 0 -10508 0 -10509 0 -10510 0 -10511 0 -10512 0 -10513 0 -10514 0 -10515 0 -10516 0 -10517 1 -10518 0 -10519 0 -10520 0 -10521 0 -10522 0 -10523 0 -10524 0 -10525 0 -10526 0 -10527 1 -10528 0 -10529 0 -10530 0 -10531 0 -10532 0 -10533 0 -10534 0 -10535 0 -10536 1 -10537 0 -10538 0 -10539 0 -10540 0 -10541 0 -10542 0 -10543 0 -10544 0 -10545 1 -10546 0 -10547 0 -10548 0 -10549 0 -10550 0 -10551 0 -10552 0 -10553 0 -10554 0 -10555 1 -10556 0 -10557 0 -10558 0 -10559 0 -10560 0 -10561 0 -10562 0 -10563 0 -10564 0 -10565 0 -10566 1 -10567 0 -10568 0 -10569 0 -10570 0 -10571 0 -10572 0 -10573 0 -10574 0 -10575 0 -10576 0 -10577 0 -10578 0 -10579 0 -10580 0 -10581 0 -10582 0 -10583 0 -10584 0 -10585 0 -10586 0 -10587 1 -10588 0 -10589 0 -10590 0 -10591 0 -10592 0 -10593 0 -10594 0 -10595 0 -10596 0 -10597 0 -10598 1 -10599 0 -10600 0 -10601 0 -10602 0 -10603 0 -10604 0 -10605 0 -10606 0 -10607 0 -10608 0 -10609 1 -10610 0 -10611 0 -10612 0 -10613 0 -10614 0 -10615 0 -10616 0 -10617 1 -10618 0 -10619 0 -10620 0 -10621 0 -10622 0 -10623 0 -10624 0 -10625 1 -10626 0 -10627 0 -10628 0 -10629 0 -10630 0 -10631 0 -10632 0 -10633 0 -10634 1 -10635 0 -10636 0 -10637 0 -10638 0 -10639 0 -10640 0 -10641 0 -10642 0 -10643 0 -10644 1 -10645 0 -10646 0 -10647 0 -10648 0 -10649 0 -10650 0 -10651 0 -10652 0 -10653 1 -10654 0 -10655 0 -10656 0 -10657 0 -10658 0 -10659 0 -10660 0 -10661 1 -10662 0 -10663 0 -10664 0 -10665 0 -10666 0 -10667 0 -10668 0 -10669 0 -10670 0 -10671 1 -10672 0 -10673 0 -10674 0 -10675 0 -10676 0 -10677 0 -10678 0 -10679 0 -10680 0 -10681 1 -10682 0 -10683 0 -10684 0 -10685 0 -10686 0 -10687 0 -10688 0 -10689 0 -10690 0 -10691 0 -10692 0 -10693 0 -10694 0 -10695 0 -10696 0 -10697 0 -10698 0 -10699 0 -10700 0 -10701 1 -10702 0 -10703 0 -10704 0 -10705 0 -10706 0 -10707 0 -10708 0 -10709 0 -10710 0 -10711 1 -10712 0 -10713 0 -10714 0 -10715 0 -10716 0 -10717 0 -10718 0 -10719 0 -10720 0 -10721 1 -10722 0 -10723 0 -10724 0 -10725 0 -10726 0 -10727 0 -10728 0 -10729 0 -10730 1 -10731 0 -10732 0 -10733 0 -10734 0 -10735 0 -10736 0 -10737 0 -10738 0 -10739 0 -10740 1 -10741 0 -10742 0 -10743 0 -10744 0 -10745 0 -10746 0 -10747 0 -10748 0 -10749 1 -10750 0 -10751 0 -10752 0 -10753 0 -10754 0 -10755 0 -10756 0 -10757 0 -10758 0 -10759 1 -10760 0 -10761 0 -10762 0 -10763 0 -10764 0 -10765 0 -10766 0 -10767 0 -10768 0 -10769 0 -10770 1 -10771 0 -10772 0 -10773 0 -10774 0 -10775 0 -10776 0 -10777 0 -10778 0 -10779 0 -10780 1 -10781 0 -10782 0 -10783 0 -10784 0 -10785 0 -10786 0 -10787 0 -10788 0 -10789 0 -10790 1 -10791 0 -10792 0 -10793 0 -10794 0 -10795 0 -10796 0 -10797 0 -10798 0 -10799 0 -10800 1 -10801 0 -10802 0 -10803 0 -10804 0 -10805 0 -10806 0 -10807 0 -10808 0 -10809 0 -10810 0 -10811 0 -10812 0 -10813 0 -10814 0 -10815 0 -10816 0 -10817 0 -10818 0 -10819 0 -10820 1 -10821 0 -10822 0 -10823 0 -10824 0 -10825 0 -10826 0 -10827 0 -10828 0 -10829 0 -10830 0 -10831 1 -10832 0 -10833 0 -10834 0 -10835 0 -10836 0 -10837 0 -10838 0 -10839 0 -10840 1 -10841 0 -10842 0 -10843 0 -10844 0 -10845 0 -10846 0 -10847 0 -10848 0 -10849 0 -10850 0 -10851 0 -10852 0 -10853 0 -10854 0 -10855 0 -10856 0 -10857 0 -10858 0 -10859 0 -10860 1 -10861 0 -10862 0 -10863 0 -10864 0 -10865 0 -10866 0 -10867 0 -10868 0 -10869 1 -10870 0 -10871 0 -10872 0 -10873 0 -10874 0 -10875 0 -10876 0 -10877 0 -10878 0 -10879 0 -10880 1 -10881 0 -10882 0 -10883 0 -10884 0 -10885 0 -10886 0 -10887 0 -10888 0 -10889 0 -10890 1 -10891 0 -10892 0 -10893 0 -10894 0 -10895 0 -10896 0 -10897 0 -10898 0 -10899 0 -10900 1 -10901 0 -10902 0 -10903 0 -10904 0 -10905 0 -10906 0 -10907 0 -10908 0 -10909 0 -10910 0 -10911 1 -10912 0 -10913 0 -10914 0 -10915 0 -10916 0 -10917 0 -10918 0 -10919 0 -10920 0 -10921 1 -10922 0 -10923 0 -10924 0 -10925 0 -10926 0 -10927 0 -10928 0 -10929 0 -10930 0 -10931 1 -10932 0 -10933 0 -10934 0 -10935 0 -10936 0 -10937 0 -10938 0 -10939 0 -10940 1 -10941 0 -10942 0 -10943 0 -10944 0 -10945 0 -10946 0 -10947 0 -10948 0 -10949 1 -10950 0 -10951 0 -10952 0 -10953 0 -10954 0 -10955 0 -10956 0 -10957 0 -10958 1 -10959 0 -10960 0 -10961 0 -10962 0 -10963 0 -10964 0 -10965 0 -10966 0 -10967 0 -10968 1 -10969 0 -10970 0 -10971 0 -10972 0 -10973 0 -10974 0 -10975 0 -10976 0 -10977 0 -10978 1 -10979 0 -10980 0 -10981 0 -10982 0 -10983 0 -10984 0 -10985 0 -10986 0 -10987 0 -10988 0 -10989 1 -10990 0 -10991 0 -10992 0 -10993 0 -10994 0 -10995 0 -10996 0 -10997 0 -10998 0 -10999 0 -11000 1 \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore deleted file mode 100644 index 38344f8..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -build/ -test/ -examples/ -fs.js -zlib.js \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE deleted file mode 100644 index 0c44ae7..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) Isaac Z. Schlueter ("Author") -All rights reserved. - -The BSD License - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/README.md deleted file mode 100644 index 34c1189..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# readable-stream - -***Node-core streams for userland*** - -[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true)](https://nodei.co/npm/readable-stream/) -[![NPM](https://nodei.co/npm-dl/readable-stream.png)](https://nodei.co/npm/readable-stream/) - -This package is a mirror of the Streams2 and Streams3 implementations in Node-core. - -If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. - -**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. - -**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js deleted file mode 100644 index ca807af..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_duplex.js") diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js deleted file mode 100644 index b513d61..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -module.exports = Duplex; - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -} -/**/ - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -forEach(objectKeys(Writable.prototype), function(method) { - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; -}); - -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) - this.readable = false; - - if (options && options.writable === false) - this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; - - this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(this.end.bind(this)); -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js deleted file mode 100644 index 895ca50..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); -}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js deleted file mode 100644 index 6307220..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js +++ /dev/null @@ -1,982 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Readable; - -/**/ -var isArray = require('isarray'); -/**/ - - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Readable.ReadableState = ReadableState; - -var EE = require('events').EventEmitter; - -/**/ -if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -var Stream = require('stream'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var StringDecoder; - -util.inherits(Readable, Stream); - -function ReadableState(options, stream) { - options = options || {}; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - if (!(this instanceof Readable)) - return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - Stream.call(this); -} - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; - - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } - - if (state.needReadable) - emitReadable(stream); - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; -}; - -// Don't raise the hwm > 128MB -var MAX_HWM = 0x800000; -function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; - } - return n; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; - - if (n === null || isNaN(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; - } - - if (n <= 0) - return 0; - - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); - - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; - } - - return n; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function(n) { - var state = this._readableState; - state.calledRead = true; - var nOrig = n; - var ret; - - if (typeof n !== 'number' || n > 0) - state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - ret = null; - - // In cases where the decoder did not receive enough data - // to produce a full chunk, then immediately received an - // EOF, state.buffer will contain [, ]. - // howMuchToRead will see this and coerce the amount to - // read to zero (because it's looking at the length of the - // first in state.buffer), and we'll end up here. - // - // This can only happen via state.decoder -- no other venue - // exists for pushing a zero-length chunk into state.buffer - // and triggering this behavior. In this case, we return our - // remaining data and end the stream, if appropriate. - if (state.length > 0 && state.decoder) { - ret = fromList(n, state); - state.length -= ret.length; - } - - if (state.length === 0) - endReadable(this); - - return ret; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) - doRead = false; - - if (doRead) { - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - } - - // If _read called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - - if (n > 0) - ret = fromList(n, state); - else - ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } - - state.length -= n; - - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; - - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); - - return ret; -}; - -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - - -function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (state.emittedReadable) - return; - - state.emittedReadable = true; - if (state.sync) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); -} - -function emitReadable_(stream) { - stream.emit('readable'); -} - - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(function() { - maybeReadMore_(stream, state); - }); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); -}; - -Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - process.nextTick(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); - } - - function onend() { - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - function cleanup() { - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (!dest._writableState || dest._writableState.needDrain) - ondrain(); - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; - - - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); - - state.flowing = true; - process.nextTick(function() { - flow(src); - }); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function() { - var dest = this; - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; -} - -function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } - - while (state.pipesCount && null !== (chunk = src.read())) { - - if (state.pipesCount === 1) - write(state.pipes, 0, null); - else - forEach(state.pipes, write); - - src.emit('data', chunk); - - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } - - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; - - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } - - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; -} - -function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } -} - - -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; - - if (!dest) - dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); - - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); -}; - -Readable.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); -}; - -function emitDataEvents(stream, startPaused) { - var state = stream._readableState; - - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } - - var paused = startPaused || false; - var readable = false; - - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream.prototype.pipe; - stream.on = stream.addListener = Stream.prototype.on; - - stream.on('readable', function() { - readable = true; - - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); - - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); - - stream.pause = function() { - paused = true; - this.emit('pause'); - }; - - stream.resume = function() { - paused = false; - if (readable) - process.nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; - - // now make it start, just in case it hadn't already. - stream.emit('readable'); -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - //if (state.objectMode && util.isNullOrUndefined(chunk)) - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - - - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; - - // nothing in the list, definitely empty. - if (list.length === 0) - return null; - - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer(n); - - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); - - if (!state.endEmitted && state.calledRead) { - state.ended = true; - process.nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js deleted file mode 100644 index eb188df..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - -module.exports = Transform; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(Transform, Duplex); - - -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) - stream.push(data); - - if (cb) - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - - -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - - Duplex.call(this, options); - - var ts = this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); -} - -Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); -}; - -Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function(n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - - -function done(stream, er) { - if (er) - return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var rs = stream._readableState; - var ts = stream._transformState; - - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); - - if (ts.transforming) - throw new Error('calling transform done when still transforming'); - - return stream.push(null); -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js deleted file mode 100644 index 4bdaa4f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js +++ /dev/null @@ -1,386 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Writable.WritableState = WritableState; - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Stream = require('stream'); - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - options = options || {}; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.buffer = []; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; -} - -function Writable(options) { - var Duplex = require('./_stream_duplex'); - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); -}; - - -function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); -} - -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; -} - -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (typeof cb !== 'function') - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); - - return ret; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; - - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); - - return ret; -} - -function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - if (sync) - process.nextTick(function() { - cb(er); - }); - else - cb(er); - - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); - - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); - - if (sync) { - process.nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, len, chunk, encoding, cb); - - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } - } - - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); -}; - -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); -}; - - -function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); -} - -function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - process.nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md deleted file mode 100644 index 5a76b41..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# core-util-is - -The `util.is*` functions introduced in Node v0.12. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch deleted file mode 100644 index a06d5c0..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch +++ /dev/null @@ -1,604 +0,0 @@ -diff --git a/lib/util.js b/lib/util.js -index a03e874..9074e8e 100644 ---- a/lib/util.js -+++ b/lib/util.js -@@ -19,430 +19,6 @@ - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - --var formatRegExp = /%[sdj%]/g; --exports.format = function(f) { -- if (!isString(f)) { -- var objects = []; -- for (var i = 0; i < arguments.length; i++) { -- objects.push(inspect(arguments[i])); -- } -- return objects.join(' '); -- } -- -- var i = 1; -- var args = arguments; -- var len = args.length; -- var str = String(f).replace(formatRegExp, function(x) { -- if (x === '%%') return '%'; -- if (i >= len) return x; -- switch (x) { -- case '%s': return String(args[i++]); -- case '%d': return Number(args[i++]); -- case '%j': -- try { -- return JSON.stringify(args[i++]); -- } catch (_) { -- return '[Circular]'; -- } -- default: -- return x; -- } -- }); -- for (var x = args[i]; i < len; x = args[++i]) { -- if (isNull(x) || !isObject(x)) { -- str += ' ' + x; -- } else { -- str += ' ' + inspect(x); -- } -- } -- return str; --}; -- -- --// Mark that a method should not be used. --// Returns a modified function which warns once by default. --// If --no-deprecation is set, then it is a no-op. --exports.deprecate = function(fn, msg) { -- // Allow for deprecating things in the process of starting up. -- if (isUndefined(global.process)) { -- return function() { -- return exports.deprecate(fn, msg).apply(this, arguments); -- }; -- } -- -- if (process.noDeprecation === true) { -- return fn; -- } -- -- var warned = false; -- function deprecated() { -- if (!warned) { -- if (process.throwDeprecation) { -- throw new Error(msg); -- } else if (process.traceDeprecation) { -- console.trace(msg); -- } else { -- console.error(msg); -- } -- warned = true; -- } -- return fn.apply(this, arguments); -- } -- -- return deprecated; --}; -- -- --var debugs = {}; --var debugEnviron; --exports.debuglog = function(set) { -- if (isUndefined(debugEnviron)) -- debugEnviron = process.env.NODE_DEBUG || ''; -- set = set.toUpperCase(); -- if (!debugs[set]) { -- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { -- var pid = process.pid; -- debugs[set] = function() { -- var msg = exports.format.apply(exports, arguments); -- console.error('%s %d: %s', set, pid, msg); -- }; -- } else { -- debugs[set] = function() {}; -- } -- } -- return debugs[set]; --}; -- -- --/** -- * Echos the value of a value. Trys to print the value out -- * in the best way possible given the different types. -- * -- * @param {Object} obj The object to print out. -- * @param {Object} opts Optional options object that alters the output. -- */ --/* legacy: obj, showHidden, depth, colors*/ --function inspect(obj, opts) { -- // default options -- var ctx = { -- seen: [], -- stylize: stylizeNoColor -- }; -- // legacy... -- if (arguments.length >= 3) ctx.depth = arguments[2]; -- if (arguments.length >= 4) ctx.colors = arguments[3]; -- if (isBoolean(opts)) { -- // legacy... -- ctx.showHidden = opts; -- } else if (opts) { -- // got an "options" object -- exports._extend(ctx, opts); -- } -- // set default options -- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; -- if (isUndefined(ctx.depth)) ctx.depth = 2; -- if (isUndefined(ctx.colors)) ctx.colors = false; -- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; -- if (ctx.colors) ctx.stylize = stylizeWithColor; -- return formatValue(ctx, obj, ctx.depth); --} --exports.inspect = inspect; -- -- --// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics --inspect.colors = { -- 'bold' : [1, 22], -- 'italic' : [3, 23], -- 'underline' : [4, 24], -- 'inverse' : [7, 27], -- 'white' : [37, 39], -- 'grey' : [90, 39], -- 'black' : [30, 39], -- 'blue' : [34, 39], -- 'cyan' : [36, 39], -- 'green' : [32, 39], -- 'magenta' : [35, 39], -- 'red' : [31, 39], -- 'yellow' : [33, 39] --}; -- --// Don't use 'blue' not visible on cmd.exe --inspect.styles = { -- 'special': 'cyan', -- 'number': 'yellow', -- 'boolean': 'yellow', -- 'undefined': 'grey', -- 'null': 'bold', -- 'string': 'green', -- 'date': 'magenta', -- // "name": intentionally not styling -- 'regexp': 'red' --}; -- -- --function stylizeWithColor(str, styleType) { -- var style = inspect.styles[styleType]; -- -- if (style) { -- return '\u001b[' + inspect.colors[style][0] + 'm' + str + -- '\u001b[' + inspect.colors[style][1] + 'm'; -- } else { -- return str; -- } --} -- -- --function stylizeNoColor(str, styleType) { -- return str; --} -- -- --function arrayToHash(array) { -- var hash = {}; -- -- array.forEach(function(val, idx) { -- hash[val] = true; -- }); -- -- return hash; --} -- -- --function formatValue(ctx, value, recurseTimes) { -- // Provide a hook for user-specified inspect functions. -- // Check that value is an object with an inspect function on it -- if (ctx.customInspect && -- value && -- isFunction(value.inspect) && -- // Filter out the util module, it's inspect function is special -- value.inspect !== exports.inspect && -- // Also filter out any prototype objects using the circular check. -- !(value.constructor && value.constructor.prototype === value)) { -- var ret = value.inspect(recurseTimes, ctx); -- if (!isString(ret)) { -- ret = formatValue(ctx, ret, recurseTimes); -- } -- return ret; -- } -- -- // Primitive types cannot have properties -- var primitive = formatPrimitive(ctx, value); -- if (primitive) { -- return primitive; -- } -- -- // Look up the keys of the object. -- var keys = Object.keys(value); -- var visibleKeys = arrayToHash(keys); -- -- if (ctx.showHidden) { -- keys = Object.getOwnPropertyNames(value); -- } -- -- // Some type of object without properties can be shortcutted. -- if (keys.length === 0) { -- if (isFunction(value)) { -- var name = value.name ? ': ' + value.name : ''; -- return ctx.stylize('[Function' + name + ']', 'special'); -- } -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } -- if (isDate(value)) { -- return ctx.stylize(Date.prototype.toString.call(value), 'date'); -- } -- if (isError(value)) { -- return formatError(value); -- } -- } -- -- var base = '', array = false, braces = ['{', '}']; -- -- // Make Array say that they are Array -- if (isArray(value)) { -- array = true; -- braces = ['[', ']']; -- } -- -- // Make functions say that they are functions -- if (isFunction(value)) { -- var n = value.name ? ': ' + value.name : ''; -- base = ' [Function' + n + ']'; -- } -- -- // Make RegExps say that they are RegExps -- if (isRegExp(value)) { -- base = ' ' + RegExp.prototype.toString.call(value); -- } -- -- // Make dates with properties first say the date -- if (isDate(value)) { -- base = ' ' + Date.prototype.toUTCString.call(value); -- } -- -- // Make error with message first say the error -- if (isError(value)) { -- base = ' ' + formatError(value); -- } -- -- if (keys.length === 0 && (!array || value.length == 0)) { -- return braces[0] + base + braces[1]; -- } -- -- if (recurseTimes < 0) { -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } else { -- return ctx.stylize('[Object]', 'special'); -- } -- } -- -- ctx.seen.push(value); -- -- var output; -- if (array) { -- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); -- } else { -- output = keys.map(function(key) { -- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); -- }); -- } -- -- ctx.seen.pop(); -- -- return reduceToSingleString(output, base, braces); --} -- -- --function formatPrimitive(ctx, value) { -- if (isUndefined(value)) -- return ctx.stylize('undefined', 'undefined'); -- if (isString(value)) { -- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') -- .replace(/'/g, "\\'") -- .replace(/\\"/g, '"') + '\''; -- return ctx.stylize(simple, 'string'); -- } -- if (isNumber(value)) { -- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, -- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . -- if (value === 0 && 1 / value < 0) -- return ctx.stylize('-0', 'number'); -- return ctx.stylize('' + value, 'number'); -- } -- if (isBoolean(value)) -- return ctx.stylize('' + value, 'boolean'); -- // For some reason typeof null is "object", so special case here. -- if (isNull(value)) -- return ctx.stylize('null', 'null'); --} -- -- --function formatError(value) { -- return '[' + Error.prototype.toString.call(value) + ']'; --} -- -- --function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { -- var output = []; -- for (var i = 0, l = value.length; i < l; ++i) { -- if (hasOwnProperty(value, String(i))) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- String(i), true)); -- } else { -- output.push(''); -- } -- } -- keys.forEach(function(key) { -- if (!key.match(/^\d+$/)) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- key, true)); -- } -- }); -- return output; --} -- -- --function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { -- var name, str, desc; -- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; -- if (desc.get) { -- if (desc.set) { -- str = ctx.stylize('[Getter/Setter]', 'special'); -- } else { -- str = ctx.stylize('[Getter]', 'special'); -- } -- } else { -- if (desc.set) { -- str = ctx.stylize('[Setter]', 'special'); -- } -- } -- if (!hasOwnProperty(visibleKeys, key)) { -- name = '[' + key + ']'; -- } -- if (!str) { -- if (ctx.seen.indexOf(desc.value) < 0) { -- if (isNull(recurseTimes)) { -- str = formatValue(ctx, desc.value, null); -- } else { -- str = formatValue(ctx, desc.value, recurseTimes - 1); -- } -- if (str.indexOf('\n') > -1) { -- if (array) { -- str = str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n').substr(2); -- } else { -- str = '\n' + str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n'); -- } -- } -- } else { -- str = ctx.stylize('[Circular]', 'special'); -- } -- } -- if (isUndefined(name)) { -- if (array && key.match(/^\d+$/)) { -- return str; -- } -- name = JSON.stringify('' + key); -- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { -- name = name.substr(1, name.length - 2); -- name = ctx.stylize(name, 'name'); -- } else { -- name = name.replace(/'/g, "\\'") -- .replace(/\\"/g, '"') -- .replace(/(^"|"$)/g, "'"); -- name = ctx.stylize(name, 'string'); -- } -- } -- -- return name + ': ' + str; --} -- -- --function reduceToSingleString(output, base, braces) { -- var numLinesEst = 0; -- var length = output.reduce(function(prev, cur) { -- numLinesEst++; -- if (cur.indexOf('\n') >= 0) numLinesEst++; -- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; -- }, 0); -- -- if (length > 60) { -- return braces[0] + -- (base === '' ? '' : base + '\n ') + -- ' ' + -- output.join(',\n ') + -- ' ' + -- braces[1]; -- } -- -- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; --} -- -- - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { -@@ -522,166 +98,10 @@ function isPrimitive(arg) { - exports.isPrimitive = isPrimitive; - - function isBuffer(arg) { -- return arg instanceof Buffer; -+ return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); --} -- -- --function pad(n) { -- return n < 10 ? '0' + n.toString(10) : n.toString(10); --} -- -- --var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', -- 'Oct', 'Nov', 'Dec']; -- --// 26 Feb 16:19:34 --function timestamp() { -- var d = new Date(); -- var time = [pad(d.getHours()), -- pad(d.getMinutes()), -- pad(d.getSeconds())].join(':'); -- return [d.getDate(), months[d.getMonth()], time].join(' '); --} -- -- --// log is just a thin wrapper to console.log that prepends a timestamp --exports.log = function() { -- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); --}; -- -- --/** -- * Inherit the prototype methods from one constructor into another. -- * -- * The Function.prototype.inherits from lang.js rewritten as a standalone -- * function (not on Function.prototype). NOTE: If this file is to be loaded -- * during bootstrapping this function needs to be rewritten using some native -- * functions as prototype setup using normal JavaScript does not work as -- * expected during bootstrapping (see mirror.js in r114903). -- * -- * @param {function} ctor Constructor function which needs to inherit the -- * prototype. -- * @param {function} superCtor Constructor function to inherit prototype from. -- */ --exports.inherits = function(ctor, superCtor) { -- ctor.super_ = superCtor; -- ctor.prototype = Object.create(superCtor.prototype, { -- constructor: { -- value: ctor, -- enumerable: false, -- writable: true, -- configurable: true -- } -- }); --}; -- --exports._extend = function(origin, add) { -- // Don't do anything if add isn't an object -- if (!add || !isObject(add)) return origin; -- -- var keys = Object.keys(add); -- var i = keys.length; -- while (i--) { -- origin[keys[i]] = add[keys[i]]; -- } -- return origin; --}; -- --function hasOwnProperty(obj, prop) { -- return Object.prototype.hasOwnProperty.call(obj, prop); --} -- -- --// Deprecated old stuff. -- --exports.p = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- console.error(exports.inspect(arguments[i])); -- } --}, 'util.p: Use console.error() instead'); -- -- --exports.exec = exports.deprecate(function() { -- return require('child_process').exec.apply(this, arguments); --}, 'util.exec is now called `child_process.exec`.'); -- -- --exports.print = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(String(arguments[i])); -- } --}, 'util.print: Use console.log instead'); -- -- --exports.puts = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(arguments[i] + '\n'); -- } --}, 'util.puts: Use console.log instead'); -- -- --exports.debug = exports.deprecate(function(x) { -- process.stderr.write('DEBUG: ' + x + '\n'); --}, 'util.debug: Use console.error instead'); -- -- --exports.error = exports.deprecate(function(x) { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stderr.write(arguments[i] + '\n'); -- } --}, 'util.error: Use console.error instead'); -- -- --exports.pump = exports.deprecate(function(readStream, writeStream, callback) { -- var callbackCalled = false; -- -- function call(a, b, c) { -- if (callback && !callbackCalled) { -- callback(a, b, c); -- callbackCalled = true; -- } -- } -- -- readStream.addListener('data', function(chunk) { -- if (writeStream.write(chunk) === false) readStream.pause(); -- }); -- -- writeStream.addListener('drain', function() { -- readStream.resume(); -- }); -- -- readStream.addListener('end', function() { -- writeStream.end(); -- }); -- -- readStream.addListener('close', function() { -- call(); -- }); -- -- readStream.addListener('error', function(err) { -- writeStream.end(); -- call(err); -- }); -- -- writeStream.addListener('error', function(err) { -- readStream.destroy(); -- call(err); -- }); --}, 'util.pump(): Use readableStream.pipe() instead'); -- -- --var uv; --exports._errnoException = function(err, syscall) { -- if (isUndefined(uv)) uv = process.binding('uv'); -- var errname = uv.errname(err); -- var e = new Error(syscall + ' ' + errname); -- e.code = errname; -- e.errno = errname; -- e.syscall = syscall; -- return e; --}; -+} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js deleted file mode 100644 index 9074e8e..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return Buffer.isBuffer(arg); -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json deleted file mode 100644 index 466dfdf..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "core-util-is", - "version": "1.0.1", - "description": "The `util.is*` functions introduced in Node v0.12.", - "main": "lib/util.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/core-util-is.git" - }, - "keywords": [ - "util", - "isBuffer", - "isArray", - "isNumber", - "isString", - "isRegExp", - "isThis", - "isThat", - "polyfill" - ], - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/isaacs/core-util-is/issues" - }, - "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", - "readmeFilename": "README.md", - "homepage": "https://github.com/isaacs/core-util-is", - "_id": "core-util-is@1.0.1", - "dist": { - "shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", - "tarball": "http://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" - }, - "_from": "core-util-is@>=1.0.0 <1.1.0", - "_npmVersion": "1.3.23", - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "directories": {}, - "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", - "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js deleted file mode 100644 index 007fa10..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && objectToString(e) === '[object Error]'; -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return arg instanceof Buffer; -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md deleted file mode 100644 index b1c5665..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js deleted file mode 100644 index 29f5e24..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('util').inherits diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js deleted file mode 100644 index c1e78a7..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,23 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json deleted file mode 100644 index 93d5078..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "inherits", - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "version": "2.0.1", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "main": "./inherits.js", - "browser": "./inherits_browser.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits.git" - }, - "license": "ISC", - "scripts": { - "test": "node test" - }, - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "_id": "inherits@2.0.1", - "dist": { - "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", - "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" - }, - "_from": "inherits@>=2.0.1 <2.1.0", - "_npmVersion": "1.3.8", - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "directories": {}, - "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", - "readme": "ERROR: No README data found!", - "homepage": "https://github.com/isaacs/inherits#readme" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js deleted file mode 100644 index fc53012..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js +++ /dev/null @@ -1,25 +0,0 @@ -var inherits = require('./inherits.js') -var assert = require('assert') - -function test(c) { - assert(c.constructor === Child) - assert(c.constructor.super_ === Parent) - assert(Object.getPrototypeOf(c) === Child.prototype) - assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) - assert(c instanceof Child) - assert(c instanceof Parent) -} - -function Child() { - Parent.call(this) - test(this) -} - -function Parent() {} - -inherits(Child, Parent) - -var c = new Child -test(c) - -console.log('ok') diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md deleted file mode 100644 index 052a62b..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md +++ /dev/null @@ -1,54 +0,0 @@ - -# isarray - -`Array#isArray` for older browsers. - -## Usage - -```js -var isArray = require('isarray'); - -console.log(isArray([])); // => true -console.log(isArray({})); // => false -``` - -## Installation - -With [npm](http://npmjs.org) do - -```bash -$ npm install isarray -``` - -Then bundle for the browser with -[browserify](https://github.com/substack/browserify). - -With [component](http://component.io) do - -```bash -$ component install juliangruber/isarray -``` - -## License - -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js deleted file mode 100644 index ec58596..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js +++ /dev/null @@ -1,209 +0,0 @@ - -/** - * Require the given path. - * - * @param {String} path - * @return {Object} exports - * @api public - */ - -function require(path, parent, orig) { - var resolved = require.resolve(path); - - // lookup failed - if (null == resolved) { - orig = orig || path; - parent = parent || 'root'; - var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); - err.path = orig; - err.parent = parent; - err.require = true; - throw err; - } - - var module = require.modules[resolved]; - - // perform real require() - // by invoking the module's - // registered function - if (!module.exports) { - module.exports = {}; - module.client = module.component = true; - module.call(this, module.exports, require.relative(resolved), module); - } - - return module.exports; -} - -/** - * Registered modules. - */ - -require.modules = {}; - -/** - * Registered aliases. - */ - -require.aliases = {}; - -/** - * Resolve `path`. - * - * Lookup: - * - * - PATH/index.js - * - PATH.js - * - PATH - * - * @param {String} path - * @return {String} path or null - * @api private - */ - -require.resolve = function(path) { - if (path.charAt(0) === '/') path = path.slice(1); - var index = path + '/index.js'; - - var paths = [ - path, - path + '.js', - path + '.json', - path + '/index.js', - path + '/index.json' - ]; - - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (require.modules.hasOwnProperty(path)) return path; - } - - if (require.aliases.hasOwnProperty(index)) { - return require.aliases[index]; - } -}; - -/** - * Normalize `path` relative to the current path. - * - * @param {String} curr - * @param {String} path - * @return {String} - * @api private - */ - -require.normalize = function(curr, path) { - var segs = []; - - if ('.' != path.charAt(0)) return path; - - curr = curr.split('/'); - path = path.split('/'); - - for (var i = 0; i < path.length; ++i) { - if ('..' == path[i]) { - curr.pop(); - } else if ('.' != path[i] && '' != path[i]) { - segs.push(path[i]); - } - } - - return curr.concat(segs).join('/'); -}; - -/** - * Register module at `path` with callback `definition`. - * - * @param {String} path - * @param {Function} definition - * @api private - */ - -require.register = function(path, definition) { - require.modules[path] = definition; -}; - -/** - * Alias a module definition. - * - * @param {String} from - * @param {String} to - * @api private - */ - -require.alias = function(from, to) { - if (!require.modules.hasOwnProperty(from)) { - throw new Error('Failed to alias "' + from + '", it does not exist'); - } - require.aliases[to] = from; -}; - -/** - * Return a require function relative to the `parent` path. - * - * @param {String} parent - * @return {Function} - * @api private - */ - -require.relative = function(parent) { - var p = require.normalize(parent, '..'); - - /** - * lastIndexOf helper. - */ - - function lastIndexOf(arr, obj) { - var i = arr.length; - while (i--) { - if (arr[i] === obj) return i; - } - return -1; - } - - /** - * The relative require() itself. - */ - - function localRequire(path) { - var resolved = localRequire.resolve(path); - return require(resolved, parent, path); - } - - /** - * Resolve relative to the parent. - */ - - localRequire.resolve = function(path) { - var c = path.charAt(0); - if ('/' == c) return path.slice(1); - if ('.' == c) return require.normalize(p, path); - - // resolve deps by returning - // the dep in the nearest "deps" - // directory - var segs = parent.split('/'); - var i = lastIndexOf(segs, 'deps') + 1; - if (!i) i = 0; - path = segs.slice(0, i + 1).join('/') + '/deps/' + path; - return path; - }; - - /** - * Check if module is defined at `path`. - */ - - localRequire.exists = function(path) { - return require.modules.hasOwnProperty(localRequire.resolve(path)); - }; - - return localRequire; -}; -require.register("isarray/index.js", function(exports, require, module){ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; - -}); -require.alias("isarray/index.js", "isarray/index.js"); - diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json deleted file mode 100644 index 9e31b68..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name" : "isarray", - "description" : "Array#isArray for older browsers", - "version" : "0.0.1", - "repository" : "juliangruber/isarray", - "homepage": "https://github.com/juliangruber/isarray", - "main" : "index.js", - "scripts" : [ - "index.js" - ], - "dependencies" : {}, - "keywords": ["browser","isarray","array"], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js deleted file mode 100644 index 5f5ad45..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json deleted file mode 100644 index 19228ab..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "isarray", - "description": "Array#isArray for older browsers", - "version": "0.0.1", - "repository": { - "type": "git", - "url": "git://github.com/juliangruber/isarray.git" - }, - "homepage": "https://github.com/juliangruber/isarray", - "main": "index.js", - "scripts": { - "test": "tap test/*.js" - }, - "dependencies": {}, - "devDependencies": { - "tap": "*" - }, - "keywords": [ - "browser", - "isarray", - "array" - ], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT", - "_id": "isarray@0.0.1", - "dist": { - "shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", - "tarball": "http://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz" - }, - "_from": "isarray@0.0.1", - "_npmVersion": "1.2.18", - "_npmUser": { - "name": "juliangruber", - "email": "julian@juliangruber.com" - }, - "maintainers": [ - { - "name": "juliangruber", - "email": "julian@juliangruber.com" - } - ], - "directories": {}, - "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", - "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "bugs": { - "url": "https://github.com/juliangruber/isarray/issues" - }, - "readme": "ERROR: No README data found!" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore deleted file mode 100644 index 206320c..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -build -test diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE deleted file mode 100644 index 6de584a..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the -following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md deleted file mode 100644 index 4d2aa00..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md +++ /dev/null @@ -1,7 +0,0 @@ -**string_decoder.js** (`require('string_decoder')`) from Node.js core - -Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. - -Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** - -The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js deleted file mode 100644 index b00e54f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var Buffer = require('buffer').Buffer; - -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } - - -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; - - -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; -}; - -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; -}; - -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); -} - -function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; -} - -function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json deleted file mode 100644 index 0364d54..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "string_decoder", - "version": "0.10.31", - "description": "The string_decoder module from Node core", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "tap": "~0.4.8" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/rvagg/string_decoder.git" - }, - "homepage": "https://github.com/rvagg/string_decoder", - "keywords": [ - "string", - "decoder", - "browser", - "browserify" - ], - "license": "MIT", - "gitHead": "d46d4fd87cf1d06e031c23f1ba170ca7d4ade9a0", - "bugs": { - "url": "https://github.com/rvagg/string_decoder/issues" - }, - "_id": "string_decoder@0.10.31", - "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", - "_from": "string_decoder@>=0.10.0 <0.11.0", - "_npmVersion": "1.4.23", - "_npmUser": { - "name": "rvagg", - "email": "rod@vagg.org" - }, - "maintainers": [ - { - "name": "substack", - "email": "mail@substack.net" - }, - { - "name": "rvagg", - "email": "rod@vagg.org" - } - ], - "dist": { - "shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", - "tarball": "http://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/package.json b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/package.json deleted file mode 100644 index 2dc3a25..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "readable-stream", - "version": "1.0.31", - "description": "Streams2, a user-land copy of the stream library from Node.js v0.10.x", - "main": "readable.js", - "dependencies": { - "core-util-is": "~1.0.0", - "isarray": "0.0.1", - "string_decoder": "~0.10.x", - "inherits": "~2.0.1" - }, - "devDependencies": { - "tap": "~0.2.6" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/isaacs/readable-stream.git" - }, - "keywords": [ - "readable", - "stream", - "pipe" - ], - "browser": { - "util": false - }, - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/isaacs/readable-stream/issues" - }, - "homepage": "https://github.com/isaacs/readable-stream", - "_id": "readable-stream@1.0.31", - "_shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", - "_from": "readable-stream@1.0.31", - "_npmVersion": "1.4.9", - "_npmUser": { - "name": "rvagg", - "email": "rod@vagg.org" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - }, - { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - }, - { - "name": "rvagg", - "email": "rod@vagg.org" - } - ], - "dist": { - "shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", - "tarball": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js deleted file mode 100644 index 27e8d8a..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_passthrough.js") diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/readable.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/readable.js deleted file mode 100644 index 4d1ddfc..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/readable.js +++ /dev/null @@ -1,6 +0,0 @@ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/transform.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/transform.js deleted file mode 100644 index 5d482f0..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/transform.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_transform.js") diff --git a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/writable.js b/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/writable.js deleted file mode 100644 index e1e9efd..0000000 --- a/util/demographicsImporter/node_modules/mongodb/node_modules/readable-stream/writable.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_writable.js") diff --git a/util/demographicsImporter/node_modules/mongodb/package.json b/util/demographicsImporter/node_modules/mongodb/package.json deleted file mode 100644 index 9036dce..0000000 --- a/util/demographicsImporter/node_modules/mongodb/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "name": "mongodb", - "version": "2.0.45", - "description": "MongoDB legacy driver emulation layer on top of mongodb-core", - "main": "index.js", - "repository": { - "type": "git", - "url": "git@github.com:mongodb/node-mongodb-native.git" - }, - "keywords": [ - "mongodb", - "driver", - "legacy" - ], - "dependencies": { - "mongodb-core": "1.2.14", - "readable-stream": "1.0.31", - "es6-promise": "2.1.1" - }, - "devDependencies": { - "integra": "0.1.8", - "optimist": "0.6.1", - "bson": "~0.4", - "jsdoc": "3.3.0-beta3", - "semver": "4.1.0", - "rimraf": "2.2.6", - "gleak": "0.5.0", - "mongodb-version-manager": "^0.7.1", - "mongodb-tools": "~1.0", - "co": "4.5.4", - "bluebird": "2.9.27" - }, - "author": { - "name": "Christian Kvalheim" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/mongodb/node-mongodb-native/issues" - }, - "scripts": { - "test": "node test/runner.js -t functional" - }, - "homepage": "https://github.com/mongodb/node-mongodb-native", - "gitHead": "45d433baa92cb160f895d47911ee5776fbaad3be", - "_id": "mongodb@2.0.45", - "_shasum": "c63d42b918f19a53b32d4c64043f6a9f66c9aba5", - "_from": "mongodb@*", - "_npmVersion": "2.14.4", - "_nodeVersion": "4.1.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "c63d42b918f19a53b32d4c64043f6a9f66c9aba5", - "tarball": "http://registry.npmjs.org/mongodb/-/mongodb-2.0.45.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-2.0.45.tgz" -} diff --git a/util/demographicsImporter/node_modules/mongodb/t.js b/util/demographicsImporter/node_modules/mongodb/t.js deleted file mode 100644 index af73362..0000000 --- a/util/demographicsImporter/node_modules/mongodb/t.js +++ /dev/null @@ -1,73 +0,0 @@ -var MongoClient = require('./').MongoClient - , assert = require('assert') - , cappedCollectionName = "capped_test"; - - -function capitalizeFirstLetter(string) { - return string.charAt(0).toUpperCase() + string.slice(1); -} - - function createTailedCursor(db, callback) { - var collection = db.collection(cappedCollectionName) - , cursor = collection.find({}, { tailable: true, awaitdata: true, numberOfRetries: Number.MAX_VALUE}) - , stream = cursor.stream() - , statusGetters = ['notified', 'closed', 'dead', 'killed']; - - console.log('After stream open'); - statusGetters.forEach(function (s) { - var getter = 'is' + capitalizeFirstLetter(s); - console.log("cursor " + getter + " => ", cursor[getter]()); - }); - - - stream.on('error', callback); - stream.on('end', callback.bind(null, 'end')); - stream.on('close', callback.bind(null, 'close')); - stream.on('readable', callback.bind(null, 'readable')); - stream.on('data', callback.bind(null, null, 'data')); - - console.log('After stream attach events'); - statusGetters.forEach(function (s) { - var getter = 'is' + capitalizeFirstLetter(s); - console.log("cursor " + getter + " => ", cursor[getter]()); - }); - } - - function cappedStreamEvent(err, evName, data) { - if (err) { - console.log("capped stream got error", err); - return; - } - - if (evName) { - console.log("capped stream got event", evName); - } - - if (data) { - console.log("capped stream got data", data); - } - } - - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - db.createCollection(cappedCollectionName, - { "capped": true, - "size": 100000, - "max": 5000 }, - function(err, collection) { - - assert.equal(null, err); - console.log("Created capped collection " + cappedCollectionName); - - createTailedCursor(db, cappedStreamEvent); - }); - - - //db.close(); -}); \ No newline at end of file diff --git a/util/demographicsImporter/node_modules/mongodb/t1.js b/util/demographicsImporter/node_modules/mongodb/t1.js deleted file mode 100644 index 392ed8e..0000000 --- a/util/demographicsImporter/node_modules/mongodb/t1.js +++ /dev/null @@ -1,77 +0,0 @@ -var MongoClient = require('./').MongoClient; - -MongoClient.connect('mongodb://localhost:27017/page-testing', function (err, db) { - collection = db.collection('test'); - - collection.insertMany([{a:1}, {a:2}], {w:1}, function (err, docs) { - if (err) { - console.log("ERROR"); - } - - collection.find().sort({'a': -1}).toArray(function(err, items) { - if (err) { - console.log("ERROR"); - } - console.log("Items: ", items); - }); - }); -}); -// var database = null; -// -// var MongoClient = require('./').MongoClient; -// -// function connect_to_mongo(callback) { -// if (database != null) { -// callback(null, database); -// } else { -// var connection = "mongodb://127.0.0.1:27017/test_db"; -// MongoClient.connect(connection, { -// server : { -// reconnectTries : 5, -// reconnectInterval: 1000, -// autoReconnect : true -// } -// }, function (err, db) { -// database = db; -// callback(err, db); -// }); -// } -// } -// -// function log(message) { -// console.log(new Date(), message); -// } -// -// var queryNumber = 0; -// -// function make_query(db) { -// var currentNumber = queryNumber; -// ++queryNumber; -// log("query " + currentNumber + ": started"); -// -// setTimeout(function() { -// make_query(db); -// }, 5000); -// -// var collection = db.collection('test_collection'); -// collection.findOne({}, -// function (err, result) { -// if (err != null) { -// log("query " + currentNumber + ": find one error: " + err.message); -// return; -// } -// log("query " + currentNumber + ": find one result: " + result); -// } -// ); -// } -// -// connect_to_mongo( -// function(err, db) { -// if (err != null) { -// log(err.message); -// return; -// } -// -// make_query(db); -// } -// ); diff --git a/util/demographicsImporter/node_modules/mongodb/wercker.yml b/util/demographicsImporter/node_modules/mongodb/wercker.yml deleted file mode 100644 index b64845f..0000000 --- a/util/demographicsImporter/node_modules/mongodb/wercker.yml +++ /dev/null @@ -1,19 +0,0 @@ -box: wercker/nodejs -services: - - wercker/mongodb@1.0.1 -# Build definition -build: - # The steps that will be executed on build - steps: - # A step that executes `npm install` command - - npm-install - # A step that executes `npm test` command - - npm-test - - # A custom script step, name value is used in the UI - # and the code value contains the command that get executed - - script: - name: echo nodejs information - code: | - echo "node version $(node -v) running" - echo "npm version $(npm -v) running" diff --git a/util/demographicsImporter/package.json b/util/demographicsImporter/package.json deleted file mode 100644 index 317d037..0000000 --- a/util/demographicsImporter/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "retroimporter", - "version": "1.0.0", - "description": "", - "main": "retroImporter.js", - "dependencies": { - "mongodb": "^2.0.45" - }, - "devDependencies": {}, - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC" -} From 47d4fbd4781deafdc5ad4acee2fbb1e49af784e4 Mon Sep 17 00:00:00 2001 From: Fieran Mason Date: Fri, 6 Nov 2015 23:29:26 +0000 Subject: [PATCH 09/10] removed node install stuffs --- .../node_modules/mongodb/HISTORY.md | 1218 -- .../node_modules/mongodb/LICENSE | 201 - .../node_modules/mongodb/Makefile | 11 - .../node_modules/mongodb/README.md | 322 - util/retroImporter/node_modules/mongodb/c.js | 24 - .../node_modules/mongodb/conf.json | 69 - .../node_modules/mongodb/index.js | 47 - .../node_modules/mongodb/lib/admin.js | 581 - .../mongodb/lib/aggregation_cursor.js | 432 - .../node_modules/mongodb/lib/apm.js | 571 - .../node_modules/mongodb/lib/bulk/common.js | 393 - .../node_modules/mongodb/lib/bulk/ordered.js | 532 - .../mongodb/lib/bulk/unordered.js | 541 - .../node_modules/mongodb/lib/collection.js | 3128 ----- .../mongodb/lib/command_cursor.js | 296 - .../node_modules/mongodb/lib/cursor.js | 1149 -- .../node_modules/mongodb/lib/db.js | 1731 --- .../node_modules/mongodb/lib/gridfs/chunk.js | 237 - .../mongodb/lib/gridfs/grid_store.js | 1919 --- .../node_modules/mongodb/lib/metadata.js | 64 - .../node_modules/mongodb/lib/mongo_client.js | 463 - .../node_modules/mongodb/lib/mongos.js | 491 - .../mongodb/lib/read_preference.js | 104 - .../node_modules/mongodb/lib/replset.js | 555 - .../node_modules/mongodb/lib/server.js | 437 - .../node_modules/mongodb/lib/topology_base.js | 152 - .../node_modules/mongodb/lib/url_parser.js | 295 - .../node_modules/mongodb/lib/utils.js | 234 - .../node_modules/mongodb/load.js | 32 - .../node_modules/es6-promise/CHANGELOG.md | 9 - .../mongodb/node_modules/es6-promise/LICENSE | 19 - .../node_modules/es6-promise/README.md | 61 - .../es6-promise/dist/es6-promise.js | 957 -- .../es6-promise/dist/es6-promise.min.js | 9 - .../es6-promise/dist/test/browserify.js | 11631 ---------------- .../es6-promise/dist/test/es6-promise.js | 950 -- .../es6-promise/dist/test/es6-promise.min.js | 1 - .../es6-promise/dist/test/index.html | 25 - .../es6-promise/dist/test/json3.js | 902 -- .../es6-promise/dist/test/mocha.css | 270 - .../es6-promise/dist/test/mocha.js | 6095 -------- .../es6-promise/dist/test/worker.js | 16 - .../es6-promise/lib/es6-promise.umd.js | 18 - .../es6-promise/lib/es6-promise/-internal.js | 250 - .../es6-promise/lib/es6-promise/asap.js | 111 - .../es6-promise/lib/es6-promise/enumerator.js | 113 - .../es6-promise/lib/es6-promise/polyfill.js | 26 - .../es6-promise/lib/es6-promise/promise.js | 408 - .../lib/es6-promise/promise/all.js | 52 - .../lib/es6-promise/promise/race.js | 104 - .../lib/es6-promise/promise/reject.js | 46 - .../lib/es6-promise/promise/resolve.js | 48 - .../es6-promise/lib/es6-promise/utils.js | 22 - .../node_modules/es6-promise/package.json | 88 - .../node_modules/mongodb-core/HISTORY.md | 246 - .../mongodb/node_modules/mongodb-core/LICENSE | 201 - .../node_modules/mongodb-core/Makefile | 11 - .../node_modules/mongodb-core/README.md | 225 - .../node_modules/mongodb-core/TESTING.md | 18 - .../node_modules/mongodb-core/conf.json | 60 - .../node_modules/mongodb-core/index.js | 18 - .../mongodb-core/lib/auth/gssapi.js | 244 - .../mongodb-core/lib/auth/mongocr.js | 160 - .../mongodb-core/lib/auth/plain.js | 150 - .../mongodb-core/lib/auth/scram.js | 317 - .../mongodb-core/lib/auth/sspi.js | 234 - .../mongodb-core/lib/auth/x509.js | 145 - .../mongodb-core/lib/connection/commands.js | 519 - .../mongodb-core/lib/connection/connection.js | 462 - .../mongodb-core/lib/connection/logger.js | 196 - .../mongodb-core/lib/connection/pool.js | 275 - .../mongodb-core/lib/connection/utils.js | 77 - .../node_modules/mongodb-core/lib/cursor.js | 756 - .../node_modules/mongodb-core/lib/error.js | 44 - .../mongodb-core/lib/tools/smoke_plugin.js | 59 - .../lib/topologies/command_result.js | 37 - .../mongodb-core/lib/topologies/mongos.js | 1000 -- .../lib/topologies/read_preference.js | 106 - .../mongodb-core/lib/topologies/replset.js | 1333 -- .../lib/topologies/replset_state.js | 483 - .../mongodb-core/lib/topologies/server.js | 1230 -- .../mongodb-core/lib/topologies/session.js | 93 - .../lib/topologies/strategies/ping.js | 276 - .../lib/wireprotocol/2_4_support.js | 559 - .../lib/wireprotocol/2_6_support.js | 291 - .../lib/wireprotocol/3_2_support.js | 494 - .../mongodb-core/lib/wireprotocol/commands.js | 357 - .../mongodb-core/node_modules/bson/HISTORY | 113 - .../mongodb-core/node_modules/bson/LICENSE | 201 - .../mongodb-core/node_modules/bson/README.md | 69 - .../bson/alternate_parsers/bson.js | 1574 --- .../bson/alternate_parsers/faster_bson.js | 429 - .../node_modules/bson/browser_build/bson.js | 4843 ------- .../bson/browser_build/package.json | 8 - .../node_modules/bson/lib/bson/binary.js | 344 - .../bson/lib/bson/binary_parser.js | 385 - .../node_modules/bson/lib/bson/bson.js | 323 - .../node_modules/bson/lib/bson/code.js | 24 - .../node_modules/bson/lib/bson/db_ref.js | 32 - .../node_modules/bson/lib/bson/double.js | 33 - .../bson/lib/bson/float_parser.js | 121 - .../node_modules/bson/lib/bson/index.js | 86 - .../node_modules/bson/lib/bson/long.js | 856 -- .../node_modules/bson/lib/bson/map.js | 126 - .../node_modules/bson/lib/bson/max_key.js | 14 - .../node_modules/bson/lib/bson/min_key.js | 14 - .../node_modules/bson/lib/bson/objectid.js | 273 - .../bson/lib/bson/parser/calculate_size.js | 310 - .../bson/lib/bson/parser/deserializer.js | 544 - .../bson/lib/bson/parser/serializer.js | 909 -- .../node_modules/bson/lib/bson/regexp.js | 30 - .../node_modules/bson/lib/bson/symbol.js | 47 - .../node_modules/bson/lib/bson/timestamp.js | 856 -- .../node_modules/bson/package.json | 70 - .../node_modules/bson/tools/gleak.js | 21 - .../node_modules/kerberos/.travis.yml | 20 - .../node_modules/kerberos/LICENSE | 201 - .../node_modules/kerberos/README.md | 4 - .../node_modules/kerberos/binding.gyp | 46 - .../node_modules/kerberos/build/Makefile | 324 - .../Release/.deps/Release/kerberos.node.d | 1 - .../.deps/Release/obj.target/kerberos.node.d | 1 - .../obj.target/kerberos/lib/base64.o.d | 4 - .../obj.target/kerberos/lib/kerberos.o.d | 71 - .../kerberos/lib/kerberos_context.o.d | 70 - .../obj.target/kerberos/lib/kerberosgss.o.d | 16 - .../obj.target/kerberos/lib/worker.o.d | 57 - .../kerberos/build/Release/kerberos.node | Bin 85259 -> 0 bytes .../build/Release/obj.target/kerberos.node | Bin 85259 -> 0 bytes .../Release/obj.target/kerberos/lib/base64.o | Bin 4176 -> 0 bytes .../obj.target/kerberos/lib/kerberos.o | Bin 86232 -> 0 bytes .../kerberos/lib/kerberos_context.o | Bin 31808 -> 0 bytes .../obj.target/kerberos/lib/kerberosgss.o | Bin 19608 -> 0 bytes .../Release/obj.target/kerberos/lib/worker.o | Bin 2720 -> 0 bytes .../kerberos/build/binding.Makefile | 6 - .../node_modules/kerberos/build/config.gypi | 138 - .../kerberos/build/kerberos.target.mk | 151 - .../node_modules/kerberos/builderror.log | 25 - .../node_modules/kerberos/index.js | 6 - .../kerberos/lib/auth_processes/mongodb.js | 281 - .../node_modules/kerberos/lib/base64.c | 134 - .../node_modules/kerberos/lib/base64.h | 22 - .../node_modules/kerberos/lib/kerberos.cc | 893 -- .../node_modules/kerberos/lib/kerberos.h | 50 - .../node_modules/kerberos/lib/kerberos.js | 164 - .../kerberos/lib/kerberos_context.cc | 134 - .../kerberos/lib/kerberos_context.h | 64 - .../node_modules/kerberos/lib/kerberosgss.c | 931 -- .../node_modules/kerberos/lib/kerberosgss.h | 73 - .../node_modules/kerberos/lib/sspi.js | 15 - .../node_modules/kerberos/lib/win32/base64.c | 121 - .../node_modules/kerberos/lib/win32/base64.h | 18 - .../kerberos/lib/win32/kerberos.cc | 51 - .../kerberos/lib/win32/kerberos.h | 60 - .../kerberos/lib/win32/kerberos_sspi.c | 244 - .../kerberos/lib/win32/kerberos_sspi.h | 106 - .../node_modules/kerberos/lib/win32/worker.cc | 7 - .../node_modules/kerberos/lib/win32/worker.h | 38 - .../lib/win32/wrappers/security_buffer.cc | 101 - .../lib/win32/wrappers/security_buffer.h | 48 - .../lib/win32/wrappers/security_buffer.js | 12 - .../wrappers/security_buffer_descriptor.cc | 182 - .../wrappers/security_buffer_descriptor.h | 46 - .../wrappers/security_buffer_descriptor.js | 3 - .../lib/win32/wrappers/security_context.cc | 856 -- .../lib/win32/wrappers/security_context.h | 74 - .../lib/win32/wrappers/security_context.js | 3 - .../win32/wrappers/security_credentials.cc | 348 - .../lib/win32/wrappers/security_credentials.h | 68 - .../win32/wrappers/security_credentials.js | 22 - .../node_modules/kerberos/lib/worker.cc | 7 - .../node_modules/kerberos/lib/worker.h | 38 - .../kerberos/node_modules/nan/.dntrc | 30 - .../kerberos/node_modules/nan/CHANGELOG.md | 374 - .../kerberos/node_modules/nan/LICENSE.md | 13 - .../kerberos/node_modules/nan/README.md | 367 - .../kerberos/node_modules/nan/appveyor.yml | 38 - .../kerberos/node_modules/nan/doc/.build.sh | 38 - .../node_modules/nan/doc/asyncworker.md | 97 - .../kerberos/node_modules/nan/doc/buffers.md | 54 - .../kerberos/node_modules/nan/doc/callback.md | 52 - .../node_modules/nan/doc/converters.md | 41 - .../kerberos/node_modules/nan/doc/errors.md | 226 - .../node_modules/nan/doc/maybe_types.md | 480 - .../kerberos/node_modules/nan/doc/methods.md | 624 - .../kerberos/node_modules/nan/doc/new.md | 141 - .../node_modules/nan/doc/node_misc.md | 114 - .../node_modules/nan/doc/persistent.md | 292 - .../kerberos/node_modules/nan/doc/scopes.md | 73 - .../kerberos/node_modules/nan/doc/script.md | 38 - .../node_modules/nan/doc/string_bytes.md | 62 - .../node_modules/nan/doc/v8_internals.md | 199 - .../kerberos/node_modules/nan/doc/v8_misc.md | 63 - .../kerberos/node_modules/nan/include_dirs.js | 1 - .../kerberos/node_modules/nan/nan.h | 2136 --- .../kerberos/node_modules/nan/nan_callbacks.h | 88 - .../node_modules/nan/nan_callbacks_12_inl.h | 512 - .../nan/nan_callbacks_pre_12_inl.h | 506 - .../node_modules/nan/nan_converters.h | 64 - .../node_modules/nan/nan_converters_43_inl.h | 42 - .../nan/nan_converters_pre_43_inl.h | 42 - .../nan/nan_implementation_12_inl.h | 399 - .../nan/nan_implementation_pre_12_inl.h | 259 - .../node_modules/nan/nan_maybe_43_inl.h | 224 - .../node_modules/nan/nan_maybe_pre_43_inl.h | 295 - .../kerberos/node_modules/nan/nan_new.h | 332 - .../node_modules/nan/nan_object_wrap.h | 155 - .../node_modules/nan/nan_persistent_12_inl.h | 129 - .../nan/nan_persistent_pre_12_inl.h | 238 - .../node_modules/nan/nan_string_bytes.h | 305 - .../kerberos/node_modules/nan/nan_weak.h | 422 - .../kerberos/node_modules/nan/package.json | 92 - .../kerberos/node_modules/nan/tools/1to2.js | 412 - .../kerberos/node_modules/nan/tools/README.md | 14 - .../node_modules/nan/tools/package.json | 19 - .../node_modules/kerberos/package.json | 55 - .../kerberos/test/kerberos_tests.js | 34 - .../kerberos/test/kerberos_win32_test.js | 15 - .../win32/security_buffer_descriptor_tests.js | 41 - .../test/win32/security_buffer_tests.js | 22 - .../test/win32/security_credentials_tests.js | 55 - .../node_modules/mongodb-core/package.json | 66 - .../simple_2_document_limit_toArray.dat | 11000 --------------- .../node_modules/readable-stream/.npmignore | 5 - .../node_modules/readable-stream/LICENSE | 27 - .../node_modules/readable-stream/README.md | 15 - .../node_modules/readable-stream/duplex.js | 1 - .../readable-stream/lib/_stream_duplex.js | 89 - .../lib/_stream_passthrough.js | 46 - .../readable-stream/lib/_stream_readable.js | 982 -- .../readable-stream/lib/_stream_transform.js | 210 - .../readable-stream/lib/_stream_writable.js | 386 - .../node_modules/core-util-is/README.md | 3 - .../node_modules/core-util-is/float.patch | 604 - .../node_modules/core-util-is/lib/util.js | 107 - .../node_modules/core-util-is/package.json | 53 - .../node_modules/core-util-is/util.js | 106 - .../node_modules/inherits/LICENSE | 16 - .../node_modules/inherits/README.md | 42 - .../node_modules/inherits/inherits.js | 1 - .../node_modules/inherits/inherits_browser.js | 23 - .../node_modules/inherits/package.json | 50 - .../node_modules/inherits/test.js | 25 - .../node_modules/isarray/README.md | 54 - .../node_modules/isarray/build/build.js | 209 - .../node_modules/isarray/component.json | 19 - .../node_modules/isarray/index.js | 3 - .../node_modules/isarray/package.json | 53 - .../node_modules/string_decoder/.npmignore | 2 - .../node_modules/string_decoder/LICENSE | 20 - .../node_modules/string_decoder/README.md | 7 - .../node_modules/string_decoder/index.js | 221 - .../node_modules/string_decoder/package.json | 54 - .../node_modules/readable-stream/package.json | 69 - .../readable-stream/passthrough.js | 1 - .../node_modules/readable-stream/readable.js | 6 - .../node_modules/readable-stream/transform.js | 1 - .../node_modules/readable-stream/writable.js | 1 - .../node_modules/mongodb/package.json | 66 - util/retroImporter/node_modules/mongodb/t.js | 73 - util/retroImporter/node_modules/mongodb/t1.js | 77 - .../node_modules/mongodb/wercker.yml | 19 - util/retroImporter/package.json | 15 - 263 files changed, 93297 deletions(-) delete mode 100644 util/retroImporter/node_modules/mongodb/HISTORY.md delete mode 100644 util/retroImporter/node_modules/mongodb/LICENSE delete mode 100644 util/retroImporter/node_modules/mongodb/Makefile delete mode 100644 util/retroImporter/node_modules/mongodb/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/c.js delete mode 100644 util/retroImporter/node_modules/mongodb/conf.json delete mode 100644 util/retroImporter/node_modules/mongodb/index.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/admin.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/aggregation_cursor.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/apm.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/bulk/common.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/bulk/ordered.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/bulk/unordered.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/collection.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/command_cursor.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/cursor.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/db.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/gridfs/chunk.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/gridfs/grid_store.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/metadata.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/mongo_client.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/mongos.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/read_preference.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/replset.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/server.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/topology_base.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/url_parser.js delete mode 100644 util/retroImporter/node_modules/mongodb/lib/utils.js delete mode 100644 util/retroImporter/node_modules/mongodb/load.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/browserify.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/index.html delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/es6-promise/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/index.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Makefile delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d delete mode 100755 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node delete mode 100755 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos.node delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/base64.o delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos_context.o delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberosgss.o delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml delete mode 100755 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/asyncworker.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/buffers.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/callback.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/converters.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/errors.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/maybe_types.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/methods.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/new.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/node_misc.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/persistent.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/scopes.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/script.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/string_bytes.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/v8_internals.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/v8_misc.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/include_dirs.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks_12_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_callbacks_pre_12_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters_43_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_converters_pre_43_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_12_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_implementation_pre_12_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_maybe_43_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_maybe_pre_43_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_new.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_object_wrap.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_persistent_12_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_persistent_pre_12_inl.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_string_bytes.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/nan_weak.h delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/package.json delete mode 100755 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/1to2.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/readable.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/transform.js delete mode 100644 util/retroImporter/node_modules/mongodb/node_modules/readable-stream/writable.js delete mode 100644 util/retroImporter/node_modules/mongodb/package.json delete mode 100644 util/retroImporter/node_modules/mongodb/t.js delete mode 100644 util/retroImporter/node_modules/mongodb/t1.js delete mode 100644 util/retroImporter/node_modules/mongodb/wercker.yml delete mode 100644 util/retroImporter/package.json diff --git a/util/retroImporter/node_modules/mongodb/HISTORY.md b/util/retroImporter/node_modules/mongodb/HISTORY.md deleted file mode 100644 index 4d8fd75..0000000 --- a/util/retroImporter/node_modules/mongodb/HISTORY.md +++ /dev/null @@ -1,1218 +0,0 @@ -2.0.45 09-30-2015 ------------------ -* NODE-566 Fix issue with rewind on capped collections causing cursor state to be reset on connection loss. - -2.0.44 09-28-2015 ------------------ -* Bug fixes for APM upconverting of legacy INSERT/UPDATE/REMOVE wire protocol messages. -* NODE-562, fixed issue where a Replicaset MongoDB URI with a single seed and replSet name set would cause a single direct connection instead of topology discovery. -* Updated mongodb-core to 1.2.14. -* NODE-563 Introduced options.ignoreUndefined for db class and MongoClient db options, made serialize undefined to null default again but allowing for overrides on insert/update/delete operations. -* Use handleCallback if result is an error for count queries. (Issue #1298, https://github.com/agclever) -* Rewind cursor to correctly force reconnect on capped collections when first query comes back empty. -* NODE-571 added code 59 to legacy server errors when SCRAM-SHA-1 mechanism fails. -* NODE-572 Remove examples that use the second parameter to `find()`. - -2.0.43 09-14-2015 ------------------ -* Propagate timeout event correctly to db instances. -* Application Monitoring API (APM) implemented. -* NOT providing replSet name in MongoClient connection URI will force single server connection. Fixes issue where it was impossible to directly connect to a replicaset member server. -* Updated mongodb-core to 1.2.12. -* NODE-541 Initial Support "read committed" isolation level where "committed" means confimed by the voting majority of a replica set. -* GridStore doesn't share readPreference setting from connection string. (Issue #1295, https://github.com/zhangyaoxing) -* fixed forceServerObjectId calls (Issue #1292, https://github.com/d-mon-) -* Pass promise library through to DB function (Issue #1294, https://github.com/RovingCodeMonkey) - -2.0.42 08-18-2015 ------------------ -* Added test case to exercise all non-crud methods on mongos topologies, fixed numberOfConnectedServers on mongos topology instance. - -2.0.41 08-14-2015 ------------------ -* Added missing Mongos.prototype.parserType function. -* Updated mongodb-core to 1.2.10. - -2.0.40 07-14-2015 ------------------ -* Updated mongodb-core to 1.2.9 for 2.4 wire protocol error handler fix. -* NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -* NODE-518 connectTimeoutMS is doubled in 2.0.39. -* NODE-506 Ensures that errors from bulk unordered and ordered are instanceof Error (Issue #1282, https://github.com/owenallenaz). -* NODE-526 Unique index not throwing duplicate key error. -* NODE-528 Ignore undefined fields in Collection.find(). -* NODE-527 The API example for collection.createIndex shows Db.createIndex functionality. - -2.0.39 07-14-2015 ------------------ -* Updated mongodb-core to 1.2.6 for NODE-505. - -2.0.38 07-14-2015 ------------------ -* NODE-505 Query fails to find records that have a 'result' property with an array value. - -2.0.37 07-14-2015 ------------------ -* NODE-504 Collection * Default options when using promiseLibrary. -* NODE-500 Accidental repeat of hostname in seed list multiplies total connections persistently. -* Updated mongodb-core to 1.2.5 to fix NODE-492. - -2.0.36 07-07-2015 ------------------ -* Fully promisified allowing the use of ES6 generators and libraries like co. Also allows for BYOP (Bring your own promises). -* NODE-493 updated mongodb-core to 1.2.4 to ensure we cannot DDOS the mongod or mongos process on large connection pool sizes. - -2.0.35 06-17-2015 ------------------ -* Upgraded to mongodb-core 1.2.2 including removing warnings when C++ bson parser is not available and a fix for SCRAM authentication. - -2.0.34 06-17-2015 ------------------ -* Upgraded to mongodb-core 1.2.1 speeding up serialization and removing the need for the c++ bson extension. -* NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -* NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -* NODE-482 fixed issue where MongoClient.connect would incorrectly identify a replset seed list server as a non replicaset member. -* NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -2.0.33 05-20-2015 ------------------ -* Bumped mongodb-core to 1.1.32. - -2.0.32 05-19-2015 ------------------ -* NODE-463 db.close immediately executes its callback. -* Don't only emit server close event once (Issue #1276, https://github.com/vkarpov15). -* NODE-464 Updated mongodb-core to 1.1.31 that uses a single socket connection to arbiters and hidden servers as well as emitting all event correctly. - -2.0.31 05-08-2015 ------------------ -* NODE-461 Tripping on error "no chunks found for file, possibly corrupt" when there is no error. - -2.0.30 05-07-2015 ------------------ -* NODE-460 fix; don't set authMechanism for user in db.authenticate() to avoid mongoose authentication issue. - -2.0.29 05-07-2015 ------------------ -* NODE-444 Possible memory leak, too many listeners added. -* NODE-459 Auth failure using Node 0.8.28, MongoDB 3.0.2 & mongodb-node-native 1.4.35. -* Bumped mongodb-core to 1.1.26. - -2.0.28 04-24-2015 ------------------ -* Bumped mongodb-core to 1.1.25 -* Added Cursor.prototype.setCursorOption to allow for setting node specific cursor options for tailable cursors. -* NODE-430 Cursor.count() opts argument masked by var opts = {} -* NODE-406 Implemented Cursor.prototype.map function tapping into MongoClient cursor transforms. -* NODE-438 replaceOne is not returning the result.ops property as described in the docs. -* NODE-433 _read, pipe and write all open gridstore automatically if not open. -* NODE-426 ensure drain event is emitted after write function returns, fixes intermittent issues in writing files to gridstore. -* NODE-440 GridStoreStream._read() doesn't check GridStore.read() error. -* Always use readPreference = primary for findAndModify command (ignore passed in read preferences) (Issue #1274, https://github.com/vkarpov15). -* Minor fix in GridStore.exists for dealing with regular expressions searches. - -2.0.27 04-07-2015 ------------------ -* NODE-410 Correctly handle issue with pause/resume in Node 0.10.x that causes exceptions when using the Node 0.12.0 style streams. - -2.0.26 04-07-2015 ------------------ -* Implements the Common Index specification Standard API at https://github.com/mongodb/specifications/blob/master/source/index-management.rst. -* NODE-408 Expose GridStore.currentChunk.chunkNumber. - -2.0.25 03-26-2015 ------------------ -* Upgraded mongodb-core to 1.1.21, making the C++ bson code an optional dependency to the bson module. - -2.0.24 03-24-2015 ------------------ -* NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. -* Upgraded mongodb-core to 1.1.20. - -2.0.23 2015-03-21 ------------------ -* NODE-380 Correctly return MongoError from toError method. -* Fixed issue where addCursorFlag was not correctly setting the flag on the command for mongodb-core. -* NODE-388 Changed length from method to property on order.js/unordered.js bulk operations. -* Upgraded mongodb-core to 1.1.19. - -2.0.22 2015-03-16 ------------------ -* NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. -* Upgraded mongodb-core to 1.1.17. - -2.0.21 2015-03-06 ------------------ -* Upgraded mongodb-core to 1.1.16 making sslValidate default to true to force validation on connection unless overriden by the user. - -2.0.20 2015-03-04 ------------------ -* Updated mongodb-core 1.1.15 to relax pickserver method. - -2.0.19 2015-03-03 ------------------ -* NODE-376 Fixes issue * Unordered batch incorrectly tracks batch size when switching batch types (Issue #1261, https://github.com/meirgottlieb) -* NODE-379 Fixes bug in cursor.count() that causes the result to always be zero for dotted collection names (Issue #1262, https://github.com/vsivsi) -* Expose MongoError from mongodb-core (Issue #1260, https://github.com/tjconcept) - -2.0.18 2015-02-27 ------------------ -* Bumped mongodb-core 1.1.14 to ensure passives are correctly added as secondaries. - -2.0.17 2015-02-27 ------------------ -* NODE-336 Added length function to ordered and unordered bulk operations to be able know the amount of current operations in bulk. -* Bumped mongodb-core 1.1.13 to ensure passives are correctly added as secondaries. - -2.0.16 2015-02-16 ------------------ -* listCollection now returns filtered result correctly removing db name for 2.6 or earlier servers. -* Bumped mongodb-core 1.1.12 to correctly work for node 0.12.0 and io.js. -* Add ability to get collection name from cursor (Issue #1253, https://github.com/vkarpov15) - -2.0.15 2015-02-02 ------------------ -* Unified behavior of listCollections results so 3.0 and pre 3.0 return same type of results. -* Bumped mongodb-core to 1.1.11 to support per document tranforms in cursors as well as relaxing the setName requirement. -* NODE-360 Aggregation cursor and command correctly passing down the maxTimeMS property. -* Added ~1.0 mongodb-tools module for test running. -* Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -2.0.14 2015-01-21 ------------------ -* Fixed some MongoClient.connect options pass through issues and added test coverage. -* Bumped mongodb-core to 1.1.9 including fixes for io.js - -2.0.13 2015-01-09 ------------------ -* Bumped mongodb-core to 1.1.8. -* Optimized query path for performance, moving Object.defineProperty outside of constructors. - -2.0.12 2014-12-22 ------------------ -* Minor fixes to listCollections to ensure correct querying of a collection when using a string. - -2.0.11 2014-12-19 ------------------ -* listCollections filters out index namespaces on < 2.8 correctly -* Bumped mongo-client to 1.1.7 - -2.0.10 2014-12-18 ------------------ -* NODE-328 fixed db.open return when no callback available issue and added test. -* NODE-327 Refactored listCollections to return cursor to support 2.8. -* NODE-327 Added listIndexes method and refactored internal methods to use the new command helper. -* NODE-335 Cannot create index for nested objects fixed by relaxing key checking for createIndex helper. -* Enable setting of connectTimeoutMS (Issue #1235, https://github.com/vkarpov15) -* Bumped mongo-client to 1.1.6 - -2.0.9 2014-12-01 ----------------- -* Bumped mongodb-core to 1.1.3 fixing global leaked variables and introducing strict across all classes. -* All classes are now strict (Issue #1233) -* NODE-324 Refactored insert/update/remove and all other crud opts to rely on internal methods to avoid any recursion. -* Fixed recursion issues in debug logging due to JSON.stringify() -* Documentation fixes (Issue #1232, https://github.com/wsmoak) -* Fix writeConcern in Db.prototype.ensureIndex (Issue #1231, https://github.com/Qard) - -2.0.8 2014-11-28 ----------------- -* NODE-322 Finished up prototype refactoring of Db class. -* NODE-322 Exposed Cursor in index.js for New Relic. - -2.0.7 2014-11-20 ----------------- -* Bumped mongodb-core to 1.1.2 fixing a UTF8 encoding issue for collection names. -* NODE-318 collection.update error while setting a function with serializeFunctions option. -* Documentation fixes. - -2.0.6 2014-11-14 ----------------- -* Refactored code to be prototype based instead of privileged methods. -* Bumped mongodb-core to 1.1.1 to take advantage of the prototype based refactorings. -* Implemented missing aspects of the CRUD specification. -* Fixed documentation issues. -* Fixed global leak REFERENCE_BY_ID in gridfs grid_store (Issue #1225, https://github.com/j) -* Fix LearnBoost/mongoose#2313: don't let user accidentally clobber geoNear params (Issue #1223, https://github.com/vkarpov15) - -2.0.5 2014-10-29 ----------------- -* Minor fixes to documentation and generation of documentation. -* NODE-306 (No results in aggregation cursor when collection name contains a dot), Merged code for cursor and aggregation cursor. - -2.0.4 2014-10-23 ----------------- -* Allow for single replicaset seed list with no setName specified (Issue #1220, https://github.com/imaman) -* Made each rewind on each call allowing for re-using the cursor. -* Fixed issue where incorrect iterations would happen on each for extensive batchSizes. -* NODE-301 specifying maxTimeMS on find causes all fields to be omitted from result. - -2.0.3 2014-10-14 ----------------- -* NODE-297 Aggregate Broken for case of pipeline with no options. - -2.0.2 2014-10-08 ----------------- -* Bumped mongodb-core to 1.0.2. -* Fixed bson module dependency issue by relying on the mongodb-core one. -* Use findOne instead of find followed by nextObject (Issue #1216, https://github.com/sergeyksv) - -2.0.1 2014-10-07 ----------------- -* Dependency fix - -2.0.0 2014-10-07 ----------------- -* First release of 2.0 driver - -2.0.0-alpha2 2014-10-02 ------------------------ -* CRUD API (insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, bulkWrite, findOneAndDelete, findOneAndUpdate, findOneAndReplace) -* Cluster Management Spec compatible. - -2.0.0-alpha1 2014-09-08 ------------------------ -* Insert method allows only up 1000 pr batch for legacy as well as 2.6 mode -* Streaming behavior is 0.10.x or higher with backwards compatibility using readable-stream npm package -* Gridfs stream only available through .stream() method due to overlapping names on Gridstore object and streams in 0.10.x and higher of node -* remove third result on update and remove and return the whole result document instead (getting rid of the weird 3 result parameters) - * Might break some application -* Returns the actual mongodb-core result instead of just the number of records changed for insert/update/remove -* MongoClient only has the connect method (no ability instantiate with Server, ReplSet or similar) -* Removed Grid class -* GridStore only supports w+ for metadata updates, no appending to file as it's not thread safe and can cause corruption of the data - + seek will fail if attempt to use with w or w+ - + write will fail if attempted with w+ or r - + w+ only works for updating metadata on a file -* Cursor toArray and each resets and re-runs the cursor -* FindAndModify returns whole result document instead of just value -* Extend cursor to allow for setting all the options via methods instead of dealing with the current messed up find -* Removed db.dereference method -* Removed db.cursorInfo method -* Removed db.stats method -* Removed db.collectionNames not needed anymore as it's just a specialized case of listCollections -* Removed db.collectionInfo removed due to not being compatible with new storage engines in 2.8 as they need to use the listCollections command due to system collections not working for namespaces. -* Added db.listCollections to replace several methods above - -1.4.10 2014-09-04 ------------------ -* Fixed BSON and Kerberos compilation issues -* Bumped BSON to ~0.2 always installing latest BSON 0.2.x series -* Fixed Kerberos and bumped to 0.0.4 - -1.4.9 2014-08-26 ----------------- -* Check _bsonType for Binary (Issue #1202, https://github.com/mchapman) -* Remove duplicate Cursor constructor (Issue #1201, https://github.com/KenPowers) -* Added missing parameter in the documentation (Issue #1199, https://github.com/wpjunior) -* Documented third parameter on the update callback(Issue #1196, https://github.com/gabmontes) -* NODE-240 Operations on SSL connection hang on node 0.11.x -* NODE-235 writeResult is not being passed on when error occurs in insert -* NODE-229 Allow count to work with query hints -* NODE-233 collection.save() does not support fullResult -* NODE-244 Should parseError also emit a `disconnected` event? -* NODE-246 Cursors are inefficiently constructed and consequently cannot be promisified. -* NODE-248 Crash with X509 auth -* NODE-252 Uncaught Exception in Base.__executeAllServerSpecificErrorCallbacks -* Bumped BSON parser to 0.2.12 - - -1.4.8 2014-08-01 ----------------- -* NODE-205 correctly emit authenticate event -* NODE-210 ensure no undefined connection error when checking server state -* NODE-212 correctly inherit socketTimeoutMS from replicaset when HA process adds new servers or reconnects to existing ones -* NODE-220 don't throw error if ensureIndex errors out in Gridstore -* Updated bson to 0.2.11 to ensure correct toBSON behavior when returning non object in nested classes -* Fixed test running filters -* Wrap debug log in a call to format (Issue #1187, https://github.com/andyroyle) -* False option values should not trigger w:1 (Issue #1186, https://github.com/jsdevel) -* Fix aggregatestream.close(Issue #1194, https://github.com/jonathanong) -* Fixed parsing issue for w:0 in url parser when in connection string -* Modified collection.geoNear to support a geoJSON point or legacy coordinate pair (Issue #1198, https://github.com/mmacmillan) - -1.4.7 2014-06-18 ----------------- -* Make callbacks to be executed in right domain when server comes back up (Issue #1184, https://github.com/anton-kotenko) -* Fix issue where currentOp query against mongos would fail due to mongos passing through $readPreference field to mongod (CS-X) - -1.4.6 2014-06-12 ----------------- -* Added better support for MongoClient IP6 parsing (Issue #1181, https://github.com/micovery) -* Remove options check on index creation (Issue #1179, Issue #1183, https://github.com/jdesboeufs, https://github.com/rubenvereecken) -* Added missing type check before calling optional callback function (Issue #1180) - -1.4.5 2014-05-21 ----------------- -* Added fullResult flag to insert/update/remove which will pass raw result document back. Document contents will vary depending on the server version the driver is talking to. No attempt is made to coerce a joint response. -* Fix to avoid MongoClient.connect hanging during auth when secondaries building indexes pre 2.6. -* return the destination stream in GridStore.pipe (Issue #1176, https://github.com/iamdoron) - -1.4.4 2014-05-13 ----------------- -* Bumped BSON version to use the NaN 1.0 package, fixed strict comparison issue for ObjectID -* Removed leaking global variable (Issue #1174, https://github.com/dainis) -* MongoClient respects connectTimeoutMS for initial discovery process (NODE-185) -* Fix bug with return messages larger than 16MB but smaller than max BSON Message Size (NODE-184) - -1.4.3 2014-05-01 ----------------- -* Clone options for commands to avoid polluting original options passed from Mongoose (Issue #1171, https://github.com/vkarpov15) -* Made geoNear and geoHaystackSearch only clean out allowed options from command generation (Issue #1167) -* Fixed typo for allowDiskUse (Issue #1168, https://github.com/joaofranca) -* A 'mapReduce' function changed 'function' to instance '\' of 'Code' class (Issue #1165, https://github.com/exabugs) -* Made findAndModify set sort only when explicitly set (Issue #1163, https://github.com/sars) -* Rewriting a gridStore file by id should use a new filename if provided (Issue #1169, https://github.com/vsivsi) - -1.4.2 2014-04-15 ----------------- -* Fix for inheritance of readPreferences from MongoClient NODE-168/NODE-169 -* Merged in fix for ping strategy to avoid hitting non-pinged servers (Issue #1161, https://github.com/vaseker) -* Merged in fix for correct debug output for connection messages (Issue #1158, https://github.com/vaseker) -* Fixed global variable leak (Issue #1160, https://github.com/vaseker) - -1.4.1 2014-04-09 ----------------- -* Correctly emit joined event when primary change -* Add _id to documents correctly when using bulk operations - -1.4.0 2014-04-03 ----------------- -* All node exceptions will no longer be caught if on('error') is defined -* Added X509 auth support -* Fix for MongoClient connection timeout issue (NODE-97) -* Pass through error messages from parseError instead of just text (Issue #1125) -* Close db connection on error (Issue #1128, https://github.com/benighted) -* Fixed documentation generation -* Added aggregation cursor for 2.6 and emulated cursor for pre 2.6 (uses stream2) -* New Bulk API implementation using write commands for 2.6 and down converts for pre 2.6 -* Insert/Update/Remove using new write commands when available -* Added support for new roles based API's in 2.6 for addUser/removeUser -* Added bufferMaxEntries to start failing if the buffer hits the specified number of entries -* Upgraded BSON parser to version 0.2.7 to work with < 0.11.10 C++ API changes -* Support for OP_LOG_REPLAY flag (NODE-94) -* Fixes for SSL HA ping and discovery. -* Uses createIndexes if available for ensureIndex/createIndex -* Added parallelCollectionScan method to collection returning CommandCursor instances for cursors -* Made CommandCursor behave as Readable stream. -* Only Db honors readPreference settings, removed Server.js legacy readPreference settings due to user confusion. -* Reconnect event emitted by ReplSet/Mongos/Server after reconnect and before replaying of buffered operations. -* GridFS buildMongoObject returns error on illegal md5 (NODE-157, https://github.com/iantocristian) -* Default GridFS chunk size changed to (255 * 1024) bytes to optimize for collections defaulting to power of 2 sizes on 2.6. -* Refactored commands to all go through command function ensuring consistent command execution. -* Fixed issues where readPreferences where not correctly passed to mongos. -* Catch error == null and make err detection more prominent (NODE-130) -* Allow reads from arbiter for single server connection (NODE-117) -* Handle error coming back with no documents (NODE-130) -* Correctly use close parameter in Gridstore.write() (NODE-125) -* Throw an error on a bulk find with no selector (NODE-129, https://github.com/vkarpov15) -* Use a shallow copy of options in find() (NODE-124, https://github.com/vkarpov15) -* Fix statistical strategy (NODE-158, https://github.com/vkarpov15) -* GridFS off-by-one bug in lastChunkNumber() causes uncaught throw and data loss (Issue #1154, https://github.com/vsivsi) -* GridStore drops passed `aliases` option, always results in `null` value in GridFS files (Issue #1152, https://github.com/vsivsi) -* Remove superfluous connect object copying in index.js (Issue #1145, https://github.com/thomseddon) -* Do not return false when the connection buffer is still empty (Issue #1143, https://github.com/eknkc) -* Check ReadPreference object on ReplSet.canRead (Issue #1142, https://github.com/eknkc) -* Fix unpack error on _executeQueryCommand (Issue #1141, https://github.com/eknkc) -* Close db on failed connect so node can exit (Issue #1128, https://github.com/benighted) -* Fix global leak with _write_concern (Issue #1126, https://github.com/shanejonas) - -1.3.19 2013-08-21 ------------------ -* Correctly rethrowing errors after change from event emission to callbacks, compatibility with 0.10.X domains without breaking 0.8.X support. -* Small fix to return the entire findAndModify result as the third parameter (Issue #1068) -* No removal of "close" event handlers on server reconnect, emits "reconnect" event when reconnection happens. Reconnect Only applies for single server connections as of now as semantics for ReplSet and Mongos is not clear (Issue #1056) - -1.3.18 2013-08-10 ------------------ -* Fixed issue when throwing exceptions in MongoClient.connect/Db.open (Issue #1057) -* Fixed an issue where _events is not cleaned up correctly causing a slow steady memory leak. - -1.3.17 2013-08-07 ------------------ -* Ignore return commands that have no registered callback -* Made collection.count not use the db.command function -* Fix throw exception on ping command (Issue #1055) - -1.3.16 2013-08-02 ------------------ -* Fixes connection issue where lots of connections would happen if a server is in recovery mode during connection (Issue #1050, NODE-50, NODE-51) -* Bug in unlink mulit filename (Issue #1054) - -1.3.15 2013-08-01 ------------------ -* Memory leak issue due to node Issue #4390 where _events[id] is set to undefined instead of deleted leading to leaks in the Event Emitter over time - -1.3.14 2013-08-01 ------------------ -* Fixed issue with checkKeys where it would error on X.X - -1.3.13 2013-07-31 ------------------ -* Added override for checkKeys on insert/update (Warning will expose you to injection attacks) (Issue #1046) -* BSON size checking now done pre serialization (Issue #1037) -* Added isConnected returns false when no connection Pool exists (Issue #1043) -* Unified command handling to ensure same handling (Issue #1041, #1042) -* Correctly emit "open" and "fullsetup" across all Db's associated with Mongos, ReplSet or Server (Issue #1040) -* Correctly handles bug in authentication when attempting to connect to a recovering node in a replicaset. -* Correctly remove recovering servers from available servers in replicaset. Piggybacks on the ping command. -* Removed findAndModify chaining to be compliant with behavior in other official drivers and to fix a known mongos issue. -* Fixed issue with Kerberos authentication on Windows for re-authentication. -* Fixed Mongos failover behavior to correctly throw out old servers. -* Ensure stored queries/write ops are executed correctly after connection timeout -* Added promoteLongs option for to allow for overriding the promotion of Longs to Numbers and return the actual Long. - -1.3.12 2013-07-19 ------------------ -* Fixed issue where timeouts sometimes would behave wrongly (Issue #1032) -* Fixed bug with callback third parameter on some commands (Issue #1033) -* Fixed possible issue where killcursor command might leave hanging functions -* Fixed issue where Mongos was not correctly removing dead servers from the pool of eligable servers -* Throw error if dbName or collection name contains null character (at command level and at collection level) -* Updated bson parser to 0.2.1 with security fix and non-promotion of Long values to javascript Numbers (once a long always a long) - -1.3.11 2013-07-04 ------------------ -* Fixed errors on geoNear and geoSearch (Issue #1024, https://github.com/ebensing) -* Add driver version to export (Issue #1021, https://github.com/aheckmann) -* Add text to readpreference obedient commands (Issue #1019) -* Drivers should check the query failure bit even on getmore response (Issue #1018) -* Map reduce has incorrect expectations of 'inline' value for 'out' option (Issue #1016, https://github.com/rcotter) -* Support SASL PLAIN authentication (Issue #1009) -* Ability to use different Service Name on the driver for Kerberos Authentication (Issue #1008) -* Remove unnecessary octal literal to allow the code to run in strict mode (Issue #1005, https://github.com/jamesallardice) -* Proper handling of recovering nodes (when they go into recovery and when they return from recovery, Issue #1027) - -1.3.10 2013-06-17 ------------------ -* Guard against possible undefined in server::canCheckoutWriter (Issue #992, https://github.com/willyaranda) -* Fixed some duplicate test names (Issue #993, https://github.com/kawanet) -* Introduced write and read concerns for GridFS (Issue #996) -* Fixed commands not correctly respecting Collection level read preference (Issue #995, #999) -* Fixed issue with pool size on replicaset connections (Issue #1000) -* Execute all query commands on master switch (Issue #1002, https://github.com/fogaztuc) - -1.3.9 2013-06-05 ----------------- -* Fixed memory leak when findAndModify errors out on w>1 and chained callbacks not properly cleaned up. - -1.3.8 2013-05-31 ----------------- -* Fixed issue with socket death on windows where it emits error event instead of close event (Issue #987) -* Emit authenticate event on db after authenticate method has finished on db instance (Issue #984) -* Allows creation of MongoClient and do new MongoClient().connect(..). Emits open event when connection correct allowing for apps to react on event. - -1.3.7 2013-05-29 ----------------- -* After reconnect, tailable getMores go on inconsistent connections (Issue #981, #982, https://github.com/glasser) -* Updated Bson to 0.1.9 to fix ARM support (Issue #985) - -1.3.6 2013-05-21 ----------------- -* Fixed issue where single server reconnect attempt would throw due to missing options variable (Issue #979) -* Fixed issue where difference in ismaster server name and seed list caused connections issues, (Issue #976) - -1.3.5 2013-05-14 ----------------- -* Fixed issue where HA for replicaset would pick the same broken connection when attempting to ping the replicaset causing the replicaset to never recover. - -1.3.4 2013-05-14 ----------------- -* Fixed bug where options not correctly passed in for uri parser (Issue #973, https://github.com/supershabam) -* Fixed bug when passing a named index hint (Issue #974) - -1.3.3 2013-05-09 ----------------- -* Fixed auto-reconnect issue with single server instance. - -1.3.2 2013-05-08 ----------------- -* Fixes for an issue where replicaset would be pronounced dead when high priority primary caused double elections. - -1.3.1 2013-05-06 ----------------- -* Fix for replicaset consisting of primary/secondary/arbiter with priority applied failing to reconnect properly -* Applied auth before server instance is set as connected when single server connection -* Throw error if array of documents passed to save method - -1.3.0 2013-04-25 ----------------- -* Whole High availability handling for Replicaset, Server and Mongos connections refactored to ensure better handling of failover cases. -* Fixed issue where findAndModify would not correctly skip issuing of chained getLastError (Issue #941) -* Fixed throw error issue on errors with findAndModify during write out operation (Issue #939, https://github.com/autopulated) -* Gridstore.prototype.writeFile now returns gridstore object correctly (Issue #938) -* Kerberos support is now an optional module that allows for use of GSSAPI authentication using MongoDB Subscriber edition -* Fixed issue where cursor.toArray could blow the stack on node 0.10.X (#950) - -1.2.14 2013-03-14 ------------------ -* Refactored test suite to speed up running of replicaset tests -* Fix of async error handling when error happens in callback (Issue #909, https://github.com/medikoo) -* Corrected a slaveOk setting issue (Issue #906, #905) -* Fixed HA issue where ping's would not go to correct server on HA server connection failure. -* Uses setImmediate if on 0.10 otherwise nextTick for cursor stream -* Fixed race condition in Cursor stream (NODE-31) -* Fixed issues related to node 0.10 and process.nextTick now correctly using setImmediate where needed on node 0.10 -* Added support for maxMessageSizeBytes if available (DRIVERS-1) -* Added support for authSource (2.4) to MongoClient URL and db.authenticate method (DRIVER-69/NODE-34) -* Fixed issue in GridStore seek and GridStore read to correctly work on multiple seeks (Issue #895) - -1.2.13 2013-02-22 ------------------ -* Allow strategy 'none' for repliaset if no strategy wanted (will default to round robin selection of servers on a set readPreference) -* Fixed missing MongoErrors on some cursor methods (Issue #882) -* Correctly returning a null for the db instance on MongoClient.connect when auth fails (Issue #890) -* Added dropTarget option support for renameCollection/rename (Issue #891, help from https://github.com/jbottigliero) -* Fixed issue where connection using MongoClient.connect would fail if first server did not exist (Issue #885) - -1.2.12 2013-02-13 ------------------ -* Added limit/skip options to Collection.count (Issue #870) -* Added applySkipLimit option to Cursor.count (Issue #870) -* Enabled ping strategy as default for Replicaset if none specified (Issue #876) -* Should correctly pick nearest server for SECONDARY/SECONDARY_PREFERRED/NEAREST (Issue #878) - -1.2.11 2013-01-29 ------------------ -* Added fixes for handling type 2 binary due to PHP driver (Issue #864) -* Moved callBackStore to Base class to have single unified store (Issue #866) -* Ping strategy now reuses sockets unless they are closed by the server to avoid overhead - -1.2.10 2013-01-25 ------------------ -* Merged in SSL support for 2.4 supporting certificate validation and presenting certificates to the server. -* Only open a new HA socket when previous one dead (Issue #859, #857) -* Minor fixes - -1.2.9 2013-01-15 ----------------- -* Fixed bug in SSL support for MongoClient/Db.connect when discovering servers (Issue #849) -* Connection string with no db specified should default to admin db (Issue #848) -* Support port passed as string to Server class (Issue #844) -* Removed noOpen support for MongoClient/Db.connect as auto discovery of servers for Mongod/Mongos makes it not possible (Issue #842) -* Included toError wrapper code moved to utils.js file (Issue #839, #840) -* Rewrote cursor handling to avoid process.nextTick using trampoline instead to avoid stack overflow, speedup about 40% - -1.2.8 2013-01-07 ----------------- -* Accept function in a Map Reduce scope object not only a function string (Issue #826, https://github.com/aheckmann) -* Typo in db.authenticate caused a check (for provided connection) to return false, causing a connection AND onAll=true to be passed into __executeQueryCommand downstream (Issue #831, https://github.com/m4tty) -* Allow gridfs objects to use non ObjectID ids (Issue #825, https://github.com/nailgun) -* Removed the double wrap, by not passing an Error object to the wrap function (Issue #832, https://github.com/m4tty) -* Fix connection leak (gh-827) for HA replicaset health checks (Issue #833, https://github.com/aheckmann) -* Modified findOne to use nextObject instead of toArray avoiding a nextTick operation (Issue #836) -* Fixes for cursor stream to avoid multiple getmore issues when one in progress (Issue #818) -* Fixes .open replaying all backed up commands correctly if called after operations performed, (Issue #829 and #823) - -1.2.7 2012-12-23 ----------------- -* Rolled back batches as they hang in certain situations -* Fixes for NODE-25, keep reading from secondaries when primary goes down - -1.2.6 2012-12-21 ----------------- -* domain sockets shouldn't require a port arg (Issue #815, https://github.com/aheckmann) -* Cannot read property 'info' of null (Issue #809, https://github.com/thesmart) -* Cursor.each should work in batches (Issue #804, https://github.com/Swatinem) -* Cursor readPreference bug for non-supported read preferences (Issue #817) - -1.2.5 2012-12-12 ----------------- -* Fixed ssl regression, added more test coverage (Issue #800) -* Added better error reporting to the Db.connect if no valid serverConfig setup found (Issue #798) - -1.2.4 2012-12-11 ----------------- -* Fix to ensure authentication is correctly applied across all secondaries when using MongoClient. - -1.2.3 2012-12-10 ----------------- -* Fix for new replicaset members correctly authenticating when being added (Issue #791, https://github.com/m4tty) -* Fixed seek issue in gridstore when using stream (Issue #790) - -1.2.2 2012-12-03 ----------------- -* Fix for journal write concern not correctly being passed under some circumstances. -* Fixed correct behavior and re-auth for servers that get stepped down (Issue #779). - -1.2.1 2012-11-30 ----------------- -* Fix for double callback on insert with w:0 specified (Issue #783) -* Small cleanup of urlparser. - -1.2.0 2012-11-27 ----------------- -* Honor connectTimeoutMS option for replicasets (Issue #750, https://github.com/aheckmann) -* Fix ping strategy regression (Issue #738, https://github.com/aheckmann) -* Small cleanup of code (Issue #753, https://github.com/sokra/node-mongodb-native) -* Fixed index declaration using objects/arrays from other contexts (Issue #755, https://github.com/sokra/node-mongodb-native) -* Intermittent (and rare) null callback exception when using ReplicaSets (Issue #752) -* Force correct setting of read_secondary based on the read preference (Issue #741) -* If using read preferences with secondaries queries will not fail if primary is down (Issue #744) -* noOpen connection for Db.connect removed as not compatible with autodetection of Mongo type -* Mongos connection with auth not working (Issue #737) -* Use the connect method directly from the require. require('mongodb')("mongodb://localhost:27017/db") -* new MongoClient introduced as the point of connecting to MongoDB's instead of the Db - * open/close/db/connect methods implemented -* Implemented common URL connection format using MongoClient.connect allowing for simialar interface across all drivers. -* Fixed a bug with aggregation helper not properly accepting readPreference - -1.1.11 2012-10-10 ------------------ -* Removed strict mode and introduced normal handling of safe at DB level. - -1.1.10 2012-10-08 ------------------ -* fix Admin.serverStatus (Issue #723, https://github.com/Contra) -* logging on connection open/close(Issue #721, https://github.com/asiletto) -* more fixes for windows bson install (Issue #724) - -1.1.9 2012-10-05 ----------------- -* Updated bson to 0.1.5 to fix build problem on sunos/windows. - -1.1.8 2012-10-01 ----------------- -* Fixed db.eval to correctly handle system.js global javascript functions (Issue #709) -* Cleanup of non-closing connections (Issue #706) -* More cleanup of connections under replicaset (Issue #707, https://github.com/elbert3) -* Set keepalive on as default, override if not needed -* Cleanup of jsbon install to correctly build without install.js script (https://github.com/shtylman) -* Added domain socket support new Server("/tmp/mongodb.sock") style - -1.1.7 2012-09-10 ----------------- -* Protect against starting PingStrategy being called more than once (Issue #694, https://github.com/aheckmann) -* Make PingStrategy interval configurable (was 1 second, relaxed to 5) (Issue #693, https://github.com/aheckmann) -* Made PingStrategy api more consistant, callback to start/stop methods are optional (Issue #693, https://github.com/aheckmann) -* Proper stopping of strategy on replicaset stop -* Throw error when gridstore file is not found in read mode (Issue #702, https://github.com/jbrumwell) -* Cursor stream resume now using nextTick to avoid duplicated records (Issue #696) - -1.1.6 2012-09-01 ----------------- -* Fix for readPreference NEAREST for replicasets (Issue #693, https://github.com/aheckmann) -* Emit end correctly on stream cursor (Issue #692, https://github.com/Raynos) - -1.1.5 2012-08-29 ----------------- -* Fix for eval on replicaset Issue #684 -* Use helpful error msg when native parser not compiled (Issue #685, https://github.com/aheckmann) -* Arbiter connect hotfix (Issue #681, https://github.com/fengmk2) -* Upgraded bson parser to 0.1.2 using gyp, deprecated support for node 0.4.X -* Added name parameter to createIndex/ensureIndex to be able to override index names larger than 128 bytes -* Added exhaust option for find for feature completion (not recommended for normal use) -* Added tailableRetryInterval to find for tailable cursors to allow to control getMore retry time interval -* Fixes for read preferences when using MongoS to correctly handle no read preference set when iterating over a cursor (Issue #686) - -1.1.4 2012-08-12 ----------------- -* Added Mongos connection type with a fallback list for mongos proxies, supports ha (on by default) and will attempt to reconnect to failed proxies. -* Documents can now have a toBSON method that lets the user control the serialization behavior for documents being saved. -* Gridstore instance object now works as a readstream or writestream (thanks to code from Aaron heckmann (https://github.com/aheckmann/gridfs-stream)). -* Fix gridfs readstream (Issue #607, https://github.com/tedeh). -* Added disableDriverBSONSizeCheck property to Server.js for people who wish to push the inserts to the limit (Issue #609). -* Fixed bug where collection.group keyf given as Code is processed as a regular object (Issue #608, https://github.com/rrusso2007). -* Case mismatch between driver's ObjectID and mongo's ObjectId, allow both (Issue #618). -* Cleanup map reduce (Issue #614, https://github.com/aheckmann). -* Add proper error handling to gridfs (Issue #615, https://github.com/aheckmann). -* Ensure cursor is using same connection for all operations to avoid potential jump of servers when using replicasets. -* Date identification handled correctly in bson js parser when running in vm context. -* Documentation updates -* GridStore filename not set on read (Issue #621) -* Optimizations on the C++ bson parser to fix a potential memory leak and avoid non-needed calls -* Added support for awaitdata for tailable cursors (Issue #624) -* Implementing read preference setting at collection and cursor level - * collection.find().setReadPreference(Server.SECONDARY_PREFERRED) - * db.collection("some", {readPreference:Server.SECONDARY}) -* Replicaset now returns when the master is discovered on db.open and lets the rest of the connections happen asynchronous. - * ReplSet/ReplSetServers emits "fullsetup" when all servers have been connected to -* Prevent callback from executing more than once in getMore function (Issue #631, https://github.com/shankar0306) -* Corrupt bson messages now errors out to all callbacks and closes up connections correctly, Issue #634 -* Replica set member status update when primary changes bug (Issue #635, https://github.com/alinsilvian) -* Fixed auth to work better when multiple connections are involved. -* Default connection pool size increased to 5 connections. -* Fixes for the ReadStream class to work properly with 0.8 of Node.js -* Added explain function support to aggregation helper -* Added socketTimeoutMS and connectTimeoutMS to socket options for repl_set.js and server.js -* Fixed addUser to correctly handle changes in 2.2 for getLastError authentication required -* Added index to gridstore chunks on file_id (Issue #649, https://github.com/jacobbubu) -* Fixed Always emit db events (Issue #657) -* Close event not correctly resets DB openCalled variable to allow reconnect -* Added open event on connection established for replicaset, mongos and server -* Much faster BSON C++ parser thanks to Lucasfilm Singapore. -* Refactoring of replicaset connection logic to simplify the code. -* Add `options.connectArbiter` to decide connect arbiters or not (Issue #675) -* Minor optimization for findAndModify when not using j,w or fsync for safe - -1.0.2 2012-05-15 ----------------- -* Reconnect functionality for replicaset fix for mongodb 2.0.5 - -1.0.1 2012-05-12 ----------------- -* Passing back getLastError object as 3rd parameter on findAndModify command. -* Fixed a bunch of performance regressions in objectId and cursor. -* Fixed issue #600 allowing for single document delete to be passed in remove command. - -1.0.0 2012-04-25 ----------------- -* Fixes to handling of failover on server error -* Only emits error messages if there are error listeners to avoid uncaught events -* Server.isConnected using the server state variable not the connection pool state - -0.9.9.8 2012-04-12 ------------------- -* _id=0 is being turned into an ObjectID (Issue #551) -* fix for error in GridStore write method (Issue #559) -* Fix for reading a GridStore from arbitrary, non-chunk aligned offsets, added test (Issue #563, https://github.com/subroutine) -* Modified limitRequest to allow negative limits to pass through to Mongo, added test (Issue #561) -* Corrupt GridFS files when chunkSize < fileSize, fixed concurrency issue (Issue #555) -* Handle dead tailable cursors (Issue #568, https://github.com/aheckmann) -* Connection pools handles closing themselves down and clearing the state -* Check bson size of documents against maxBsonSize and throw client error instead of server error, (Issue #553) -* Returning update status document at the end of the callback for updates, (Issue #569) -* Refactor use of Arguments object to gain performance (Issue #574, https://github.com/AaronAsAChimp) - -0.9.9.7 2012-03-16 ------------------- -* Stats not returned from map reduce with inline results (Issue #542) -* Re-enable testing of whether or not the callback is called in the multi-chunk seek, fix small GridStore bug (Issue #543, https://github.com/pgebheim) -* Streaming large files from GridFS causes truncation (Issue #540) -* Make callback type checks agnostic to V8 context boundaries (Issue #545) -* Correctly throw error if an attempt is made to execute an insert/update/remove/createIndex/ensureIndex with safe enabled and no callback -* Db.open throws if the application attemps to call open again without calling close first - -0.9.9.6 2012-03-12 ------------------- -* BSON parser is externalized in it's own repository, currently using git master -* Fixes for Replicaset connectivity issue (Issue #537) -* Fixed issues with node 0.4.X vs 0.6.X (Issue #534) -* Removed SimpleEmitter and replaced with standard EventEmitter -* GridStore.seek fails to change chunks and call callback when in read mode (Issue #532) - -0.9.9.5 2012-03-07 ------------------- -* Merged in replSetGetStatus helper to admin class (Issue #515, https://github.com/mojodna) -* Merged in serverStatus helper to admin class (Issue #516, https://github.com/mojodna) -* Fixed memory leak in C++ bson parser (Issue #526) -* Fix empty MongoError "message" property (Issue #530, https://github.com/aheckmann) -* Cannot save files with the same file name to GridFS (Issue #531) - -0.9.9.4 2012-02-26 ------------------- -* bugfix for findAndModify: Error: corrupt bson message < 5 bytes long (Issue #519) - -0.9.9.3 2012-02-23 ------------------- -* document: save callback arguments are both undefined, (Issue #518) -* Native BSON parser install error with npm, (Issue #517) - -0.9.9.2 2012-02-17 ------------------- -* Improved detection of Buffers using Buffer.isBuffer instead of instanceof. -* Added wrap error around db.dropDatabase to catch all errors (Issue #512) -* Added aggregate helper to collection, only for MongoDB >= 2.1 - -0.9.9.1 2012-02-15 ------------------- -* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. -* Mapreduce now throws error if out parameter is not specified. - -0.9.9 2012-02-13 ----------------- -* Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. -* Db.close(true) now makes connection unusable as it's been force closed by app. -* Fixed mapReduce and group functions to correctly send slaveOk on queries. -* Fixes for find method to correctly work with find(query, fields, callback) (Issue #506). -* A fix for connection error handling when using the SSL on MongoDB. - -0.9.8-7 2012-02-06 ------------------- -* Simplified findOne to use the find command instead of the custom code (Issue #498). -* BSON JS parser not also checks for _bsonType variable in case BSON object is in weird scope (Issue #495). - -0.9.8-6 2012-02-04 ------------------- -* Removed the check for replicaset change code as it will never work with node.js. - -0.9.8-5 2012-02-02 ------------------- -* Added geoNear command to Collection. -* Added geoHaystackSearch command to Collection. -* Added indexes command to collection to retrieve the indexes on a Collection. -* Added stats command to collection to retrieve the statistics on a Collection. -* Added listDatabases command to admin object to allow retrieval of all available dbs. -* Changed createCreateIndexCommand to work better with options. -* Fixed dereference method on Db class to correctly dereference Db reference objects. -* Moved connect object onto Db class(Db.connect) as well as keeping backward compatibility. -* Removed writeBuffer method from gridstore, write handles switching automatically now. -* Changed readBuffer to read on Gridstore, Gridstore now only supports Binary Buffers no Strings anymore. -* Moved Long class to bson directory. - -0.9.8-4 2012-01-28 ------------------- -* Added reIndex command to collection and db level. -* Added support for $returnKey, $maxScan, $min, $max, $showDiskLoc, $comment to cursor and find/findOne methods. -* Added dropDups and v option to createIndex and ensureIndex. -* Added isCapped method to Collection. -* Added indexExists method to Collection. -* Added findAndRemove method to Collection. -* Fixed bug for replicaset connection when no active servers in the set. -* Fixed bug for replicaset connections when errors occur during connection. -* Merged in patch for BSON Number handling from Lee Salzman, did some small fixes and added test coverage. - -0.9.8-3 2012-01-21 ------------------- -* Workaround for issue with Object.defineProperty (Issue #484) -* ObjectID generation with date does not set rest of fields to zero (Issue #482) - -0.9.8-2 2012-01-20 ------------------- -* Fixed a missing this in the ReplSetServers constructor. - -0.9.8-1 2012-01-17 ------------------- -* FindAndModify bug fix for duplicate errors (Issue #481) - -0.9.8 2012-01-17 ----------------- -* Replicasets now correctly adjusts to live changes in the replicaset configuration on the servers, reconnecting correctly. - * Set the interval for checking for changes setting the replicaSetCheckInterval property when creating the ReplSetServers instance or on db.serverConfig.replicaSetCheckInterval. (default 1000 miliseconds) -* Fixes formattedOrderClause in collection.js to accept a plain hash as a parameter (Issue #469) https://github.com/tedeh -* Removed duplicate code for formattedOrderClause and moved to utils module -* Pass in poolSize for ReplSetServers to set default poolSize for new replicaset members -* Bug fix for BSON JS deserializer. Isolating the eval functions in separate functions to avoid V8 deoptimizations -* Correct handling of illegal BSON messages during deserialization -* Fixed Infinite loop when reading GridFs file with no chunks (Issue #471) -* Correctly update existing user password when using addUser (Issue #470) - -0.9.7.3-5 2012-01-04 --------------------- -* Fix for RegExp serialization for 0.4.X where typeof /regexp/ == 'function' vs in 0.6.X typeof /regexp/ == 'object' -* Don't allow keepAlive and setNoDelay for 0.4.X as it throws errors - -0.9.7.3-4 2012-01-04 --------------------- -* Chased down potential memory leak on findAndModify, Issue #467 (node.js removeAllListeners leaves the key in the _events object, node.js bug on eventlistener?, leads to extremely slow memory leak on listener object) -* Sanity checks for GridFS performance with benchmark added - -0.9.7.3-3 2012-01-04 --------------------- -* Bug fixes for performance issues going form 0.9.6.X to 0.9.7.X on linux -* BSON bug fixes for performance - -0.9.7.3-2 2012-01-02 --------------------- -* Fixed up documentation to reflect the preferred way of instantiating bson types -* GC bug fix for JS bson parser to avoid stop-and-go GC collection - -0.9.7.3-1 2012-01-02 --------------------- -* Fix to make db.bson_serializer and db.bson_deserializer work as it did previously - -0.9.7.3 2011-12-30 --------------------- -* Moved BSON_BINARY_SUBTYPE_DEFAULT from BSON object to Binary object and removed the BSON_BINARY_ prefixes -* Removed Native BSON types, C++ parser uses JS types (faster due to cost of crossing the JS-C++ barrier for each call) -* Added build fix for 0.4.X branch of Node.js where GetOwnPropertyNames is not defined in v8 -* Fix for wire protocol parser for corner situation where the message is larger than the maximum socket buffer in node.js (Issue #464, #461, #447) -* Connection pool status set to connected on poolReady, isConnected returns false on anything but connected status (Issue #455) - -0.9.7.2-5 2011-12-22 --------------------- -* Brand spanking new Streaming Cursor support Issue #458 (https://github.com/christkv/node-mongodb-native/pull/458) thanks to Mr Aaron Heckmann - -0.9.7.2-4 2011-12-21 --------------------- -* Refactoring of callback code to work around performance regression on linux -* Fixed group function to correctly use the command mode as default - -0.9.7.2-3 2011-12-18 --------------------- -* Fixed error handling for findAndModify while still working for mongodb 1.8.6 (Issue #450). -* Allow for force send query to primary, pass option (read:'primary') on find command. - * ``find({a:1}, {read:'primary'}).toArray(function(err, items) {});`` - -0.9.7.2-2 2011-12-16 --------------------- -* Fixes infinite streamRecords QueryFailure fix when using Mongos (Issue #442) - -0.9.7.2-1 2011-12-16 --------------------- -* ~10% perf improvement for ObjectId#toHexString (Issue #448, https://github.com/aheckmann) -* Only using process.nextTick on errors emitted on callbacks not on all parsing, reduces number of ticks in the driver -* Changed parsing off bson messages to use process.nextTick to do bson parsing in batches if the message is over 10K as to yield more time to the event look increasing concurrency on big mongoreply messages with multiple documents - -0.9.7.2 2011-12-15 ------------------- -* Added SSL support for future version of mongodb (VERY VERY EXPERIMENTAL) - * pass in the ssl:true option to the server or replicaset server config to enable - * a bug either in mongodb or node.js does not allow for more than 1 connection pr db instance (poolSize:1). -* Added getTimestamp() method to objectID that returns a date object -* Added finalize function to collection.group - * function group (keys, condition, initial, reduce, finalize, command, callback) -* Reaper no longer using setTimeout to handle reaping. Triggering is done in the general flow leading to predictable behavior. - * reaperInterval, set interval for reaper (default 10000 miliseconds) - * reaperTimeout, set timeout for calls (default 30000 miliseconds) - * reaper, enable/disable reaper (default false) -* Work around for issues with findAndModify during high concurrency load, insure that the behavior is the same across the 1.8.X branch and 2.X branch of MongoDb -* Reworked multiple db's sharing same connection pool to behave correctly on error, timeout and close -* EnsureIndex command can be executed without a callback (Issue #438) -* Eval function no accepts options including nolock (Issue #432) - * eval(code, parameters, options, callback) (where options = {nolock:true}) - -0.9.7.1-4 2011-11-27 --------------------- -* Replaced install.sh with install.js to install correctly on all supported os's - -0.9.7.1-3 2011-11-27 --------------------- -* Fixes incorrect scope for ensureIndex error wrapping (Issue #419) https://github.com/ritch - -0.9.7.1-2 2011-11-27 --------------------- -* Set statistical selection strategy as default for secondary choice. - -0.9.7.1-1 2011-11-27 --------------------- -* Better handling of single server reconnect (fixes some bugs) -* Better test coverage of single server failure -* Correct handling of callbacks on replicaset servers when firewall dropping packets, correct reconnect - -0.9.7.1 2011-11-24 ------------------- -* Better handling of dead server for single server instances -* FindOne and find treats selector == null as {}, Issue #403 -* Possible to pass in a strategy for the replicaset to pick secondary reader node - * parameter strategy - * ping (default), pings the servers and picks the one with the lowest ping time - * statistical, measures each request and pick the one with the lowest mean and std deviation -* Set replicaset read preference replicaset.setReadPreference() - * Server.READ_PRIMARY (use primary server for reads) - * Server.READ_SECONDARY (from a secondary server (uses the strategy set)) - * tags, {object of tags} -* Added replay of commands issued to a closed connection when the connection is re-established -* Fix isConnected and close on unopened connections. Issue #409, fix by (https://github.com/sethml) -* Moved reaper to db.open instead of constructor (Issue #406) -* Allows passing through of socket connection settings to Server or ReplSetServer under the option socketOptions - * timeout = set seconds before connection times out (default 0) - * noDelay = Disables the Nagle algorithm (default true) - * keepAlive = Set if keepAlive is used (default 0, which means no keepAlive, set higher than 0 for keepAlive) - * encoding = ['ascii', 'utf8', or 'base64'] (default null) -* Fixes for handling of errors during shutdown off a socket connection -* Correctly applies socket options including timeout -* Cleanup of test management code to close connections correctly -* Handle parser errors better, closing down the connection and emitting an error -* Correctly emit errors from server.js only wrapping errors that are strings - -0.9.7 2011-11-10 ----------------- -* Added priority setting to replicaset manager -* Added correct handling of passive servers in replicaset -* Reworked socket code for simpler clearer handling -* Correct handling of connections in test helpers -* Added control of retries on failure - * control with parameters retryMiliSeconds and numberOfRetries when creating a db instance -* Added reaper that will timeout and cleanup queries that never return - * control with parameters reaperInterval and reaperTimeout when creating a db instance -* Refactored test helper classes for replicaset tests -* Allows raw (no bson parser mode for insert, update, remove, find and findOne) - * control raw mode passing in option raw:true on the commands - * will return buffers with the binary bson objects -* Fixed memory leak in cursor.toArray -* Fixed bug in command creation for mongodb server with wrong scope of call -* Added db(dbName) method to db.js to allow for reuse of connections against other databases -* Serialization of functions in an object is off by default, override with parameter - * serializeFunctions [true/false] on db level, collection level or individual insert/update/findAndModify -* Added Long.fromString to c++ class and fixed minor bug in the code (Test case for $gt operator on 64-bit integers, Issue #394) -* FindOne and find now share same code execution and will work in the same manner, Issue #399 -* Fix for tailable cursors, Issue #384 -* Fix for Cursor rewind broken, Issue #389 -* Allow Gridstore.exist to query using regexp, Issue #387, fix by (https://github.com/kaij) -* Updated documentation on https://github.com/christkv/node-mongodb-native -* Fixed toJSON methods across all objects for BSON, Binary return Base64 Encoded data - -0.9.6-22 2011-10-15 -------------------- -* Fixed bug in js bson parser that could cause wrong object size on serialization, Issue #370 -* Fixed bug in findAndModify that did not throw error on replicaset timeout, Issue #373 - -0.9.6-21 2011-10-05 -------------------- -* Reworked reconnect code to work correctly -* Handling errors in different parts of the code to ensure that it does not lock the connection -* Consistent error handling for Object.createFromHexString for JS and C++ - -0.9.6-20 2011-10-04 -------------------- -* Reworked bson.js parser to get rid off Array.shift() due to it allocating new memory for each call. Speedup varies between 5-15% depending on doc -* Reworked bson.cc to throw error when trying to serialize js bson types -* Added MinKey, MaxKey and Double support for JS and C++ parser -* Reworked socket handling code to emit errors on unparsable messages -* Added logger option for Db class, lets you pass in a function in the shape - { - log : function(message, object) {}, - error : function(errorMessage, errorObject) {}, - debug : function(debugMessage, object) {}, - } - - Usage is new Db(new Server(..), {logger: loggerInstance}) - -0.9.6-19 2011-09-29 -------------------- -* Fixing compatibility issues between C++ bson parser and js parser -* Added Symbol support to C++ parser -* Fixed socket handling bug for seldom misaligned message from mongodb -* Correctly handles serialization of functions using the C++ bson parser - -0.9.6-18 2011-09-22 -------------------- -* Fixed bug in waitForConnection that would lead to 100% cpu usage, Issue #352 - -0.9.6-17 2011-09-21 -------------------- -* Fixed broken exception test causing bamboo to hang -* Handling correctly command+lastError when both return results as in findAndModify, Issue #351 - -0.9.6-16 2011-09-14 -------------------- -* Fixing a bunch of issues with compatibility with MongoDB 2.0.X branch. Some fairly big changes in behavior from 1.8.X to 2.0.X on the server. -* Error Connection MongoDB V2.0.0 with Auth=true, Issue #348 - -0.9.6-15 2011-09-09 -------------------- -* Fixed issue where pools would not be correctly cleaned up after an error, Issue #345 -* Fixed authentication issue with secondary servers in Replicaset, Issue #334 -* Duplicate replica-set servers when omitting port, Issue #341 -* Fixing findAndModify to correctly work with Replicasets ensuring proper error handling, Issue #336 -* Merged in code from (https://github.com/aheckmann) that checks for global variable leaks - -0.9.6-14 2011-09-05 -------------------- -* Minor fixes for error handling in cursor streaming (https://github.com/sethml), Issue #332 -* Minor doc fixes -* Some more cursor sort tests added, Issue #333 -* Fixes to work with 0.5.X branch -* Fix Db not removing reconnect listener from serverConfig, (https://github.com/sbrekken), Issue #337 -* Removed node_events.h includes (https://github.com/jannehietamaki), Issue #339 -* Implement correct safe/strict mode for findAndModify. - -0.9.6-13 2011-08-24 -------------------- -* Db names correctly error checked for illegal characters - -0.9.6-12 2011-08-24 -------------------- -* Nasty bug in GridFS if you changed the default chunk size -* Fixed error handling bug in findOne - -0.9.6-11 2011-08-23 -------------------- -* Timeout option not correctly making it to the cursor, Issue #320, Fix from (https://github.com/year2013) -* Fixes for memory leaks when using buffers and C++ parser -* Fixes to make tests pass on 0.5.X -* Cleanup of bson.js to remove duplicated code paths -* Fix for errors occurring in ensureIndex, Issue #326 -* Removing require.paths to make tests work with the 0.5.X branch - -0.9.6-10 2011-08-11 -------------------- -* Specific type Double for capped collections (https://github.com/mbostock), Issue #312 -* Decorating Errors with all all object info from Mongo (https://github.com/laurie71), Issue #308 -* Implementing fixes for mongodb 1.9.1 and higher to make tests pass -* Admin validateCollection now takes an options argument for you to pass in full option -* Implemented keepGoing parameter for mongodb 1.9.1 or higher, Issue #310 -* Added test for read_secondary count issue, merged in fix from (https://github.com/year2013), Issue #317 - -0.9.6-9 -------- -* Bug fix for bson parsing the key '':'' correctly without crashing - -0.9.6-8 -------- -* Changed to using node.js crypto library MD5 digest -* Connect method support documented mongodb: syntax by (https://github.com/sethml) -* Support Symbol type for BSON, serializes to it's own type Symbol, Issue #302, #288 -* Code object without scope serializing to correct BSON type -* Lot's of fixes to avoid double callbacks (https://github.com/aheckmann) Issue #304 -* Long deserializes as Number for values in the range -2^53 to 2^53, Issue #305 (https://github.com/sethml) -* Fixed C++ parser to reflect JS parser handling of long deserialization -* Bson small optimizations - -0.9.6-7 2011-07-13 ------------------- -* JS Bson deserialization bug #287 - -0.9.6-6 2011-07-12 ------------------- -* FindAndModify not returning error message as other methods Issue #277 -* Added test coverage for $push, $pushAll and $inc atomic operations -* Correct Error handling for non 12/24 bit ids on Pure JS ObjectID class Issue #276 -* Fixed terrible deserialization bug in js bson code #285 -* Fix by andrewjstone to avoid throwing errors when this.primary not defined - -0.9.6-5 2011-07-06 ------------------- -* Rewritten BSON js parser now faster than the C parser on my core2duo laptop -* Added option full to indexInformation to get all index info Issue #265 -* Passing in ObjectID for new Gridstore works correctly Issue #272 - -0.9.6-4 2011-07-01 ------------------- -* Added test and bug fix for insert/update/remove without callback supplied - -0.9.6-3 2011-07-01 ------------------- -* Added simple grid class called Grid with put, get, delete methods -* Fixed writeBuffer/readBuffer methods on GridStore so they work correctly -* Automatic handling of buffers when using write method on GridStore -* GridStore now accepts a ObjectID instead of file name for write and read methods -* GridStore.list accepts id option to return of file ids instead of filenames -* GridStore close method returns document for the file allowing user to reference _id field - -0.9.6-2 2011-06-30 ------------------- -* Fixes for reconnect logic for server object (replays auth correctly) -* More testcases for auth -* Fixes in error handling for replicaset -* Fixed bug with safe parameter that would fail to execute safe when passing w or wtimeout -* Fixed slaveOk bug for findOne method -* Implemented auth support for replicaset and test cases -* Fixed error when not passing in rs_name - -0.9.6-1 2011-06-25 ------------------- -* Fixes for test to run properly using c++ bson parser -* Fixes for dbref in native parser (correctly handles ref without db component) -* Connection fixes for replicasets to avoid runtime conditions in cygwin (https://github.com/vincentcr) -* Fixes for timestamp in js bson parser (distinct timestamp type now) - -0.9.6 2011-06-21 ----------------- -* Worked around npm version handling bug -* Race condition fix for cygwin (https://github.com/vincentcr) - -0.9.5-1 2011-06-21 ------------------- -* Extracted Timestamp as separate class for bson js parser to avoid instanceof problems -* Fixed driver strict mode issue - -0.9.5 2011-06-20 ----------------- -* Replicaset support (failover and reading from secondary servers) -* Removed ServerPair and ServerCluster -* Added connection pool functionality -* Fixed serious bug in C++ bson parser where bytes > 127 would generate 2 byte sequences -* Allows for forcing the server to assign ObjectID's using the option {forceServerObjectId: true} - -0.6.8 ------ -* Removed multiple message concept from bson -* Changed db.open(db) to be db.open(err, db) - -0.1 2010-01-30 --------------- -* Initial release support of driver using native node.js interface -* Supports gridfs specification -* Supports admin functionality diff --git a/util/retroImporter/node_modules/mongodb/LICENSE b/util/retroImporter/node_modules/mongodb/LICENSE deleted file mode 100644 index ad410e1..0000000 --- a/util/retroImporter/node_modules/mongodb/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/Makefile b/util/retroImporter/node_modules/mongodb/Makefile deleted file mode 100644 index 36e1202..0000000 --- a/util/retroImporter/node_modules/mongodb/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -NODE = node -NPM = npm -JSDOC = jsdoc -name = all - -generate_docs: - # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md - hugo -s docs/reference -d ../../public - $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api - cp -R ./public/api/scripts ./public/. - cp -R ./public/api/styles ./public/. diff --git a/util/retroImporter/node_modules/mongodb/README.md b/util/retroImporter/node_modules/mongodb/README.md deleted file mode 100644 index 2828713..0000000 --- a/util/retroImporter/node_modules/mongodb/README.md +++ /dev/null @@ -1,322 +0,0 @@ -[![NPM](https://nodei.co/npm/mongodb.png?downloads=true&downloadRank=true)](https://nodei.co/npm/mongodb/) [![NPM](https://nodei.co/npm-dl/mongodb.png?months=6&height=3)](https://nodei.co/npm/mongodb/) - -[![Build Status](https://secure.travis-ci.org/mongodb/node-mongodb-native.png)](http://travis-ci.org/mongodb/node-mongodb-native) - -[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/mongodb/node-mongodb-native?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) - -# Description - -The MongoDB driver is the high level part of the 2.0 or higher MongoDB driver and is meant for end users. - -## MongoDB Node.JS Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native/ | -| api-doc | http://mongodb.github.io/node-mongodb-native/2.0/api/ | -| source | https://github.com/mongodb/node-mongodb-native | -| mongodb | http://www.mongodb.org/ | - -### Blogs of Engineers involved in the driver -- Christian Kvalheim [@christkv](https://twitter.com/christkv) - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a -case in our issue management tool, JIRA: - -- Create an account and login . -- Navigate to the NODE project . -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Questions and Bug Reports - - * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native - * jira: http://jira.mongodb.org/ - -### Change Log - -http://jira.mongodb.org/browse/NODE - -QuickStart -========== -The quick start guide will show you how to setup a simple application using node.js and MongoDB. Its scope is only how to set up the driver and perform the simple crud operations. For more in depth coverage we encourage reading the tutorials. - -Create the package.json file ----------------------------- -Let's create a directory where our application will live. In our case we will put this under our projects directory. - -``` -mkdir myproject -cd myproject -``` - -Enter the following command and answer the questions to create the initial structure for your new project - -``` -npm init -``` - -Next we need to edit the generated package.json file to add the dependency for the MongoDB driver. The package.json file below is just an example and your will look different depending on how you answered the questions after entering `npm init` - -``` -{ - "name": "myproject", - "version": "1.0.0", - "description": "My first project", - "main": "index.js", - "repository": { - "type": "git", - "url": "git://github.com/christkv/myfirstproject.git" - }, - "dependencies": { - "mongodb": "~2.0" - }, - "author": "Christian Kvalheim", - "license": "Apache 2.0", - "bugs": { - "url": "https://github.com/christkv/myfirstproject/issues" - }, - "homepage": "https://github.com/christkv/myfirstproject" -} -``` - -Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. - -``` -npm install -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -Booting up a MongoDB Server ---------------------------- -Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). - -``` -mongod --dbpath=/data --port 27017 -``` - -You should see the **mongod** process start up and print some status information. - -Connecting to MongoDB ---------------------- -Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. - -First let's add code to connect to the server and the database **myproject**. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - db.close(); -}); -``` - -Given that you booted up the **mongod** process earlier the application should connect successfully and print **Connected correctly to server** to the console. - -Let's Add some code to show the different CRUD operations available. - -Inserting a Document --------------------- -Let's create a function that will insert some documents for us. - -```js -var insertDocuments = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Insert some documents - collection.insert([ - {a : 1}, {a : 2}, {a : 3} - ], function(err, result) { - assert.equal(err, null); - assert.equal(3, result.result.n); - assert.equal(3, result.ops.length); - console.log("Inserted 3 documents into the document collection"); - callback(result); - }); -} -``` - -The insert command will return a results object that contains several fields that might be useful. - -* **result** Contains the result document from MongoDB -* **ops** Contains the documents inserted with added **_id** fields -* **connection** Contains the connection used to perform the insert - -Let's add call the **insertDocuments** command to the **MongoClient.connect** method callback. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - db.close(); - }); -}); -``` - -We can now run the update **app.js** file. - -``` -node app.js -``` - -You should see the following output after running the **app.js** file. - -``` -Connected correctly to server -Inserted 3 documents into the document collection -``` - -Updating a document -------------------- -Let's look at how to do a simple document update by adding a new field **b** to the document that has the field **a** set to **2**. - -```js -var updateDocument = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Update document where a is 2, set b equal to 1 - collection.update({ a : 2 } - , { $set: { b : 1 } }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Updated the document with the field a equal to 2"); - callback(result); - }); -} -``` - -The method will update the first document where the field **a** is equal to **2** by adding a new field **b** to the document set to **1**. Let's update the callback function from **MongoClient.connect** to include the update method. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - updateDocument(db, function() { - db.close(); - }); - }); -}); -``` - -Remove a document ------------------ -Next lets remove the document where the field **a** equals to **3**. - -```js -var removeDocument = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Insert some documents - collection.remove({ a : 3 }, function(err, result) { - assert.equal(err, null); - assert.equal(1, result.result.n); - console.log("Removed the document with the field a equal to 3"); - callback(result); - }); -} -``` - -This will remove the first document where the field **a** equals to **3**. Let's add the method to the **MongoClient.connect** callback function. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - db.close(); - }); - }); - }); -}); -``` - -Finally let's retrieve all the documents using a simple find. - -Find All Documents ------------------- -We will finish up the Quickstart CRUD methods by performing a simple query that returns all the documents matching the query. - -```js -var findDocuments = function(db, callback) { - // Get the documents collection - var collection = db.collection('documents'); - // Find some documents - collection.find({}).toArray(function(err, docs) { - assert.equal(err, null); - assert.equal(2, docs.length); - console.log("Found the following records"); - console.dir(docs); - callback(docs); - }); -} -``` - -This query will return all the documents in the **documents** collection. Since we removed a document the total documents returned is **2**. Finally let's add the findDocument method to the **MongoClient.connect** callback. - -```js -var MongoClient = require('mongodb').MongoClient - , assert = require('assert'); - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - insertDocuments(db, function() { - updateDocument(db, function() { - removeDocument(db, function() { - findDocuments(db, function() { - db.close(); - }); - }); - }); - }); -}); -``` - -This concludes the QuickStart of connecting and performing some Basic operations using the MongoDB Node.js driver. For more detailed information you can look at the tutorials covering more specific topics of interest. - -## Next Steps - - * [MongoDB Documentation](http://mongodb.org/) - * [Read about Schemas](http://learnmongodbthehardway.com/) - * [Star us on GitHub](https://github.com/mongodb/node-mongodb-native) diff --git a/util/retroImporter/node_modules/mongodb/c.js b/util/retroImporter/node_modules/mongodb/c.js deleted file mode 100644 index 5b6bc1e..0000000 --- a/util/retroImporter/node_modules/mongodb/c.js +++ /dev/null @@ -1,24 +0,0 @@ -var MongoClient = require('./').MongoClient; - -var index = 0; - -MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { - setInterval(function() { - db = db.db("index" + index, {noListener:true}); - var collection = db.collection("index" + index); - collection.insert({a:index}) - }, 1); -}); - -// var Server = require('./').Server, -// Db = require('./').Db, -// ReadPreference = require('./').ReadPreference; -// -// new Db('test', new Server('localhost', 31001), {readPreference: ReadPreference.SECONDARY}).open(function(err, db) { -// -// db.collection('test').find().toArray(function(err, docs) { -// console.dir(err) -// console.dir(docs) -// db.close(); -// }); -// }); diff --git a/util/retroImporter/node_modules/mongodb/conf.json b/util/retroImporter/node_modules/mongodb/conf.json deleted file mode 100644 index 15f3021..0000000 --- a/util/retroImporter/node_modules/mongodb/conf.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], - "source": { - "include": [ - "test/functional/operation_example_tests.js", - "test/functional/operation_promises_example_tests.js", - "test/functional/operation_generators_example_tests.js", - "test/functional/authentication_tests.js", - "lib/admin.js", - "lib/collection.js", - "lib/cursor.js", - "lib/aggregation_cursor.js", - "lib/command_cursor.js", - "lib/db.js", - "lib/mongo_client.js", - "lib/mongos.js", - "lib/read_preference.js", - "lib/replset.js", - "lib/server.js", - "lib/bulk/common.js", - "lib/bulk/ordered.js", - "lib/bulk/unordered.js", - "lib/gridfs/grid_store.js", - "node_modules/mongodb-core/lib/error.js", - "node_modules/mongodb-core/lib/connection/logger.js", - "node_modules/bson/lib/bson/binary.js", - "node_modules/bson/lib/bson/code.js", - "node_modules/bson/lib/bson/db_ref.js", - "node_modules/bson/lib/bson/double.js", - "node_modules/bson/lib/bson/long.js", - "node_modules/bson/lib/bson/objectid.js", - "node_modules/bson/lib/bson/symbol.js", - "node_modules/bson/lib/bson/timestamp.js", - "node_modules/bson/lib/bson/max_key.js", - "node_modules/bson/lib/bson/min_key.js" - ] - }, - "templates": { - "cleverLinks": true, - "monospaceLinks": true, - "default": { - "outputSourceFiles" : true - }, - "applicationName": "Node.js MongoDB Driver API", - "disqus": true, - "googleAnalytics": "UA-29229787-1", - "openGraph": { - "title": "", - "type": "website", - "image": "", - "site_name": "", - "url": "" - }, - "meta": { - "title": "", - "description": "", - "keyword": "" - }, - "linenums": true - }, - "markdown": { - "parser": "gfm", - "hardwrap": true, - "tags": ["examples"] - }, - "examples": { - "indent": 4 - } -} diff --git a/util/retroImporter/node_modules/mongodb/index.js b/util/retroImporter/node_modules/mongodb/index.js deleted file mode 100644 index df24555..0000000 --- a/util/retroImporter/node_modules/mongodb/index.js +++ /dev/null @@ -1,47 +0,0 @@ -// Core module -var core = require('mongodb-core'), - Instrumentation = require('./lib/apm'); - -// Set up the connect function -var connect = require('./lib/mongo_client').connect; - -// Expose error class -connect.MongoError = core.MongoError; - -// Actual driver classes exported -connect.MongoClient = require('./lib/mongo_client'); -connect.Db = require('./lib/db'); -connect.Collection = require('./lib/collection'); -connect.Server = require('./lib/server'); -connect.ReplSet = require('./lib/replset'); -connect.Mongos = require('./lib/mongos'); -connect.ReadPreference = require('./lib/read_preference'); -connect.GridStore = require('./lib/gridfs/grid_store'); -connect.Chunk = require('./lib/gridfs/chunk'); -connect.Logger = core.Logger; -connect.Cursor = require('./lib/cursor'); - -// BSON types exported -connect.Binary = core.BSON.Binary; -connect.Code = core.BSON.Code; -connect.DBRef = core.BSON.DBRef; -connect.Double = core.BSON.Double; -connect.Long = core.BSON.Long; -connect.MinKey = core.BSON.MinKey; -connect.MaxKey = core.BSON.MaxKey; -connect.ObjectID = core.BSON.ObjectID; -connect.ObjectId = core.BSON.ObjectID; -connect.Symbol = core.BSON.Symbol; -connect.Timestamp = core.BSON.Timestamp; - -// Add connect method -connect.connect = connect; - -// Set up the instrumentation method -connect.instrument = function(options, callback) { - if(typeof options == 'function') callback = options, options = {}; - return new Instrumentation(core, options, callback); -} - -// Set our exports to be the connect function -module.exports = connect; diff --git a/util/retroImporter/node_modules/mongodb/lib/admin.js b/util/retroImporter/node_modules/mongodb/lib/admin.js deleted file mode 100644 index 1f89512..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/admin.js +++ /dev/null @@ -1,581 +0,0 @@ -"use strict"; - -var toError = require('./utils').toError, - Define = require('./metadata'), - shallowClone = require('./utils').shallowClone; - -/** - * @fileOverview The **Admin** class is an internal class that allows convenient access to - * the admin functionality and commands for MongoDB. - * - * **ADMIN Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Use the admin database for the operation - * var adminDb = db.admin(); - * - * // List all the available databases - * adminDb.listDatabases(function(err, dbs) { - * test.equal(null, err); - * test.ok(dbs.databases.length > 0); - * db.close(); - * }); - * }); - */ - -/** - * Create a new Admin instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {Admin} a collection instance. - */ -var Admin = function(db, topology, promiseLibrary) { - if(!(this instanceof Admin)) return new Admin(db, topology); - var self = this; - - // Internal state - this.s = { - db: db - , topology: topology - , promiseLibrary: promiseLibrary - } -} - -var define = Admin.define = new Define('Admin', Admin, false); - -/** - * The callback format for results - * @callback Admin~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.command = function(command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - - // Execute using callback - if(typeof callback == 'function') return this.s.db.executeDbAdminCommand(command, options, function(err, doc) { - return callback != null ? callback(err, doc) : null; - }); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand(command, options, function(err, doc) { - if(err) return reject(err); - resolve(doc); - }); - }); -} - -define.classMethod('command', {callback: true, promise:true}); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.buildInfo = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return this.serverInfo(callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.serverInfo(function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('buildInfo', {callback: true, promise:true}); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverInfo = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err != null) return callback(err, null); - callback(null, doc); - }); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand({buildinfo:1}, function(err, doc) { - if(err) return reject(err); - resolve(doc); - }); - }); -} - -define.classMethod('serverInfo', {callback: true, promise:true}); - -/** - * Retrieve this db's server status. - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.serverStatus = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return serverStatus(self, callback) - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - serverStatus(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var serverStatus = function(self, callback) { - self.s.db.executeDbAdminCommand({serverStatus: 1}, function(err, doc) { - if(err == null && doc.ok === 1) { - callback(null, doc); - } else { - if(err) return callback(err, false); - return callback(toError(doc), false); - } - }); -} - -define.classMethod('serverStatus', {callback: true, promise:true}); - -/** - * Retrieve the current profiling Level for MongoDB - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.profilingLevel = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return profilingLevel(self, callback) - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - profilingLevel(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var profilingLevel = function(self, callback) { - self.s.db.executeDbAdminCommand({profile:-1}, function(err, doc) { - doc = doc; - - if(err == null && doc.ok === 1) { - var was = doc.was; - if(was == 0) return callback(null, "off"); - if(was == 1) return callback(null, "slow_only"); - if(was == 2) return callback(null, "all"); - return callback(new Error("Error: illegal profiling level value " + was), null); - } else { - err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - } - }); -} - -define.classMethod('profilingLevel', {callback: true, promise:true}); - -/** - * Ping the MongoDB server and retrieve results - * - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.ping = function(options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - - // Execute using callback - if(typeof callback == 'function') return this.s.db.executeDbAdminCommand({ping: 1}, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand({ping: 1}, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('ping', {callback: true, promise:true}); - -/** - * Authenticate a user against the server. - * @method - * @param {string} username The username. - * @param {string} [password] The password. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.authenticate = function(username, password, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options); - options.authdb = 'admin'; - - // Execute using callback - if(typeof callback == 'function') return this.s.db.authenticate(username, password, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.authenticate(username, password, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('authenticate', {callback: true, promise:true}); - -/** - * Logout user from server, fire off on all connections and remove all auth info - * @method - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.logout = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return this.s.db.logout({authdb: 'admin'}, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.logout({authdb: 'admin'}, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('logout', {callback: true, promise:true}); - -// Get write concern -var writeConcern = function(options, db) { - options = shallowClone(options); - - // If options already contain write concerns return it - if(options.w || options.wtimeout || options.j || options.fsync) { - return options; - } - - // Set db write concern if available - if(db.writeConcern) { - if(options.w) options.w = db.writeConcern.w; - if(options.wtimeout) options.wtimeout = db.writeConcern.wtimeout; - if(options.j) options.j = db.writeConcern.j; - if(options.fsync) options.fsync = db.writeConcern.fsync; - } - - // Return modified options - return options; -} - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.addUser = function(username, password, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - // Get the options - options = writeConcern(options, self.s.db) - // Set the db name to admin - options.dbName = 'admin'; - - // Execute using callback - if(typeof callback == 'function') - return self.s.db.addUser(username, password, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.addUser(username, password, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('addUser', {callback: true, promise:true}); - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {Admin~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.removeUser = function(username, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - // Get the options - options = writeConcern(options, self.s.db) - // Set the db name - options.dbName = 'admin'; - - // Execute using callback - if(typeof callback == 'function') - return self.s.db.removeUser(username, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.removeUser(username, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('removeUser', {callback: true, promise:true}); - -/** - * Set the current profiling level of MongoDB - * - * @param {string} level The new profiling level (off, slow_only, all). - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.setProfilingLevel = function(level, callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return setProfilingLevel(self, level, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - setProfilingLevel(self, level, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var setProfilingLevel = function(self, level, callback) { - var command = {}; - var profile = 0; - - if(level == "off") { - profile = 0; - } else if(level == "slow_only") { - profile = 1; - } else if(level == "all") { - profile = 2; - } else { - return callback(new Error("Error: illegal profiling level value " + level)); - } - - // Set up the profile number - command['profile'] = profile; - - self.s.db.executeDbAdminCommand(command, function(err, doc) { - doc = doc; - - if(err == null && doc.ok === 1) - return callback(null, level); - return err != null ? callback(err, null) : callback(new Error("Error with profile command"), null); - }); -} - -define.classMethod('setProfilingLevel', {callback: true, promise:true}); - -/** - * Retrive the current profiling information for MongoDB - * - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.profilingInfo = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return profilingInfo(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - profilingInfo(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var profilingInfo = function(self, callback) { - try { - self.s.topology.cursor("admin.system.profile", { find: 'system.profile', query: {}}, {}).toArray(callback); - } catch (err) { - return callback(err, null); - } -} - -define.classMethod('profilingLevel', {callback: true, promise:true}); - -/** - * Validate an existing collection - * - * @param {string} collectionName The name of the collection to validate. - * @param {object} [options=null] Optional settings. - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.validateCollection = function(collectionName, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') - return validateCollection(self, collectionName, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - validateCollection(self, collectionName, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var validateCollection = function(self, collectionName, options, callback) { - var command = {validate: collectionName}; - var keys = Object.keys(options); - - // Decorate command with extra options - for(var i = 0; i < keys.length; i++) { - if(options.hasOwnProperty(keys[i])) { - command[keys[i]] = options[keys[i]]; - } - } - - self.s.db.command(command, function(err, doc) { - if(err != null) return callback(err, null); - - if(doc.ok === 0) - return callback(new Error("Error with validate command"), null); - if(doc.result != null && doc.result.constructor != String) - return callback(new Error("Error with validation data"), null); - if(doc.result != null && doc.result.match(/exception|corrupt/) != null) - return callback(new Error("Error: invalid collection " + collectionName), null); - if(doc.valid != null && !doc.valid) - return callback(new Error("Error: invalid collection " + collectionName), null); - - return callback(null, doc); - }); -} - -define.classMethod('validateCollection', {callback: true, promise:true}); - -/** - * List the available databases - * - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.listDatabases = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return self.s.db.executeDbAdminCommand({listDatabases:1}, {}, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.executeDbAdminCommand({listDatabases:1}, {}, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('listDatabases', {callback: true, promise:true}); - -/** - * Get ReplicaSet status - * - * @param {Admin~resultCallback} [callback] The command result callback. - * @return {Promise} returns Promise if no callback passed - */ -Admin.prototype.replSetGetStatus = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return replSetGetStatus(self, callback); - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - replSetGetStatus(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var replSetGetStatus = function(self, callback) { - self.s.db.executeDbAdminCommand({replSetGetStatus:1}, function(err, doc) { - if(err == null && doc.ok === 1) - return callback(null, doc); - if(err) return callback(err, false); - callback(toError(doc), false); - }); -} - -define.classMethod('replSetGetStatus', {callback: true, promise:true}); - -module.exports = Admin; diff --git a/util/retroImporter/node_modules/mongodb/lib/aggregation_cursor.js b/util/retroImporter/node_modules/mongodb/lib/aggregation_cursor.js deleted file mode 100644 index 3663229..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/aggregation_cursor.js +++ /dev/null @@ -1,432 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , toError = require('./utils').toError - , getSingleProperty = require('./utils').getSingleProperty - , formattedOrderClause = require('./utils').formattedOrderClause - , handleCallback = require('./utils').handleCallback - , Logger = require('mongodb-core').Logger - , EventEmitter = require('events').EventEmitter - , ReadPreference = require('./read_preference') - , MongoError = require('mongodb-core').MongoError - , Readable = require('stream').Readable || require('readable-stream').Readable - , Define = require('./metadata') - , CoreCursor = require('./cursor') - , Query = require('mongodb-core').Query - , CoreReadPreference = require('mongodb-core').ReadPreference; - -/** - * @fileOverview The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X - * or higher stream - * - * **AGGREGATIONCURSOR Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * // Show that duplicate records got dropped - * col.aggregation({}, {cursor: {}}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * db.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Aggregation Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class AggregationCursor - * @extends external:Readable - * @fires AggregationCursor#data - * @fires AggregationCursor#end - * @fires AggregationCursor#close - * @fires AggregationCursor#readable - * @return {AggregationCursor} an AggregationCursor instance. - */ -var AggregationCursor = function(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - var self = this; - var state = AggregationCursor.INIT; - var streamOptions = {}; - - // MaxTimeMS - var maxTimeMS = null; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set up - Readable.call(this, {objectMode: true}); - - // Internal state - this.s = { - // MaxTimeMS - maxTimeMS: maxTimeMS - // State - , state: state - // Stream options - , streamOptions: streamOptions - // BSON - , bson: bson - // Namespae - , ns: ns - // Command - , cmd: cmd - // Options - , options: options - // Topology - , topology: topology - // Topology Options - , topologyOptions: topologyOptions - // Promise library - , promiseLibrary: promiseLibrary - } -} - -/** - * AggregationCursor stream data event, fired for each document in the cursor. - * - * @event AggregationCursor#data - * @type {object} - */ - -/** - * AggregationCursor stream end event - * - * @event AggregationCursor#end - * @type {null} - */ - -/** - * AggregationCursor stream close event - * - * @event AggregationCursor#close - * @type {null} - */ - -/** - * AggregationCursor stream readable event - * - * @event AggregationCursor#readable - * @type {null} - */ - -// Inherit from Readable -inherits(AggregationCursor, Readable); - -// Set the methods to inherit from prototype -var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' - , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' - , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified']; - -// Extend the Cursor -for(var name in CoreCursor.prototype) { - AggregationCursor.prototype[name] = CoreCursor.prototype[name]; -} - -var define = AggregationCursor.define = new Define('AggregationCursor', AggregationCursor, true); - -/** - * Set the batch size for the cursor. - * @method - * @param {number} value The batchSize for the cursor. - * @throws {MongoError} - * @return {AggregationCursor} - */ -AggregationCursor.prototype.batchSize = function(value) { - if(this.s.state == AggregationCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true }); - if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", drvier:true }); - if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; - this.setCursorBatchSize(value); - return this; -} - -define.classMethod('batchSize', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a geoNear stage to the aggregation pipeline - * @method - * @param {object} document The geoNear stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.geoNear = function(document) { - this.s.cmd.pipeline.push({$geoNear: document}); - return this; -} - -define.classMethod('geoNear', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a group stage to the aggregation pipeline - * @method - * @param {object} document The group stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.group = function(document) { - this.s.cmd.pipeline.push({$group: document}); - return this; -} - -define.classMethod('group', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a limit stage to the aggregation pipeline - * @method - * @param {number} value The state limit value. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.limit = function(value) { - this.s.cmd.pipeline.push({$limit: value}); - return this; -} - -define.classMethod('limit', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a match stage to the aggregation pipeline - * @method - * @param {object} document The match stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.match = function(document) { - this.s.cmd.pipeline.push({$match: document}); - return this; -} - -define.classMethod('match', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.maxTimeMS = function(value) { - if(this.s.topology.lastIsMaster().minWireVersion > 2) { - this.s.cmd.maxTimeMS = value; - } - return this; -} - -define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a out stage to the aggregation pipeline - * @method - * @param {number} destination The destination name. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.out = function(destination) { - this.s.cmd.pipeline.push({$out: destination}); - return this; -} - -define.classMethod('out', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a project stage to the aggregation pipeline - * @method - * @param {object} document The project stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.project = function(document) { - this.s.cmd.pipeline.push({$project: document}); - return this; -} - -define.classMethod('project', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a redact stage to the aggregation pipeline - * @method - * @param {object} document The redact stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.redact = function(document) { - this.s.cmd.pipeline.push({$redact: document}); - return this; -} - -define.classMethod('redact', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a skip stage to the aggregation pipeline - * @method - * @param {number} value The state skip value. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.skip = function(value) { - this.s.cmd.pipeline.push({$skip: value}); - return this; -} - -define.classMethod('skip', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a sort stage to the aggregation pipeline - * @method - * @param {object} document The sort stage document. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.sort = function(document) { - this.s.cmd.pipeline.push({$sort: document}); - return this; -} - -define.classMethod('sort', {callback: false, promise:false, returns: [AggregationCursor]}); - -/** - * Add a unwind stage to the aggregation pipeline - * @method - * @param {number} field The unwind field name. - * @return {AggregationCursor} - */ -AggregationCursor.prototype.unwind = function(field) { - this.s.cmd.pipeline.push({$unwind: field}); - return this; -} - -define.classMethod('unwind', {callback: false, promise:false, returns: [AggregationCursor]}); - -AggregationCursor.prototype.get = AggregationCursor.prototype.toArray; - -// Inherited methods -define.classMethod('toArray', {callback: true, promise:true}); -define.classMethod('each', {callback: true, promise:false}); -define.classMethod('forEach', {callback: true, promise:false}); -define.classMethod('next', {callback: true, promise:true}); -define.classMethod('close', {callback: true, promise:true}); -define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); -define.classMethod('rewind', {callback: false, promise:false}); -define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); -define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function AggregationCursor.prototype.next - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method AggregationCursor.prototype.toArray - * @param {AggregationCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback AggregationCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method AggregationCursor.prototype.each - * @param {AggregationCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a AggregationCursor command and emitting close. - * @method AggregationCursor.prototype.close - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method AggregationCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Execute the explain for the cursor - * @method AggregationCursor.prototype.explain - * @param {AggregationCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Clone the cursor - * @function AggregationCursor.prototype.clone - * @return {AggregationCursor} - */ - -/** - * Resets the cursor - * @function AggregationCursor.prototype.rewind - * @return {AggregationCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback AggregationCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback AggregationCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method AggregationCursor.prototype.forEach - * @param {AggregationCursor~iteratorCallback} iterator The iteration callback. - * @param {AggregationCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -AggregationCursor.INIT = 0; -AggregationCursor.OPEN = 1; -AggregationCursor.CLOSED = 2; - -module.exports = AggregationCursor; diff --git a/util/retroImporter/node_modules/mongodb/lib/apm.js b/util/retroImporter/node_modules/mongodb/lib/apm.js deleted file mode 100644 index aba5b86..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/apm.js +++ /dev/null @@ -1,571 +0,0 @@ -var EventEmitter = require('events').EventEmitter, - inherits = require('util').inherits; - -// Get prototypes -var AggregationCursor = require('./aggregation_cursor'), - CommandCursor = require('./command_cursor'), - OrderedBulkOperation = require('./bulk/ordered').OrderedBulkOperation, - UnorderedBulkOperation = require('./bulk/unordered').UnorderedBulkOperation, - GridStore = require('./gridfs/grid_store'), - Server = require('./server'), - ReplSet = require('./replset'), - Mongos = require('./mongos'), - Cursor = require('./cursor'), - Collection = require('./collection'), - Db = require('./db'), - Admin = require('./admin'); - -var basicOperationIdGenerator = { - operationId: 1, - - next: function() { - return this.operationId++; - } -} - -var basicTimestampGenerator = { - current: function() { - return new Date().getTime(); - }, - - duration: function(start, end) { - return end - start; - } -} - -var senstiveCommands = ['authenticate', 'saslStart', 'saslContinue', 'getnonce', - 'createUser', 'updateUser', 'copydbgetnonce', 'copydbsaslstart', 'copydb']; - -var Instrumentation = function(core, options, callback) { - options = options || {}; - - // Optional id generators - var operationIdGenerator = options.operationIdGenerator || basicOperationIdGenerator; - // Optional timestamp generator - var timestampGenerator = options.timestampGenerator || basicTimestampGenerator; - // Extend with event emitter functionality - EventEmitter.call(this); - - // Contains all the instrumentation overloads - this.overloads = []; - - // --------------------------------------------------------- - // - // Instrument prototype - // - // --------------------------------------------------------- - - var instrumentPrototype = function(callback) { - var instrumentations = [] - - // Classes to support - var classes = [GridStore, OrderedBulkOperation, UnorderedBulkOperation, - CommandCursor, AggregationCursor, Cursor, Collection, Db]; - - // Add instrumentations to the available list - for(var i = 0; i < classes.length; i++) { - if(classes[i].define) { - instrumentations.push(classes[i].define.generate()); - } - } - - // Return the list of instrumentation points - callback(null, instrumentations); - } - - // Did the user want to instrument the prototype - if(typeof callback == 'function') { - instrumentPrototype(callback); - } - - // --------------------------------------------------------- - // - // Server - // - // --------------------------------------------------------- - - // Reference - var self = this; - // Names of methods we need to wrap - var methods = ['command', 'insert', 'update', 'remove']; - // Prototype - var proto = core.Server.prototype; - // Core server method we are going to wrap - methods.forEach(function(x) { - var func = proto[x]; - - // Add to overloaded methods - self.overloads.push({proto: proto, name:x, func:func}); - - // The actual prototype - proto[x] = function() { - var requestId = core.Query.nextRequestId(); - // Get the aruments - var args = Array.prototype.slice.call(arguments, 0); - var ns = args[0]; - var commandObj = args[1]; - var options = args[2] || {}; - var keys = Object.keys(commandObj); - var commandName = keys[0]; - var db = ns.split('.')[0]; - - // Do we have a legacy insert/update/remove command - if(x == 'insert' && !this.lastIsMaster().maxWireVersion) { - commandName = 'insert'; - // Get the collection - var col = ns.split('.'); - col.shift(); - col = col.join('.'); - - // Re-write the command - commandObj = { - insert: col, documents: commandObj - } - - if(options.writeConcern) commandObj.writeConcern = options.writeConcern; - commandObj.ordered = options.ordered != undefined ? options.ordered : true; - } else if(x == 'update' && !this.lastIsMaster().maxWireVersion) { - commandName = 'update'; - - // Get the collection - var col = ns.split('.'); - col.shift(); - col = col.join('.'); - - // Re-write the command - commandObj = { - update: col, updates: commandObj - } - - if(options.writeConcern) commandObj.writeConcern = options.writeConcern; - commandObj.ordered = options.ordered != undefined ? options.ordered : true; - } else if(x == 'remove' && !this.lastIsMaster().maxWireVersion) { - commandName = 'delete'; - - // Get the collection - var col = ns.split('.'); - col.shift(); - col = col.join('.'); - - // Re-write the command - commandObj = { - delete: col, deletes: commandObj - } - - if(options.writeConcern) commandObj.writeConcern = options.writeConcern; - commandObj.ordered = options.ordered != undefined ? options.ordered : true; - } else if(x == 'insert' || x == 'update' || x == 'remove' && this.lastIsMaster().maxWireVersion >= 2) { - // Skip the insert/update/remove commands as they are executed as actual write commands in 2.6 or higher - return func.apply(this, args); - } - - // Get the callback - var callback = args.pop(); - // Set current callback operation id from the current context or create - // a new one - var ourOpId = callback.operationId || operationIdGenerator.next(); - - // Get a connection reference for this server instance - var connection = this.s.pool.get() - - // Emit the start event for the command - var command = { - // Returns the command. - command: commandObj, - // Returns the database name. - databaseName: db, - // Returns the command name. - commandName: commandName, - // Returns the driver generated request id. - requestId: requestId, - // Returns the driver generated operation id. - // This is used to link events together such as bulk write operations. OPTIONAL. - operationId: ourOpId, - // Returns the connection id for the command. For languages that do not have this, - // this MUST return the driver equivalent which MUST include the server address and port. - // The name of this field is flexible to match the object that is returned from the driver. - connectionId: connection - }; - - // Filter out any sensitive commands - if(senstiveCommands.indexOf(commandName.toLowerCase())) { - command.commandObj = {}; - command.commandObj[commandName] = true; - } - - // Emit the started event - self.emit('started', command) - - // Start time - var startTime = timestampGenerator.current(); - - // Push our handler callback - args.push(function(err, r) { - var endTime = timestampGenerator.current(); - var command = { - duration: timestampGenerator.duration(startTime, endTime), - commandName: commandName, - requestId: requestId, - operationId: ourOpId, - connectionId: connection - }; - - // If we have an error - if(err || (r.result.ok == 0)) { - command.failure = err || r.result.writeErrors || r.result; - - // Filter out any sensitive commands - if(senstiveCommands.indexOf(commandName.toLowerCase())) { - command.failure = {}; - } - - self.emit('failed', command); - } else { - command.reply = r; - - // Filter out any sensitive commands - if(senstiveCommands.indexOf(commandName.toLowerCase())) { - command.reply = {}; - } - - self.emit('succeeded', command); - } - - // Return to caller - callback(err, r); - }); - - // Apply the call - func.apply(this, args); - } - }); - - // --------------------------------------------------------- - // - // Bulk Operations - // - // --------------------------------------------------------- - - // Inject ourselves into the Bulk methods - var methods = ['execute']; - var prototypes = [ - require('./bulk/ordered').Bulk.prototype, - require('./bulk/unordered').Bulk.prototype - ] - - prototypes.forEach(function(proto) { - // Core server method we are going to wrap - methods.forEach(function(x) { - var func = proto[x]; - - // Add to overloaded methods - self.overloads.push({proto: proto, name:x, func:func}); - - // The actual prototype - proto[x] = function() { - var bulk = this; - // Get the aruments - var args = Array.prototype.slice.call(arguments, 0); - // Set an operation Id on the bulk object - this.operationId = operationIdGenerator.next(); - - // Get the callback - var callback = args.pop(); - // If we have a callback use this - if(typeof callback == 'function') { - args.push(function(err, r) { - // Return to caller - callback(err, r); - }); - - // Apply the call - func.apply(this, args); - } else { - return func.apply(this, args); - } - } - }); - }); - - // --------------------------------------------------------- - // - // Cursor - // - // --------------------------------------------------------- - - // Inject ourselves into the Cursor methods - var methods = ['_find', '_getmore', '_killcursor']; - var prototypes = [ - require('./cursor').prototype, - require('./command_cursor').prototype, - require('./aggregation_cursor').prototype - ] - - // Command name translation - var commandTranslation = { - '_find': 'find', '_getmore': 'getMore', '_killcursor': 'killCursors', '_explain': 'explain' - } - - prototypes.forEach(function(proto) { - - // Core server method we are going to wrap - methods.forEach(function(x) { - var func = proto[x]; - - // Add to overloaded methods - self.overloads.push({proto: proto, name:x, func:func}); - - // The actual prototype - proto[x] = function() { - var cursor = this; - var requestId = core.Query.nextRequestId(); - var ourOpId = operationIdGenerator.next(); - var parts = this.ns.split('.'); - var db = parts[0]; - - // Get the collection - parts.shift(); - var collection = parts.join('.'); - - // Set the command - var command = this.query; - var cmd = this.s.cmd; - - // If we have a find method, set the operationId on the cursor - if(x == '_find') { - cursor.operationId = ourOpId; - } - - // Do we have a find command rewrite it - if(cmd.find) { - command = { - find: collection, filter: cmd.query - } - - if(cmd.sort) command.sort = cmd.sort; - if(cmd.fields) command.projection = cmd.fields; - if(cmd.limit && cmd.limit < 0) { - command.limit = Math.abs(cmd.limit); - command.singleBatch = true; - } else if(cmd.limit) { - command.limit = Math.abs(cmd.limit); - } - - // Options - if(cmd.skip) command.skip = cmd.skip; - if(cmd.hint) command.hint = cmd.hint; - if(cmd.batchSize) command.batchSize = cmd.batchSize; - if(cmd.returnKey) command.returnKey = cmd.returnKey; - if(cmd.comment) command.comment = cmd.comment; - if(cmd.min) command.min = cmd.min; - if(cmd.max) command.max = cmd.max; - if(cmd.maxScan) command.maxScan = cmd.maxScan; - if(cmd.readPreference) command['$readPreference'] = cmd.readPreference; - if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; - - // Flags - if(cmd.awaitData) command.awaitData = cmd.awaitData; - if(cmd.snapshot) command.snapshot = cmd.snapshot; - if(cmd.tailable) command.tailable = cmd.tailable; - if(cmd.oplogReplay) command.oplogReplay = cmd.oplogReplay; - if(cmd.noCursorTimeout) command.noCursorTimeout = cmd.noCursorTimeout; - if(cmd.partial) command.partial = cmd.partial; - if(cmd.showDiskLoc) command.showRecordId = cmd.showDiskLoc; - - // Read Concern - if(cmd.readConcern) command.readConcern = cmd.readConcern; - - // Override method - if(cmd.explain) command.explain = cmd.explain; - if(cmd.exhaust) command.exhaust = cmd.exhaust; - - // If we have a explain flag - if(cmd.explain) { - // Create fake explain command - command = { - explain: command, - verbosity: 'allPlansExecution' - } - - // Set readConcern on the command if available - if(cmd.readConcern) command.readConcern = cmd.readConcern - - // Set up the _explain name for the command - x = '_explain'; - } - } else if(x == '_getmore') { - command = { - getMore: this.cursorState.cursorId, - collection: collection, - batchSize: cmd.batchSize - } - - if(cmd.maxTimeMS) command.maxTimeMS = cmd.maxTimeMS; - } else if(x == '_killcursors') { - command = { - killCursors: collection, - cursors: [this.cursorState.cursorId] - } - } else { - command = cmd; - } - - // Set up the connection - var connectionId = null; - - // Set local connection - if(this.connection) connectionId = this.connection; - if(!connectionId && this.server && this.server.getConnection) connectionId = this.server.getConnection(); - - // Get the command Name - var commandName = x == '_find' ? Object.keys(command)[0] : commandTranslation[x]; - - // Emit the start event for the command - var command = { - // Returns the command. - command: command, - // Returns the database name. - databaseName: db, - // Returns the command name. - commandName: commandName, - // Returns the driver generated request id. - requestId: requestId, - // Returns the driver generated operation id. - // This is used to link events together such as bulk write operations. OPTIONAL. - operationId: this.operationId, - // Returns the connection id for the command. For languages that do not have this, - // this MUST return the driver equivalent which MUST include the server address and port. - // The name of this field is flexible to match the object that is returned from the driver. - connectionId: connectionId - }; - - // Get the aruments - var args = Array.prototype.slice.call(arguments, 0); - - // Get the callback - var callback = args.pop(); - - // We do not have a callback but a Promise - if(typeof callback == 'function' || command.commandName == 'killCursors') { - var startTime = timestampGenerator.current(); - // Emit the started event - self.emit('started', command) - - // Emit succeeded event with killcursor if we have a legacy protocol - if(command.commandName == 'killCursors' - && this.server.lastIsMaster() - && this.server.lastIsMaster().maxWireVersion < 4) { - // Emit the succeeded command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: cursor.operationId, - connectionId: cursor.server.getConnection(), - reply: [{ok:1}] - }; - - // Emit the command - return self.emit('succeeded', command) - } - - // Add our callback handler - args.push(function(err, r) { - - if(err) { - // Command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: ourOpId, - connectionId: cursor.server.getConnection(), - failure: err }; - - // Emit the command - self.emit('failed', command) - } else { - // cursor id is zero, we can issue success command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: cursor.operationId, - connectionId: cursor.server.getConnection(), - reply: cursor.cursorState.documents - }; - - // Emit the command - self.emit('succeeded', command) - } - - // Return - if(!callback) return; - - // Return to caller - callback(err, r); - }); - - // Apply the call - func.apply(this, args); - } else { - // Assume promise, push back the missing value - args.push(callback); - // Get the promise - var promise = func.apply(this, args); - // Return a new promise - return new cursor.s.promiseLibrary(function(resolve, reject) { - var startTime = timestampGenerator.current(); - // Emit the started event - self.emit('started', command) - // Execute the function - promise.then(function(r) { - // cursor id is zero, we can issue success command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: cursor.operationId, - connectionId: cursor.server.getConnection(), - reply: cursor.cursorState.documents - }; - - // Emit the command - self.emit('succeeded', command) - }).catch(function(err) { - // Command - var command = { - duration: timestampGenerator.duration(startTime, timestampGenerator.current()), - commandName: commandName, - requestId: requestId, - operationId: ourOpId, - connectionId: cursor.server.getConnection(), - failure: err }; - - // Emit the command - self.emit('failed', command) - // reject the promise - reject(err); - }); - }); - } - } - }); - }); -} - -inherits(Instrumentation, EventEmitter); - -Instrumentation.prototype.uninstrument = function() { - for(var i = 0; i < this.overloads.length; i++) { - var obj = this.overloads[i]; - obj.proto[obj.name] = obj.func; - } - - // Remove all listeners - this.removeAllListeners('started'); - this.removeAllListeners('succeeded'); - this.removeAllListeners('failed'); -} - -module.exports = Instrumentation; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/lib/bulk/common.js b/util/retroImporter/node_modules/mongodb/lib/bulk/common.js deleted file mode 100644 index 7ec023e..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/bulk/common.js +++ /dev/null @@ -1,393 +0,0 @@ -"use strict"; - -var utils = require('../utils'); - -// Error codes -var UNKNOWN_ERROR = 8; -var INVALID_BSON_ERROR = 22; -var WRITE_CONCERN_ERROR = 64; -var MULTIPLE_ERROR = 65; - -// Insert types -var INSERT = 1; -var UPDATE = 2; -var REMOVE = 3 - - -// Get write concern -var writeConcern = function(target, col, options) { - if(options.w != null || options.j != null || options.fsync != null) { - target.writeConcern = options; - } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { - target.writeConcern = col.writeConcern; - } - - return target -} - -/** - * Helper function to define properties - * @ignore - */ -var defineReadOnlyProperty = function(self, name, value) { - Object.defineProperty(self, name, { - enumerable: true - , get: function() { - return value; - } - }); -} - -/** - * Keeps the state of a unordered batch so we can rewrite the results - * correctly after command execution - * @ignore - */ -var Batch = function(batchType, originalZeroIndex) { - this.originalZeroIndex = originalZeroIndex; - this.currentIndex = 0; - this.originalIndexes = []; - this.batchType = batchType; - this.operations = []; - this.size = 0; - this.sizeBytes = 0; -} - -/** - * Wraps a legacy operation so we can correctly rewrite it's error - * @ignore - */ -var LegacyOp = function(batchType, operation, index) { - this.batchType = batchType; - this.index = index; - this.operation = operation; -} - -/** - * Create a new BulkWriteResult instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @property {boolean} ok Did bulk operation correctly execute - * @property {number} nInserted number of inserted documents - * @property {number} nUpdated number of documents updated logically - * @property {number} nUpserted Number of upserted documents - * @property {number} nModified Number of documents updated physically on disk - * @property {number} nRemoved Number of removed documents - * @return {BulkWriteResult} a BulkWriteResult instance - */ -var BulkWriteResult = function(bulkResult) { - defineReadOnlyProperty(this, "ok", bulkResult.ok); - defineReadOnlyProperty(this, "nInserted", bulkResult.nInserted); - defineReadOnlyProperty(this, "nUpserted", bulkResult.nUpserted); - defineReadOnlyProperty(this, "nMatched", bulkResult.nMatched); - defineReadOnlyProperty(this, "nModified", bulkResult.nModified); - defineReadOnlyProperty(this, "nRemoved", bulkResult.nRemoved); - - /** - * Return an array of inserted ids - * - * @return {object[]} - */ - this.getInsertedIds = function() { - return bulkResult.insertedIds; - } - - /** - * Return an array of upserted ids - * - * @return {object[]} - */ - this.getUpsertedIds = function() { - return bulkResult.upserted; - } - - /** - * Return the upserted id at position x - * - * @param {number} index the number of the upserted id to return, returns undefined if no result for passed in index - * @return {object} - */ - this.getUpsertedIdAt = function(index) { - return bulkResult.upserted[index]; - } - - /** - * Return raw internal result - * - * @return {object} - */ - this.getRawResponse = function() { - return bulkResult; - } - - /** - * Returns true if the bulk operation contains a write error - * - * @return {boolean} - */ - this.hasWriteErrors = function() { - return bulkResult.writeErrors.length > 0; - } - - /** - * Returns the number of write errors off the bulk operation - * - * @return {number} - */ - this.getWriteErrorCount = function() { - return bulkResult.writeErrors.length; - } - - /** - * Returns a specific write error object - * - * @return {WriteError} - */ - this.getWriteErrorAt = function(index) { - if(index < bulkResult.writeErrors.length) { - return bulkResult.writeErrors[index]; - } - return null; - } - - /** - * Retrieve all write errors - * - * @return {object[]} - */ - this.getWriteErrors = function() { - return bulkResult.writeErrors; - } - - /** - * Retrieve lastOp if available - * - * @return {object} - */ - this.getLastOp = function() { - return bulkResult.lastOp; - } - - /** - * Retrieve the write concern error if any - * - * @return {WriteConcernError} - */ - this.getWriteConcernError = function() { - if(bulkResult.writeConcernErrors.length == 0) { - return null; - } else if(bulkResult.writeConcernErrors.length == 1) { - // Return the error - return bulkResult.writeConcernErrors[0]; - } else { - - // Combine the errors - var errmsg = ""; - for(var i = 0; i < bulkResult.writeConcernErrors.length; i++) { - var err = bulkResult.writeConcernErrors[i]; - errmsg = errmsg + err.errmsg; - - // TODO: Something better - if(i == 0) errmsg = errmsg + " and "; - } - - return new WriteConcernError({ errmsg : errmsg, code : WRITE_CONCERN_ERROR }); - } - } - - this.toJSON = function() { - return bulkResult; - } - - this.toString = function() { - return "BulkWriteResult(" + this.toJSON(bulkResult) + ")"; - } - - this.isOk = function() { - return bulkResult.ok == 1; - } -} - -/** - * Create a new WriteConcernError instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @property {number} code Write concern error code. - * @property {string} errmsg Write concern error message. - * @return {WriteConcernError} a WriteConcernError instance - */ -var WriteConcernError = function(err) { - if(!(this instanceof WriteConcernError)) return new WriteConcernError(err); - - // Define properties - defineReadOnlyProperty(this, "code", err.code); - defineReadOnlyProperty(this, "errmsg", err.errmsg); - - this.toJSON = function() { - return {code: err.code, errmsg: err.errmsg}; - } - - this.toString = function() { - return "WriteConcernError(" + err.errmsg + ")"; - } -} - -/** - * Create a new WriteError instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @property {number} code Write concern error code. - * @property {number} index Write concern error original bulk operation index. - * @property {string} errmsg Write concern error message. - * @return {WriteConcernError} a WriteConcernError instance - */ -var WriteError = function(err) { - if(!(this instanceof WriteError)) return new WriteError(err); - - // Define properties - defineReadOnlyProperty(this, "code", err.code); - defineReadOnlyProperty(this, "index", err.index); - defineReadOnlyProperty(this, "errmsg", err.errmsg); - - // - // Define access methods - this.getOperation = function() { - return err.op; - } - - this.toJSON = function() { - return {code: err.code, index: err.index, errmsg: err.errmsg, op: err.op}; - } - - this.toString = function() { - return "WriteError(" + JSON.stringify(this.toJSON()) + ")"; - } -} - -/** - * Merges results into shared data structure - * @ignore - */ -var mergeBatchResults = function(ordered, batch, bulkResult, err, result) { - // If we have an error set the result to be the err object - if(err) { - result = err; - } else if(result && result.result) { - result = result.result; - } else if(result == null) { - return; - } - - // Do we have a top level error stop processing and return - if(result.ok == 0 && bulkResult.ok == 1) { - bulkResult.ok = 0; - // bulkResult.error = utils.toError(result); - var writeError = { - index: 0 - , code: result.code || 0 - , errmsg: result.message - , op: batch.operations[0] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - return; - } else if(result.ok == 0 && bulkResult.ok == 0) { - return; - } - - // Add lastop if available - if(result.lastOp) { - bulkResult.lastOp = result.lastOp; - } - - // If we have an insert Batch type - if(batch.batchType == INSERT && result.n) { - bulkResult.nInserted = bulkResult.nInserted + result.n; - } - - // If we have an insert Batch type - if(batch.batchType == REMOVE && result.n) { - bulkResult.nRemoved = bulkResult.nRemoved + result.n; - } - - var nUpserted = 0; - - // We have an array of upserted values, we need to rewrite the indexes - if(Array.isArray(result.upserted)) { - nUpserted = result.upserted.length; - - for(var i = 0; i < result.upserted.length; i++) { - bulkResult.upserted.push({ - index: result.upserted[i].index + batch.originalZeroIndex - , _id: result.upserted[i]._id - }); - } - } else if(result.upserted) { - - nUpserted = 1; - - bulkResult.upserted.push({ - index: batch.originalZeroIndex - , _id: result.upserted - }); - } - - // If we have an update Batch type - if(batch.batchType == UPDATE && result.n) { - var nModified = result.nModified; - bulkResult.nUpserted = bulkResult.nUpserted + nUpserted; - bulkResult.nMatched = bulkResult.nMatched + (result.n - nUpserted); - - if(typeof nModified == 'number') { - bulkResult.nModified = bulkResult.nModified + nModified; - } else { - bulkResult.nModified = null; - } - } - - if(Array.isArray(result.writeErrors)) { - for(var i = 0; i < result.writeErrors.length; i++) { - - var writeError = { - index: batch.originalZeroIndex + result.writeErrors[i].index - , code: result.writeErrors[i].code - , errmsg: result.writeErrors[i].errmsg - , op: batch.operations[result.writeErrors[i].index] - }; - - bulkResult.writeErrors.push(new WriteError(writeError)); - } - } - - if(result.writeConcernError) { - bulkResult.writeConcernErrors.push(new WriteConcernError(result.writeConcernError)); - } -} - -// -// Clone the options -var cloneOptions = function(options) { - var clone = {}; - var keys = Object.keys(options); - for(var i = 0; i < keys.length; i++) { - clone[keys[i]] = options[keys[i]]; - } - - return clone; -} - -// Exports symbols -exports.BulkWriteResult = BulkWriteResult; -exports.WriteError = WriteError; -exports.Batch = Batch; -exports.LegacyOp = LegacyOp; -exports.mergeBatchResults = mergeBatchResults; -exports.cloneOptions = cloneOptions; -exports.writeConcern = writeConcern; -exports.INVALID_BSON_ERROR = INVALID_BSON_ERROR; -exports.WRITE_CONCERN_ERROR = WRITE_CONCERN_ERROR; -exports.MULTIPLE_ERROR = MULTIPLE_ERROR; -exports.UNKNOWN_ERROR = UNKNOWN_ERROR; -exports.INSERT = INSERT; -exports.UPDATE = UPDATE; -exports.REMOVE = REMOVE; diff --git a/util/retroImporter/node_modules/mongodb/lib/bulk/ordered.js b/util/retroImporter/node_modules/mongodb/lib/bulk/ordered.js deleted file mode 100644 index 319a030..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/bulk/ordered.js +++ /dev/null @@ -1,532 +0,0 @@ -"use strict"; - -var common = require('./common') - , utils = require('../utils') - , toError = require('../utils').toError - , f = require('util').format - , shallowClone = utils.shallowClone - , WriteError = common.WriteError - , BulkWriteResult = common.BulkWriteResult - , LegacyOp = common.LegacyOp - , ObjectID = require('mongodb-core').BSON.ObjectID - , Define = require('../metadata') - , Batch = common.Batch - , mergeBatchResults = common.mergeBatchResults; - -/** - * Create a FindOperatorsOrdered instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {FindOperatorsOrdered} a FindOperatorsOrdered instance. - */ -var FindOperatorsOrdered = function(self) { - this.s = self.s; -} - -/** - * Add a single update document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.update = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: true - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a single update one document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.updateOne = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: false - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} doc the new document to replace the existing one with - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.replaceOne = function(updateDocument) { - this.updateOne(updateDocument); -} - -/** - * Upsert modifier for update bulk operation - * - * @method - * @throws {MongoError} - * @return {FindOperatorsOrdered} - */ -FindOperatorsOrdered.prototype.upsert = function() { - this.s.currentOp.upsert = true; - return this; -} - -/** - * Add a remove one operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.deleteOne = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 1 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -// Backward compatibility -FindOperatorsOrdered.prototype.removeOne = FindOperatorsOrdered.prototype.deleteOne; - -/** - * Add a remove operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -FindOperatorsOrdered.prototype.delete = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 0 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -// Backward compatibility -FindOperatorsOrdered.prototype.remove = FindOperatorsOrdered.prototype.delete; - -// Add to internal list of documents -var addToOperationsList = function(_self, docType, document) { - // Get the bsonSize - var bsonSize = _self.s.bson.calculateObjectSize(document, false); - - // Throw error if the doc is bigger than the max BSON size - if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); - // Create a new batch object if we don't have a current one - if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - - // Check if we need to create a new batch - if(((_self.s.currentBatchSize + 1) >= _self.s.maxWriteBatchSize) - || ((_self.s.currentBatchSizeBytes + _self.s.currentBatchSizeBytes) >= _self.s.maxBatchSizeBytes) - || (_self.s.currentBatch.batchType != docType)) { - // Save the batch to the execution stack - _self.s.batches.push(_self.s.currentBatch); - - // Create a new batch - _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - - // Reset the current size trackers - _self.s.currentBatchSize = 0; - _self.s.currentBatchSizeBytes = 0; - } else { - // Update current batch size - _self.s.currentBatchSize = _self.s.currentBatchSize + 1; - _self.s.currentBatchSizeBytes = _self.s.currentBatchSizeBytes + bsonSize; - } - - if(docType == common.INSERT) { - _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); - } - - // We have an array of documents - if(Array.isArray(document)) { - throw toError("operation passed in cannot be an Array"); - } else { - _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); - _self.s.currentBatch.operations.push(document) - _self.s.currentIndex = _self.s.currentIndex + 1; - } - - // Return self - return _self; -} - -/** - * Create a new OrderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {number} length Get the number of operations in the bulk. - * @return {OrderedBulkOperation} a OrderedBulkOperation instance. - */ -function OrderedBulkOperation(topology, collection, options) { - options = options == null ? {} : options; - // TODO Bring from driver information in isMaster - var self = this; - var executed = false; - - // Current item - var currentOp = null; - - // Handle to the bson serializer, used to calculate running sizes - var bson = topology.bson; - - // Namespace for the operation - var namespace = collection.collectionName; - - // Set max byte size - var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; - var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; - - // Get the capabilities - var capabilities = topology.capabilities(); - - // Get the write concern - var writeConcern = common.writeConcern(shallowClone(options), collection, options); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Current batch - var currentBatch = null; - var currentIndex = 0; - var currentBatchSize = 0; - var currentBatchSizeBytes = 0; - var batches = []; - - // Final results - var bulkResult = { - ok: 1 - , writeErrors: [] - , writeConcernErrors: [] - , insertedIds: [] - , nInserted: 0 - , nUpserted: 0 - , nMatched: 0 - , nModified: 0 - , nRemoved: 0 - , upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult - // Current batch state - , currentBatch: null - , currentIndex: 0 - , currentBatchSize: 0 - , currentBatchSizeBytes: 0 - , batches: [] - // Write concern - , writeConcern: writeConcern - // Capabilities - , capabilities: capabilities - // Max batch size options - , maxBatchSizeBytes: maxBatchSizeBytes - , maxWriteBatchSize: maxWriteBatchSize - // Namespace - , namespace: namespace - // BSON - , bson: bson - // Topology - , topology: topology - // Options - , options: options - // Current operation - , currentOp: currentOp - // Executed - , executed: executed - // Collection - , collection: collection - // Promise Library - , promiseLibrary: promiseLibrary - // Fundamental error - , err: null - // Bypass validation - , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false - } -} - -var define = OrderedBulkOperation.define = new Define('OrderedBulkOperation', OrderedBulkOperation, false); - -OrderedBulkOperation.prototype.raw = function(op) { - var key = Object.keys(op)[0]; - - // Set up the force server object id - var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' - ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if((op.updateOne && op.updateOne.q) - || (op.updateMany && op.updateMany.q) - || (op.replaceOne && op.replaceOne.q)) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return addToOperationsList(this, common.UPDATE, op[key]); - } - - // Crud spec update format - if(op.updateOne || op.updateMany || op.replaceOne) { - var multi = op.updateOne || op.replaceOne ? false : true; - var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} - if(op[key].upsert) operation.upsert = true; - return addToOperationsList(this, common.UPDATE, operation); - } - - // Remove operations - if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { - op[key].limit = op.removeOne ? 1 : 0; - return addToOperationsList(this, common.REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if(op.deleteOne || op.deleteMany) { - var limit = op.deleteOne ? 1 : 0; - var operation = {q: op[key].filter, limit: limit} - return addToOperationsList(this, common.REMOVE, operation); - } - - // Insert operations - if(op.insertOne && op.insertOne.document == null) { - if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne); - } else if(op.insertOne && op.insertOne.document) { - if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne.document); - } - - if(op.insertMany) { - for(var i = 0; i < op.insertMany.length; i++) { - if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); - addToOperationsList(this, common.INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); -} - -/** - * Add a single insert document to the bulk operation - * - * @param {object} doc the document to insert - * @throws {MongoError} - * @return {OrderedBulkOperation} - */ -OrderedBulkOperation.prototype.insert = function(document) { - if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, document); -} - -/** - * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne - * - * @method - * @param {object} selector The selector for the bulk operation. - * @throws {MongoError} - * @return {FindOperatorsOrdered} - */ -OrderedBulkOperation.prototype.find = function(selector) { - if (!selector) { - throw toError("Bulk find operation must specify a selector"); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - } - - return new FindOperatorsOrdered(this); -} - -Object.defineProperty(OrderedBulkOperation.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -// -// Execute next write command in a chain -var executeCommands = function(self, callback) { - if(self.s.batches.length == 0) { - return callback(null, new BulkWriteResult(self.s.bulkResult)); - } - - // Ordered execution of the command - var batch = self.s.batches.shift(); - - var resultHandler = function(err, result) { - // Error is a driver related error not a bulk op error, terminate - if(err && err.driver || err && err.message) { - return callback(err); - } - - // If we have and error - if(err) err.ok = 0; - // Merge the results together - var mergeResult = mergeBatchResults(true, batch, self.s.bulkResult, err, result); - if(mergeResult != null) { - return callback(null, new BulkWriteResult(self.s.bulkResult)); - } - - // If we are ordered and have errors and they are - // not all replication errors terminate the operation - if(self.s.bulkResult.writeErrors.length > 0) { - return callback(toError(self.s.bulkResult.writeErrors[0]), new BulkWriteResult(self.s.bulkResult)); - } - - // Execute the next command in line - executeCommands(self, callback); - } - - var finalOptions = {ordered: true} - if(self.s.writeConcern != null) { - finalOptions.writeConcern = self.s.writeConcern; - } - - // Set an operationIf if provided - if(self.operationId) { - resultHandler.operationId = self.operationId; - } - - // Serialize functions - if(self.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true - } - - // Serialize functions - if(self.s.options.ignoreUndefined) { - finalOptions.ignoreUndefined = true - } - - // Is the bypassDocumentValidation options specific - if(self.s.bypassDocumentValidation == true) { - finalOptions.bypassDocumentValidation = true; - } - - try { - if(batch.batchType == common.INSERT) { - self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.UPDATE) { - self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.REMOVE) { - self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } - } catch(err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); - } -} - -/** - * The callback format for results - * @callback OrderedBulkOperation~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - -/** - * Execute the ordered bulk operation - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {OrderedBulkOperation~resultCallback} [callback] The result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -OrderedBulkOperation.prototype.execute = function(_writeConcern, callback) { - var self = this; - if(this.s.executed) throw new toError("batch cannot be re-executed"); - if(typeof _writeConcern == 'function') { - callback = _writeConcern; - } else { - this.s.writeConcern = _writeConcern; - } - - // If we have current batch - if(this.s.currentBatch) this.s.batches.push(this.s.currentBatch); - - // If we have no operations in the bulk raise an error - if(this.s.batches.length == 0) { - throw toError("Invalid Operation, No operations in bulk"); - } - - // Execute using callback - if(typeof callback == 'function') { - return executeCommands(this, callback); - } - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - executeCommands(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('execute', {callback: true, promise:false}); - -/** - * Returns an unordered batch object - * @ignore - */ -var initializeOrderedBulkOp = function(topology, collection, options) { - return new OrderedBulkOperation(topology, collection, options); -} - -initializeOrderedBulkOp.OrderedBulkOperation = OrderedBulkOperation; -module.exports = initializeOrderedBulkOp; -module.exports.Bulk = OrderedBulkOperation; diff --git a/util/retroImporter/node_modules/mongodb/lib/bulk/unordered.js b/util/retroImporter/node_modules/mongodb/lib/bulk/unordered.js deleted file mode 100644 index ca45b96..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/bulk/unordered.js +++ /dev/null @@ -1,541 +0,0 @@ -"use strict"; - -var common = require('./common') - , utils = require('../utils') - , toError = require('../utils').toError - , f = require('util').format - , shallowClone = utils.shallowClone - , WriteError = common.WriteError - , BulkWriteResult = common.BulkWriteResult - , LegacyOp = common.LegacyOp - , ObjectID = require('mongodb-core').BSON.ObjectID - , Define = require('../metadata') - , Batch = common.Batch - , mergeBatchResults = common.mergeBatchResults; - -/** - * Create a FindOperatorsUnordered instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {number} length Get the number of operations in the bulk. - * @return {FindOperatorsUnordered} a FindOperatorsUnordered instance. - */ -var FindOperatorsUnordered = function(self) { - this.s = self.s; -} - -/** - * Add a single update document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.update = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: true - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a single update one document to the bulk operation - * - * @method - * @param {object} doc update operations - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.updateOne = function(updateDocument) { - // Perform upsert - var upsert = typeof this.s.currentOp.upsert == 'boolean' ? this.s.currentOp.upsert : false; - - // Establish the update command - var document = { - q: this.s.currentOp.selector - , u: updateDocument - , multi: false - , upsert: upsert - } - - // Clear out current Op - this.s.currentOp = null; - // Add the update document to the list - return addToOperationsList(this, common.UPDATE, document); -} - -/** - * Add a replace one operation to the bulk operation - * - * @method - * @param {object} doc the new document to replace the existing one with - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.replaceOne = function(updateDocument) { - this.updateOne(updateDocument); -} - -/** - * Upsert modifier for update bulk operation - * - * @method - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.upsert = function() { - this.s.currentOp.upsert = true; - return this; -} - -/** - * Add a remove one operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.removeOne = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 1 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -/** - * Add a remove operation to the bulk operation - * - * @method - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -FindOperatorsUnordered.prototype.remove = function() { - // Establish the update command - var document = { - q: this.s.currentOp.selector - , limit: 0 - } - - // Clear out current Op - this.s.currentOp = null; - // Add the remove document to the list - return addToOperationsList(this, common.REMOVE, document); -} - -// -// Add to the operations list -// -var addToOperationsList = function(_self, docType, document) { - // Get the bsonSize - var bsonSize = _self.s.bson.calculateObjectSize(document, false); - // Throw error if the doc is bigger than the max BSON size - if(bsonSize >= _self.s.maxBatchSizeBytes) throw toError("document is larger than the maximum size " + _self.s.maxBatchSizeBytes); - // Holds the current batch - _self.s.currentBatch = null; - // Get the right type of batch - if(docType == common.INSERT) { - _self.s.currentBatch = _self.s.currentInsertBatch; - } else if(docType == common.UPDATE) { - _self.s.currentBatch = _self.s.currentUpdateBatch; - } else if(docType == common.REMOVE) { - _self.s.currentBatch = _self.s.currentRemoveBatch; - } - - // Create a new batch object if we don't have a current one - if(_self.s.currentBatch == null) _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - - // Check if we need to create a new batch - if(((_self.s.currentBatch.size + 1) >= _self.s.maxWriteBatchSize) - || ((_self.s.currentBatch.sizeBytes + bsonSize) >= _self.s.maxBatchSizeBytes) - || (_self.s.currentBatch.batchType != docType)) { - // Save the batch to the execution stack - _self.s.batches.push(_self.s.currentBatch); - - // Create a new batch - _self.s.currentBatch = new Batch(docType, _self.s.currentIndex); - } - - // We have an array of documents - if(Array.isArray(document)) { - throw toError("operation passed in cannot be an Array"); - } else { - _self.s.currentBatch.operations.push(document); - _self.s.currentBatch.originalIndexes.push(_self.s.currentIndex); - _self.s.currentIndex = _self.s.currentIndex + 1; - } - - // Save back the current Batch to the right type - if(docType == common.INSERT) { - _self.s.currentInsertBatch = _self.s.currentBatch; - _self.s.bulkResult.insertedIds.push({index: _self.s.currentIndex, _id: document._id}); - } else if(docType == common.UPDATE) { - _self.s.currentUpdateBatch = _self.s.currentBatch; - } else if(docType == common.REMOVE) { - _self.s.currentRemoveBatch = _self.s.currentBatch; - } - - // Update current batch size - _self.s.currentBatch.size = _self.s.currentBatch.size + 1; - _self.s.currentBatch.sizeBytes = _self.s.currentBatch.sizeBytes + bsonSize; - - // Return self - return _self; -} - -/** - * Create a new UnorderedBulkOperation instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @return {UnorderedBulkOperation} a UnorderedBulkOperation instance. - */ -var UnorderedBulkOperation = function(topology, collection, options) { - options = options == null ? {} : options; - - // Contains reference to self - var self = this; - // Get the namesspace for the write operations - var namespace = collection.collectionName; - // Used to mark operation as executed - var executed = false; - - // Current item - // var currentBatch = null; - var currentOp = null; - var currentIndex = 0; - var batches = []; - - // The current Batches for the different operations - var currentInsertBatch = null; - var currentUpdateBatch = null; - var currentRemoveBatch = null; - - // Handle to the bson serializer, used to calculate running sizes - var bson = topology.bson; - - // Get the capabilities - var capabilities = topology.capabilities(); - - // Set max byte size - var maxBatchSizeBytes = topology.isMasterDoc.maxBsonObjectSize; - var maxWriteBatchSize = topology.isMasterDoc.maxWriteBatchSize || 1000; - - // Get the write concern - var writeConcern = common.writeConcern(shallowClone(options), collection, options); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Final results - var bulkResult = { - ok: 1 - , writeErrors: [] - , writeConcernErrors: [] - , insertedIds: [] - , nInserted: 0 - , nUpserted: 0 - , nMatched: 0 - , nModified: 0 - , nRemoved: 0 - , upserted: [] - }; - - // Internal state - this.s = { - // Final result - bulkResult: bulkResult - // Current batch state - , currentInsertBatch: null - , currentUpdateBatch: null - , currentRemoveBatch: null - , currentBatch: null - , currentIndex: 0 - , batches: [] - // Write concern - , writeConcern: writeConcern - // Capabilities - , capabilities: capabilities - // Max batch size options - , maxBatchSizeBytes: maxBatchSizeBytes - , maxWriteBatchSize: maxWriteBatchSize - // Namespace - , namespace: namespace - // BSON - , bson: bson - // Topology - , topology: topology - // Options - , options: options - // Current operation - , currentOp: currentOp - // Executed - , executed: executed - // Collection - , collection: collection - // Promise Library - , promiseLibrary: promiseLibrary - // Bypass validation - , bypassDocumentValidation: typeof options.bypassDocumentValidation == 'boolean' ? options.bypassDocumentValidation : false - } -} - -var define = UnorderedBulkOperation.define = new Define('UnorderedBulkOperation', UnorderedBulkOperation, false); - -/** - * Add a single insert document to the bulk operation - * - * @param {object} doc the document to insert - * @throws {MongoError} - * @return {UnorderedBulkOperation} - */ -UnorderedBulkOperation.prototype.insert = function(document) { - if(this.s.collection.s.db.options.forceServerObjectId !== true && document._id == null) document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, document); -} - -/** - * Initiate a find operation for an update/updateOne/remove/removeOne/replaceOne - * - * @method - * @param {object} selector The selector for the bulk operation. - * @throws {MongoError} - * @return {FindOperatorsUnordered} - */ -UnorderedBulkOperation.prototype.find = function(selector) { - if (!selector) { - throw toError("Bulk find operation must specify a selector"); - } - - // Save a current selector - this.s.currentOp = { - selector: selector - } - - return new FindOperatorsUnordered(this); -} - -Object.defineProperty(UnorderedBulkOperation.prototype, 'length', { - enumerable: true, - get: function() { - return this.s.currentIndex; - } -}); - -UnorderedBulkOperation.prototype.raw = function(op) { - var key = Object.keys(op)[0]; - - // Set up the force server object id - var forceServerObjectId = typeof this.s.options.forceServerObjectId == 'boolean' - ? this.s.options.forceServerObjectId : this.s.collection.s.db.options.forceServerObjectId; - - // Update operations - if((op.updateOne && op.updateOne.q) - || (op.updateMany && op.updateMany.q) - || (op.replaceOne && op.replaceOne.q)) { - op[key].multi = op.updateOne || op.replaceOne ? false : true; - return addToOperationsList(this, common.UPDATE, op[key]); - } - - // Crud spec update format - if(op.updateOne || op.updateMany || op.replaceOne) { - var multi = op.updateOne || op.replaceOne ? false : true; - var operation = {q: op[key].filter, u: op[key].update || op[key].replacement, multi: multi} - if(op[key].upsert) operation.upsert = true; - return addToOperationsList(this, common.UPDATE, operation); - } - - // Remove operations - if(op.removeOne || op.removeMany || (op.deleteOne && op.deleteOne.q) || op.deleteMany && op.deleteMany.q) { - op[key].limit = op.removeOne ? 1 : 0; - return addToOperationsList(this, common.REMOVE, op[key]); - } - - // Crud spec delete operations, less efficient - if(op.deleteOne || op.deleteMany) { - var limit = op.deleteOne ? 1 : 0; - var operation = {q: op[key].filter, limit: limit} - return addToOperationsList(this, common.REMOVE, operation); - } - - // Insert operations - if(op.insertOne && op.insertOne.document == null) { - if(forceServerObjectId !== true && op.insertOne._id == null) op.insertOne._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne); - } else if(op.insertOne && op.insertOne.document) { - if(forceServerObjectId !== true && op.insertOne.document._id == null) op.insertOne.document._id = new ObjectID(); - return addToOperationsList(this, common.INSERT, op.insertOne.document); - } - - if(op.insertMany) { - for(var i = 0; i < op.insertMany.length; i++) { - if(forceServerObjectId !== true && op.insertMany[i]._id == null) op.insertMany[i]._id = new ObjectID(); - addToOperationsList(this, common.INSERT, op.insertMany[i]); - } - - return; - } - - // No valid type of operation - throw toError("bulkWrite only supports insertOne, insertMany, updateOne, updateMany, removeOne, removeMany, deleteOne, deleteMany"); -} - -// -// Execute the command -var executeBatch = function(self, batch, callback) { - var finalOptions = {ordered: false} - if(self.s.writeConcern != null) { - finalOptions.writeConcern = self.s.writeConcern; - } - - var resultHandler = function(err, result) { - // Error is a driver related error not a bulk op error, terminate - if(err && err.driver || err && err.message) { - return callback(err); - } - - // If we have and error - if(err) err.ok = 0; - callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, result)); - } - - // Set an operationIf if provided - if(self.operationId) { - resultHandler.operationId = self.operationId; - } - - // Serialize functions - if(self.s.options.serializeFunctions) { - finalOptions.serializeFunctions = true - } - - // Is the bypassDocumentValidation options specific - if(self.s.bypassDocumentValidation == true) { - finalOptions.bypassDocumentValidation = true; - } - - try { - if(batch.batchType == common.INSERT) { - self.s.topology.insert(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.UPDATE) { - self.s.topology.update(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } else if(batch.batchType == common.REMOVE) { - self.s.topology.remove(self.s.collection.namespace, batch.operations, finalOptions, resultHandler); - } - } catch(err) { - // Force top level error - err.ok = 0; - // Merge top level error and return - callback(null, mergeBatchResults(false, batch, self.s.bulkResult, err, null)); - } -} - -// -// Execute all the commands -var executeBatches = function(self, callback) { - var numberOfCommandsToExecute = self.s.batches.length; - var error = null; - // Execute over all the batches - for(var i = 0; i < self.s.batches.length; i++) { - executeBatch(self, self.s.batches[i], function(err, result) { - // Driver layer error capture it - if(err) error = err; - // Count down the number of commands left to execute - numberOfCommandsToExecute = numberOfCommandsToExecute - 1; - - // Execute - if(numberOfCommandsToExecute == 0) { - // Driver level error - if(error) return callback(error); - // Treat write errors - var error = self.s.bulkResult.writeErrors.length > 0 ? toError(self.s.bulkResult.writeErrors[0]) : null; - callback(error, new BulkWriteResult(self.s.bulkResult)); - } - }); - } -} - -/** - * The callback format for results - * @callback UnorderedBulkOperation~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {BulkWriteResult} result The bulk write result. - */ - -/** - * Execute the ordered bulk operation - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {UnorderedBulkOperation~resultCallback} [callback] The result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -UnorderedBulkOperation.prototype.execute = function(_writeConcern, callback) { - var self = this; - if(this.s.executed) throw toError("batch cannot be re-executed"); - if(typeof _writeConcern == 'function') { - callback = _writeConcern; - } else { - this.s.writeConcern = _writeConcern; - } - - // If we have current batch - if(this.s.currentInsertBatch) this.s.batches.push(this.s.currentInsertBatch); - if(this.s.currentUpdateBatch) this.s.batches.push(this.s.currentUpdateBatch); - if(this.s.currentRemoveBatch) this.s.batches.push(this.s.currentRemoveBatch); - - // If we have no operations in the bulk raise an error - if(this.s.batches.length == 0) { - throw toError("Invalid Operation, No operations in bulk"); - } - - // Execute using callback - if(typeof callback == 'function') return executeBatches(this, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - executeBatches(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('execute', {callback: true, promise:false}); - -/** - * Returns an unordered batch object - * @ignore - */ -var initializeUnorderedBulkOp = function(topology, collection, options) { - return new UnorderedBulkOperation(topology, collection, options); -} - -initializeUnorderedBulkOp.UnorderedBulkOperation = UnorderedBulkOperation; -module.exports = initializeUnorderedBulkOp; -module.exports.Bulk = UnorderedBulkOperation; diff --git a/util/retroImporter/node_modules/mongodb/lib/collection.js b/util/retroImporter/node_modules/mongodb/lib/collection.js deleted file mode 100644 index 5ae1ebc..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/collection.js +++ /dev/null @@ -1,3128 +0,0 @@ -"use strict"; - -var checkCollectionName = require('./utils').checkCollectionName - , ObjectID = require('mongodb-core').BSON.ObjectID - , Long = require('mongodb-core').BSON.Long - , Code = require('mongodb-core').BSON.Code - , f = require('util').format - , AggregationCursor = require('./aggregation_cursor') - , MongoError = require('mongodb-core').MongoError - , shallowClone = require('./utils').shallowClone - , isObject = require('./utils').isObject - , toError = require('./utils').toError - , normalizeHintField = require('./utils').normalizeHintField - , handleCallback = require('./utils').handleCallback - , decorateCommand = require('./utils').decorateCommand - , formattedOrderClause = require('./utils').formattedOrderClause - , ReadPreference = require('./read_preference') - , CoreReadPreference = require('mongodb-core').ReadPreference - , CommandCursor = require('./command_cursor') - , Define = require('./metadata') - , Cursor = require('./cursor') - , unordered = require('./bulk/unordered') - , ordered = require('./bulk/ordered'); - -/** - * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection - * allowing for insert/update/remove/find and other command operation on that MongoDB collection. - * - * **COLLECTION Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('createIndexExample1'); - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * db.close(); - * }); - * }); - */ - -/** - * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) - * @class - * @property {string} collectionName Get the collection name. - * @property {string} namespace Get the full collection namespace. - * @property {object} writeConcern The current write concern values. - * @property {object} readConcern The current read concern values. - * @property {object} hint Get current index hint for collection. - * @return {Collection} a Collection instance. - */ -var Collection = function(db, topology, dbName, name, pkFactory, options) { - checkCollectionName(name); - var self = this; - // Unpack variables - var internalHint = null; - var opts = options != null && ('object' === typeof options) ? options : {}; - var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; - var serializeFunctions = options == null || options.serializeFunctions == null ? db.serializeFunctions : options.serializeFunctions; - var raw = options == null || options.raw == null ? db.raw : options.raw; - var readPreference = null; - var collectionHint = null; - var namespace = f("%s.%s", dbName, name); - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Assign the right collection level readPreference - if(options && options.readPreference) { - readPreference = options.readPreference; - } else if(db.options.readPreference) { - readPreference = db.options.readPreference; - } - - // Set custom primary key factory if provided - pkFactory = pkFactory == null - ? ObjectID - : pkFactory; - - // Internal state - this.s = { - // Set custom primary key factory if provided - pkFactory: pkFactory - // Db - , db: db - // Topology - , topology: topology - // dbName - , dbName: dbName - // Options - , options: options - // Namespace - , namespace: namespace - // Read preference - , readPreference: readPreference - // Raw - , raw: raw - // SlaveOK - , slaveOk: slaveOk - // Serialize functions - , serializeFunctions: serializeFunctions - // internalHint - , internalHint: internalHint - // collectionHint - , collectionHint: collectionHint - // Name - , name: name - // Promise library - , promiseLibrary: promiseLibrary - // Read Concern - , readConcern: options.readConcern - } -} - -var define = Collection.define = new Define('Collection', Collection, false); - -Object.defineProperty(Collection.prototype, 'collectionName', { - enumerable: true, get: function() { return this.s.name; } -}); - -Object.defineProperty(Collection.prototype, 'namespace', { - enumerable: true, get: function() { return this.s.namespace; } -}); - -Object.defineProperty(Collection.prototype, 'readConcern', { - enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; } -}); - -Object.defineProperty(Collection.prototype, 'writeConcern', { - enumerable:true, - get: function() { - var ops = {}; - if(this.s.options.w != null) ops.w = this.s.options.w; - if(this.s.options.j != null) ops.j = this.s.options.j; - if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync; - if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout; - return ops; - } -}); - -/** - * @ignore - */ -Object.defineProperty(Collection.prototype, "hint", { - enumerable: true - , get: function () { return this.s.collectionHint; } - , set: function (v) { this.s.collectionHint = normalizeHintField(v); } -}); - -/** - * Creates a cursor for a query that can be used to iterate over results from MongoDB - * @method - * @param {object} query The cursor query object. - * @throws {MongoError} - * @return {Cursor} - */ -Collection.prototype.find = function() { - var options - , args = Array.prototype.slice.call(arguments, 0) - , has_callback = typeof args[args.length - 1] === 'function' - , has_weird_callback = typeof args[0] === 'function' - , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null) - , len = args.length - , selector = len >= 1 ? args[0] : {} - , fields = len >= 2 ? args[1] : undefined; - - if(len === 1 && has_weird_callback) { - // backwards compat for callback?, options case - selector = {}; - options = args[0]; - } - - if(len === 2 && fields !== undefined && !Array.isArray(fields)) { - var fieldKeys = Object.keys(fields); - var is_option = false; - - for(var i = 0; i < fieldKeys.length; i++) { - if(testForFields[fieldKeys[i]] != null) { - is_option = true; - break; - } - } - - if(is_option) { - options = fields; - fields = undefined; - } else { - options = {}; - } - } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) { - var newFields = {}; - // Rewrite the array - for(var i = 0; i < fields.length; i++) { - newFields[fields[i]] = 1; - } - // Set the fields - fields = newFields; - } - - if(3 === len) { - options = args[2]; - } - - // Ensure selector is not null - selector = selector == null ? {} : selector; - // Validate correctness off the selector - var object = selector; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Validate correctness of the field selector - var object = fields; - if(Buffer.isBuffer(object)) { - var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24; - if(object_size != object.length) { - var error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]"); - error.name = 'MongoError'; - throw error; - } - } - - // Check special case where we are using an objectId - if(selector instanceof ObjectID || (selector != null && selector._bsontype == 'ObjectID')) { - selector = {_id:selector}; - } - - // If it's a serialized fields field we need to just let it through - // user be warned it better be good - if(options && options.fields && !(Buffer.isBuffer(options.fields))) { - fields = {}; - - if(Array.isArray(options.fields)) { - if(!options.fields.length) { - fields['_id'] = 1; - } else { - for (var i = 0, l = options.fields.length; i < l; i++) { - fields[options.fields[i]] = 1; - } - } - } else { - fields = options.fields; - } - } - - if (!options) options = {}; - - var newOptions = {}; - // Make a shallow copy of options - for (var key in options) { - newOptions[key] = options[key]; - } - - // Unpack options - newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0; - newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0; - newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.s.raw; - newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; - newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout; - // // If we have overridden slaveOk otherwise use the default db setting - newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; - - // Add read preference if needed - newOptions = getReadPreference(this, newOptions, this.s.db, this); - // Set slave ok to true if read preference different from primary - if(newOptions.readPreference != null - && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) { - newOptions.slaveOk = true; - } - - // Ensure the query is an object - if(selector != null && typeof selector != 'object') { - throw MongoError.create({message: "query selector must be an object", driver:true }); - } - - // Build the find command - var findCommand = { - find: this.s.namespace - , limit: newOptions.limit - , skip: newOptions.skip - , query: selector - } - - // Ensure we use the right await data option - if(typeof newOptions.awaitdata == 'boolean') { - newOptions.awaitData = newOptions.awaitdata - }; - - // Translate to new command option noCursorTimeout - if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout; - - // Merge in options to command - for(var name in newOptions) { - if(newOptions[name] != null) findCommand[name] = newOptions[name]; - } - - // Format the fields - var formatFields = function(fields) { - var object = {}; - if(Array.isArray(fields)) { - for(var i = 0; i < fields.length; i++) { - if(Array.isArray(fields[i])) { - object[fields[i][0]] = fields[i][1]; - } else { - object[fields[i][0]] = 1; - } - } - } else { - object = fields; - } - - return object; - } - - // Special treatment for the fields selector - if(fields) findCommand.fields = formatFields(fields); - - // Add db object to the new options - newOptions.db = this.s.db; - - // Add the promise library - newOptions.promiseLibrary = this.s.promiseLibrary; - - // Set raw if available at collection level - if(newOptions.raw == null && this.s.raw) newOptions.raw = this.s.raw; - - // Sort options - if(findCommand.sort) - findCommand.sort = formattedOrderClause(findCommand.sort); - - // Set the readConcern - if(this.s.readConcern) { - findCommand.readConcern = this.s.readConcern; - } - - // Create the cursor - if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions)); - return this.s.topology.cursor(this.s.namespace, findCommand, newOptions); -} - -define.classMethod('find', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Inserts a single document into MongoDB. - * @method - * @param {object} doc Document to insert. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertOne = function(doc, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - if(Array.isArray(doc)) return callback(MongoError.create({message: 'doc parameter must be an object', driver:true })); - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return insertOne(self, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - insertOne(self, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var insertOne = function(self, doc, options, callback) { - insertDocuments(self, [doc], options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - // Workaround for pre 2.6 servers - if(r == null) return callback(null, {result: {ok:1}}); - // Add values to top level to ensure crud spec compatibility - r.insertedCount = r.result.n; - r.insertedId = doc._id; - if(callback) callback(null, r); - }); -} - -var mapInserManyResults = function(docs, r) { - var ids = r.getInsertedIds(); - var keys = Object.keys(ids); - var finalIds = new Array(keys); - - for(var i = 0; i < keys.length; i++) { - if(ids[keys[i]]._id) { - finalIds[ids[keys[i]].index] = ids[keys[i]]._id; - } - } - - return { - result: {ok: 1, n: r.insertedCount}, - ops: docs, - insertedCount: r.insertedCount, - insertedIds: finalIds - } -} - -define.classMethod('insertOne', {callback: true, promise:true}); - -/** - * Inserts an array of documents into MongoDB. - * @method - * @param {object[]} docs Documents to insert. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.insertMany = function(docs, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {ordered:true}; - if(!Array.isArray(docs)) return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true })); - - // Get the write concern options - if(typeof options.checkKeys != 'boolean') { - options.checkKeys = true; - } - - // If keep going set unordered - options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; - - // Set up the force server object id - var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' - ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; - - // Do we want to force the server to assign the _id key - if(forceServerObjectId !== true) { - // Add _id if not specified - for(var i = 0; i < docs.length; i++) { - if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); - } - } - - // Generate the bulk write operations - var operations = [{ - insertMany: docs - }]; - - // Execute using callback - if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) { - if(err) return callback(err, r); - callback(null, mapInserManyResults(docs, r)); - }); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - bulkWrite(self, operations, options, function(err, r) { - if(err) return reject(err); - resolve(mapInserManyResults(docs, r)); - }); - }); -} - -define.classMethod('insertMany', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~BulkWriteOpResult - * @property {number} insertedCount Number of documents inserted. - * @property {number} matchedCount Number of documents matched for update. - * @property {number} modifiedCount Number of documents modified. - * @property {number} deletedCount Number of documents deleted. - * @property {number} upsertedCount Number of documents upserted. - * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation - * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~bulkWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Perform a bulkWrite operation without a fluent API - * - * Legal operation types are - * - * { insertOne: { document: { a: 1 } } } - * - * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } - * - * { deleteOne: { filter: {c:1} } } - * - * { deleteMany: { filter: {c:1} } } - * - * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} - * - * @method - * @param {object[]} operations Bulk operations to perform. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~bulkWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.bulkWrite = function(operations, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {ordered:true}; - - if(!Array.isArray(operations)) { - throw MongoError.create({message: "operations must be an array of documents", driver:true }); - } - - // Execute using callback - if(typeof callback == 'function') return bulkWrite(self, operations, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - bulkWrite(self, operations, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var bulkWrite = function(self, operations, options, callback) { - // Add ignoreUndfined - if(self.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = self.s.options.ignoreUndefined; - } - - // Create the bulk operation - var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options); - - // for each op go through and add to the bulk - for(var i = 0; i < operations.length; i++) { - bulk.raw(operations[i]); - } - - // Final options for write concern - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {}; - - // Execute the bulk - bulk.execute(writeCon, function(err, r) { - // We have connection level error - if(!r && err) return callback(err, null); - // We have single error - if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) { - return callback(toError(r.getWriteErrorAt(0)), r); - } - - // if(err) return callback(err); - r.insertedCount = r.nInserted; - r.matchedCount = r.nMatched; - r.modifiedCount = r.nModified || 0; - r.deletedCount = r.nRemoved; - r.upsertedCount = r.getUpsertedIds().length; - r.upsertedIds = {}; - r.insertedIds = {}; - - // Update the n - r.n = r.insertedCount; - - // Inserted documents - var inserted = r.getInsertedIds(); - // Map inserted ids - for(var i = 0; i < inserted.length; i++) { - r.insertedIds[inserted[i].index] = inserted[i]._id; - } - - // Upserted documents - var upserted = r.getUpsertedIds(); - // Map upserted ids - for(var i = 0; i < upserted.length; i++) { - r.upsertedIds[upserted[i].index] = upserted[i]._id; - } - - // Check if we have write errors - if(r.hasWriteErrors()) { - // Get all the errors - var errors = r.getWriteErrors(); - // Return the MongoError object - return callback(toError({ - message: 'write operation failed', code: errors[0].code, writeErrors: errors - }), r); - } - - // Check if we have a writeConcern error - if(r.getWriteConcernError()) { - // Return the MongoError object - return callback(toError(r.getWriteConcernError()), r); - } - - // Return the results - callback(null, r); - }); -} - -var insertDocuments = function(self, docs, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Ensure we are operating on an array op docs - docs = Array.isArray(docs) ? docs : [docs]; - - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true; - - // If keep going set unordered - if(finalOptions.keepGoing == true) finalOptions.ordered = false; - finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; - - // Set up the force server object id - var forceServerObjectId = typeof options.forceServerObjectId == 'boolean' - ? options.forceServerObjectId : self.s.db.options.forceServerObjectId; - - // Add _id if not specified - if(forceServerObjectId !== true){ - for(var i = 0; i < docs.length; i++) { - if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk(); - } - } - - // File inserts - self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err); - if(result == null) return handleCallback(callback, null, null); - if(result.result.code) return handleCallback(callback, toError(result.result)); - if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); - // Add docs to the list - result.ops = docs; - // Return the results - handleCallback(callback, null, result); - }); -} - -define.classMethod('bulkWrite', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~WriteOpResult - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {object} connection The connection object used for the operation. - * @property {object} result The command result object. - */ - -/** - * The callback format for inserts - * @callback Collection~writeOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * @typedef {Object} Collection~insertWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * @typedef {Object} Collection~insertOneWriteOpResult - * @property {Number} insertedCount The total amount of documents inserted. - * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany - * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. - * @property {object} connection The connection object used for the operation. - * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents inserted. - */ - -/** - * The callback format for inserts - * @callback Collection~insertWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * The callback format for inserts - * @callback Collection~insertOneWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Inserts a single document or a an array of documents into MongoDB. - * @method - * @param {(object|object[])} docs Documents to insert. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~insertWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated Use insertOne, insertMany or bulkWrite - */ -Collection.prototype.insert = function(docs, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {ordered:false}; - docs = !Array.isArray(docs) ? [docs] : docs; - - if(options.keepGoing == true) { - options.ordered = false; - } - - return this.insertMany(docs, options, callback); -} - -define.classMethod('insert', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~updateWriteOpResult - * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents scanned. - * @property {Number} result.nModified The total count of documents modified. - * @property {Object} connection The connection object used for the operation. - * @property {Number} matchedCount The number of documents that matched the filter. - * @property {Number} modifiedCount The number of documents that were modified. - * @property {Number} upsertedCount The number of documents upserted. - * @property {Object} upsertedId The upserted id. - * @property {ObjectId} upsertedId._id The upserted _id returned from the server. - */ - -/** - * The callback format for inserts - * @callback Collection~updateWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Update a single document on MongoDB - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateOne = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options) - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return updateOne(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - updateOne(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var updateOne = function(self, filter, update, options, callback) { - // Set single document update - options.multi = false; - // Execute update - updateDocuments(self, filter, update, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.matchedCount = r.result.n; - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; - r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - if(callback) callback(null, r); - }); -} - -define.classMethod('updateOne', {callback: true, promise:true}); - -/** - * Replace a document on MongoDB - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} doc The Document that replaces the matching document - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.replaceOne = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options) - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return replaceOne(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - replaceOne(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var replaceOne = function(self, filter, update, options, callback) { - // Set single document update - options.multi = false; - // Execute update - updateDocuments(self, filter, update, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.matchedCount = r.result.n; - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; - r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - r.ops = [update]; - if(callback) callback(null, r); - }); -} - -define.classMethod('replaceOne', {callback: true, promise:true}); - -/** - * Update multiple documents on MongoDB - * @method - * @param {object} filter The Filter used to select the document to update - * @param {object} update The update operations to be applied to the document - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~updateWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.updateMany = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = shallowClone(options) - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return updateMany(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - updateMany(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var updateMany = function(self, filter, update, options, callback) { - // Set single document update - options.multi = true; - // Execute update - updateDocuments(self, filter, update, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.matchedCount = r.result.n; - r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n; - r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null; - r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0; - if(callback) callback(null, r); - }); -} - -define.classMethod('updateMany', {callback: true, promise:true}); - -var updateDocuments = function(self, selector, document, options, callback) { - if('function' === typeof options) callback = options, options = null; - if(options == null) options = {}; - if(!('function' === typeof callback)) callback = null; - - // If we are not providing a selector or document throw - if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object")); - if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object")); - - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - - // Do we return the actual result document - // Either use override on the function, or go back to default on either the collection - // level or db - finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions; - - // Execute the operation - var op = {q: selector, u: document}; - if(options.upsert) op.upsert = true; - if(options.multi) op.multi = true; - - // Update options - self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - if(result == null) return handleCallback(callback, null, null); - if(result.result.code) return handleCallback(callback, toError(result.result)); - if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -/** - * Updates documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} document The update document. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.upsert=false] Update operation is an upsert. - * @param {boolean} [options.multi=false] Update one/all documents with operation. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - * @deprecated use updateOne, updateMany or bulkWrite - */ -Collection.prototype.update = function(selector, document, options, callback) { - var self = this; - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - updateDocuments(self, selector, document, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('update', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~deleteWriteOpResult - * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version. - * @property {Number} result.ok Is 1 if the command executed correctly. - * @property {Number} result.n The total count of documents deleted. - * @property {Object} connection The connection object used for the operation. - * @property {Number} deletedCount The number of documents deleted. - */ - -/** - * The callback format for inserts - * @callback Collection~deleteWriteOpCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Delete a document on MongoDB - * @method - * @param {object} filter The Filter used to select the document to remove - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteOne = function(filter, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - var options = shallowClone(options); - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return deleteOne(self, filter, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - deleteOne(self, filter, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var deleteOne = function(self, filter, options, callback) { - options.single = true; - removeDocuments(self, filter, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.deletedCount = r.result.n; - if(callback) callback(null, r); - }); -} - -define.classMethod('deleteOne', {callback: true, promise:true}); - -Collection.prototype.removeOne = Collection.prototype.deleteOne; - -define.classMethod('removeOne', {callback: true, promise:true}); - -/** - * Delete multiple documents on MongoDB - * @method - * @param {object} filter The Filter used to select the documents to remove - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~deleteWriteOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.deleteMany = function(filter, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - var options = shallowClone(options); - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return deleteMany(self, filter, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - deleteMany(self, filter, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var deleteMany = function(self, filter, options, callback) { - options.single = false; - removeDocuments(self, filter, options, function(err, r) { - if(callback == null) return; - if(err && callback) return callback(err); - if(r == null) return callback(null, {result: {ok:1}}); - r.deletedCount = r.result.n; - if(callback) callback(null, r); - }); -} - -var removeDocuments = function(self, selector, options, callback) { - if(typeof options == 'function') { - callback = options, options = {}; - } else if (typeof selector === 'function') { - callback = selector; - options = {}; - selector = {}; - } - - // Create an empty options object if the provided one is null - options = options || {}; - - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - - // If selector is null set empty - if(selector == null) selector = {}; - - // Build the op - var op = {q: selector, limit: 0}; - if(options.single) op.limit = 1; - - // Execute the remove - self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - if(result == null) return handleCallback(callback, null, null); - if(result.result.code) return handleCallback(callback, toError(result.result)); - if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0])); - // Return the results - handleCallback(callback, null, result); - }); -} - -define.classMethod('deleteMany', {callback: true, promise:true}); - -Collection.prototype.removeMany = Collection.prototype.deleteMany; - -define.classMethod('removeMany', {callback: true, promise:true}); - -/** - * Remove documents. - * @method - * @param {object} selector The selector for the update operation. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.single=false] Removes the first document found. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use deleteOne, deleteMany or bulkWrite - */ -Collection.prototype.remove = function(selector, options, callback) { - var self = this; - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return removeDocuments(self, selector, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - removeDocuments(self, selector, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('remove', {callback: true, promise:true}); - -/** - * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic - * operators and update instead for more efficient operations. - * @method - * @param {object} doc Document to save - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~writeOpCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use insertOne, insertMany, updateOne or updateMany - */ -Collection.prototype.save = function(doc, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Add ignoreUndfined - if(this.s.options.ignoreUndefined) { - options = shallowClone(options); - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute using callback - if(typeof callback == 'function') return save(self, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - save(self, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var save = function(self, doc, options, callback) { - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options); - // Establish if we need to perform an insert or update - if(doc._id != null) { - finalOptions.upsert = true; - return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback); - } - - // Insert the document - insertDocuments(self, [doc], options, function(err, r) { - if(callback == null) return; - if(doc == null) return handleCallback(callback, null, null); - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, r); - }); -} - -define.classMethod('save', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Collection~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -/** - * Fetches the first document that matches the query - * @method - * @param {object} query Query for find Operation - * @param {object} [options=null] Optional settings. - * @param {number} [options.limit=0] Sets the limit of documents returned in the query. - * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. - * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} - * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). - * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} - * @param {boolean} [options.explain=false] Explain the query instead of returning the data. - * @param {boolean} [options.snapshot=false] Snapshot query. - * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. - * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. - * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {boolean} [options.returnKey=false] Only return the index key. - * @param {number} [options.maxScan=null] Limit the number of items to scan. - * @param {number} [options.min=null] Set index bounds. - * @param {number} [options.max=null] Set index bounds. - * @param {boolean} [options.showDiskLoc=false] Show disk location of results. - * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler. - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system - * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use find().limit(1).next(function(err, doc){}) - */ -Collection.prototype.findOne = function() { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - var callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - - // Execute using callback - if(typeof callback == 'function') return findOne(self, args, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - findOne(self, args, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOne = function(self, args, callback) { - var cursor = self.find.apply(self, args).limit(-1).batchSize(1); - // Return the item - cursor.next(function(err, item) { - if(err != null) return handleCallback(callback, toError(err), null); - handleCallback(callback, null, item); - }); -} - -define.classMethod('findOne', {callback: true, promise:true}); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Collection~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Rename the collection. - * - * @method - * @param {string} newName New name of of the collection. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {Collection~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.rename = function(newName, opt, callback) { - var self = this; - if(typeof opt == 'function') callback = opt, opt = {}; - opt = opt || {}; - - // Execute using callback - if(typeof callback == 'function') return rename(self, newName, opt, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - rename(self, newName, opt, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var rename = function(self, newName, opt, callback) { - // Check the collection name - checkCollectionName(newName); - // Build the command - var renameCollection = f("%s.%s", self.s.dbName, self.s.name); - var toCollection = f("%s.%s", self.s.dbName, newName); - var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false; - var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget}; - - // Execute against admin - self.s.db.admin().command(cmd, opt, function(err, doc) { - if(err) return handleCallback(callback, err, null); - // We have an error - if(doc.errmsg) return handleCallback(callback, toError(doc), null); - try { - return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options)); - } catch(err) { - return handleCallback(callback, toError(err), null); - } - }); -} - -define.classMethod('rename', {callback: true, promise:true}); - -/** - * Drop the collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.drop = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, callback); - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.s.db.dropCollection(self.s.name, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('drop', {callback: true, promise:true}); - -/** - * Returns the options of the collection. - * - * @method - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.options = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return options(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var options = function(self, callback) { - self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) { - if(err) return handleCallback(callback, err); - if(collections.length == 0) { - return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true })); - } - - handleCallback(callback, err, collections[0].options || null); - }); -} - -define.classMethod('options', {callback: true, promise:true}); - -/** - * Returns if the collection is a capped collection - * - * @method - * @param {Collection~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.isCapped = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return isCapped(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - isCapped(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var isCapped = function(self, callback) { - self.options(function(err, document) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, document && document.capped); - }); -} - -define.classMethod('isCapped', {callback: true, promise:true}); - -/** - * Creates an index on the db and collection collection. - * @method - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.createIndex = function(fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - - // Execute using callback - if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - createIndex(self, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var createIndex = function(self, fieldOrSpec, options, callback) { - self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback); -} - -define.classMethod('createIndex', {callback: true, promise:true}); - -/** - * Creates multiple indexes in the collection, this method is only supported for - * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported - * error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/. - * @method - * @param {array} indexSpecs An array of index specifications to be created - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.createIndexes = function(indexSpecs, callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - createIndexes(self, indexSpecs, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var createIndexes = function(self, indexSpecs, callback) { - // Ensure we generate the correct name if the parameter is not set - for(var i = 0; i < indexSpecs.length; i++) { - if(indexSpecs[i].name == null) { - var keys = []; - - for(var name in indexSpecs[i].key) { - keys.push(f('%s_%s', name, indexSpecs[i].key[name])); - } - - // Set the name - indexSpecs[i].name = keys.join('_'); - } - } - - // Execute the index - self.s.db.command({ - createIndexes: self.s.name, indexes: indexSpecs - }, callback); -} - -define.classMethod('createIndexes', {callback: true, promise:true}); - -/** - * Drops an index from this collection. - * @method - * @param {string} indexName Name of the index to drop. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndex = function(indexName, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - // Execute using callback - if(typeof callback == 'function') return dropIndex(self, indexName, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - dropIndex(self, indexName, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var dropIndex = function(self, indexName, options, callback) { - // Delete index command - var cmd = {'deleteIndexes':self.s.name, 'index':indexName}; - - // Execute command - self.s.db.command(cmd, options, function(err, result) { - if(typeof callback != 'function') return; - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result); - }); -} - -define.classMethod('dropIndex', {callback: true, promise:true}); - -/** - * Drops all indexes from this collection. - * @method - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.dropIndexes = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return dropIndexes(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - dropIndexes(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var dropIndexes = function(self, callback) { - self.dropIndex('*', function (err, result) { - if(err) return handleCallback(callback, err, false); - handleCallback(callback, null, true); - }); -} - -define.classMethod('dropIndexes', {callback: true, promise:true}); - -/** - * Drops all indexes from this collection. - * @method - * @deprecated use dropIndexes - * @param {Collection~resultCallback} callback The command result callback - * @return {Promise} returns Promise if no [callback] passed - */ -Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes; - -define.classMethod('dropAllIndexes', {callback: true, promise:true}); - -/** - * Reindex all indexes on the collection - * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections. - * @method - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.reIndex = function(options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return reIndex(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - reIndex(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var reIndex = function(self, options, callback) { - // Reindex - var cmd = {'reIndex':self.s.name}; - - // Execute the command - self.s.db.command(cmd, options, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); -} - -define.classMethod('reIndex', {callback: true, promise:true}); - -/** - * Get the list of all indexes information for the collection. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @return {CommandCursor} - */ -Collection.prototype.listIndexes = function(options) { - options = options || {}; - // Clone the options - options = shallowClone(options); - // Set the CommandCursor constructor - options.cursorFactory = CommandCursor; - // Set the promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // We have a list collections command - if(this.s.db.serverConfig.capabilities().hasListIndexesCommand) { - // Cursor options - var cursor = options.batchSize ? {batchSize: options.batchSize} : {} - // Build the command - var command = { listIndexes: this.s.name, cursor: cursor }; - // Execute the cursor - return this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options); - } - - // Get the namespace - var ns = f('%s.system.indexes', this.s.dbName); - // Get the query - return this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options); -}; - -define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]}); - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated use createIndexes instead - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - ensureIndex(self, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var ensureIndex = function(self, fieldOrSpec, options, callback) { - self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback); -} - -define.classMethod('ensureIndex', {callback: true, promise:true}); - -/** - * Checks if one or more indexes exist on the collection, fails on first non-existing index - * @method - * @param {(string|array)} indexes One or more index names to check. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexExists = function(indexes, callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') return indexExists(self, indexes, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexExists(self, indexes, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var indexExists = function(self, indexes, callback) { - self.indexInformation(function(err, indexInformation) { - // If we have an error return - if(err != null) return handleCallback(callback, err, null); - // Let's check for the index names - if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null); - // Check in list of indexes - for(var i = 0; i < indexes.length; i++) { - if(indexInformation[indexes[i]] == null) { - return handleCallback(callback, null, false); - } - } - - // All keys found return true - return handleCallback(callback, null, true); - }); -} - -define.classMethod('indexExists', {callback: true, promise:true}); - -/** - * Retrieves this collections index info. - * @method - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexInformation = function(options, callback) { - var self = this; - // Unpack calls - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return indexInformation(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexInformation(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var indexInformation = function(self, options, callback) { - self.s.db.indexInformation(self.s.name, options, callback); -} - -define.classMethod('indexInformation', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Collection~countCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} result The count of documents that matched the query. - */ - -/** - * Count number of matching documents in the db to a query. - * @method - * @param {object} query The query for the count. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.limit=null] The limit of documents to count. - * @param {boolean} [options.skip=null] The number of documents to skip for the count. - * @param {string} [options.hint=null] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Collection~countCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.count = function(query, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - var queryOption = args.length ? args.shift() || {} : {}; - var optionsOption = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback); - - // Check if query is empty - query = query || {}; - options = options || {}; - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - count(self, query, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var count = function(self, query, options, callback) { - var skip = options.skip; - var limit = options.limit; - var hint = options.hint; - var maxTimeMS = options.maxTimeMS; - - // Final query - var cmd = { - 'count': self.s.name, 'query': query - , 'fields': null - }; - - // Add limit and skip if defined - if(typeof skip == 'number') cmd.skip = skip; - if(typeof limit == 'number') cmd.limit = limit; - if(hint) options.hint = hint; - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - cmd.readConcern = self.s.readConcern; - } - - // Execute command - self.s.db.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.n); - }); -} - -define.classMethod('count', {callback: true, promise:true}); - -/** - * The distinct command returns returns a list of distinct values for the given key across a collection. - * @method - * @param {string} key Field of the document to find distinct values for. - * @param {object} query The query for filtering the set of documents to which we apply the distinct filter. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.distinct = function(key, query, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - var queryOption = args.length ? args.shift() || {} : {}; - var optionsOption = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback); - - // Ensure the query and options are set - query = query || {}; - options = options || {}; - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - distinct(self, key, query, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var distinct = function(self, key, query, options, callback) { - // maxTimeMS option - var maxTimeMS = options.maxTimeMS; - - // Distinct command - var cmd = { - 'distinct': self.s.name, 'key': key, 'query': query - }; - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - cmd.readConcern = self.s.readConcern; - } - - // Execute the command - self.s.db.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.values); - }); -} - -define.classMethod('distinct', {callback: true, promise:true}); - -/** - * Retrieve all the indexes on the collection. - * @method - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.indexes = function(callback) { - var self = this; - // Execute using callback - if(typeof callback == 'function') return indexes(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexes(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var indexes = function(self, callback) { - self.s.db.indexInformation(self.s.name, {full:true}, callback); -} - -define.classMethod('indexes', {callback: true, promise:true}); - -/** - * Get all the collection statistics. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {number} [options.scale=null] Divide the returned sizes by scale value. - * @param {Collection~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.stats = function(options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return stats(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - stats(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var stats = function(self, options, callback) { - // Build command object - var commandObject = { - collStats:self.s.name - } - - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Execute the command - self.s.db.command(commandObject, options, callback); -} - -define.classMethod('stats', {callback: true, promise:true}); - -/** - * @typedef {Object} Collection~findAndModifyWriteOpResult - * @property {object} value Document returned from findAndModify command. - * @property {object} lastErrorObject The raw lastErrorObject returned from the command. - * @property {Number} ok Is 1 if the command executed correctly. - */ - -/** - * The callback format for inserts - * @callback Collection~findAndModifyCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully. - */ - -/** - * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter Document selection filter. - * @param {object} [options=null] Optional settings. - * @param {object} [options.projection=null] Limits the fields to return for all matching documents. - * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndDelete = function(filter, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findOneAndDelete(self, filter, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOneAndDelete = function(self, filter, options, callback) { - // Final options - var finalOptions = shallowClone(options); - finalOptions['fields'] = options.projection; - finalOptions['remove'] = true; - // Execute find and Modify - self.findAndModify( - filter - , options.sort - , null - , finalOptions - , callback - ); -} - -define.classMethod('findOneAndDelete', {callback: true, promise:true}); - -/** - * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter Document selection filter. - * @param {object} replacement Document replacing the matching document. - * @param {object} [options=null] Optional settings. - * @param {object} [options.projection=null] Limits the fields to return for all matching documents. - * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findOneAndReplace(self, filter, replacement, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOneAndReplace = function(self, filter, replacement, options, callback) { - // Final options - var finalOptions = shallowClone(options); - finalOptions['fields'] = options.projection; - finalOptions['update'] = true; - finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; - finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Execute findAndModify - self.findAndModify( - filter - , options.sort - , replacement - , finalOptions - , callback - ); -} - -define.classMethod('findOneAndReplace', {callback: true, promise:true}); - -/** - * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation. - * - * @method - * @param {object} filter Document selection filter. - * @param {object} update Update operations to be performed on the document - * @param {object} [options=null] Optional settings. - * @param {object} [options.projection=null] Limits the fields to return for all matching documents. - * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents. - * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run. - * @param {boolean} [options.upsert=false] Upsert the document if it does not exist. - * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true. - * @param {Collection~findAndModifyCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // Execute using callback - if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findOneAndUpdate(self, filter, update, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findOneAndUpdate = function(self, filter, update, options, callback) { - // Final options - var finalOptions = shallowClone(options); - finalOptions['fields'] = options.projection; - finalOptions['update'] = true; - finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false; - finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false; - - // Execute findAndModify - self.findAndModify( - filter - , options.sort - , update - , finalOptions - , callback - ); -} - -define.classMethod('findOneAndUpdate', {callback: true, promise:true}); - -/** - * Find and update a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} doc The fields/vals to be updated. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.remove=false] Set to true to remove the object before returning. - * @param {boolean} [options.upsert=false] Perform an upsert operation. - * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove. - * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead - */ -Collection.prototype.findAndModify = function(query, sort, doc, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - sort = args.length ? args.shift() || [] : []; - doc = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Clone options - var options = shallowClone(options); - // Force read preference primary - options.readPreference = ReadPreference.PRIMARY; - - // Execute using callback - if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - options = options || {}; - - findAndModify(self, query, sort, doc, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findAndModify = function(self, query, sort, doc, options, callback) { - // Create findAndModify command object - var queryObject = { - 'findandmodify': self.s.name - , 'query': query - }; - - sort = formattedOrderClause(sort); - if(sort) { - queryObject.sort = sort; - } - - queryObject.new = options.new ? true : false; - queryObject.remove = options.remove ? true : false; - queryObject.upsert = options.upsert ? true : false; - - if(options.fields) { - queryObject.fields = options.fields; - } - - if(doc && !options.remove) { - queryObject.update = doc; - } - - // Either use override on the function, or go back to default on either the collection - // level or db - if(options['serializeFunctions'] != null) { - options['serializeFunctions'] = options['serializeFunctions']; - } else { - options['serializeFunctions'] = self.s.serializeFunctions; - } - - // No check on the documents - options.checkKeys = false; - - // Get the write concern settings - var finalOptions = writeConcern(options, self.s.db, self, options); - - // Decorate the findAndModify command with the write Concern - if(finalOptions.writeConcern) { - queryObject.writeConcern = finalOptions.writeConcern; - } - - // Have we specified bypassDocumentValidation - if(typeof finalOptions.bypassDocumentValidation == 'boolean') { - queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation; - } - - // Execute the command - self.s.db.command(queryObject - , options, function(err, result) { - if(err) return handleCallback(callback, err, null); - return handleCallback(callback, null, result); - }); -} - -define.classMethod('findAndModify', {callback: true, promise:true}); - -/** - * Find and remove a document. - * @method - * @param {object} query Query object to locate the object to modify. - * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - * @deprecated use findOneAndDelete instead - */ -Collection.prototype.findAndRemove = function(query, sort, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - sort = args.length ? args.shift() || [] : []; - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - findAndRemove(self, query, sort, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var findAndRemove = function(self, query, sort, options, callback) { - // Add the remove option - options['remove'] = true; - // Execute the callback - self.findAndModify(query, sort, null, options, callback); -} - -define.classMethod('findAndRemove', {callback: true, promise:true}); - -/** - * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2 - * @method - * @param {object} pipeline Array containing all the aggregation framework commands for the execution. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor. - * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor - * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >). - * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >). - * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~resultCallback} callback The command result callback - * @return {(null|AggregationCursor)} - */ -Collection.prototype.aggregate = function(pipeline, options, callback) { - var self = this; - if(Array.isArray(pipeline)) { - // Set up callback if one is provided - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // If we have no options or callback we are doing - // a cursor based aggregation - if(options == null && callback == null) { - options = {}; - } - } else { - // Aggregation pipeline passed as arguments on the method - var args = Array.prototype.slice.call(arguments, 0); - // Get the callback - callback = args.pop(); - // Get the possible options object - var opts = args[args.length - 1]; - // If it contains any of the admissible options pop it of the args - options = opts && (opts.readPreference - || opts.explain || opts.cursor || opts.out - || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {}; - // Left over arguments is the pipeline - pipeline = args; - } - - // If out was specified - if(typeof options.out == 'string') { - pipeline.push({$out: options.out}); - } - - // Build the command - var command = { aggregate : this.s.name, pipeline : pipeline}; - - // If we have bypassDocumentValidation set - if(typeof options.bypassDocumentValidation == 'boolean') { - command.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Do we have a readConcern specified - if(this.s.readConcern) { - command.readConcern = this.s.readConcern; - } - - // If we have allowDiskUse defined - if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse; - if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; - - // Ensure we have the right read preference inheritance - options = getReadPreference(this, options, this.s.db, this); - - // If explain has been specified add it - if(options.explain) command.explain = options.explain; - - // Validate that cursor options is valid - if(options.cursor != null && typeof options.cursor != 'object') { - throw toError('cursor options must be an object'); - } - - // promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // Set the AggregationCursor constructor - options.cursorFactory = AggregationCursor; - if(typeof callback != 'function') { - if(this.s.topology.capabilities().hasAggregationCursor) { - options.cursor = options.cursor || { batchSize : 1000 }; - command.cursor = options.cursor; - } - - // Allow disk usage command - if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse; - if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS; - - // Execute the cursor - return this.s.topology.cursor(this.s.namespace, command, options); - } - - var cursor = null; - // We do not allow cursor - if(options.cursor) { - return this.s.topology.cursor(this.s.namespace, command, options); - } - - // Execute the command - this.s.db.command(command, options, function(err, result) { - if(err) { - handleCallback(callback, err); - } else if(result['err'] || result['errmsg']) { - handleCallback(callback, toError(result)); - } else if(typeof result == 'object' && result['serverPipeline']) { - handleCallback(callback, null, result['serverPipeline']); - } else if(typeof result == 'object' && result['stages']) { - handleCallback(callback, null, result['stages']); - } else { - handleCallback(callback, null, result.result); - } - }); -} - -define.classMethod('aggregate', {callback: true, promise:false}); - -/** - * The callback format for results - * @callback Collection~parallelCollectionScanCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection. - */ - -/** - * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are - * no ordering guarantees for returned results. - * @method - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results. - * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors) - * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents. - * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.parallelCollectionScan = function(options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {numCursors: 1}; - // Set number of cursors to 1 - options.numCursors = options.numCursors || 1; - options.batchSize = options.batchSize || 1000; - - // Ensure we have the right read preference inheritance - options = getReadPreference(this, options, this.s.db, this); - - // Add a promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // Execute using callback - if(typeof callback == 'function') return parallelCollectionScan(self, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - parallelCollectionScan(self, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var parallelCollectionScan = function(self, options, callback) { - // Create command object - var commandObject = { - parallelCollectionScan: self.s.name - , numCursors: options.numCursors - } - - // Do we have a readConcern specified - if(self.s.readConcern) { - commandObject.readConcern = self.s.readConcern; - } - - // Execute the command - self.s.db.command(commandObject, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null); - - var cursors = []; - // Create command cursors for each item - for(var i = 0; i < result.cursors.length; i++) { - var rawId = result.cursors[i].cursor.id - // Convert cursorId to Long if needed - var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId; - - // Command cursor options - var cmd = { - batchSize: options.batchSize - , cursorId: cursorId - , items: result.cursors[i].cursor.firstBatch - } - - // Add a command cursor - cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options)); - } - - handleCallback(callback, null, cursors); - }); -} - -define.classMethod('parallelCollectionScan', {callback: true, promise:true}); - -/** - * Execute the geoNear command to search for items in the collection - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.num=null] Max number of results to return. - * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher) - * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. - * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions. - * @param {object} [options.query=null] Filter the results by a query. - * @param {boolean} [options.spherical=false] Perform query using a spherical model. - * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X. - * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoNear = function(x, y, options, callback) { - var self = this; - var point = typeof(x) == 'object' && x - , args = Array.prototype.slice.call(arguments, point?1:2); - - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - geoNear(self, x, y, point, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var geoNear = function(self, x, y, point, options, callback) { - // Build command object - var commandObject = { - geoNear:self.s.name, - near: point || [x, y] - } - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Exclude readPreference and existing options to prevent user from - // shooting themselves in the foot - var exclude = { - readPreference: true, - geoNear: true, - near: true - }; - - // Filter out any excluded objects - commandObject = decorateCommand(commandObject, options, exclude); - - // Do we have a readConcern specified - if(self.s.readConcern) { - commandObject.readConcern = self.s.readConcern; - } - - // Execute the command - self.s.db.command(commandObject, options, function (err, res) { - if(err) return handleCallback(callback, err); - if(res.err || res.errmsg) return handleCallback(callback, toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); -} - -define.classMethod('geoNear', {callback: true, promise:true}); - -/** - * Execute a geo search using a geo haystack index on a collection. - * - * @method - * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order. - * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point. - * @param {object} [options.search=null] Filter the results by a query. - * @param {number} [options.limit=false] Max number of results to return. - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.geoHaystackSearch = function(x, y, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - options = args.length ? args.shift() || {} : {}; - - // Execute using callback - if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - geoHaystackSearch(self, x, y, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var geoHaystackSearch = function(self, x, y, options, callback) { - // Build command object - var commandObject = { - geoSearch: self.s.name, - near: [x, y] - } - - // Remove read preference from hash if it exists - commandObject = decorateCommand(commandObject, options, {readPreference: true}); - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - commandObject.readConcern = self.s.readConcern; - } - - // Execute the command - self.s.db.command(commandObject, options, function (err, res) { - if(err) return handleCallback(callback, err); - if(res.err || res.errmsg) handleCallback(callback, utils.toError(res)); - // should we only be returning res.results here? Not sure if the user - // should see the other return information - handleCallback(callback, null, res); - }); -} - -define.classMethod('geoHaystackSearch', {callback: true, promise:true}); - -/** - * Group function helper - * @ignore - */ -var groupFunction = function () { - var c = db[ns].find(condition); - var map = new Map(); - var reduce_function = reduce; - - while (c.hasNext()) { - var obj = c.next(); - var key = {}; - - for (var i = 0, len = keys.length; i < len; ++i) { - var k = keys[i]; - key[k] = obj[k]; - } - - var aggObj = map.get(key); - - if (aggObj == null) { - var newObj = Object.extend({}, key); - aggObj = Object.extend(newObj, initial); - map.put(key, aggObj); - } - - reduce_function(obj, aggObj); - } - - return { "result": map.values() }; -}.toString(); - -/** - * Run a group command across a collection - * - * @method - * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by. - * @param {object} condition An optional condition that must be true for a row to be considered. - * @param {object} initial Initial value of the aggregation counter object. - * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated - * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned. - * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Collection~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 3); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - // Fetch all commands - reduce = args.length ? args.shift() : null; - finalize = args.length ? args.shift() : null; - command = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Make sure we are backward compatible - if(!(typeof finalize == 'function')) { - command = finalize; - finalize = null; - } - - if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys instanceof Code)) { - keys = Object.keys(keys); - } - - if(typeof reduce === 'function') { - reduce = reduce.toString(); - } - - if(typeof finalize === 'function') { - finalize = finalize.toString(); - } - - // Set up the command as default - command = command == null ? true : command; - - // Execute using callback - if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) { - // Execute using the command - if(command) { - var reduceFunction = reduce instanceof Code - ? reduce - : new Code(reduce); - - var selector = { - group: { - 'ns': self.s.name - , '$reduce': reduceFunction - , 'cond': condition - , 'initial': initial - , 'out': "inline" - } - }; - - // if finalize is defined - if(finalize != null) selector.group['finalize'] = finalize; - // Set up group selector - if ('function' === typeof keys || keys instanceof Code) { - selector.group.$keyf = keys instanceof Code - ? keys - : new Code(keys); - } else { - var hash = {}; - keys.forEach(function (key) { - hash[key] = 1; - }); - selector.group.key = hash; - } - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // Do we have a readConcern specified - if(self.s.readConcern) { - selector.readConcern = self.s.readConcern; - } - - // Execute command - self.s.db.command(selector, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.retval); - }); - } else { - // Create execution scope - var scope = reduce != null && reduce instanceof Code - ? reduce.scope - : {}; - - scope.ns = self.s.name; - scope.keys = keys; - scope.condition = condition; - scope.initial = initial; - - // Pass in the function text to execute within mongodb. - var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';'); - - self.s.db.eval(new Code(groupfn, scope), function (err, results) { - if (err) return handleCallback(callback, err, null); - handleCallback(callback, null, results.result || results); - }); - } -} - -define.classMethod('group', {callback: true, promise:true}); - -/** - * Functions that are passed as scope args must - * be converted to Code instances. - * @ignore - */ -function processScope (scope) { - if(!isObject(scope)) { - return scope; - } - - var keys = Object.keys(scope); - var i = keys.length; - var key; - var new_scope = {}; - - while (i--) { - key = keys[i]; - if ('function' == typeof scope[key]) { - new_scope[key] = new Code(String(scope[key])); - } else { - new_scope[key] = processScope(scope[key]); - } - } - - return new_scope; -} - -/** - * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection. - * - * @method - * @param {(function|string)} map The mapping function. - * @param {(function|string)} reduce The reduce function. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}* - * @param {object} [options.query=null] Query filter object. - * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces. - * @param {number} [options.limit=null] Number of objects to return from collection. - * @param {boolean} [options.keeptemp=false] Keep temporary data. - * @param {(function|string)} [options.finalize=null] Finalize function. - * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize. - * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X. - * @param {boolean} [options.verbose=false] Provide statistics on job execution time. - * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. - * @param {Collection~resultCallback} [callback] The command result callback - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Collection.prototype.mapReduce = function(map, reduce, options, callback) { - var self = this; - if('function' === typeof options) callback = options, options = {}; - // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) - if(null == options.out) { - throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); - } - - if('function' === typeof map) { - map = map.toString(); - } - - if('function' === typeof reduce) { - reduce = reduce.toString(); - } - - if('function' === typeof options.finalize) { - options.finalize = options.finalize.toString(); - } - - // Execute using callback - if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - mapReduce(self, map, reduce, options, function(err, r, r1) { - if(err) return reject(err); - if(r instanceof Collection) return resolve(r); - resolve({results: r, stats: r1}); - }); - }); -} - -var mapReduce = function(self, map, reduce, options, callback) { - var mapCommandHash = { - mapreduce: self.s.name - , map: map - , reduce: reduce - }; - - // Add any other options passed in - for(var n in options) { - if('scope' == n) { - mapCommandHash[n] = processScope(options[n]); - } else { - mapCommandHash[n] = options[n]; - } - } - - // Ensure we have the right read preference inheritance - options = getReadPreference(self, options, self.s.db, self); - - // If we have a read preference and inline is not set as output fail hard - if((options.readPreference != false && options.readPreference != 'primary') - && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) { - options.readPreference = 'primary'; - } - - // Is bypassDocumentValidation specified - if(typeof options.bypassDocumentValidation == 'boolean') { - mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Do we have a readConcern specified - if(self.s.readConcern) { - mapCommandHash.readConcern = self.s.readConcern; - } - - // Execute command - self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) { - if(err) return handleCallback(callback, err); - // Check if we have an error - if(1 != result.ok || result.err || result.errmsg) { - return handleCallback(callback, toError(result)); - } - - // Create statistics value - var stats = {}; - if(result.timeMillis) stats['processtime'] = result.timeMillis; - if(result.counts) stats['counts'] = result.counts; - if(result.timing) stats['timing'] = result.timing; - - // invoked with inline? - if(result.results) { - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, null, result.results); - } - - return handleCallback(callback, null, result.results, stats); - } - - // The returned collection - var collection = null; - - // If we have an object it's a different db - if(result.result != null && typeof result.result == 'object') { - var doc = result.result; - collection = self.s.db.db(doc.db).collection(doc.collection); - } else { - // Create a collection object that wraps the result collection - collection = self.s.db.collection(result.result) - } - - // If we wish for no verbosity - if(options['verbose'] == null || !options['verbose']) { - return handleCallback(callback, err, collection); - } - - // Return stats as third set of values - handleCallback(callback, err, collection, stats); - }); -} - -define.classMethod('mapReduce', {callback: true, promise:true}); - -/** - * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @return {UnorderedBulkOperation} - */ -Collection.prototype.initializeUnorderedBulkOp = function(options) { - options = options || {}; - options.promiseLibrary = this.s.promiseLibrary; - return unordered(this.s.topology, this, options); -} - -define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]}); - -/** - * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {OrderedBulkOperation} callback The command result callback - * @return {null} - */ -Collection.prototype.initializeOrderedBulkOp = function(options) { - options = options || {}; - options.promiseLibrary = this.s.promiseLibrary; - return ordered(this.s.topology, this, options); -} - -define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]}); - -// Get write concern -var writeConcern = function(target, db, col, options) { - if(options.w != null || options.j != null || options.fsync != null) { - var opts = {}; - if(options.w != null) opts.w = options.w; - if(options.wtimeout != null) opts.wtimeout = options.wtimeout; - if(options.j != null) opts.j = options.j; - if(options.fsync != null) opts.fsync = options.fsync; - target.writeConcern = opts; - } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) { - target.writeConcern = col.writeConcern; - } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { - target.writeConcern = db.writeConcern; - } - - return target -} - -// Figure out the read preference -var getReadPreference = function(self, options, db, coll) { - var r = null - if(options.readPreference) { - r = options.readPreference - } else if(self.s.readPreference) { - r = self.s.readPreference - } else if(db.readPreference) { - r = db.readPreference; - } - - if(r instanceof ReadPreference) { - options.readPreference = new CoreReadPreference(r.mode, r.tags); - } else if(typeof r == 'string') { - options.readPreference = new CoreReadPreference(r); - } - - return options; -} - -var testForFields = { - limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1 - , numberOfRetries: 1, awaitdata: 1, awaitData: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1 - , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms: 1 -} - -module.exports = Collection; diff --git a/util/retroImporter/node_modules/mongodb/lib/command_cursor.js b/util/retroImporter/node_modules/mongodb/lib/command_cursor.js deleted file mode 100644 index 37df593..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/command_cursor.js +++ /dev/null @@ -1,296 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , toError = require('./utils').toError - , getSingleProperty = require('./utils').getSingleProperty - , formattedOrderClause = require('./utils').formattedOrderClause - , handleCallback = require('./utils').handleCallback - , Logger = require('mongodb-core').Logger - , EventEmitter = require('events').EventEmitter - , ReadPreference = require('./read_preference') - , MongoError = require('mongodb-core').MongoError - , Readable = require('stream').Readable || require('readable-stream').Readable - , Define = require('./metadata') - , CoreCursor = require('./cursor') - , Query = require('mongodb-core').Query - , CoreReadPreference = require('mongodb-core').ReadPreference; - -/** - * @fileOverview The **CommandCursor** class is an internal class that embodies a - * generalized cursor based on a MongoDB command allowing for iteration over the - * results returned. It supports one by one document iteration, conversion to an - * array or can be iterated as a Node 0.10.X or higher stream - * - * **CommandCursor Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('listCollectionsExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * - * // List the database collections available - * db.listCollections().toArray(function(err, items) { - * test.equal(null, err); - * db.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the browser. - * @external Readable - */ - -/** - * Creates a new Command Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class CommandCursor - * @extends external:Readable - * @fires CommandCursor#data - * @fires CommandCursor#end - * @fires CommandCursor#close - * @fires CommandCursor#readable - * @return {CommandCursor} an CommandCursor instance. - */ -var CommandCursor = function(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - var self = this; - var state = CommandCursor.INIT; - var streamOptions = {}; - - // MaxTimeMS - var maxTimeMS = null; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set up - Readable.call(this, {objectMode: true}); - - // Internal state - this.s = { - // MaxTimeMS - maxTimeMS: maxTimeMS - // State - , state: state - // Stream options - , streamOptions: streamOptions - // BSON - , bson: bson - // Namespae - , ns: ns - // Command - , cmd: cmd - // Options - , options: options - // Topology - , topology: topology - // Topology Options - , topologyOptions: topologyOptions - // Promise library - , promiseLibrary: promiseLibrary - } -} - -/** - * CommandCursor stream data event, fired for each document in the cursor. - * - * @event CommandCursor#data - * @type {object} - */ - -/** - * CommandCursor stream end event - * - * @event CommandCursor#end - * @type {null} - */ - -/** - * CommandCursor stream close event - * - * @event CommandCursor#close - * @type {null} - */ - -/** - * CommandCursor stream readable event - * - * @event CommandCursor#readable - * @type {null} - */ - -// Inherit from Readable -inherits(CommandCursor, Readable); - -// Set the methods to inherit from prototype -var methodsToInherit = ['_next', 'next', 'each', 'forEach', 'toArray' - , 'rewind', 'bufferedCount', 'readBufferedDocuments', 'close', 'isClosed', 'kill' - , '_find', '_getmore', '_killcursor', 'isDead', 'explain', 'isNotified', 'isKilled']; - -// Only inherit the types we need -for(var i = 0; i < methodsToInherit.length; i++) { - CommandCursor.prototype[methodsToInherit[i]] = CoreCursor.prototype[methodsToInherit[i]]; -} - -var define = CommandCursor.define = new Define('CommandCursor', CommandCursor, true); - -/** - * Set the batch size for the cursor. - * @method - * @param {number} value The batchSize for the cursor. - * @throws {MongoError} - * @return {CommandCursor} - */ -CommandCursor.prototype.batchSize = function(value) { - if(this.s.state == CommandCursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); - if(this.s.cmd.cursor) this.s.cmd.cursor.batchSize = value; - this.setCursorBatchSize(value); - return this; -} - -define.classMethod('batchSize', {callback: false, promise:false, returns: [CommandCursor]}); - -/** - * Add a maxTimeMS stage to the aggregation pipeline - * @method - * @param {number} value The state maxTimeMS value. - * @return {CommandCursor} - */ -CommandCursor.prototype.maxTimeMS = function(value) { - if(this.s.topology.lastIsMaster().minWireVersion > 2) { - this.s.cmd.maxTimeMS = value; - } - return this; -} - -define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [CommandCursor]}); - -CommandCursor.prototype.get = CommandCursor.prototype.toArray; - -define.classMethod('get', {callback: true, promise:false}); - -// Inherited methods -define.classMethod('toArray', {callback: true, promise:true}); -define.classMethod('each', {callback: true, promise:false}); -define.classMethod('forEach', {callback: true, promise:false}); -define.classMethod('next', {callback: true, promise:true}); -define.classMethod('close', {callback: true, promise:true}); -define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); -define.classMethod('rewind', {callback: false, promise:false}); -define.classMethod('bufferedCount', {callback: false, promise:false, returns: [Number]}); -define.classMethod('readBufferedDocuments', {callback: false, promise:false, returns: [Array]}); - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @function CommandCursor.prototype.next - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. - * @method CommandCursor.prototype.toArray - * @param {CommandCursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ - -/** - * The callback format for results - * @callback CommandCursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null)} result The result object if the command was executed successfully. - */ - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method CommandCursor.prototype.each - * @param {CommandCursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method CommandCursor.prototype.close - * @param {CommandCursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ - -/** - * Is the cursor closed - * @method CommandCursor.prototype.isClosed - * @return {boolean} - */ - -/** - * Clone the cursor - * @function CommandCursor.prototype.clone - * @return {CommandCursor} - */ - -/** - * Resets the cursor - * @function CommandCursor.prototype.rewind - * @return {CommandCursor} - */ - -/** - * The callback format for the forEach iterator method - * @callback CommandCursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback CommandCursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/* - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method CommandCursor.prototype.forEach - * @param {CommandCursor~iteratorCallback} iterator The iteration callback. - * @param {CommandCursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ - -CommandCursor.INIT = 0; -CommandCursor.OPEN = 1; -CommandCursor.CLOSED = 2; - -module.exports = CommandCursor; diff --git a/util/retroImporter/node_modules/mongodb/lib/cursor.js b/util/retroImporter/node_modules/mongodb/lib/cursor.js deleted file mode 100644 index 1a446a8..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/cursor.js +++ /dev/null @@ -1,1149 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , toError = require('./utils').toError - , getSingleProperty = require('./utils').getSingleProperty - , formattedOrderClause = require('./utils').formattedOrderClause - , handleCallback = require('./utils').handleCallback - , Logger = require('mongodb-core').Logger - , EventEmitter = require('events').EventEmitter - , ReadPreference = require('./read_preference') - , MongoError = require('mongodb-core').MongoError - , Readable = require('stream').Readable || require('readable-stream').Readable - , Define = require('./metadata') - , CoreCursor = require('mongodb-core').Cursor - , Query = require('mongodb-core').Query - , CoreReadPreference = require('mongodb-core').ReadPreference; - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. It supports - * one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X - * or higher stream - * - * **CURSORS Cannot directly be instantiated** - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Create a collection we want to drop later - * var col = db.collection('createIndexExample1'); - * // Insert a bunch of documents - * col.insert([{a:1, b:1} - * , {a:2, b:2}, {a:3, b:3} - * , {a:4, b:4}], {w:1}, function(err, result) { - * test.equal(null, err); - * - * // Show that duplicate records got dropped - * col.find({}).toArray(function(err, items) { - * test.equal(null, err); - * test.equal(4, items.length); - * db.close(); - * }); - * }); - * }); - */ - -/** - * Namespace provided by the mongodb-core and node.js - * @external CoreCursor - * @external Readable - */ - -// Flags allowed for cursor -var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']; -var fields = ['numberOfRetries', 'tailableRetryInterval']; - -/** - * Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly) - * @class Cursor - * @extends external:CoreCursor - * @extends external:Readable - * @property {string} sortValue Cursor query sort setting. - * @property {boolean} timeout Is Cursor able to time out. - * @property {ReadPreference} readPreference Get cursor ReadPreference. - * @fires Cursor#data - * @fires Cursor#end - * @fires Cursor#close - * @fires Cursor#readable - * @return {Cursor} a Cursor instance. - * @example - * Cursor cursor options. - * - * collection.find({}).project({a:1}) // Create a projection of field a - * collection.find({}).skip(1).limit(10) // Skip 1 and limit 10 - * collection.find({}).batchSize(5) // Set batchSize on cursor to 5 - * collection.find({}).filter({a:1}) // Set query on the cursor - * collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries - * collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable - * collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay - * collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout - * collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData - * collection.find({}).addCursorFlag('exhaust', true) // Set cursor as exhaust - * collection.find({}).addCursorFlag('partial', true) // Set cursor as partial - * collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1} - * collection.find({}).max(10) // Set the cursor maxScan - * collection.find({}).maxScan(10) // Set the cursor maxScan - * collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS - * collection.find({}).min(100) // Set the cursor min - * collection.find({}).returnKey(10) // Set the cursor returnKey - * collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference - * collection.find({}).showRecordId(true) // Set the cursor showRecordId - * collection.find({}).snapshot(true) // Set the cursor snapshot - * collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query - * collection.find({}).hint('a_1') // Set the cursor hint - * - * All options are chainable, so one can do the following. - * - * collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..) - */ -var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { - CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0)); - var self = this; - var state = Cursor.INIT; - var streamOptions = {}; - - // Tailable cursor options - var numberOfRetries = options.numberOfRetries || 5; - var tailableRetryInterval = options.tailableRetryInterval || 500; - var currentNumberOfRetries = numberOfRetries; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set up - Readable.call(this, {objectMode: true}); - - // Internal cursor state - this.s = { - // Tailable cursor options - numberOfRetries: numberOfRetries - , tailableRetryInterval: tailableRetryInterval - , currentNumberOfRetries: currentNumberOfRetries - // State - , state: state - // Stream options - , streamOptions: streamOptions - // BSON - , bson: bson - // Namespace - , ns: ns - // Command - , cmd: cmd - // Options - , options: options - // Topology - , topology: topology - // Topology options - , topologyOptions: topologyOptions - // Promise library - , promiseLibrary: promiseLibrary - // Current doc - , currentDoc: null - } - - // Legacy fields - this.timeout = self.s.options.noCursorTimeout == true; - this.sortValue = self.s.cmd.sort; - this.readPreference = self.s.options.readPreference; -} - -/** - * Cursor stream data event, fired for each document in the cursor. - * - * @event Cursor#data - * @type {object} - */ - -/** - * Cursor stream end event - * - * @event Cursor#end - * @type {null} - */ - -/** - * Cursor stream close event - * - * @event Cursor#close - * @type {null} - */ - -/** - * Cursor stream readable event - * - * @event Cursor#readable - * @type {null} - */ - -// Inherit from Readable -inherits(Cursor, Readable); - -// Map core cursor _next method so we can apply mapping -CoreCursor.prototype._next = CoreCursor.prototype.next; - -for(var name in CoreCursor.prototype) { - Cursor.prototype[name] = CoreCursor.prototype[name]; -} - -var define = Cursor.define = new Define('Cursor', Cursor, true); - -/** - * Check if there is any document still available in the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.hasNext = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') { - if(self.s.currentDoc){ - return callback(null, true); - } else { - return nextObject(self, function(err, doc) { - if(!doc) return callback(null, false); - self.s.currentDoc = doc; - callback(null, true); - }); - } - } - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - if(self.s.currentDoc){ - resolve(true); - } else { - nextObject(self, function(err, doc) { - if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false); - if(err) return reject(err); - if(!doc) return resolve(false); - self.s.currentDoc = doc; - resolve(true); - }); - } - }); -} - -define.classMethod('hasNext', {callback: true, promise:true}); - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.next = function(callback) { - var self = this; - - // Execute using callback - if(typeof callback == 'function') { - // Return the currentDoc if someone called hasNext first - if(self.s.currentDoc) { - var doc = self.s.currentDoc; - self.s.currentDoc = null; - return callback(null, doc); - } - - // Return the next object - return nextObject(self, callback) - }; - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - // Return the currentDoc if someone called hasNext first - if(self.s.currentDoc) { - var doc = self.s.currentDoc; - self.s.currentDoc = null; - return resolve(doc); - } - - nextObject(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('next', {callback: true, promise:true}); - -/** - * Set the cursor query - * @method - * @param {object} filter The filter object used for the cursor. - * @return {Cursor} - */ -Cursor.prototype.filter = function(filter) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.query = filter; - return this; -} - -define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor maxScan - * @method - * @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query - * @return {Cursor} - */ -Cursor.prototype.maxScan = function(maxScan) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.maxScan = maxScan; - return this; -} - -define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor hint - * @method - * @param {object} hint If specified, then the query system will only consider plans using the hinted index. - * @return {Cursor} - */ -Cursor.prototype.hint = function(hint) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.hint = hint; - return this; -} - -define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor min - * @method - * @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order. - * @return {Cursor} - */ -Cursor.prototype.min = function(min) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.min = min; - return this; -} - -define.classMethod('min', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor max - * @method - * @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order. - * @return {Cursor} - */ -Cursor.prototype.max = function(max) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.max = max; - return this; -} - -define.classMethod('max', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor returnKey - * @method - * @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms: - * @return {Cursor} - */ -Cursor.prototype.returnKey = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.returnKey = value; - return this; -} - -define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor showRecordId - * @method - * @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find. - * @return {Cursor} - */ -Cursor.prototype.showRecordId = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.showDiskLoc = value; - return this; -} - -define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the cursor snapshot - * @method - * @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document. - * @return {Cursor} - */ -Cursor.prototype.snapshot = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.snapshot = value; - return this; -} - -define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set a node.js specific cursor option - * @method - * @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval']. - * @param {object} value The field value. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.setCursorOption = function(field, value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true }); - this.s[field] = value; - if(field == 'numberOfRetries') - this.s.currentNumberOfRetries = value; - return this; -} - -define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Add a cursor flag to the cursor - * @method - * @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial']. - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.addCursorFlag = function(flag, value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true }); - if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true}); - this.s.cmd[flag] = value; - return this; -} - -define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Add a query modifier to the cursor query - * @method - * @param {string} name The query modifier (must start with $, such as $orderby etc) - * @param {boolean} value The flag boolean value. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.addQueryModifier = function(name, value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true}); - // Strip of the $ - var field = name.substr(1); - // Set on the command - this.s.cmd[field] = value; - // Deal with the special case for sort - if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field]; - return this; -} - -define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Add a comment to the cursor query allowing for tracking the comment in the log. - * @method - * @param {string} value The comment attached to this query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.comment = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.comment = value; - return this; -} - -define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher) - * @method - * @param {number} value Number of milliseconds to wait before aborting the query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.maxTimeMS = function(value) { - if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true}); - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.maxTimeMS = value; - return this; -} - -define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]}); - -Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS; - -define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Sets a field projection for the query. - * @method - * @param {object} value The field projection object. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.project = function(value) { - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - this.s.cmd.fields = value; - return this; -} - -define.classMethod('project', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Sets the sort order of the cursor query. - * @method - * @param {(string|array|object)} keyOrList The key or keys set for the sort. - * @param {number} [direction] The direction of the sorting (1 or -1). - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.sort = function(keyOrList, direction) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true}); - if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - var order = keyOrList; - - if(direction != null) { - order = [[keyOrList, direction]]; - } - - this.s.cmd.sort = order; - this.sortValue = order; - return this; -} - -define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the batch size for the cursor. - * @method - * @param {number} value The batchSize for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.batchSize = function(value) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true}); - if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true}); - this.s.cmd.batchSize = value; - this.setCursorBatchSize(value); - return this; -} - -define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the limit for the cursor. - * @method - * @param {number} value The limit for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.limit = function(value) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true}); - if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true}); - this.s.cmd.limit = value; - // this.cursorLimit = value; - this.setCursorLimit(value); - return this; -} - -define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Set the skip for the cursor. - * @method - * @param {number} value The skip for the cursor query. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.skip = function(value) { - if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true}); - if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true}); - if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true}); - this.s.cmd.skip = value; - this.setCursorSkip(value); - return this; -} - -define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]}); - -/** - * The callback format for results - * @callback Cursor~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {(object|null|boolean)} result The result object if the command was executed successfully. - */ - -/** - * Clone the cursor - * @function external:CoreCursor#clone - * @return {Cursor} - */ - -/** - * Resets the cursor - * @function external:CoreCursor#rewind - * @return {null} - */ - -/** - * Get the next available document from the cursor, returns null if no more documents are available. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @throws {MongoError} - * @deprecated - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.nextObject = Cursor.prototype.next; - -var nextObject = function(self, callback) { - if(self.s.state == Cursor.CLOSED || self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); - if(self.s.state == Cursor.INIT && self.s.cmd.sort) { - try { - self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort); - } catch(err) { - return handleCallback(callback, err); - } - } - - // Get the next object - self._next(function(err, doc) { - if(err && err.tailable && self.s.currentNumberOfRetries == 0) return callback(err); - if(err && err.tailable && self.s.currentNumberOfRetries > 0) { - self.s.currentNumberOfRetries = self.s.currentNumberOfRetries - 1; - - return setTimeout(function() { - // Rewind the cursor only when it has not actually read any documents yet - if(self.cursorState.currentLimit == 0) self.rewind(); - // Read the next document, forcing a re-issue of query if no cursorId exists - self.nextObject(callback); - }, self.s.tailableRetryInterval); - } - - self.s.state = Cursor.OPEN; - if(err) return handleCallback(callback, err); - handleCallback(callback, null, doc); - }); -} - -define.classMethod('nextObject', {callback: true, promise:true}); - -// Trampoline emptying the number of retrieved items -// without incurring a nextTick operation -var loop = function(self, callback) { - // No more items we are done - if(self.bufferedCount() == 0) return; - // Get the next document - self._next(callback); - // Loop - return loop; -} - -Cursor.prototype.next = Cursor.prototype.nextObject; - -define.classMethod('next', {callback: true, promise:true}); - -/** - * Iterates over all the documents for this cursor. As with **{cursor.toArray}**, - * not all of the elements will be iterated if this cursor had been previouly accessed. - * In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike - * **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements - * at any given time if batch size is specified. Otherwise, the caller is responsible - * for making sure that the entire result can fit the memory. - * @method - * @deprecated - * @param {Cursor~resultCallback} callback The result callback. - * @throws {MongoError} - * @return {null} - */ -Cursor.prototype.each = function(callback) { - // Rewind cursor state - this.rewind(); - // Set current cursor to INIT - this.s.state = Cursor.INIT; - // Run the query - _each(this, callback); -}; - -define.classMethod('each', {callback: true, promise:false}); - -// Run the each loop -var _each = function(self, callback) { - if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true}); - if(self.isNotified()) return; - if(self.s.state == Cursor.CLOSED || self.isDead()) { - return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true})); - } - - if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN; - - // Define function to avoid global scope escape - var fn = null; - // Trampoline all the entries - if(self.bufferedCount() > 0) { - while(fn = loop(self, callback)) fn(self, callback); - _each(self, callback); - } else { - self.next(function(err, item) { - if(err) return handleCallback(callback, err); - if(item == null) { - self.s.state = Cursor.CLOSED; - return handleCallback(callback, null, null); - } - - if(handleCallback(callback, null, item) == false) return; - _each(self, callback); - }) - } -} - -/** - * The callback format for the forEach iterator method - * @callback Cursor~iteratorCallback - * @param {Object} doc An emitted document for the iterator - */ - -/** - * The callback error format for the forEach iterator method - * @callback Cursor~endCallback - * @param {MongoError} error An error instance representing the error during the execution. - */ - -/** - * Iterates over all the documents for this cursor using the iterator, callback pattern. - * @method - * @param {Cursor~iteratorCallback} iterator The iteration callback. - * @param {Cursor~endCallback} callback The end callback. - * @throws {MongoError} - * @return {null} - */ -Cursor.prototype.forEach = function(iterator, callback) { - this.each(function(err, doc){ - if(err) { callback(err); return false; } - if(doc != null) { iterator(doc); return true; } - if(doc == null && callback) { - var internalCallback = callback; - callback = null; - internalCallback(null); - return false; - } - }); -} - -define.classMethod('forEach', {callback: true, promise:false}); - -/** - * Set the ReadPreference for the cursor. - * @method - * @param {(string|ReadPreference)} readPreference The new read preference for the cursor. - * @throws {MongoError} - * @return {Cursor} - */ -Cursor.prototype.setReadPreference = function(r) { - if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true}); - if(r instanceof ReadPreference) { - this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags); - } else { - this.s.options.readPreference = new CoreReadPreference(r); - } - - return this; -} - -define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]}); - -/** - * The callback format for results - * @callback Cursor~toArrayResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object[]} documents All the documents the satisfy the cursor. - */ - -/** - * Returns an array of documents. The caller is responsible for making sure that there - * is enough memory to store the results. Note that the array only contain partial - * results when this cursor had been previouly accessed. In that case, - * cursor.rewind() can be used to reset the cursor. - * @method - * @param {Cursor~toArrayResultCallback} [callback] The result callback. - * @throws {MongoError} - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.toArray = function(callback) { - var self = this; - if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true}); - - // Execute using callback - if(typeof callback == 'function') return toArray(self, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - toArray(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -var toArray = function(self, callback) { - var items = []; - - // Reset cursor - self.rewind(); - self.s.state = Cursor.INIT; - - // Fetch all the documents - var fetchDocs = function() { - self._next(function(err, doc) { - if(err) return handleCallback(callback, err); - if(doc == null) { - self.s.state = Cursor.CLOSED; - return handleCallback(callback, null, items); - } - - // Add doc to items - items.push(doc) - - // Get all buffered objects - if(self.bufferedCount() > 0) { - var docs = self.readBufferedDocuments(self.bufferedCount()) - - // Transform the doc if transform method added - if(self.s.transforms && typeof self.s.transforms.doc == 'function') { - docs = docs.map(self.s.transforms.doc); - } - - items = items.concat(docs); - } - - // Attempt a fetch - fetchDocs(); - }) - } - - fetchDocs(); -} - -define.classMethod('toArray', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Cursor~countResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} count The count of documents. - */ - -/** - * Get the count of documents for this cursor - * @method - * @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options. - * @param {object} [options=null] Optional settings. - * @param {number} [options.skip=null] The number of documents to skip. - * @param {number} [options.limit=null] The maximum amounts to count before aborting. - * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query. - * @param {string} [options.hint=null] An index name hint for the query. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Cursor~countResultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.count = function(applySkipLimit, opts, callback) { - var self = this; - if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true}); - if(typeof opts == 'function') callback = opts, opts = {}; - opts = opts || {}; - - // Execute using callback - if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - count(self, applySkipLimit, opts, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var count = function(self, applySkipLimit, opts, callback) { - if(typeof applySkipLimit == 'function') { - callback = applySkipLimit; - applySkipLimit = true; - } - - if(applySkipLimit) { - if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip(); - if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit(); - } - - // Command - var delimiter = self.s.ns.indexOf('.'); - - var command = { - 'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query - } - - if(typeof opts.maxTimeMS == 'number') { - command.maxTimeMS = opts.maxTimeMS; - } else if(typeof self.s.maxTimeMS == 'number') { - command.maxTimeMS = self.s.maxTimeMS; - } - - // Get a server - var server = self.s.topology.getServer(opts); - // Get a connection - var connection = self.s.topology.getConnection(opts); - // Get the callbacks - var callbacks = server.getCallbacks(); - - // Merge in any options - if(opts.skip) command.skip = opts.skip; - if(opts.limit) command.limit = opts.limit; - if(self.s.options.hint) command.hint = self.s.options.hint; - - // Build Query object - var query = new Query(self.s.bson, f("%s.$cmd", self.s.ns.substr(0, delimiter)), command, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false - }); - - // Set up callback - callbacks.register(query.requestId, function(err, result) { - if(err) return handleCallback(callback, err); - if(result.documents.length == 1 - && (result.documents[0].errmsg - || result.documents[0].err - || result.documents[0]['$err'])) { - return handleCallback(callback, MongoError.create(result.documents[0])); - } - handleCallback(callback, null, result.documents[0].n); - }); - - // Write the initial command out - connection.write(query.toBin()); -} - -define.classMethod('count', {callback: true, promise:true}); - -/** - * Close the cursor, sending a KillCursor command and emitting close. - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.close = function(callback) { - this.s.state = Cursor.CLOSED; - // Kill the cursor - this.kill(); - // Emit the close event for the cursor - this.emit('close'); - // Callback if provided - if(typeof callback == 'function') return handleCallback(callback, null, this); - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - resolve(); - }); -} - -define.classMethod('close', {callback: true, promise:true}); - -/** - * Map all documents using the provided function - * @method - * @param {function} [transform] The mapping transformation method. - * @return {null} - */ -Cursor.prototype.map = function(transform) { - this.cursorState.transforms = { doc: transform }; - return this; -} - -define.classMethod('map', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Is the cursor closed - * @method - * @return {boolean} - */ -Cursor.prototype.isClosed = function() { - return this.isDead(); -} - -define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]}); - -Cursor.prototype.destroy = function(err) { - this.pause(); - this.close(); - if(err) this.emit('error', err); -} - -define.classMethod('destroy', {callback: false, promise:false}); - -/** - * Return a modified Readable stream including a possible transform method. - * @method - * @param {object} [options=null] Optional settings. - * @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream. - * @return {Cursor} - */ -Cursor.prototype.stream = function(options) { - this.s.streamOptions = options || {}; - return this; -} - -define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]}); - -/** - * Execute the explain for the cursor - * @method - * @param {Cursor~resultCallback} [callback] The result callback. - * @return {Promise} returns Promise if no callback passed - */ -Cursor.prototype.explain = function(callback) { - var self = this; - this.s.cmd.explain = true; - - // Execute using callback - if(typeof callback == 'function') return this._next(callback); - - // Return a Promise - return new this.s.promiseLibrary(function(resolve, reject) { - self._next(function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('explain', {callback: true, promise:true}); - -Cursor.prototype._read = function(n) { - var self = this; - if(self.s.state == Cursor.CLOSED || self.isDead()) { - return self.push(null); - } - - // Get the next item - self.nextObject(function(err, result) { - if(err) { - if(!self.isDead()) self.close(); - if(self.listeners('error') && self.listeners('error').length > 0) { - self.emit('error', err); - } - - // Emit end event - self.emit('end'); - return self.emit('finish'); - } - - // If we provided a transformation method - if(typeof self.s.streamOptions.transform == 'function' && result != null) { - return self.push(self.s.streamOptions.transform(result)); - } - - // If we provided a map function - if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) { - return self.push(self.cursorState.transforms.doc(result)); - } - - // Return the result - self.push(result); - }); -} - -Object.defineProperty(Cursor.prototype, 'namespace', { - enumerable: true, - get: function() { - if (!this || !this.s) { - return null; - } - - // TODO: refactor this logic into core - var ns = this.s.ns || ''; - var firstDot = ns.indexOf('.'); - if (firstDot < 0) { - return { - database: this.s.ns, - collection: '' - }; - } - return { - database: ns.substr(0, firstDot), - collection: ns.substr(firstDot + 1) - }; - } -}); - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Readable#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Readable#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Readable#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Readable#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Readable#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Readable#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Readable#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Readable#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -Cursor.INIT = 0; -Cursor.OPEN = 1; -Cursor.CLOSED = 2; -Cursor.GET_MORE = 3; - -module.exports = Cursor; diff --git a/util/retroImporter/node_modules/mongodb/lib/db.js b/util/retroImporter/node_modules/mongodb/lib/db.js deleted file mode 100644 index 6667297..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/db.js +++ /dev/null @@ -1,1731 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , getSingleProperty = require('./utils').getSingleProperty - , shallowClone = require('./utils').shallowClone - , parseIndexOptions = require('./utils').parseIndexOptions - , debugOptions = require('./utils').debugOptions - , CommandCursor = require('./command_cursor') - , handleCallback = require('./utils').handleCallback - , toError = require('./utils').toError - , ReadPreference = require('./read_preference') - , f = require('util').format - , Admin = require('./admin') - , Code = require('mongodb-core').BSON.Code - , CoreReadPreference = require('mongodb-core').ReadPreference - , MongoError = require('mongodb-core').MongoError - , ObjectID = require('mongodb-core').ObjectID - , Define = require('./metadata') - , Logger = require('mongodb-core').Logger - , Collection = require('./collection') - , crypto = require('crypto'); - -var debugFields = ['authSource', 'w', 'wtimeout', 'j', 'native_parser', 'forceServerObjectId' - , 'serializeFunctions', 'raw', 'promoteLongs', 'bufferMaxEntries', 'numberOfRetries', 'retryMiliSeconds' - , 'readPreference', 'pkFactory']; - -/** - * @fileOverview The **Db** class is a class that represents a MongoDB Database. - * - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Get an additional db - * var testDb = db.db('test'); - * db.close(); - * }); - */ - -/** - * Creates a new Db instance - * @class - * @param {string} databaseName The name of the database this instance represents. - * @param {(Server|ReplSet|Mongos)} topology The server topology for the database. - * @param {object} [options=null] Optional settings. - * @param {string} [options.authSource=null] If the database authentication is dependent on another databaseName. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.native_parser=true] Select C++ bson parser instead of JavaScript parser. - * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. - * @param {number} [options.bufferMaxEntries=-1] Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited. - * @param {number} [options.numberOfRetries=5] Number of times a tailable cursor will re-poll when it gets nothing back. - * @param {number} [options.retryMiliSeconds=500] Number of milliseconds between retries. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @property {(Server|ReplSet|Mongos)} serverConfig Get the current db topology. - * @property {number} bufferMaxEntries Current bufferMaxEntries value for the database - * @property {string} databaseName The name of the database this instance represents. - * @property {object} options The options associated with the db instance. - * @property {boolean} native_parser The current value of the parameter native_parser. - * @property {boolean} slaveOk The current slaveOk value for the db instance. - * @property {object} writeConcern The current write concern values. - * @fires Db#close - * @fires Db#authenticated - * @fires Db#reconnect - * @fires Db#error - * @fires Db#timeout - * @fires Db#parseError - * @fires Db#fullsetup - * @return {Db} a Db instance. - */ -var Db = function(databaseName, topology, options) { - options = options || {}; - if(!(this instanceof Db)) return new Db(databaseName, topology, options); - EventEmitter.call(this); - var self = this; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Ensure we put the promiseLib in the options - options.promiseLibrary = promiseLibrary; - - // var self = this; // Internal state of the db object - this.s = { - // Database name - databaseName: databaseName - // DbCache - , dbCache: {} - // Children db's - , children: [] - // Topology - , topology: topology - // Options - , options: options - // Logger instance - , logger: Logger('Db', options) - // Get the bson parser - , bson: topology ? topology.bson : null - // Authsource if any - , authSource: options.authSource - // Unpack read preference - , readPreference: options.readPreference - // Set buffermaxEntries - , bufferMaxEntries: typeof options.bufferMaxEntries == 'number' ? options.bufferMaxEntries : -1 - // Parent db (if chained) - , parentDb: options.parentDb || null - // Set up the primary key factory or fallback to ObjectID - , pkFactory: options.pkFactory || ObjectID - // Get native parser - , nativeParser: options.nativeParser || options.native_parser - // Promise library - , promiseLibrary: promiseLibrary - // No listener - , noListener: typeof options.noListener == 'boolean' ? options.noListener : false - // ReadConcern - , readConcern: options.readConcern - } - - // Ensure we have a valid db name - validateDatabaseName(self.s.databaseName); - - // If we have specified the type of parser - if(typeof self.s.nativeParser == 'boolean') { - if(self.s.nativeParser) { - topology.setBSONParserType("c++"); - } else { - topology.setBSONParserType("js"); - } - } - - // Add a read Only property - getSingleProperty(this, 'serverConfig', self.s.topology); - getSingleProperty(this, 'bufferMaxEntries', self.s.bufferMaxEntries); - getSingleProperty(this, 'databaseName', self.s.databaseName); - - // Last ismaster - Object.defineProperty(this, 'options', { - enumerable:true, - get: function() { return self.s.options; } - }); - - // Last ismaster - Object.defineProperty(this, 'native_parser', { - enumerable:true, - get: function() { return self.s.topology.parserType() == 'c++'; } - }); - - // Last ismaster - Object.defineProperty(this, 'slaveOk', { - enumerable:true, - get: function() { - if(self.s.options.readPreference != null - && (self.s.options.readPreference != 'primary' || self.s.options.readPreference.mode != 'primary')) { - return true; - } - return false; - } - }); - - Object.defineProperty(this, 'writeConcern', { - enumerable:true, - get: function() { - var ops = {}; - if(self.s.options.w != null) ops.w = self.s.options.w; - if(self.s.options.j != null) ops.j = self.s.options.j; - if(self.s.options.fsync != null) ops.fsync = self.s.options.fsync; - if(self.s.options.wtimeout != null) ops.wtimeout = self.s.options.wtimeout; - return ops; - } - }); - - // This is a child db, do not register any listeners - if(options.parentDb) return; - if(this.s.noListener) return; - - // Add listeners - topology.on('error', createListener(self, 'error', self)); - topology.on('timeout', createListener(self, 'timeout', self)); - topology.on('close', createListener(self, 'close', self)); - topology.on('parseError', createListener(self, 'parseError', self)); - topology.once('open', createListener(self, 'open', self)); - topology.once('fullsetup', createListener(self, 'fullsetup', self)); - topology.once('all', createListener(self, 'all', self)); - topology.on('reconnect', createListener(self, 'reconnect', self)); -} - -inherits(Db, EventEmitter); - -var define = Db.define = new Define('Db', Db, false); - -/** - * The callback format for the Db.open method - * @callback Db~openCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Db} db The Db instance if the open method was successful. - */ - -// Internal method -var open = function(self, callback) { - self.s.topology.connect(self, self.s.options, function(err, topology) { - if(callback == null) return; - var internalCallback = callback; - callback == null; - - if(err) { - self.close(); - return internalCallback(err); - } - - internalCallback(null, self); - }); -} - -/** - * Open the database - * @method - * @param {Db~openCallback} [callback] Callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.open = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return open(self, callback); - // Return promise - return new self.s.promiseLibrary(function(resolve, reject) { - open(self, function(err, db) { - if(err) return reject(err); - resolve(db); - }) - }); -} - -define.classMethod('open', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Db~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result object if the command was executed successfully. - */ - -var executeCommand = function(self, command, options, callback) { - var dbName = options.dbName || options.authdb || self.s.databaseName; - // If we have a readPreference set - if(options.readPreference == null && self.s.readPreference) { - options.readPreference = self.s.readPreference; - } - - // Convert the readPreference - if(options.readPreference && typeof options.readPreference == 'string') { - options.readPreference = new CoreReadPreference(options.readPreference); - } else if(options.readPreference instanceof ReadPreference) { - options.readPreference = new CoreReadPreference(options.readPreference.mode - , options.readPreference.tags); - } - - // Debug information - if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command %s against %s with options [%s]' - , JSON.stringify(command), f('%s.$cmd', dbName), JSON.stringify(debugOptions(debugFields, options)))); - - // Execute command - self.s.topology.command(f('%s.$cmd', dbName), command, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); -} - -/** - * Execute a command - * @method - * @param {object} command The command hash - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.command = function(command, options, callback) { - var self = this; - // Change the callback - if(typeof options == 'function') callback = options, options = {}; - // Clone the options - options = shallowClone(options); - - // Do we have a callback - if(typeof callback == 'function') return executeCommand(self, command, options, callback); - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - executeCommand(self, command, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('command', {callback: true, promise:true}); - -/** - * The callback format for results - * @callback Db~noResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {null} result Is not set to a value - */ - -/** - * Close the db and it's underlying connections - * @method - * @param {boolean} force Force close, emitting no events - * @param {Db~noResultCallback} [callback] The result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.close = function(force, callback) { - if(typeof force == 'function') callback = force, force = false; - this.s.topology.close(force); - var self = this; - - // Fire close event if any listeners - if(this.listeners('close').length > 0) { - this.emit('close'); - - // If it's the top level db emit close on all children - if(this.parentDb == null) { - // Fire close on all children - for(var i = 0; i < this.s.children.length; i++) { - this.s.children[i].emit('close'); - } - } - - // Remove listeners after emit - self.removeAllListeners('close'); - } - - // Close parent db if set - if(this.s.parentDb) this.s.parentDb.close(); - // Callback after next event loop tick - if(typeof callback == 'function') return process.nextTick(function() { - handleCallback(callback, null); - }) - - // Return dummy promise - return new this.s.promiseLibrary(function(resolve, reject) { - resolve(); - }); -} - -define.classMethod('close', {callback: true, promise:true}); - -/** - * Return the Admin db instance - * @method - * @return {Admin} return the new Admin db instance - */ -Db.prototype.admin = function() { - return new Admin(this, this.s.topology, this.s.promiseLibrary); -}; - -define.classMethod('admin', {callback: false, promise:false, returns: [Admin]}); - -/** - * The callback format for the collection method, must be used if strict is specified - * @callback Db~collectionResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection instance. - */ - -/** - * Fetch a specific collection (containing the actual collection information). If the application does not use strict mode you can - * can use it without a callback in the following way. var collection = db.collection('mycollection'); - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {object} [options.readConcern=null] Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) - * @param {object} [options.readConcern.level='local'] Specify a read concern level for the collection operations, one of [local|majority]. (only MongoDB 3.2 or higher supported) - * @param {Db~collectionResultCallback} callback The collection result callback - * @return {Collection} return the new Collection instance if not in strict mode - */ -Db.prototype.collection = function(name, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - options = shallowClone(options); - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // If we have not set a collection level readConcern set the db level one - options.readConcern = options.readConcern || this.s.readConcern; - - // Do we have ignoreUndefined set - if(this.s.options.ignoreUndefined) { - options.ignoreUndefined = this.s.options.ignoreUndefined; - } - - // Execute - if(options == null || !options.strict) { - try { - var collection = new Collection(this, this.s.topology, this.s.databaseName, name, this.s.pkFactory, options); - if(callback) callback(null, collection); - return collection; - } catch(err) { - if(callback) return callback(err); - throw err; - } - } - - // Strict mode - if(typeof callback != 'function') { - throw toError(f("A callback is required in strict mode. While getting collection %s.", name)); - } - - // Strict mode - this.listCollections({name:name}).toArray(function(err, collections) { - if(err != null) return handleCallback(callback, err, null); - if(collections.length == 0) return handleCallback(callback, toError(f("Collection %s does not exist. Currently in strict mode.", name)), null); - - try { - return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); - } catch(err) { - return handleCallback(callback, err, null); - } - }); -} - -define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); - -var createCollection = function(self, name, options, callback) { - // Get the write concern options - var finalOptions = writeConcern(shallowClone(options), self, options); - - // Check if we have the name - self.listCollections({name: name}).toArray(function(err, collections) { - if(err != null) return handleCallback(callback, err, null); - if(collections.length > 0 && finalOptions.strict) { - return handleCallback(callback, MongoError.create({message: f("Collection %s already exists. Currently in strict mode.", name), driver:true}), null); - } else if (collections.length > 0) { - try { return handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); } - catch(err) { return handleCallback(callback, err); } - } - - // Create collection command - var cmd = {'create':name}; - - // Add all optional parameters - for(var n in options) { - if(options[n] != null && typeof options[n] != 'function') - cmd[n] = options[n]; - } - - // Execute command - self.command(cmd, finalOptions, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, new Collection(self, self.s.topology, self.s.databaseName, name, self.s.pkFactory, options)); - }); - }); -} - -/** - * Creates a collection on a server pre-allocating space, need to create f.ex capped collections. - * - * @method - * @param {string} name the collection name we wish to access. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. - * @param {object} [options.pkFactory=null] A primary key factory object for generation of custom _id keys. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. - * @param {boolean} [options.strict=false] Returns an error if the collection does not exist - * @param {boolean} [options.capped=false] Create a capped collection. - * @param {number} [options.size=null] The size of the capped collection in bytes. - * @param {number} [options.max=null] The maximum number of documents in the capped collection. - * @param {boolean} [options.autoIndexId=true] Create an index on the _id field of the document, True by default on MongoDB 2.2 or higher off for version < 2.2. - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createCollection = function(name, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - name = args.length ? args.shift() : null; - options = args.length ? args.shift() || {} : {}; - - // Do we have a promisesLibrary - options.promiseLibrary = options.promiseLibrary || this.s.promiseLibrary; - - // Check if the callback is in fact a string - if(typeof callback == 'string') name = callback; - - // Execute the fallback callback - if(typeof callback == 'function') return createCollection(self, name, options, callback); - return new this.s.promiseLibrary(function(resolve, reject) { - createCollection(self, name, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -} - -define.classMethod('createCollection', {callback: true, promise:true}); - -/** - * Get all the db statistics. - * - * @method - * @param {object} [options=null] Optional settings. - * @param {number} [options.scale=null] Divide the returned sizes by scale value. - * @param {Db~resultCallback} [callback] The collection result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.stats = function(options, callback) { - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Build command object - var commandObject = { dbStats:true }; - // Check if we have the scale value - if(options['scale'] != null) commandObject['scale'] = options['scale']; - // Execute the command - return this.command(commandObject, options, callback); -} - -define.classMethod('stats', {callback: true, promise:true}); - -// Transformation methods for cursor results -var listCollectionsTranforms = function(databaseName) { - var matching = f('%s.', databaseName); - - return { - doc: function(doc) { - var index = doc.name.indexOf(matching); - // Remove database name if available - if(doc.name && index == 0) { - doc.name = doc.name.substr(index + matching.length); - } - - return doc; - } - } -} - -/** - * Get the list of all collection information for the specified db. - * - * @method - * @param {object} filter Query to filter collections by - * @param {object} [options=null] Optional settings. - * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection - * @return {CommandCursor} - */ -Db.prototype.listCollections = function(filter, options) { - filter = filter || {}; - options = options || {}; - - // Shallow clone the object - options = shallowClone(options); - // Set the promise library - options.promiseLibrary = this.s.promiseLibrary; - - // We have a list collections command - if(this.serverConfig.capabilities().hasListCollectionsCommand) { - // Cursor options - var cursor = options.batchSize ? {batchSize: options.batchSize} : {} - // Build the command - var command = { listCollections : true, filter: filter, cursor: cursor }; - // Set the AggregationCursor constructor - options.cursorFactory = CommandCursor; - // Filter out the correct field values - options.transforms = listCollectionsTranforms(this.s.databaseName); - // Execute the cursor - return this.s.topology.cursor(f('%s.$cmd', this.s.databaseName), command, options); - } - - // We cannot use the listCollectionsCommand - if(!this.serverConfig.capabilities().hasListCollectionsCommand) { - // If we have legacy mode and have not provided a full db name filter it - if(typeof filter.name == 'string' && !(new RegExp('^' + this.databaseName + '\\.').test(filter.name))) { - filter = shallowClone(filter); - filter.name = f('%s.%s', this.s.databaseName, filter.name); - } - } - - // No filter, filter by current database - if(filter == null) { - filter.name = f('/%s/', this.s.databaseName); - } - - // Rewrite the filter to use $and to filter out indexes - if(filter.name) { - filter = {$and: [{name: filter.name}, {name:/^((?!\$).)*$/}]}; - } else { - filter = {name:/^((?!\$).)*$/}; - } - - // Return options - var options = {transforms: listCollectionsTranforms(this.s.databaseName)} - // Get the cursor - var cursor = this.collection(Db.SYSTEM_NAMESPACE_COLLECTION).find(filter, options); - // Set the passed in batch size if one was provided - if(options.batchSize) cursor = cursor.batchSize(options.batchSize); - // We have a fallback mode using legacy systems collections - return cursor; -}; - -define.classMethod('listCollections', {callback: false, promise:false, returns: [CommandCursor]}); - -var evaluate = function(self, code, parameters, options, callback) { - var finalCode = code; - var finalParameters = []; - - // If not a code object translate to one - if(!(finalCode instanceof Code)) finalCode = new Code(finalCode); - // Ensure the parameters are correct - if(parameters != null && !Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = [parameters]; - } else if(parameters != null && Array.isArray(parameters) && typeof parameters !== 'function') { - finalParameters = parameters; - } - - // Create execution selector - var cmd = {'$eval':finalCode, 'args':finalParameters}; - // Check if the nolock parameter is passed in - if(options['nolock']) { - cmd['nolock'] = options['nolock']; - } - - // Set primary read preference - options.readPreference = new CoreReadPreference(ReadPreference.PRIMARY); - - // Execute the command - self.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - if(result && result.ok == 1) return handleCallback(callback, null, result.retval); - if(result) return handleCallback(callback, MongoError.create({message: f("eval failed: %s", result.errmsg), driver:true}), null); - handleCallback(callback, err, result); - }); -} - -/** - * Evaluate JavaScript on the server - * - * @method - * @param {Code} code JavaScript to execute on server. - * @param {(object|array)} parameters The parameters for the call. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.nolock=false] Tell MongoDB not to block on the evaulation of the javascript. - * @param {Db~resultCallback} [callback] The results callback - * @deprecated Eval is deprecated on MongoDB 3.2 and forward - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.eval = function(code, parameters, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - parameters = args.length ? args.shift() : parameters; - options = args.length ? args.shift() || {} : {}; - - // Check if the callback is in fact a string - if(typeof callback == 'function') return evaluate(self, code, parameters, options, callback); - // Execute the command - return new this.s.promiseLibrary(function(resolve, reject) { - evaluate(self, code, parameters, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('eval', {callback: true, promise:true}); - -/** - * Rename a collection. - * - * @method - * @param {string} fromCollection Name of current collection to rename. - * @param {string} toCollection New name of of the collection. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists. - * @param {Db~collectionResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.renameCollection = function(fromCollection, toCollection, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - // Add return new collection - options.new_collection = true; - - // Check if the callback is in fact a string - if(typeof callback == 'function') { - return this.collection(fromCollection).rename(toCollection, options, callback); - } - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.collection(fromCollection).rename(toCollection, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('renameCollection', {callback: true, promise:true}); - -/** - * Drop a collection from the database, removing it permanently. New accesses will create a new collection. - * - * @method - * @param {string} name Name of collection to drop - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropCollection = function(name, callback) { - var self = this; - - // Command to execute - var cmd = {'drop':name} - - // Check if the callback is in fact a string - if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { - if(err) return handleCallback(callback, err); - if(result.ok) return handleCallback(callback, null, true); - handleCallback(callback, null, false); - }); - - // Execute the command - return new this.s.promiseLibrary(function(resolve, reject) { - // Execute command - self.command(cmd, self.s.options, function(err, result) { - if(err) return reject(err); - if(result.ok) return resolve(true); - resolve(false); - }); - }); -}; - -define.classMethod('dropCollection', {callback: true, promise:true}); - -/** - * Drop a database. - * - * @method - * @param {Db~resultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.dropDatabase = function(callback) { - var self = this; - // Drop database command - var cmd = {'dropDatabase':1}; - - // Check if the callback is in fact a string - if(typeof callback == 'function') return this.command(cmd, this.s.options, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }); - - // Execute the command - return new this.s.promiseLibrary(function(resolve, reject) { - // Execute command - self.command(cmd, self.s.options, function(err, result) { - if(err) return reject(err); - if(result.ok) return resolve(true); - resolve(false); - }); - }); -} - -define.classMethod('dropDatabase', {callback: true, promise:true}); - -/** - * The callback format for the collections method. - * @callback Db~collectionsResultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection[]} collections An array of all the collections objects for the db instance. - */ -var collections = function(self, callback) { - // Let's get the collection names - self.listCollections().toArray(function(err, documents) { - if(err != null) return handleCallback(callback, err, null); - // Filter collections removing any illegal ones - documents = documents.filter(function(doc) { - return doc.name.indexOf('$') == -1; - }); - - // Return the collection objects - handleCallback(callback, null, documents.map(function(d) { - return new Collection(self, self.s.topology, self.s.databaseName, d.name.replace(self.s.databaseName + ".", ''), self.s.pkFactory, self.s.options); - })); - }); -} - -/** - * Fetch all collections for the current db. - * - * @method - * @param {Db~collectionsResultCallback} [callback] The results callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.collections = function(callback) { - var self = this; - - // Return the callback - if(typeof callback == 'function') return collections(self, callback); - // Return the promise - return new self.s.promiseLibrary(function(resolve, reject) { - collections(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('collections', {callback: true, promise:true}); - -/** - * Runs a command on the database as admin. - * @method - * @param {object} command The command hash - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.executeDbAdminCommand = function(selector, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - if(options.readPreference) { - options.readPreference = options.readPreference; - } - - // Return the callback - if(typeof callback == 'function') return self.s.topology.command('admin.$cmd', selector, options, function(err, result) { - if(err) return handleCallback(callback, err); - handleCallback(callback, null, result.result); - }); - - // Return promise - return new self.s.promiseLibrary(function(resolve, reject) { - self.s.topology.command('admin.$cmd', selector, options, function(err, result) { - if(err) return reject(err); - resolve(result.result); - }); - }); -}; - -define.classMethod('executeDbAdminCommand', {callback: true, promise:true}); - -/** - * Creates an index on the db and collection collection. - * @method - * @param {string} name Name of the collection to create the index on. - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.createIndex = function(name, fieldOrSpec, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - options = typeof callback === 'function' ? options : callback; - options = options == null ? {} : options; - // Shallow clone the options - options = shallowClone(options); - // Run only against primary - options.readPreference = ReadPreference.PRIMARY; - - // If we have a callback fallback - if(typeof callback == 'function') return createIndex(self, name, fieldOrSpec, options, callback); - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - createIndex(self, name, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var createIndex = function(self, name, fieldOrSpec, options, callback) { - // Get the write concern options - var finalOptions = writeConcern({}, self, options); - // Ensure we have a callback - if(finalOptions.writeConcern && typeof callback != 'function') { - throw MongoError.create({message: "Cannot use a writeConcern without a provided callback", driver:true}); - } - - // Attempt to run using createIndexes command - createIndexUsingCreateIndexes(self, name, fieldOrSpec, options, function(err, result) { - if(err == null) return handleCallback(callback, err, result); - // Create command - var doc = createCreateIndexCommand(self, name, fieldOrSpec, options); - // Set no key checking - finalOptions.checkKeys = false; - // Insert document - self.s.topology.insert(f("%s.%s", self.s.databaseName, Db.SYSTEM_INDEX_COLLECTION), doc, finalOptions, function(err, result) { - if(callback == null) return; - if(err) return handleCallback(callback, err); - if(result == null) return handleCallback(callback, null, null); - if(result.result.writeErrors) return handleCallback(callback, MongoError.create(result.result.writeErrors[0]), null); - handleCallback(callback, null, doc.name); - }); - }); -} - -define.classMethod('createIndex', {callback: true, promise:true}); - -/** - * Ensures that an index exists, if it does not it creates it - * @method - * @deprecated since version 2.0 - * @param {string} name The index name - * @param {(string|object)} fieldOrSpec Defines the index. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.unique=false] Creates an unique index. - * @param {boolean} [options.sparse=false] Creates a sparse index. - * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible. - * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value - * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates. - * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates. - * @param {number} [options.v=null] Specify the format version of the indexes. - * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) - * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.ensureIndex = function(name, fieldOrSpec, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // If we have a callback fallback - if(typeof callback == 'function') return ensureIndex(self, name, fieldOrSpec, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - ensureIndex(self, name, fieldOrSpec, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var ensureIndex = function(self, name, fieldOrSpec, options, callback) { - // Get the write concern options - var finalOptions = writeConcern({}, self, options); - // Create command - var selector = createCreateIndexCommand(self, name, fieldOrSpec, options); - var index_name = selector.name; - - // Default command options - var commandOptions = {}; - // Check if the index allready exists - self.indexInformation(name, finalOptions, function(err, indexInformation) { - if(err != null && err.code != 26) return handleCallback(callback, err, null); - // If the index does not exist, create it - if(indexInformation == null || !indexInformation[index_name]) { - self.createIndex(name, fieldOrSpec, options, callback); - } else { - if(typeof callback === 'function') return handleCallback(callback, null, index_name); - } - }); -} - -define.classMethod('ensureIndex', {callback: true, promise:true}); - -Db.prototype.addChild = function(db) { - if(this.s.parentDb) return this.s.parentDb.addChild(db); - this.s.children.push(db); -} - -/** - * Create a new Db instance sharing the current socket connections. Be aware that the new db instances are - * related in a parent-child relationship to the original instance so that events are correctly emitted on child - * db instances. Child db instances are cached so performing db('db1') twice will return the same instance. - * You can control these behaviors with the options noListener and returnNonCachedInstance. - * - * @method - * @param {string} name The name of the database we want to use. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.noListener=false] Do not make the db an event listener to the original connection. - * @param {boolean} [options.returnNonCachedInstance=false] Control if you want to return a cached instance or have a new one created - * @return {Db} - */ -Db.prototype.db = function(dbName, options) { - options = options || {}; - // Copy the options and add out internal override of the not shared flag - for(var key in this.options) { - options[key] = this.options[key]; - } - - // Do we have the db in the cache already - if(this.s.dbCache[dbName] && options.returnNonCachedInstance !== true) { - return this.s.dbCache[dbName]; - } - - // Add current db as parentDb - if(options.noListener == null || options.noListener == false) { - options.parentDb = this; - } - - // Add promiseLibrary - options.promiseLibrary = this.s.promiseLibrary; - - // Return the db object - var db = new Db(dbName, this.s.topology, options) - - // Add as child - if(options.noListener == null || options.noListener == false) { - this.addChild(db); - } - - // Add the db to the cache - this.s.dbCache[dbName] = db; - // Return the database - return db; -}; - -define.classMethod('db', {callback: false, promise:false, returns: [Db]}); - -var _executeAuthCreateUserCommand = function(self, username, password, options, callback) { - // Special case where there is no password ($external users) - if(typeof username == 'string' - && password != null && typeof password == 'object') { - options = password; - password = null; - } - - // Unpack all options - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Error out if we digestPassword set - if(options.digestPassword != null) { - throw toError("The digestPassword option is not supported via add_user. Please use db.command('createUser', ...) instead for this option."); - } - - // Get additional values - var customData = options.customData != null ? options.customData : {}; - var roles = Array.isArray(options.roles) ? options.roles : []; - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // If not roles defined print deprecated message - if(roles.length == 0) { - console.log("Creating a user without roles is deprecated in MongoDB >= 2.6"); - } - - // Get the error options - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Check the db name and add roles if needed - if((self.databaseName.toLowerCase() == 'admin' || options.dbName == 'admin') && !Array.isArray(options.roles)) { - roles = ['root'] - } else if(!Array.isArray(options.roles)) { - roles = ['dbOwner'] - } - - // Build the command to execute - var command = { - createUser: username - , customData: customData - , roles: roles - , digestPassword:false - } - - // Apply write concern to command - command = writeConcern(command, self, options); - - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - - // No password - if(typeof password == 'string') { - command.pwd = userPassword; - } - - // Force write using primary - commandOptions.readPreference = CoreReadPreference.primary; - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err && err.ok == 0 && err.code == undefined) return handleCallback(callback, {code: -5000}, null); - if(err) return handleCallback(callback, err, null); - handleCallback(callback, !result.ok ? toError(result) : null - , result.ok ? [{user: username, pwd: ''}] : null); - }) -} - -var addUser = function(self, username, password, options, callback) { - // Attempt to execute auth command - _executeAuthCreateUserCommand(self, username, password, options, function(err, r) { - // We need to perform the backward compatible insert operation - if(err && err.code == -5000) { - var finalOptions = writeConcern(shallowClone(options), self, options); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var userPassword = md5.digest('hex'); - - // If we have another db set - var db = options.dbName ? self.db(options.dbName) : self; - - // Fetch a user collection - var collection = db.collection(Db.SYSTEM_USER_COLLECTION); - - // Check if we are inserting the first user - collection.count({}, function(err, count) { - // We got an error (f.ex not authorized) - if(err != null) return handleCallback(callback, err, null); - // Check if the user exists and update i - collection.find({user: username}, {dbName: options['dbName']}).toArray(function(err, documents) { - // We got an error (f.ex not authorized) - if(err != null) return handleCallback(callback, err, null); - // Add command keys - finalOptions.upsert = true; - - // We have a user, let's update the password or upsert if not - collection.update({user: username},{$set: {user: username, pwd: userPassword}}, finalOptions, function(err, results, full) { - if(count == 0 && err) return handleCallback(callback, null, [{user:username, pwd:userPassword}]); - if(err) return handleCallback(callback, err, null) - handleCallback(callback, null, [{user:username, pwd:userPassword}]); - }); - }); - }); - - return; - } - - if(err) return handleCallback(callback, err); - handleCallback(callback, err, r); - }); -} - -/** - * Add a user to the database. - * @method - * @param {string} username The username. - * @param {string} password The password. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {object} [options.customData=null] Custom data associated with the user (only Mongodb 2.6 or higher) - * @param {object[]} [options.roles=null] Roles associated with the created user (only Mongodb 2.6 or higher) - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.addUser = function(username, password, options, callback) { - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // If we have a callback fallback - if(typeof callback == 'function') return addUser(self, username, password, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - addUser(self, username, password, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('addUser', {callback: true, promise:true}); - -var _executeAuthRemoveUserCommand = function(self, username, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - // Get the error options - var commandOptions = {writeCommand:true}; - if(options['dbName']) commandOptions.dbName = options['dbName']; - - // Get additional values - var maxTimeMS = typeof options.maxTimeMS == 'number' ? options.maxTimeMS : null; - - // Add maxTimeMS to options if set - if(maxTimeMS != null) commandOptions.maxTimeMS = maxTimeMS; - - // Build the command to execute - var command = { - dropUser: username - } - - // Apply write concern to command - command = writeConcern(command, self, options); - - // Force write using primary - commandOptions.readPreference = CoreReadPreference.primary; - - // Execute the command - self.command(command, commandOptions, function(err, result) { - if(err && !err.ok && err.code == undefined) return handleCallback(callback, {code: -5000}); - if(err) return handleCallback(callback, err, null); - handleCallback(callback, null, result.ok ? true : false); - }) -} - -var removeUser = function(self, username, options, callback) { - // Attempt to execute command - _executeAuthRemoveUserCommand(self, username, options, function(err, result) { - if(err && err.code == -5000) { - var finalOptions = writeConcern(shallowClone(options), self, options); - // If we have another db set - var db = options.dbName ? self.db(options.dbName) : self; - - // Fetch a user collection - var collection = db.collection(Db.SYSTEM_USER_COLLECTION); - - // Locate the user - collection.findOne({user: username}, {}, function(err, user) { - if(user == null) return handleCallback(callback, err, false); - collection.remove({user: username}, finalOptions, function(err, result) { - handleCallback(callback, err, true); - }); - }); - - return; - } - - if(err) return handleCallback(callback, err); - handleCallback(callback, err, result); - }); -} - -define.classMethod('removeUser', {callback: true, promise:true}); - -/** - * Remove a user from a database - * @method - * @param {string} username The username. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.removeUser = function(username, options, callback) { - // Unpack the parameters - var self = this; - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // If we have a callback fallback - if(typeof callback == 'function') return removeUser(self, username, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - removeUser(self, username, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var authenticate = function(self, username, password, options, callback) { - // the default db to authenticate against is 'self' - // if authententicate is called from a retry context, it may be another one, like admin - var authdb = options.authdb ? options.authdb : options.dbName; - authdb = options.authSource ? options.authSource : authdb; - authdb = authdb ? authdb : self.databaseName; - - // Callback - var _callback = function(err, result) { - if(self.listeners('authenticated').length > 0) { - self.emit('authenticated', err, result); - } - - // Return to caller - handleCallback(callback, err, result); - } - - // authMechanism - var authMechanism = options.authMechanism || ''; - authMechanism = authMechanism.toUpperCase(); - - // If classic auth delegate to auth command - if(authMechanism == 'MONGODB-CR') { - self.s.topology.auth('mongocr', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'PLAIN') { - self.s.topology.auth('plain', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'MONGODB-X509') { - self.s.topology.auth('x509', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'SCRAM-SHA-1') { - self.s.topology.auth('scram-sha-1', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else if(authMechanism == 'GSSAPI') { - if(process.platform == 'win32') { - self.s.topology.auth('sspi', authdb, username, password, options, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else { - self.s.topology.auth('gssapi', authdb, username, password, options, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } - } else if(authMechanism == 'DEFAULT') { - self.s.topology.auth('default', authdb, username, password, function(err, result) { - if(err) return handleCallback(callback, err, false); - _callback(null, true); - }); - } else { - handleCallback(callback, MongoError.create({message: f("authentication mechanism %s not supported", options.authMechanism), driver:true})); - } -} - -/** - * Authenticate a user against the server. - * @method - * @param {string} username The username. - * @param {string} [password] The password. - * @param {object} [options=null] Optional settings. - * @param {string} [options.authMechanism=MONGODB-CR] The authentication mechanism to use, GSSAPI, MONGODB-CR, MONGODB-X509, PLAIN - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.authenticate = function(username, password, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - // Shallow copy the options - options = shallowClone(options); - - // Set default mechanism - if(!options.authMechanism) { - options.authMechanism = 'DEFAULT'; - } else if(options.authMechanism != 'GSSAPI' - && options.authMechanism != 'MONGODB-CR' - && options.authMechanism != 'MONGODB-X509' - && options.authMechanism != 'SCRAM-SHA-1' - && options.authMechanism != 'PLAIN') { - return handleCallback(callback, MongoError.create({message: "only GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism", driver:true})); - } - - // If we have a callback fallback - if(typeof callback == 'function') return authenticate(self, username, password, options, function(err, r) { - // Support failed auth method - if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; - // Reject error - if(err) return callback(err, r); - callback(null, r); - }); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - authenticate(self, username, password, options, function(err, r) { - // Support failed auth method - if(err && err.message && err.message.indexOf('saslStart') != -1) err.code = 59; - // Reject error - if(err) return reject(err); - resolve(r); - }); - }); -}; - -define.classMethod('authenticate', {callback: true, promise:true}); - -/** - * Logout user from server, fire off on all connections and remove all auth info - * @method - * @param {object} [options=null] Optional settings. - * @param {string} [options.dbName=null] Logout against different database than current. - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.logout = function(options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() || {} : {}; - - // logout command - var cmd = {'logout':1}; - - // Add onAll to login to ensure all connection are logged out - options.onAll = true; - - // We authenticated against a different db use that - if(this.s.authSource) options.dbName = this.s.authSource; - - // Execute the command - if(typeof callback == 'function') return this.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err, false); - handleCallback(callback, null, true) - }); - - // Return promise - return new this.s.promiseLibrary(function(resolve, reject) { - self.command(cmd, options, function(err, result) { - if(err) return reject(err); - resolve(true); - }); - }); -} - -define.classMethod('logout', {callback: true, promise:true}); - -// Figure out the read preference -var getReadPreference = function(options, db) { - if(options.readPreference) return options; - if(db.readPreference) options.readPreference = db.readPreference; - return options; -} - -/** - * Retrieves this collections index info. - * @method - * @param {string} name The name of the collection. - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.full=false] Returns the full raw index information. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {Db~resultCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -Db.prototype.indexInformation = function(name, options, callback) { - var self = this; - if(typeof options == 'function') callback = options, options = {}; - options = options || {}; - - // If we have a callback fallback - if(typeof callback == 'function') return indexInformation(self, name, options, callback); - - // Return a promise - return new this.s.promiseLibrary(function(resolve, reject) { - indexInformation(self, name, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }); - }); -}; - -var indexInformation = function(self, name, options, callback) { - // If we specified full information - var full = options['full'] == null ? false : options['full']; - - // Process all the results from the index command and collection - var processResults = function(indexes) { - // Contains all the information - var info = {}; - // Process all the indexes - for(var i = 0; i < indexes.length; i++) { - var index = indexes[i]; - // Let's unpack the object - info[index.name] = []; - for(var name in index.key) { - info[index.name].push([name, index.key[name]]); - } - } - - return info; - } - - // Get the list of indexes of the specified collection - self.collection(name).listIndexes().toArray(function(err, indexes) { - if(err) return callback(toError(err)); - if(!Array.isArray(indexes)) return handleCallback(callback, null, []); - if(full) return handleCallback(callback, null, indexes); - handleCallback(callback, null, processResults(indexes)); - }); -} - -define.classMethod('indexInformation', {callback: true, promise:true}); - -var createCreateIndexCommand = function(db, name, fieldOrSpec, options) { - var indexParameters = parseIndexOptions(fieldOrSpec); - var fieldHash = indexParameters.fieldHash; - var keys = indexParameters.keys; - - // Generate the index name - var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; - var selector = { - 'ns': db.databaseName + "." + name, 'key': fieldHash, 'name': indexName - } - - // Ensure we have a correct finalUnique - var finalUnique = options == null || 'object' === typeof options ? false : options; - // Set up options - options = options == null || typeof options == 'boolean' ? {} : options; - - // Add all the options - var keysToOmit = Object.keys(selector); - for(var optionName in options) { - if(keysToOmit.indexOf(optionName) == -1) { - selector[optionName] = options[optionName]; - } - } - - if(selector['unique'] == null) selector['unique'] = finalUnique; - - // Remove any write concern operations - var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; - for(var i = 0; i < removeKeys.length; i++) { - delete selector[removeKeys[i]]; - } - - // Return the command creation selector - return selector; -} - -var createIndexUsingCreateIndexes = function(self, name, fieldOrSpec, options, callback) { - // Build the index - var indexParameters = parseIndexOptions(fieldOrSpec); - // Generate the index name - var indexName = typeof options.name == 'string' ? options.name : indexParameters.name; - // Set up the index - var indexes = [{ name: indexName, key: indexParameters.fieldHash }]; - // merge all the options - var keysToOmit = Object.keys(indexes[0]); - for(var optionName in options) { - if(keysToOmit.indexOf(optionName) == -1) { - indexes[0][optionName] = options[optionName]; - } - - // Remove any write concern operations - var removeKeys = ['w', 'wtimeout', 'j', 'fsync', 'readPreference']; - for(var i = 0; i < removeKeys.length; i++) { - delete indexes[0][removeKeys[i]]; - } - } - - // Create command - var cmd = {createIndexes: name, indexes: indexes}; - - // Apply write concern to command - cmd = writeConcern(cmd, self, options); - - // Build the command - self.command(cmd, options, function(err, result) { - if(err) return handleCallback(callback, err, null); - if(result.ok == 0) return handleCallback(callback, toError(result), null); - // Return the indexName for backward compatibility - handleCallback(callback, null, indexName); - }); -} - -// Validate the database name -var validateDatabaseName = function(databaseName) { - if(typeof databaseName !== 'string') throw MongoError.create({message: "database name must be a string", driver:true}); - if(databaseName.length === 0) throw MongoError.create({message: "database name cannot be the empty string", driver:true}); - if(databaseName == '$external') return; - - var invalidChars = [" ", ".", "$", "/", "\\"]; - for(var i = 0; i < invalidChars.length; i++) { - if(databaseName.indexOf(invalidChars[i]) != -1) throw MongoError.create({message: "database names cannot contain the character '" + invalidChars[i] + "'", driver:true}); - } -} - -// Get write concern -var writeConcern = function(target, db, options) { - if(options.w != null || options.j != null || options.fsync != null) { - var opts = {}; - if(options.w) opts.w = options.w; - if(options.wtimeout) opts.wtimeout = options.wtimeout; - if(options.j) opts.j = options.j; - if(options.fsync) opts.fsync = options.fsync; - target.writeConcern = opts; - } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) { - target.writeConcern = db.writeConcern; - } - - return target -} - -// Add listeners to topology -var createListener = function(self, e, object) { - var listener = function(err) { - if(e != 'error') { - object.emit(e, err, self); - - // Emit on all associated db's if available - for(var i = 0; i < self.s.children.length; i++) { - self.s.children[i].emit(e, err, self.s.children[i]); - } - } - } - return listener; -} - -/** - * Db close event - * - * Emitted after a socket closed against a single server or mongos proxy. - * - * @event Db#close - * @type {MongoError} - */ - -/** - * Db authenticated event - * - * Emitted after all server members in the topology (single server, replicaset or mongos) have successfully authenticated. - * - * @event Db#authenticated - * @type {object} - */ - -/** - * Db reconnect event - * - * * Server: Emitted when the driver has reconnected and re-authenticated. - * * ReplicaSet: N/A - * * Mongos: Emitted when the driver reconnects and re-authenticates successfully against a Mongos. - * - * @event Db#reconnect - * @type {object} - */ - -/** - * Db error event - * - * Emitted after an error occurred against a single server or mongos proxy. - * - * @event Db#error - * @type {MongoError} - */ - -/** - * Db timeout event - * - * Emitted after a socket timeout occurred against a single server or mongos proxy. - * - * @event Db#timeout - * @type {MongoError} - */ - -/** - * Db parseError event - * - * The parseError event is emitted if the driver detects illegal or corrupt BSON being received from the server. - * - * @event Db#parseError - * @type {MongoError} - */ - -/** - * Db fullsetup event, emitted when all servers in the topology have been connected to at start up time. - * - * * Server: Emitted when the driver has connected to the single server and has authenticated. - * * ReplSet: Emitted after the driver has attempted to connect to all replicaset members. - * * Mongos: Emitted after the driver has attempted to connect to all mongos proxies. - * - * @event Db#fullsetup - * @type {Db} - */ - -// Constants -Db.SYSTEM_NAMESPACE_COLLECTION = "system.namespaces"; -Db.SYSTEM_INDEX_COLLECTION = "system.indexes"; -Db.SYSTEM_PROFILE_COLLECTION = "system.profile"; -Db.SYSTEM_USER_COLLECTION = "system.users"; -Db.SYSTEM_COMMAND_COLLECTION = "$cmd"; -Db.SYSTEM_JS_COLLECTION = "system.js"; - -module.exports = Db; diff --git a/util/retroImporter/node_modules/mongodb/lib/gridfs/chunk.js b/util/retroImporter/node_modules/mongodb/lib/gridfs/chunk.js deleted file mode 100644 index d96095f..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/gridfs/chunk.js +++ /dev/null @@ -1,237 +0,0 @@ -"use strict"; - -var Binary = require('mongodb-core').BSON.Binary, - ObjectID = require('mongodb-core').BSON.ObjectID; - -/** - * Class for representing a single chunk in GridFS. - * - * @class - * - * @param file {GridStore} The {@link GridStore} object holding this chunk. - * @param mongoObject {object} The mongo object representation of this chunk. - * - * @throws Error when the type of data field for {@link mongoObject} is not - * supported. Currently supported types for data field are instances of - * {@link String}, {@link Array}, {@link Binary} and {@link Binary} - * from the bson module - * - * @see Chunk#buildMongoObject - */ -var Chunk = function(file, mongoObject, writeConcern) { - if(!(this instanceof Chunk)) return new Chunk(file, mongoObject); - - this.file = file; - var self = this; - var mongoObjectFinal = mongoObject == null ? {} : mongoObject; - this.writeConcern = writeConcern || {w:1}; - this.objectId = mongoObjectFinal._id == null ? new ObjectID() : mongoObjectFinal._id; - this.chunkNumber = mongoObjectFinal.n == null ? 0 : mongoObjectFinal.n; - this.data = new Binary(); - - if(mongoObjectFinal.data == null) { - } else if(typeof mongoObjectFinal.data == "string") { - var buffer = new Buffer(mongoObjectFinal.data.length); - buffer.write(mongoObjectFinal.data, 0, mongoObjectFinal.data.length, 'binary'); - this.data = new Binary(buffer); - } else if(Array.isArray(mongoObjectFinal.data)) { - var buffer = new Buffer(mongoObjectFinal.data.length); - var data = mongoObjectFinal.data.join(''); - buffer.write(data, 0, data.length, 'binary'); - this.data = new Binary(buffer); - } else if(mongoObjectFinal.data._bsontype === 'Binary') { - this.data = mongoObjectFinal.data; - } else if(Buffer.isBuffer(mongoObjectFinal.data)) { - } else { - throw Error("Illegal chunk format"); - } - - // Update position - this.internalPosition = 0; -}; - -/** - * Writes a data to this object and advance the read/write head. - * - * @param data {string} the data to write - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.write = function(data, callback) { - this.data.write(data, this.internalPosition, data.length, 'binary'); - this.internalPosition = this.data.length(); - if(callback != null) return callback(null, this); - return this; -}; - -/** - * Reads data and advances the read/write head. - * - * @param length {number} The length of data to read. - * - * @return {string} The data read if the given length will not exceed the end of - * the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.read = function(length) { - // Default to full read if no index defined - length = length == null || length == 0 ? this.length() : length; - - if(this.length() - this.internalPosition + 1 >= length) { - var data = this.data.read(this.internalPosition, length); - this.internalPosition = this.internalPosition + length; - return data; - } else { - return ''; - } -}; - -Chunk.prototype.readSlice = function(length) { - if ((this.length() - this.internalPosition) >= length) { - var data = null; - if (this.data.buffer != null) { //Pure BSON - data = this.data.buffer.slice(this.internalPosition, this.internalPosition + length); - } else { //Native BSON - data = new Buffer(length); - length = this.data.readInto(data, this.internalPosition); - } - this.internalPosition = this.internalPosition + length; - return data; - } else { - return null; - } -}; - -/** - * Checks if the read/write head is at the end. - * - * @return {boolean} Whether the read/write head has reached the end of this - * chunk. - */ -Chunk.prototype.eof = function() { - return this.internalPosition == this.length() ? true : false; -}; - -/** - * Reads one character from the data of this chunk and advances the read/write - * head. - * - * @return {string} a single character data read if the the read/write head is - * not at the end of the chunk. Returns an empty String otherwise. - */ -Chunk.prototype.getc = function() { - return this.read(1); -}; - -/** - * Clears the contents of the data in this chunk and resets the read/write head - * to the initial position. - */ -Chunk.prototype.rewind = function() { - this.internalPosition = 0; - this.data = new Binary(); -}; - -/** - * Saves this chunk to the database. Also overwrites existing entries having the - * same id as this chunk. - * - * @param callback {function(*, GridStore)} This will be called after executing - * this method. The first parameter will contain null and the second one - * will contain a reference to this object. - */ -Chunk.prototype.save = function(options, callback) { - var self = this; - if(typeof options == 'function') { - callback = options; - options = {}; - } - - self.file.chunkCollection(function(err, collection) { - if(err) return callback(err); - - // Merge the options - var writeOptions = {}; - for(var name in options) writeOptions[name] = options[name]; - for(var name in self.writeConcern) writeOptions[name] = self.writeConcern[name]; - - // collection.remove({'_id':self.objectId}, self.writeConcern, function(err, result) { - collection.remove({'_id':self.objectId}, writeOptions, function(err, result) { - if(err) return callback(err); - - if(self.data.length() > 0) { - self.buildMongoObject(function(mongoObject) { - var options = {forceServerObjectId:true}; - for(var name in self.writeConcern) { - options[name] = self.writeConcern[name]; - } - - collection.insert(mongoObject, writeOptions, function(err, collection) { - callback(err, self); - }); - }); - } else { - callback(null, self); - } - }); - }); -}; - -/** - * Creates a mongoDB object representation of this chunk. - * - * @param callback {function(Object)} This will be called after executing this - * method. The object will be passed to the first parameter and will have - * the structure: - * - *
        
        - *        {
        - *          '_id' : , // {number} id for this chunk
        - *          'files_id' : , // {number} foreign key to the file collection
        - *          'n' : , // {number} chunk number
        - *          'data' : , // {bson#Binary} the chunk data itself
        - *        }
        - *        
        - * - * @see MongoDB GridFS Chunk Object Structure - */ -Chunk.prototype.buildMongoObject = function(callback) { - var mongoObject = { - 'files_id': this.file.fileId, - 'n': this.chunkNumber, - 'data': this.data}; - // If we are saving using a specific ObjectId - if(this.objectId != null) mongoObject._id = this.objectId; - - callback(mongoObject); -}; - -/** - * @return {number} the length of the data - */ -Chunk.prototype.length = function() { - return this.data.length(); -}; - -/** - * The position of the read/write head - * @name position - * @lends Chunk# - * @field - */ -Object.defineProperty(Chunk.prototype, "position", { enumerable: true - , get: function () { - return this.internalPosition; - } - , set: function(value) { - this.internalPosition = value; - } -}); - -/** - * The default chunk size - * @constant - */ -Chunk.DEFAULT_CHUNK_SIZE = 1024 * 255; - -module.exports = Chunk; diff --git a/util/retroImporter/node_modules/mongodb/lib/gridfs/grid_store.js b/util/retroImporter/node_modules/mongodb/lib/gridfs/grid_store.js deleted file mode 100644 index 62943bd..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/gridfs/grid_store.js +++ /dev/null @@ -1,1919 +0,0 @@ -"use strict"; - -/** - * @fileOverview GridFS is a tool for MongoDB to store files to the database. - * Because of the restrictions of the object size the database can hold, a - * facility to split a file into several chunks is needed. The {@link GridStore} - * class offers a simplified api to interact with files while managing the - * chunks of split files behind the scenes. More information about GridFS can be - * found here. - * - * @example - * var MongoClient = require('mongodb').MongoClient, - * GridStore = require('mongodb').GridStore, - * ObjectID = require('mongodb').ObjectID, - * test = require('assert'); - * - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * var gridStore = new GridStore(db, null, "w"); - * gridStore.open(function(err, gridStore) { - * gridStore.write("hello world!", function(err, gridStore) { - * gridStore.close(function(err, result) { - * - * // Let's read the file using object Id - * GridStore.read(db, result._id, function(err, data) { - * test.equal('hello world!', data); - * db.close(); - * test.done(); - * }); - * }); - * }); - * }); - * }); - */ -var Chunk = require('./chunk'), - ObjectID = require('mongodb-core').BSON.ObjectID, - ReadPreference = require('../read_preference'), - Buffer = require('buffer').Buffer, - Collection = require('../collection'), - fs = require('fs'), - timers = require('timers'), - f = require('util').format, - util = require('util'), - Define = require('../metadata'), - MongoError = require('mongodb-core').MongoError, - inherits = util.inherits, - Duplex = require('stream').Duplex || require('readable-stream').Duplex; - -var REFERENCE_BY_FILENAME = 0, - REFERENCE_BY_ID = 1; - -/** - * Namespace provided by the mongodb-core and node.js - * @external Duplex - */ - -/** - * Create a new GridStore instance - * - * Modes - * - **"r"** - read only. This is the default mode. - * - **"w"** - write in truncate mode. Existing data will be overwriten. - * - * @class - * @param {Db} db A database instance to interact with. - * @param {object} [id] optional unique id for this file - * @param {string} [filename] optional filename for this file, no unique constrain on the field - * @param {string} mode set the mode for this file. - * @param {object} [options=null] Optional settings. - * @param {(number|string)} [options.w=null] The write concern. - * @param {number} [options.wtimeout=null] The write concern timeout. - * @param {boolean} [options.j=false] Specify a journal write concern. - * @param {boolean} [options.fsync=false] Specify a file sync write concern. - * @param {string} [options.root=null] Root collection to use. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {string} [options.content_type=null] MIME type of the file. Defaults to **{GridStore.DEFAULT_CONTENT_TYPE}**. - * @param {number} [options.chunk_size=261120] Size for the chunk. Defaults to **{Chunk.DEFAULT_CHUNK_SIZE}**. - * @param {object} [options.metadata=null] Arbitrary data the user wants to store. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @property {number} chunkSize Get the gridstore chunk size. - * @property {number} md5 The md5 checksum for this file. - * @property {number} chunkNumber The current chunk number the gridstore has materialized into memory - * @return {GridStore} a GridStore instance. - */ -var GridStore = function GridStore(db, id, filename, mode, options) { - if(!(this instanceof GridStore)) return new GridStore(db, id, filename, mode, options); - var self = this; - this.db = db; - - // Handle options - if(typeof options === 'undefined') options = {}; - // Handle mode - if(typeof mode === 'undefined') { - mode = filename; - filename = undefined; - } else if(typeof mode == 'object') { - options = mode; - mode = filename; - filename = undefined; - } - - if(id instanceof ObjectID) { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } else if(typeof filename == 'undefined') { - this.referenceBy = REFERENCE_BY_FILENAME; - this.filename = id; - if (mode.indexOf('w') != null) { - this.fileId = new ObjectID(); - } - } else { - this.referenceBy = REFERENCE_BY_ID; - this.fileId = id; - this.filename = filename; - } - - // Set up the rest - this.mode = mode == null ? "r" : mode; - this.options = options || {}; - - // Opened - this.isOpen = false; - - // Set the root if overridden - this.root = this.options['root'] == null ? GridStore.DEFAULT_ROOT_COLLECTION : this.options['root']; - this.position = 0; - this.readPreference = this.options.readPreference || db.options.readPreference || ReadPreference.PRIMARY; - this.writeConcern = _getWriteConcern(db, this.options); - // Set default chunk size - this.internalChunkSize = this.options['chunkSize'] == null ? Chunk.DEFAULT_CHUNK_SIZE : this.options['chunkSize']; - - // Get the promiseLibrary - var promiseLibrary = this.options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Set the promiseLibrary - this.promiseLibrary = promiseLibrary; - - Object.defineProperty(this, "chunkSize", { enumerable: true - , get: function () { - return this.internalChunkSize; - } - , set: function(value) { - if(!(this.mode[0] == "w" && this.position == 0 && this.uploadDate == null)) { - this.internalChunkSize = this.internalChunkSize; - } else { - this.internalChunkSize = value; - } - } - }); - - Object.defineProperty(this, "md5", { enumerable: true - , get: function () { - return this.internalMd5; - } - }); - - Object.defineProperty(this, "chunkNumber", { enumerable: true - , get: function () { - return this.currentChunk && this.currentChunk.chunkNumber ? this.currentChunk.chunkNumber : null; - } - }); -} - -var define = GridStore.define = new Define('Gridstore', GridStore, true); - -/** - * The callback format for the Gridstore.open method - * @callback GridStore~openCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The GridStore instance if the open method was successful. - */ - -/** - * Opens the file from the database and initialize this object. Also creates a - * new one if file does not exist. - * - * @method - * @param {GridStore~openCallback} [callback] this will be called after executing this method - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.open = function(callback) { - var self = this; - if( this.mode != "w" && this.mode != "w+" && this.mode != "r"){ - throw MongoError.create({message: "Illegal mode " + this.mode, driver:true}); - } - - // We provided a callback leg - if(typeof callback == 'function') return open(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - open(self, function(err, store) { - if(err) return reject(err); - resolve(store); - }) - }); -}; - -var open = function(self, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(self.db, self.options); - - // If we are writing we need to ensure we have the right indexes for md5's - if((self.mode == "w" || self.mode == "w+")) { - // Get files collection - var collection = self.collection(); - // Put index on filename - collection.ensureIndex([['filename', 1]], writeConcern, function(err, index) { - // Get chunk collection - var chunkCollection = self.chunkCollection(); - // Ensure index on chunk collection - chunkCollection.ensureIndex([['files_id', 1], ['n', 1]], writeConcern, function(err, index) { - // Open the connection - _open(self, writeConcern, function(err, r) { - if(err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - }); - }); - } else { - // Open the gridstore - _open(self, writeConcern, function(err, r) { - if(err) return callback(err); - self.isOpen = true; - callback(err, r); - }); - } -} - -// Push the definition for open -define.classMethod('open', {callback: true, promise:true}); - -/** - * Verify if the file is at EOF. - * - * @method - * @return {boolean} true if the read/write head is at the end of this file. - */ -GridStore.prototype.eof = function() { - return this.position == this.length ? true : false; -} - -define.classMethod('eof', {callback: false, promise:false, returns: [Boolean]}); - -/** - * The callback result format. - * @callback GridStore~resultCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {object} result The result from the callback. - */ - -/** - * Retrieves a single character from this file. - * - * @method - * @param {GridStore~resultCallback} [callback] this gets called after this method is executed. Passes null to the first parameter and the character read to the second or null to the second if the read/write head is at the end of the file. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.getc = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return eof(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - eof(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -var eof = function(self, callback) { - if(self.eof()) { - callback(null, null); - } else if(self.currentChunk.eof()) { - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - self.currentChunk = chunk; - self.position = self.position + 1; - callback(err, self.currentChunk.getc()); - }); - } else { - self.position = self.position + 1; - callback(null, self.currentChunk.getc()); - } -} - -define.classMethod('getc', {callback: true, promise:true}); - -/** - * Writes a string to the file with a newline character appended at the end if - * the given string does not have one. - * - * @method - * @param {string} string the string to write. - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.puts = function(string, callback) { - var self = this; - var finalString = string.match(/\n$/) == null ? string + "\n" : string; - // We provided a callback leg - if(typeof callback == 'function') return this.write(finalString, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - self.write(finalString, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -define.classMethod('puts', {callback: true, promise:true}); - -/** - * Return a modified Readable stream including a possible transform method. - * - * @method - * @return {GridStoreStream} - */ -GridStore.prototype.stream = function() { - return new GridStoreStream(this); -} - -define.classMethod('stream', {callback: false, promise:false, returns: [GridStoreStream]}); - -/** - * Writes some data. This method will work properly only if initialized with mode "w" or "w+". - * - * @method - * @param {(string|Buffer)} data the data to write. - * @param {boolean} [close] closes this file after writing if set to true. - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.write = function write(data, close, callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return _writeNormal(this, data, close, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - _writeNormal(self, data, close, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -define.classMethod('write', {callback: true, promise:true}); - -/** - * Handles the destroy part of a stream - * - * @method - * @result {null} - */ -GridStore.prototype.destroy = function destroy() { - // close and do not emit any more events. queued data is not sent. - if(!this.writable) return; - this.readable = false; - if(this.writable) { - this.writable = false; - this._q.length = 0; - this.emit('close'); - } -} - -define.classMethod('destroy', {callback: false, promise:false}); - -/** - * Stores a file from the file system to the GridFS database. - * - * @method - * @param {(string|Buffer|FileHandle)} file the file to store. - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.writeFile = function (file, callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return writeFile(self, file, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - writeFile(self, file, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var writeFile = function(self, file, callback) { - if (typeof file === 'string') { - fs.open(file, 'r', function (err, fd) { - if(err) return callback(err); - self.writeFile(fd, callback); - }); - return; - } - - self.open(function (err, self) { - if(err) return callback(err, self); - - fs.fstat(file, function (err, stats) { - if(err) return callback(err, self); - - var offset = 0; - var index = 0; - var numberOfChunksLeft = Math.min(stats.size / self.chunkSize); - - // Write a chunk - var writeChunk = function() { - fs.read(file, self.chunkSize, offset, 'binary', function(err, data, bytesRead) { - if(err) return callback(err, self); - - offset = offset + bytesRead; - - // Create a new chunk for the data - var chunk = new Chunk(self, {n:index++}, self.writeConcern); - chunk.write(data, function(err, chunk) { - if(err) return callback(err, self); - - chunk.save({}, function(err, result) { - if(err) return callback(err, self); - - self.position = self.position + data.length; - - // Point to current chunk - self.currentChunk = chunk; - - if(offset >= stats.size) { - fs.close(file); - self.close(function(err, result) { - if(err) return callback(err, self); - return callback(null, self); - }); - } else { - return process.nextTick(writeChunk); - } - }); - }); - }); - } - - // Process the first write - process.nextTick(writeChunk); - }); - }); -} - -define.classMethod('writeFile', {callback: true, promise:true}); - -/** - * Saves this file to the database. This will overwrite the old entry if it - * already exists. This will work properly only if mode was initialized to - * "w" or "w+". - * - * @method - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.close = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return close(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - close(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var close = function(self, callback) { - if(self.mode[0] == "w") { - // Set up options - var options = self.writeConcern; - - if(self.currentChunk != null && self.currentChunk.position > 0) { - self.currentChunk.save({}, function(err, chunk) { - if(err && typeof callback == 'function') return callback(err); - - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - // Build the mongo object - if(self.uploadDate != null) { - files.remove({'_id':self.fileId}, self.writeConcern, function(err, collection) { - if(err && typeof callback == 'function') return callback(err); - - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } else { - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - } - }); - }); - } else { - self.collection(function(err, files) { - if(err && typeof callback == 'function') return callback(err); - - self.uploadDate = new Date(); - buildMongoObject(self, function(err, mongoObject) { - if(err) { - if(typeof callback == 'function') return callback(err); else throw err; - } - - files.save(mongoObject, options, function(err) { - if(typeof callback == 'function') - callback(err, mongoObject); - }); - }); - }); - } - } else if(self.mode[0] == "r") { - if(typeof callback == 'function') - callback(null, null); - } else { - if(typeof callback == 'function') - callback(MongoError.create({message: f("Illegal mode %s", self.mode), driver:true})); - } -} - -define.classMethod('close', {callback: true, promise:true}); - -/** - * The collection callback format. - * @callback GridStore~collectionCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Collection} collection The collection from the command execution. - */ - -/** - * Retrieve this file's chunks collection. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - */ -GridStore.prototype.chunkCollection = function(callback) { - if(typeof callback == 'function') - return this.db.collection((this.root + ".chunks"), callback); - return this.db.collection((this.root + ".chunks")); -}; - -define.classMethod('chunkCollection', {callback: true, promise:false, returns: [Collection]}); - -/** - * Deletes all the chunks of this file in the database. - * - * @method - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.unlink = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return unlink(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - unlink(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var unlink = function(self, callback) { - deleteChunks(self, function(err) { - if(err!==null) { - err.message = "at deleteChunks: " + err.message; - return callback(err); - } - - self.collection(function(err, collection) { - if(err!==null) { - err.message = "at collection: " + err.message; - return callback(err); - } - - collection.remove({'_id':self.fileId}, self.writeConcern, function(err) { - callback(err, self); - }); - }); - }); -} - -define.classMethod('unlink', {callback: true, promise:true}); - -/** - * Retrieves the file collection associated with this object. - * - * @method - * @param {GridStore~collectionCallback} callback the command callback. - * @return {Collection} - */ -GridStore.prototype.collection = function(callback) { - if(typeof callback == 'function') - this.db.collection(this.root + ".files", callback); - return this.db.collection(this.root + ".files"); -}; - -define.classMethod('collection', {callback: true, promise:false, returns: [Collection]}); - -/** - * The readlines callback format. - * @callback GridStore~readlinesCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {string[]} strings The array of strings returned. - */ - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.readlines = function(separator, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - separator = args.length ? args.shift() : "\n"; - separator = separator || "\n"; - - // We provided a callback leg - if(typeof callback == 'function') return readlines(self, separator, callback); - - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - readlines(self, separator, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var readlines = function(self, separator, callback) { - self.read(function(err, data) { - if(err) return callback(err); - - var items = data.toString().split(separator); - items = items.length > 0 ? items.splice(0, items.length - 1) : []; - for(var i = 0; i < items.length; i++) { - items[i] = items[i] + separator; - } - - callback(null, items); - }); -} - -define.classMethod('readlines', {callback: true, promise:true}); - -/** - * Deletes all the chunks of this file in the database if mode was set to "w" or - * "w+" and resets the read/write head to the initial position. - * - * @method - * @param {GridStore~resultCallback} [callback] this will be called after executing this method. The first parameter will contain null and the second one will contain a reference to this object. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.rewind = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return rewind(self, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - rewind(self, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var rewind = function(self, callback) { - if(self.currentChunk.chunkNumber != 0) { - if(self.mode[0] == "w") { - deleteChunks(self, function(err, gridStore) { - if(err) return callback(err); - self.currentChunk = new Chunk(self, {'n': 0}, self.writeConcern); - self.position = 0; - callback(null, self); - }); - } else { - self.currentChunk(0, function(err, chunk) { - if(err) return callback(err); - self.currentChunk = chunk; - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - }); - } - } else { - self.currentChunk.rewind(); - self.position = 0; - callback(null, self); - } -} - -define.classMethod('rewind', {callback: true, promise:true}); - -/** - * The read callback format. - * @callback GridStore~readCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Buffer} data The data read from the GridStore object - */ - -/** - * Retrieves the contents of this file and advances the read/write head. Works with Buffers only. - * - * There are 3 signatures for this method: - * - * (callback) - * (length, callback) - * (length, buffer, callback) - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.read = function(length, buffer, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - length = args.length ? args.shift() : null; - buffer = args.length ? args.shift() : null; - // We provided a callback leg - if(typeof callback == 'function') return read(self, length, buffer, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - read(self, length, buffer, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -var read = function(self, length, buffer, callback) { - // The data is a c-terminated string and thus the length - 1 - var finalLength = length == null ? self.length - self.position : length; - var finalBuffer = buffer == null ? new Buffer(finalLength) : buffer; - // Add a index to buffer to keep track of writing position or apply current index - finalBuffer._index = buffer != null && buffer._index != null ? buffer._index : 0; - - if((self.currentChunk.length() - self.currentChunk.position + finalBuffer._index) >= finalLength) { - var slice = self.currentChunk.readSlice(finalLength - finalBuffer._index); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update internal position - self.position = self.position + finalBuffer.length; - // Check if we don't have a file at all - if(finalLength == 0 && finalBuffer.length == 0) return callback(MongoError.create({message: "File does not exist", driver:true}), null); - // Else return data - return callback(null, finalBuffer); - } - - // Read the next chunk - var slice = self.currentChunk.readSlice(self.currentChunk.length() - self.currentChunk.position); - // Copy content to final buffer - slice.copy(finalBuffer, finalBuffer._index); - // Update index position - finalBuffer._index += slice.length; - - // Load next chunk and read more - nthChunk(self, self.currentChunk.chunkNumber + 1, function(err, chunk) { - if(err) return callback(err); - - if(chunk.length() > 0) { - self.currentChunk = chunk; - self.read(length, finalBuffer, callback); - } else { - if(finalBuffer._index > 0) { - callback(null, finalBuffer) - } else { - callback(MongoError.create({message: "no chunks found for file, possibly corrupt", driver:true}), null); - } - } - }); -} - -define.classMethod('read', {callback: true, promise:true}); - -/** - * The tell callback format. - * @callback GridStore~tellCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {number} position The current read position in the GridStore. - */ - -/** - * Retrieves the position of the read/write head of this file. - * - * @method - * @param {number} [length] the number of characters to read. Reads all the characters from the read/write head to the EOF if not specified. - * @param {(string|Buffer)} [buffer] a string to hold temporary data. This is used for storing the string data read so far when recursively calling this method. - * @param {GridStore~tellCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.tell = function(callback) { - var self = this; - // We provided a callback leg - if(typeof callback == 'function') return callback(null, this.position); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - resolve(self.position); - }); -}; - -define.classMethod('tell', {callback: true, promise:true}); - -/** - * The tell callback format. - * @callback GridStore~gridStoreCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {GridStore} gridStore The gridStore. - */ - -/** - * Moves the read/write head to a new location. - * - * There are 3 signatures for this method - * - * Seek Location Modes - * - **GridStore.IO_SEEK_SET**, **(default)** set the position from the start of the file. - * - **GridStore.IO_SEEK_CUR**, set the position from the current position in the file. - * - **GridStore.IO_SEEK_END**, set the position from the end of the file. - * - * @method - * @param {number} [position] the position to seek to - * @param {number} [seekLocation] seek mode. Use one of the Seek Location modes. - * @param {GridStore~gridStoreCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.prototype.seek = function(position, seekLocation, callback) { - var self = this; - - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - seekLocation = args.length ? args.shift() : null; - - // We provided a callback leg - if(typeof callback == 'function') return seek(self, position, seekLocation, callback); - // Return promise - return new self.promiseLibrary(function(resolve, reject) { - seek(self, position, seekLocation, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -} - -var seek = function(self, position, seekLocation, callback) { - // Seek only supports read mode - if(self.mode != 'r') { - return callback(MongoError.create({message: "seek is only supported for mode r", driver:true})) - } - - var seekLocationFinal = seekLocation == null ? GridStore.IO_SEEK_SET : seekLocation; - var finalPosition = position; - var targetPosition = 0; - - // Calculate the position - if(seekLocationFinal == GridStore.IO_SEEK_CUR) { - targetPosition = self.position + finalPosition; - } else if(seekLocationFinal == GridStore.IO_SEEK_END) { - targetPosition = self.length + finalPosition; - } else { - targetPosition = finalPosition; - } - - // Get the chunk - var newChunkNumber = Math.floor(targetPosition/self.chunkSize); - var seekChunk = function() { - nthChunk(self, newChunkNumber, function(err, chunk) { - self.currentChunk = chunk; - self.position = targetPosition; - self.currentChunk.position = (self.position % self.chunkSize); - callback(err, self); - }); - }; - - seekChunk(); -} - -define.classMethod('seek', {callback: true, promise:true}); - -/** - * @ignore - */ -var _open = function(self, options, callback) { - var collection = self.collection(); - // Create the query - var query = self.referenceBy == REFERENCE_BY_ID ? {_id:self.fileId} : {filename:self.filename}; - query = null == self.fileId && self.filename == null ? null : query; - options.readPreference = self.readPreference; - - // Fetch the chunks - if(query != null) { - collection.findOne(query, options, function(err, doc) { - if(err) return error(err); - - // Check if the collection for the files exists otherwise prepare the new one - if(doc != null) { - self.fileId = doc._id; - // Prefer a new filename over the existing one if this is a write - self.filename = ((self.mode == 'r') || (self.filename == undefined)) ? doc.filename : self.filename; - self.contentType = doc.contentType; - self.internalChunkSize = doc.chunkSize; - self.uploadDate = doc.uploadDate; - self.aliases = doc.aliases; - self.length = doc.length; - self.metadata = doc.metadata; - self.internalMd5 = doc.md5; - } else if (self.mode != 'r') { - self.fileId = self.fileId == null ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - } else { - self.length = 0; - var txtId = self.fileId instanceof ObjectID ? self.fileId.toHexString() : self.fileId; - return error(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? txtId : self.filename)), driver:true}), self); - } - - // Process the mode of the object - if(self.mode == "r") { - nthChunk(self, 0, options, function(err, chunk) { - if(err) return error(err); - self.currentChunk = chunk; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, options, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - }); - } else { - // Write only mode - self.fileId = null == self.fileId ? new ObjectID() : self.fileId; - self.contentType = GridStore.DEFAULT_CONTENT_TYPE; - self.internalChunkSize = self.internalChunkSize == null ? Chunk.DEFAULT_CHUNK_SIZE : self.internalChunkSize; - self.length = 0; - - var collection2 = self.chunkCollection(); - // No file exists set up write mode - if(self.mode == "w") { - // Delete any existing chunks - deleteChunks(self, options, function(err, result) { - if(err) return error(err); - self.currentChunk = new Chunk(self, {'n':0}, self.writeConcern); - self.contentType = self.options['content_type'] == null ? self.contentType : self.options['content_type']; - self.internalChunkSize = self.options['chunk_size'] == null ? self.internalChunkSize : self.options['chunk_size']; - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = 0; - callback(null, self); - }); - } else if(self.mode == "w+") { - nthChunk(self, lastChunkNumber(self), options, function(err, chunk) { - if(err) return error(err); - // Set the current chunk - self.currentChunk = chunk == null ? new Chunk(self, {'n':0}, self.writeConcern) : chunk; - self.currentChunk.position = self.currentChunk.data.length(); - self.metadata = self.options['metadata'] == null ? self.metadata : self.options['metadata']; - self.aliases = self.options['aliases'] == null ? self.aliases : self.options['aliases']; - self.position = self.length; - callback(null, self); - }); - } - } - - // only pass error to callback once - function error (err) { - if(error.err) return; - callback(error.err = err); - } -}; - -/** - * @ignore - */ -var writeBuffer = function(self, buffer, close, callback) { - if(typeof close === "function") { callback = close; close = null; } - var finalClose = typeof close == 'boolean' ? close : false; - - if(self.mode != "w") { - callback(MongoError.create({message: f("file with id %s not opened for writing", (self.referenceBy == REFERENCE_BY_ID ? self.referenceBy : self.filename)), driver:true}), null); - } else { - if(self.currentChunk.position + buffer.length >= self.chunkSize) { - // Write out the current Chunk and then keep writing until we have less data left than a chunkSize left - // to a new chunk (recursively) - var previousChunkNumber = self.currentChunk.chunkNumber; - var leftOverDataSize = self.chunkSize - self.currentChunk.position; - var firstChunkData = buffer.slice(0, leftOverDataSize); - var leftOverData = buffer.slice(leftOverDataSize); - // A list of chunks to write out - var chunksToWrite = [self.currentChunk.write(firstChunkData)]; - // If we have more data left than the chunk size let's keep writing new chunks - while(leftOverData.length >= self.chunkSize) { - // Create a new chunk and write to it - var newChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - var firstChunkData = leftOverData.slice(0, self.chunkSize); - leftOverData = leftOverData.slice(self.chunkSize); - // Update chunk number - previousChunkNumber = previousChunkNumber + 1; - // Write data - newChunk.write(firstChunkData); - // Push chunk to save list - chunksToWrite.push(newChunk); - } - - // Set current chunk with remaining data - self.currentChunk = new Chunk(self, {'n': (previousChunkNumber + 1)}, self.writeConcern); - // If we have left over data write it - if(leftOverData.length > 0) self.currentChunk.write(leftOverData); - - // Update the position for the gridstore - self.position = self.position + buffer.length; - // Total number of chunks to write - var numberOfChunksToWrite = chunksToWrite.length; - - for(var i = 0; i < chunksToWrite.length; i++) { - chunksToWrite[i].save({}, function(err, result) { - if(err) return callback(err); - - numberOfChunksToWrite = numberOfChunksToWrite - 1; - - if(numberOfChunksToWrite <= 0) { - // We care closing the file before returning - if(finalClose) { - return self.close(function(err, result) { - callback(err, self); - }); - } - - // Return normally - return callback(null, self); - } - }); - } - } else { - // Update the position for the gridstore - self.position = self.position + buffer.length; - // We have less data than the chunk size just write it and callback - self.currentChunk.write(buffer); - // We care closing the file before returning - if(finalClose) { - return self.close(function(err, result) { - callback(err, self); - }); - } - // Return normally - return callback(null, self); - } - } -}; - -/** - * Creates a mongoDB object representation of this object. - * - *
        
        - *        {
        - *          '_id' : , // {number} id for this file
        - *          'filename' : , // {string} name for this file
        - *          'contentType' : , // {string} mime type for this file
        - *          'length' : , // {number} size of this file?
        - *          'chunksize' : , // {number} chunk size used by this file
        - *          'uploadDate' : , // {Date}
        - *          'aliases' : , // {array of string}
        - *          'metadata' : , // {string}
        - *        }
        - *        
        - * - * @ignore - */ -var buildMongoObject = function(self, callback) { - // Calcuate the length - var mongoObject = { - '_id': self.fileId, - 'filename': self.filename, - 'contentType': self.contentType, - 'length': self.position ? self.position : 0, - 'chunkSize': self.chunkSize, - 'uploadDate': self.uploadDate, - 'aliases': self.aliases, - 'metadata': self.metadata - }; - - var md5Command = {filemd5:self.fileId, root:self.root}; - self.db.command(md5Command, function(err, results) { - if(err) return callback(err); - - mongoObject.md5 = results.md5; - callback(null, mongoObject); - }); -}; - -/** - * Gets the nth chunk of this file. - * @ignore - */ -var nthChunk = function(self, chunkNumber, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - options.readPreference = self.readPreference; - // Get the nth chunk - self.chunkCollection().findOne({'files_id':self.fileId, 'n':chunkNumber}, options, function(err, chunk) { - if(err) return callback(err); - - var finalChunk = chunk == null ? {} : chunk; - callback(null, new Chunk(self, finalChunk, self.writeConcern)); - }); -}; - -/** - * @ignore - */ -var lastChunkNumber = function(self) { - return Math.floor((self.length ? self.length - 1 : 0)/self.chunkSize); -}; - -/** - * Deletes all the chunks of this file in the database. - * - * @ignore - */ -var deleteChunks = function(self, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - options = options || self.writeConcern; - - if(self.fileId != null) { - self.chunkCollection().remove({'files_id':self.fileId}, options, function(err, result) { - if(err) return callback(err, false); - callback(null, true); - }); - } else { - callback(null, true); - } -}; - -/** -* The collection to be used for holding the files and chunks collection. -* -* @classconstant DEFAULT_ROOT_COLLECTION -**/ -GridStore.DEFAULT_ROOT_COLLECTION = 'fs'; - -/** -* Default file mime type -* -* @classconstant DEFAULT_CONTENT_TYPE -**/ -GridStore.DEFAULT_CONTENT_TYPE = 'binary/octet-stream'; - -/** -* Seek mode where the given length is absolute. -* -* @classconstant IO_SEEK_SET -**/ -GridStore.IO_SEEK_SET = 0; - -/** -* Seek mode where the given length is an offset to the current read/write head. -* -* @classconstant IO_SEEK_CUR -**/ -GridStore.IO_SEEK_CUR = 1; - -/** -* Seek mode where the given length is an offset to the end of the file. -* -* @classconstant IO_SEEK_END -**/ -GridStore.IO_SEEK_END = 2; - -/** - * Checks if a file exists in the database. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file to look for. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.exist = function(db, fileIdObject, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return exists(db, fileIdObject, rootCollection, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - exists(db, fileIdObject, rootCollection, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var exists = function(db, fileIdObject, rootCollection, options, callback) { - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Fetch collection - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - db.collection(rootCollectionFinal + ".files", function(err, collection) { - if(err) return callback(err); - - // Build query - var query = (typeof fileIdObject == 'string' || Object.prototype.toString.call(fileIdObject) == '[object RegExp]' ) - ? {'filename':fileIdObject} - : {'_id':fileIdObject}; // Attempt to locate file - - // We have a specific query - if(fileIdObject != null - && typeof fileIdObject == 'object' - && Object.prototype.toString.call(fileIdObject) != '[object RegExp]') { - query = fileIdObject; - } - - // Check if the entry exists - collection.findOne(query, {readPreference:readPreference}, function(err, item) { - if(err) return callback(err); - callback(null, item == null ? false : true); - }); - }); -} - -define.staticMethod('exist', {callback: true, promise:true}); - -/** - * Gets the list of files stored in the GridFS. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} [rootCollection] The root collection that holds the files and chunks collection. Defaults to **{GridStore.DEFAULT_ROOT_COLLECTION}**. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~resultCallback} [callback] result from exists. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.list = function(db, rootCollection, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - rootCollection = args.length ? args.shift() : null; - options = args.length ? args.shift() : {}; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return list(db, rootCollection, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - list(db, rootCollection, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var list = function(db, rootCollection, options, callback) { - // Ensure we have correct values - if(rootCollection != null && typeof rootCollection == 'object') { - options = rootCollection; - rootCollection = null; - } - - // Establish read preference - var readPreference = options.readPreference || ReadPreference.PRIMARY; - // Check if we are returning by id not filename - var byId = options['id'] != null ? options['id'] : false; - // Fetch item - var rootCollectionFinal = rootCollection != null ? rootCollection : GridStore.DEFAULT_ROOT_COLLECTION; - var items = []; - db.collection((rootCollectionFinal + ".files"), function(err, collection) { - if(err) return callback(err); - - collection.find({}, {readPreference:readPreference}, function(err, cursor) { - if(err) return callback(err); - - cursor.each(function(err, item) { - if(item != null) { - items.push(byId ? item._id : item.filename); - } else { - callback(err, items); - } - }); - }); - }); -} - -define.staticMethod('list', {callback: true, promise:true}); - -/** - * Reads the contents of a file. - * - * This method has the following signatures - * - * (db, name, callback) - * (db, name, length, callback) - * (db, name, length, offset, callback) - * (db, name, length, offset, options, callback) - * - * @method - * @static - * @param {Db} db the database to query. - * @param {string} name The name of the file. - * @param {number} [length] The size of data to read. - * @param {number} [offset] The offset from the head of the file of which to start reading from. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~readCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ - -GridStore.read = function(db, name, length, offset, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - length = args.length ? args.shift() : null; - offset = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options ? options.promiseLibrary : null; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return readStatic(db, name, length, offset, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - readStatic(db, name, length, offset, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var readStatic = function(db, name, length, offset, options, callback) { - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - // Make sure we are not reading out of bounds - if(offset && offset >= gridStore.length) return callback("offset larger than size of file", null); - if(length && length > gridStore.length) return callback("length is larger than the size of the file", null); - if(offset && length && (offset + length) > gridStore.length) return callback("offset and length is larger than the size of the file", null); - - if(offset != null) { - gridStore.seek(offset, function(err, gridStore) { - if(err) return callback(err); - gridStore.read(length, callback); - }); - } else { - gridStore.read(length, callback); - } - }); -} - -define.staticMethod('read', {callback: true, promise:true}); - -/** - * Read the entire file as a list of strings splitting by the provided separator. - * - * @method - * @static - * @param {Db} db the database to query. - * @param {(String|object)} name the name of the file. - * @param {string} [separator] The character to be recognized as the newline separator. - * @param {object} [options=null] Optional settings. - * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~readlinesCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.readlines = function(db, name, separator, options, callback) { - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - separator = args.length ? args.shift() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options ? options.promiseLibrary : null; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return readlinesStatic(db, name, separator, options, callback); - // Return promise - return new promiseLibrary(function(resolve, reject) { - readlinesStatic(db, name, separator, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var readlinesStatic = function(db, name, separator, options, callback) { - var finalSeperator = separator == null ? "\n" : separator; - new GridStore(db, name, "r", options).open(function(err, gridStore) { - if(err) return callback(err); - gridStore.readlines(finalSeperator, callback); - }); -} - -define.staticMethod('readlines', {callback: true, promise:true}); - -/** - * Deletes the chunks and metadata information of a file from GridFS. - * - * @method - * @static - * @param {Db} db The database to query. - * @param {(string|array)} names The name/names of the files to delete. - * @param {object} [options=null] Optional settings. - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {GridStore~resultCallback} [callback] the command callback. - * @return {Promise} returns Promise if no callback passed - */ -GridStore.unlink = function(db, names, options, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - options = args.length ? args.shift() : {}; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // We provided a callback leg - if(typeof callback == 'function') return unlinkStatic(self, db, names, options, callback); - - // Return promise - return new promiseLibrary(function(resolve, reject) { - unlinkStatic(self, db, names, options, function(err, r) { - if(err) return reject(err); - resolve(r); - }) - }); -}; - -var unlinkStatic = function(self, db, names, options, callback) { - // Get the write concern - var writeConcern = _getWriteConcern(db, options); - - // List of names - if(names.constructor == Array) { - var tc = 0; - for(var i = 0; i < names.length; i++) { - ++tc; - GridStore.unlink(db, names[i], options, function(result) { - if(--tc == 0) { - callback(null, self); - } - }); - } - } else { - new GridStore(db, names, "w", options).open(function(err, gridStore) { - if(err) return callback(err); - deleteChunks(gridStore, function(err, result) { - if(err) return callback(err); - gridStore.collection(function(err, collection) { - if(err) return callback(err); - collection.remove({'_id':gridStore.fileId}, writeConcern, function(err, result) { - callback(err, self); - }); - }); - }); - }); - } -} - -define.staticMethod('unlink', {callback: true, promise:true}); - -/** - * @ignore - */ -var _writeNormal = function(self, data, close, callback) { - // If we have a buffer write it using the writeBuffer method - if(Buffer.isBuffer(data)) { - return writeBuffer(self, data, close, callback); - } else { - return writeBuffer(self, new Buffer(data, 'binary'), close, callback); - } -} - -/** - * @ignore - */ -var _setWriteConcernHash = function(options) { - var finalOptions = {}; - if(options.w != null) finalOptions.w = options.w; - if(options.journal == true) finalOptions.j = options.journal; - if(options.j == true) finalOptions.j = options.j; - if(options.fsync == true) finalOptions.fsync = options.fsync; - if(options.wtimeout != null) finalOptions.wtimeout = options.wtimeout; - return finalOptions; -} - -/** - * @ignore - */ -var _getWriteConcern = function(self, options) { - // Final options - var finalOptions = {w:1}; - options = options || {}; - - // Local options verification - if(options.w != null || typeof options.j == 'boolean' || typeof options.journal == 'boolean' || typeof options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(options); - } else if(options.safe != null && typeof options.safe == 'object') { - finalOptions = _setWriteConcernHash(options.safe); - } else if(typeof options.safe == "boolean") { - finalOptions = {w: (options.safe ? 1 : 0)}; - } else if(self.options.w != null || typeof self.options.j == 'boolean' || typeof self.options.journal == 'boolean' || typeof self.options.fsync == 'boolean') { - finalOptions = _setWriteConcernHash(self.options); - } else if(self.safe && (self.safe.w != null || typeof self.safe.j == 'boolean' || typeof self.safe.journal == 'boolean' || typeof self.safe.fsync == 'boolean')) { - finalOptions = _setWriteConcernHash(self.safe); - } else if(typeof self.safe == "boolean") { - finalOptions = {w: (self.safe ? 1 : 0)}; - } - - // Ensure we don't have an invalid combination of write concerns - if(finalOptions.w < 1 - && (finalOptions.journal == true || finalOptions.j == true || finalOptions.fsync == true)) throw MongoError.create({message: "No acknowledgement using w < 1 cannot be combined with journal:true or fsync:true", driver:true}); - - // Return the options - return finalOptions; -} - -/** - * Create a new GridStoreStream instance (INTERNAL TYPE, do not instantiate directly) - * - * @class - * @extends external:Duplex - * @return {GridStoreStream} a GridStoreStream instance. - */ -var GridStoreStream = function(gs) { - var self = this; - // Initialize the duplex stream - Duplex.call(this); - - // Get the gridstore - this.gs = gs; - - // End called - this.endCalled = false; - - // If we have a seek - this.totalBytesToRead = this.gs.length - this.gs.position; - this.seekPosition = this.gs.position; -} - -// -// Inherit duplex -inherits(GridStoreStream, Duplex); - -GridStoreStream.prototype._pipe = GridStoreStream.prototype.pipe; - -// Set up override -GridStoreStream.prototype.pipe = function(destination) { - var self = this; - - // Only open gridstore if not already open - if(!self.gs.isOpen) { - self.gs.open(function(err) { - if(err) return self.emit('error', err); - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - }); - } else { - self.totalBytesToRead = self.gs.length - self.gs.position; - self._pipe.apply(self, [destination]); - } -} - -// Called by stream -GridStoreStream.prototype._read = function(n) { - var self = this; - - var read = function() { - // Read data - self.gs.read(length, function(err, buffer) { - if(err && !self.endCalled) return self.emit('error', err); - - // Stream is closed - if(self.endCalled || buffer == null) return self.push(null); - // Remove bytes read - if(buffer.length <= self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer.length; - self.push(buffer); - } else if(buffer.length > self.totalBytesToRead) { - self.totalBytesToRead = self.totalBytesToRead - buffer._index; - self.push(buffer.slice(0, buffer._index)); - } - - // Finished reading - if(self.totalBytesToRead <= 0) { - self.endCalled = true; - } - }); - } - - // Set read length - var length = self.gs.length < self.gs.chunkSize ? self.gs.length - self.seekPosition : self.gs.chunkSize; - if(!self.gs.isOpen) { - self.gs.open(function(err, gs) { - self.totalBytesToRead = self.gs.length - self.gs.position; - if(err) return self.emit('error', err); - read(); - }); - } else { - read(); - } -} - -GridStoreStream.prototype.destroy = function() { - this.pause(); - this.endCalled = true; - this.gs.close(); - this.emit('end'); -} - -GridStoreStream.prototype.write = function(chunk, encoding, callback) { - var self = this; - if(self.endCalled) return self.emit('error', MongoError.create({message: 'attempting to write to stream after end called', driver:true})) - // Do we have to open the gridstore - if(!self.gs.isOpen) { - self.gs.open(function() { - self.gs.isOpen = true; - self.gs.write(chunk, function() { - process.nextTick(function() { - self.emit('drain'); - }); - }); - }); - return false; - } else { - self.gs.write(chunk, function() { - self.emit('drain'); - }); - return true; - } -} - -GridStoreStream.prototype.end = function(chunk, encoding, callback) { - var self = this; - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - if(typeof callback != 'function') args.push(callback); - chunk = args.length ? args.shift() : null; - encoding = args.length ? args.shift() : null; - self.endCalled = true; - - if(chunk) { - self.gs.write(chunk, function() { - self.gs.close(function() { - if(typeof callback == 'function') callback(); - self.emit('end') - }); - }); - } - - self.gs.close(function() { - if(typeof callback == 'function') callback(); - self.emit('end') - }); -} - -/** - * The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null. - * @function external:Duplex#read - * @param {number} size Optional argument to specify how much data to read. - * @return {(String | Buffer | null)} - */ - -/** - * Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects. - * @function external:Duplex#setEncoding - * @param {string} encoding The encoding to use. - * @return {null} - */ - -/** - * This method will cause the readable stream to resume emitting data events. - * @function external:Duplex#resume - * @return {null} - */ - -/** - * This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer. - * @function external:Duplex#pause - * @return {null} - */ - -/** - * This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream. - * @function external:Duplex#pipe - * @param {Writable} destination The destination for writing data - * @param {object} [options] Pipe options - * @return {null} - */ - -/** - * This method will remove the hooks set up for a previous pipe() call. - * @function external:Duplex#unpipe - * @param {Writable} [destination] The destination for writing data - * @return {null} - */ - -/** - * This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party. - * @function external:Duplex#unshift - * @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue. - * @return {null} - */ - -/** - * Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.) - * @function external:Duplex#wrap - * @param {Stream} stream An "old style" readable stream. - * @return {null} - */ - -/** - * This method writes some data to the underlying system, and calls the supplied callback once the data has been fully handled. - * @function external:Duplex#write - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {boolean} - */ - -/** - * Call this method when no more data will be written to the stream. If supplied, the callback is attached as a listener on the finish event. - * @function external:Duplex#end - * @param {(string|Buffer)} chunk The data to write - * @param {string} encoding The encoding, if chunk is a String - * @param {function} callback Callback for when this chunk of data is flushed - * @return {null} - */ - -/** - * GridStoreStream stream data event, fired for each document in the cursor. - * - * @event GridStoreStream#data - * @type {object} - */ - -/** - * GridStoreStream stream end event - * - * @event GridStoreStream#end - * @type {null} - */ - -/** - * GridStoreStream stream close event - * - * @event GridStoreStream#close - * @type {null} - */ - -/** - * GridStoreStream stream readable event - * - * @event GridStoreStream#readable - * @type {null} - */ - -/** - * GridStoreStream stream drain event - * - * @event GridStoreStream#drain - * @type {null} - */ - -/** - * GridStoreStream stream finish event - * - * @event GridStoreStream#finish - * @type {null} - */ - -/** - * GridStoreStream stream pipe event - * - * @event GridStoreStream#pipe - * @type {null} - */ - -/** - * GridStoreStream stream unpipe event - * - * @event GridStoreStream#unpipe - * @type {null} - */ - -/** - * GridStoreStream stream error event - * - * @event GridStoreStream#error - * @type {null} - */ - -/** - * @ignore - */ -module.exports = GridStore; diff --git a/util/retroImporter/node_modules/mongodb/lib/metadata.js b/util/retroImporter/node_modules/mongodb/lib/metadata.js deleted file mode 100644 index 7dae562..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/metadata.js +++ /dev/null @@ -1,64 +0,0 @@ -var f = require('util').format; - -var Define = function(name, object, stream) { - this.name = name; - this.object = object; - this.stream = typeof stream == 'boolean' ? stream : false; - this.instrumentations = {}; -} - -Define.prototype.classMethod = function(name, options) { - var keys = Object.keys(options).sort(); - var key = generateKey(keys, options); - - // Add a list of instrumentations - if(this.instrumentations[key] == null) { - this.instrumentations[key] = { - methods: [], options: options - } - } - - // Push to list of method for this instrumentation - this.instrumentations[key].methods.push(name); -} - -var generateKey = function(keys, options) { - var parts = []; - for(var i = 0; i < keys.length; i++) { - parts.push(f('%s=%s', keys[i], options[keys[i]])); - } - - return parts.join(); -} - -Define.prototype.staticMethod = function(name, options) { - options.static = true; - var keys = Object.keys(options).sort(); - var key = generateKey(keys, options); - - // Add a list of instrumentations - if(this.instrumentations[key] == null) { - this.instrumentations[key] = { - methods: [], options: options - } - } - - // Push to list of method for this instrumentation - this.instrumentations[key].methods.push(name); -} - -Define.prototype.generate = function(keys, options) { - // Generate the return object - var object = { - name: this.name, obj: this.object, stream: this.stream, - instrumentations: [] - } - - for(var name in this.instrumentations) { - object.instrumentations.push(this.instrumentations[name]); - } - - return object; -} - -module.exports = Define; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/lib/mongo_client.js b/util/retroImporter/node_modules/mongodb/lib/mongo_client.js deleted file mode 100644 index 3ce2ad6..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/mongo_client.js +++ /dev/null @@ -1,463 +0,0 @@ -"use strict"; - -var parse = require('./url_parser') - , Server = require('./server') - , Mongos = require('./mongos') - , ReplSet = require('./replset') - , Define = require('./metadata') - , ReadPreference = require('./read_preference') - , Db = require('./db'); - -/** - * @fileOverview The **MongoClient** class is a class that allows for making Connections to MongoDB. - * - * @example - * var MongoClient = require('mongodb').MongoClient, - * test = require('assert'); - * // Connection url - * var url = 'mongodb://localhost:27017/test'; - * // Connect using MongoClient - * MongoClient.connect(url, function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - -/** - * Creates a new MongoClient instance - * @class - * @return {MongoClient} a MongoClient instance. - */ -function MongoClient() { - /** - * The callback format for results - * @callback MongoClient~connectCallback - * @param {MongoError} error An error instance representing the error during the execution. - * @param {Db} db The connected database. - */ - - /** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @param {string} url The connection URI string - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication - * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** - * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** - * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** - * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ - this.connect = MongoClient.connect; -} - -var define = MongoClient.define = new Define('MongoClient', MongoClient, false); - -/** - * Connect to MongoDB using a url as documented at - * - * docs.mongodb.org/manual/reference/connection-string/ - * - * Note that for replicasets the replicaSet query parameter is required in the 2.0 driver - * - * @method - * @static - * @param {string} url The connection URI string - * @param {object} [options=null] Optional settings. - * @param {boolean} [options.uri_decode_auth=false] Uri decode the user name and password for authentication - * @param {object} [options.db=null] A hash of options to set on the db object, see **Db constructor** - * @param {object} [options.server=null] A hash of options to set on the server objects, see **Server** constructor** - * @param {object} [options.replSet=null] A hash of options to set on the replSet object, see **ReplSet** constructor** - * @param {object} [options.mongos=null] A hash of options to set on the mongos object, see **Mongos** constructor** - * @param {object} [options.promiseLibrary=null] A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible - * @param {MongoClient~connectCallback} [callback] The command result callback - * @return {Promise} returns Promise if no callback passed - */ -MongoClient.connect = function(url, options, callback) { - var args = Array.prototype.slice.call(arguments, 1); - callback = typeof args[args.length - 1] == 'function' ? args.pop() : null; - options = args.length ? args.shift() : null; - options = options || {}; - - // Get the promiseLibrary - var promiseLibrary = options.promiseLibrary; - - // No promise library selected fall back - if(!promiseLibrary) { - promiseLibrary = typeof global.Promise == 'function' ? - global.Promise : require('es6-promise').Promise; - } - - // Return a promise - if(typeof callback != 'function') { - return new promiseLibrary(function(resolve, reject) { - connect(url, options, function(err, db) { - if(err) return reject(err); - resolve(db); - }); - }); - } - - // Fallback to callback based connect - connect(url, options, callback); -} - -define.staticMethod('connect', {callback: true, promise:true}); - -var connect = function(url, options, callback) { - var serverOptions = options.server || {}; - var mongosOptions = options.mongos || {}; - var replSetServersOptions = options.replSet || options.replSetServers || {}; - var dbOptions = options.db || {}; - - // If callback is null throw an exception - if(callback == null) - throw new Error("no callback function provided"); - - // Parse the string - var object = parse(url, options); - - // Merge in any options for db in options object - if(dbOptions) { - for(var name in dbOptions) object.db_options[name] = dbOptions[name]; - } - - // Added the url to the options - object.db_options.url = url; - - // Merge in any options for server in options object - if(serverOptions) { - for(var name in serverOptions) object.server_options[name] = serverOptions[name]; - } - - // Merge in any replicaset server options - if(replSetServersOptions) { - for(var name in replSetServersOptions) object.rs_options[name] = replSetServersOptions[name]; - } - - if(replSetServersOptions.ssl - || replSetServersOptions.sslValidate - || replSetServersOptions.sslCA - || replSetServersOptions.sslCert - || replSetServersOptions.sslKey - || replSetServersOptions.sslPass) { - object.server_options.ssl = replSetServersOptions.ssl; - object.server_options.sslValidate = replSetServersOptions.sslValidate; - object.server_options.sslCA = replSetServersOptions.sslCA; - object.server_options.sslCert = replSetServersOptions.sslCert; - object.server_options.sslKey = replSetServersOptions.sslKey; - object.server_options.sslPass = replSetServersOptions.sslPass; - } - - // Merge in any replicaset server options - if(mongosOptions) { - for(var name in mongosOptions) object.mongos_options[name] = mongosOptions[name]; - } - - if(typeof object.server_options.poolSize == 'number') { - if(!object.mongos_options.poolSize) object.mongos_options.poolSize = object.server_options.poolSize; - if(!object.rs_options.poolSize) object.rs_options.poolSize = object.server_options.poolSize; - } - - if(mongosOptions.ssl - || mongosOptions.sslValidate - || mongosOptions.sslCA - || mongosOptions.sslCert - || mongosOptions.sslKey - || mongosOptions.sslPass) { - object.server_options.ssl = mongosOptions.ssl; - object.server_options.sslValidate = mongosOptions.sslValidate; - object.server_options.sslCA = mongosOptions.sslCA; - object.server_options.sslCert = mongosOptions.sslCert; - object.server_options.sslKey = mongosOptions.sslKey; - object.server_options.sslPass = mongosOptions.sslPass; - } - - // Set the promise library - object.db_options.promiseLibrary = options.promiseLibrary; - - // We need to ensure that the list of servers are only either direct members or mongos - // they cannot be a mix of monogs and mongod's - var totalNumberOfServers = object.servers.length; - var totalNumberOfMongosServers = 0; - var totalNumberOfMongodServers = 0; - var serverConfig = null; - var errorServers = {}; - - // Failure modes - if(object.servers.length == 0) throw new Error("connection string must contain at least one seed host"); - - // If we have no db setting for the native parser try to set the c++ one first - object.db_options.native_parser = _setNativeParser(object.db_options); - // If no auto_reconnect is set, set it to true as default for single servers - if(typeof object.server_options.auto_reconnect != 'boolean') { - object.server_options.auto_reconnect = true; - } - - // If we have more than a server, it could be replicaset or mongos list - // need to verify that it's one or the other and fail if it's a mix - // Connect to all servers and run ismaster - for(var i = 0; i < object.servers.length; i++) { - // Set up socket options - var providedSocketOptions = object.server_options.socketOptions || {}; - - var _server_options = { - poolSize:1 - , socketOptions: { - connectTimeoutMS: providedSocketOptions.connectTimeoutMS || 30000 - , socketTimeoutMS: providedSocketOptions.socketTimeoutMS || 30000 - } - , auto_reconnect:false}; - - // Ensure we have ssl setup for the servers - if(object.server_options.ssl) { - _server_options.ssl = object.server_options.ssl; - _server_options.sslValidate = object.server_options.sslValidate; - _server_options.sslCA = object.server_options.sslCA; - _server_options.sslCert = object.server_options.sslCert; - _server_options.sslKey = object.server_options.sslKey; - _server_options.sslPass = object.server_options.sslPass; - } else if(object.rs_options.ssl) { - _server_options.ssl = object.rs_options.ssl; - _server_options.sslValidate = object.rs_options.sslValidate; - _server_options.sslCA = object.rs_options.sslCA; - _server_options.sslCert = object.rs_options.sslCert; - _server_options.sslKey = object.rs_options.sslKey; - _server_options.sslPass = object.rs_options.sslPass; - } - - // Error - var error = null; - // Set up the Server object - var _server = object.servers[i].domain_socket - ? new Server(object.servers[i].domain_socket, _server_options) - : new Server(object.servers[i].host, object.servers[i].port, _server_options); - - var connectFunction = function(__server) { - // Attempt connect - new Db(object.dbName, __server, {w:1, native_parser:false, promiseLibrary:options.promiseLibrary}).open(function(err, db) { - // Update number of servers - totalNumberOfServers = totalNumberOfServers - 1; - - // If no error do the correct checks - if(!err) { - // Close the connection - db.close(); - var isMasterDoc = db.serverConfig.isMasterDoc; - - // Check what type of server we have - if(isMasterDoc.setName) { - totalNumberOfMongodServers++; - } - - if(isMasterDoc.msg && isMasterDoc.msg == "isdbgrid") totalNumberOfMongosServers++; - } else { - error = err; - errorServers[__server.host + ":" + __server.port] = __server; - } - - if(totalNumberOfServers == 0) { - // Error out - if(totalNumberOfMongodServers == 0 && totalNumberOfMongosServers == 0 && error) { - return callback(error, null); - } - - // If we have a mix of mongod and mongos, throw an error - if(totalNumberOfMongosServers > 0 && totalNumberOfMongodServers > 0) { - if(db) db.close(); - return process.nextTick(function() { - try { - callback(new Error("cannot combine a list of replicaset seeds and mongos seeds")); - } catch (err) { - throw err - } - }) - } - - if(totalNumberOfMongodServers == 0 - && totalNumberOfMongosServers == 0 - && object.servers.length == 1 - && (!object.rs_options.replicaSet || !object.rs_options.rs_name)) { - - var obj = object.servers[0]; - serverConfig = obj.domain_socket ? - new Server(obj.domain_socket, object.server_options) - : new Server(obj.host, obj.port, object.server_options); - - } else if(totalNumberOfMongodServers > 0 - || totalNumberOfMongosServers > 0 - || object.rs_options.replicaSet || object.rs_options.rs_name) { - - var finalServers = object.servers - .filter(function(serverObj) { - return errorServers[serverObj.host + ":" + serverObj.port] == null; - }) - .map(function(serverObj) { - return new Server(serverObj.host, serverObj.port, object.server_options); - }); - - // Clean out any error servers - errorServers = {}; - - // Set up the final configuration - if(totalNumberOfMongodServers > 0) { - try { - - // If no replicaset name was provided, we wish to perform a - // direct connection - if(totalNumberOfMongodServers == 1 - && (!object.rs_options.replicaSet && !object.rs_options.rs_name)) { - serverConfig = finalServers[0]; - } else if(totalNumberOfMongodServers == 1) { - object.rs_options.replicaSet = object.rs_options.replicaSet || object.rs_options.rs_name; - serverConfig = new ReplSet(finalServers, object.rs_options); - } else { - serverConfig = new ReplSet(finalServers, object.rs_options); - } - - } catch(err) { - return callback(err, null); - } - } else { - serverConfig = new Mongos(finalServers, object.mongos_options); - } - } - - if(serverConfig == null) { - return process.nextTick(function() { - try { - callback(new Error("Could not locate any valid servers in initial seed list")); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - - // Ensure no firing of open event before we are ready - serverConfig.emitOpen = false; - // Set up all options etc and connect to the database - _finishConnecting(serverConfig, object, options, callback) - } - }); - } - - // Wrap the context of the call - connectFunction(_server); - } -} - -var _setNativeParser = function(db_options) { - if(typeof db_options.native_parser == 'boolean') return db_options.native_parser; - - try { - require('mongodb-core').BSON.BSONNative.BSON; - return true; - } catch(err) { - return false; - } -} - -var _finishConnecting = function(serverConfig, object, options, callback) { - // If we have a readPreference passed in by the db options - if(typeof object.db_options.readPreference == 'string') { - object.db_options.readPreference = new ReadPreference(object.db_options.readPreference); - } else if(typeof object.db_options.read_preference == 'string') { - object.db_options.readPreference = new ReadPreference(object.db_options.read_preference); - } - - // Do we have readPreference tags - if(object.db_options.readPreference && object.db_options.readPreferenceTags) { - object.db_options.readPreference.tags = object.db_options.readPreferenceTags; - } else if(object.db_options.readPreference && object.db_options.read_preference_tags) { - object.db_options.readPreference.tags = object.db_options.read_preference_tags; - } - - // Get the socketTimeoutMS - var socketTimeoutMS = object.server_options.socketOptions.socketTimeoutMS || 0; - - // If we have a replset, override with replicaset socket timeout option if available - if(serverConfig instanceof ReplSet) { - socketTimeoutMS = object.rs_options.socketOptions.socketTimeoutMS || socketTimeoutMS; - } - - // Set socketTimeout to the same as the connectTimeoutMS or 30 sec - serverConfig.connectTimeoutMS = serverConfig.connectTimeoutMS || 30000; - serverConfig.socketTimeoutMS = serverConfig.connectTimeoutMS; - - // Set up the db options - var db = new Db(object.dbName, serverConfig, object.db_options); - // Open the db - db.open(function(err, db){ - - if(err) { - return process.nextTick(function() { - try { - callback(err, null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - - // Reset the socket timeout - serverConfig.socketTimeoutMS = socketTimeoutMS || 0; - - // Return object - if(err == null && object.auth){ - // What db to authenticate against - var authentication_db = db; - if(object.db_options && object.db_options.authSource) { - authentication_db = db.db(object.db_options.authSource); - } - - // Build options object - var options = {}; - if(object.db_options.authMechanism) options.authMechanism = object.db_options.authMechanism; - if(object.db_options.gssapiServiceName) options.gssapiServiceName = object.db_options.gssapiServiceName; - - // Authenticate - authentication_db.authenticate(object.auth.user, object.auth.password, options, function(err, success){ - if(success){ - process.nextTick(function() { - try { - callback(null, db); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } else { - if(db) db.close(); - process.nextTick(function() { - try { - callback(err ? err : new Error('Could not authenticate user ' + object.auth[0]), null); - } catch (err) { - if(db) db.close(); - throw err - } - }); - } - }); - } else { - process.nextTick(function() { - try { - callback(err, db); - } catch (err) { - if(db) db.close(); - throw err - } - }) - } - }); -} - -module.exports = MongoClient diff --git a/util/retroImporter/node_modules/mongodb/lib/mongos.js b/util/retroImporter/node_modules/mongodb/lib/mongos.js deleted file mode 100644 index 6087d76..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/mongos.js +++ /dev/null @@ -1,491 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , f = require('util').format - , ServerCapabilities = require('./topology_base').ServerCapabilities - , MongoCR = require('mongodb-core').MongoCR - , CMongos = require('mongodb-core').Mongos - , Cursor = require('./cursor') - , AggregationCursor = require('./aggregation_cursor') - , CommandCursor = require('./command_cursor') - , Define = require('./metadata') - , Server = require('./server') - , Store = require('./topology_base').Store - , shallowClone = require('./utils').shallowClone; - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * **Mongos Should not be used, use MongoClient.connect** - * @example - * var Db = require('mongodb').Db, - * Mongos = require('mongodb').Mongos, - * Server = require('mongodb').Server, - * test = require('assert'); - * // Connect using Mongos - * var server = new Server('localhost', 27017); - * var db = new Db('test', new Mongos([server])); - * db.open(function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - -/** - * Creates a new Mongos instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options=null] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {object} [options.socketOptions=null] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @fires Mongos#connect - * @fires Mongos#ha - * @fires Mongos#joined - * @fires Mongos#left - * @fires Mongos#fullsetup - * @fires Mongos#open - * @fires Mongos#close - * @fires Mongos#error - * @fires Mongos#timeout - * @fires Mongos#parseError - * @return {Mongos} a Mongos instance. - */ -var Mongos = function(servers, options) { - if(!(this instanceof Mongos)) return new Mongos(servers, options); - options = options || {}; - var self = this; - - // Ensure all the instances are Server - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) { - throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); - } - } - - // Store option defaults - var storeOptions = { - force: false - , bufferMaxEntries: -1 - } - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Set up event emitter - EventEmitter.call(this); - - // Debug tag - var tag = options.tag; - - // Build seed list - var seedlist = servers.map(function(x) { - return {host: x.host, port: x.port} - }); - - // Final options - var finalOptions = shallowClone(options); - - // Default values - finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; - finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; - finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; - finalOptions.cursorFactory = Cursor; - - // Add the store - finalOptions.disconnectHandler = store; - - // Ensure we change the sslCA option to ca if available - if(options.sslCA) finalOptions.ca = options.sslCA; - if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; - if(options.sslKey) finalOptions.key = options.sslKey; - if(options.sslCert) finalOptions.cert = options.sslCert; - if(options.sslPass) finalOptions.passphrase = options.sslPass; - - // Socket options passed down - if(options.socketOptions) { - if(options.socketOptions.connectTimeoutMS) { - this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; - finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; - } - if(options.socketOptions.socketTimeoutMS) - finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; - } - - // Are we running in debug mode - var debug = typeof options.debug == 'boolean' ? options.debug : false; - if(debug) { - finalOptions.debug = debug; - } - - // Map keep alive setting - if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { - finalOptions.keepAlive = true; - if(typeof options.socketOptions.keepAlive == 'number') { - finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; - } - } - - // Connection timeout - if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { - finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; - } - - // Socket timeout - if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { - finalOptions.socketTimeout = options.socketOptions.socketTimeout; - } - - // noDelay - if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { - finalOptions.noDelay = options.socketOptions.noDelay; - } - - if(typeof options.secondaryAcceptableLatencyMS == 'number') { - finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; - } - - // Add the non connection store - finalOptions.disconnectHandler = store; - - // Create the Mongos - var mongos = new CMongos(seedlist, finalOptions) - // Server capabilities - var sCapabilities = null; - // Add auth prbufferMaxEntriesoviders - mongos.addAuthProvider('mongocr', new MongoCR()); - - // Internal state - this.s = { - // Create the Mongos - mongos: mongos - // Server capabilities - , sCapabilities: sCapabilities - // Debug turned on - , debug: debug - // Store option defaults - , storeOptions: storeOptions - // Cloned options - , clonedOptions: finalOptions - // Actual store of callbacks - , store: store - // Options - , options: options - } - - - // Last ismaster - Object.defineProperty(this, 'isMasterDoc', { - enumerable:true, get: function() { return self.s.mongos.lastIsMaster(); } - }); - - // Last ismaster - Object.defineProperty(this, 'numberOfConnectedServers', { - enumerable:true, get: function() { - return self.s.mongos.s.mongosState.connectedServers().length; - } - }); - - // BSON property - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - return self.s.mongos.bson; - } - }); - - Object.defineProperty(this, 'haInterval', { - enumerable:true, get: function() { return self.s.mongos.haInterval; } - }); -} - -/** - * @ignore - */ -inherits(Mongos, EventEmitter); - -var define = Mongos.define = new Define('Mongos', Mongos, false); - -// Connect -Mongos.prototype.connect = function(db, _options, callback) { - var self = this; - if('function' === typeof _options) callback = _options, _options = {}; - if(_options == null) _options = {}; - if(!('function' === typeof callback)) callback = null; - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; - - // Error handler - var connectErrorHandler = function(event) { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.removeListener(e, connectErrorHandler); - }); - - self.s.mongos.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - } - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if(event != 'error') { - self.emit(event, err); - } - } - } - - // Error handler - var reconnectHandler = function(err) { - self.emit('reconnect'); - self.s.store.execute(); - } - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ["timeout", "error", "close"].forEach(function(e) { - self.s.mongos.removeAllListeners(e); - }); - - // Set up listeners - self.s.mongos.once('timeout', errorHandler('timeout')); - self.s.mongos.once('error', errorHandler('error')); - self.s.mongos.once('close', errorHandler('close')); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - } - } - - // Set up serverConfig listeners - self.s.mongos.on('joined', relay('joined')); - self.s.mongos.on('left', relay('left')); - self.s.mongos.on('fullsetup', relay('fullsetup')); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - - // Set up listeners - self.s.mongos.once('timeout', connectErrorHandler('timeout')); - self.s.mongos.once('error', connectErrorHandler('error')); - self.s.mongos.once('close', connectErrorHandler('close')); - self.s.mongos.once('connect', connectHandler); - // Reconnect server - self.s.mongos.on('reconnect', reconnectHandler); - - // Start connection - self.s.mongos.connect(_options); -} - -Mongos.prototype.parserType = function() { - return this.s.mongos.parserType(); -} - -define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); - -// Server capabilities -Mongos.prototype.capabilities = function() { - if(this.s.sCapabilities) return this.s.sCapabilities; - if(this.s.mongos.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); - this.s.sCapabilities = new ServerCapabilities(this.s.mongos.lastIsMaster()); - return this.s.sCapabilities; -} - -define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); - -// Command -Mongos.prototype.command = function(ns, cmd, options, callback) { - this.s.mongos.command(ns, cmd, options, callback); -} - -define.classMethod('command', {callback: true, promise:false}); - -// Insert -Mongos.prototype.insert = function(ns, ops, options, callback) { - this.s.mongos.insert(ns, ops, options, function(e, m) { - callback(e, m) - }); -} - -define.classMethod('insert', {callback: true, promise:false}); - -// Update -Mongos.prototype.update = function(ns, ops, options, callback) { - this.s.mongos.update(ns, ops, options, callback); -} - -define.classMethod('update', {callback: true, promise:false}); - -// Remove -Mongos.prototype.remove = function(ns, ops, options, callback) { - this.s.mongos.remove(ns, ops, options, callback); -} - -define.classMethod('remove', {callback: true, promise:false}); - -// IsConnected -Mongos.prototype.isConnected = function() { - return this.s.mongos.isConnected(); -} - -define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); - -// Insert -Mongos.prototype.cursor = function(ns, cmd, options) { - options.disconnectHandler = this.s.store; - return this.s.mongos.cursor(ns, cmd, options); -} - -define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); - -Mongos.prototype.setBSONParserType = function(type) { - return this.s.mongos.setBSONParserType(type); -} - -Mongos.prototype.lastIsMaster = function() { - return this.s.mongos.lastIsMaster(); -} - -Mongos.prototype.close = function(forceClosed) { - this.s.mongos.destroy(); - // We need to wash out all stored processes - if(forceClosed == true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } -} - -define.classMethod('close', {callback: false, promise:false}); - -Mongos.prototype.auth = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.mongos.auth.apply(this.s.mongos, args); -} - -define.classMethod('auth', {callback: true, promise:false}); - -/** - * All raw connections - * @method - * @return {array} - */ -Mongos.prototype.connections = function() { - return this.s.mongos.connections(); -} - -define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * The mongos high availability event - * - * @event Mongos#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the mongos set - * - * @event Mongos#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos set - * - * @event Mongos#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * Mongos fullsetup event, emitted when all proxies in the topology have been connected to. - * - * @event Mongos#fullsetup - * @type {Mongos} - */ - -/** - * Mongos open event, emitted when mongos can start processing commands. - * - * @event Mongos#open - * @type {Mongos} - */ - -/** - * Mongos close event - * - * @event Mongos#close - * @type {object} - */ - -/** - * Mongos error event, emitted if there is an error listener. - * - * @event Mongos#error - * @type {MongoError} - */ - -/** - * Mongos timeout event - * - * @event Mongos#timeout - * @type {object} - */ - -/** - * Mongos parseError event - * - * @event Mongos#parseError - * @type {object} - */ - -module.exports = Mongos; diff --git a/util/retroImporter/node_modules/mongodb/lib/read_preference.js b/util/retroImporter/node_modules/mongodb/lib/read_preference.js deleted file mode 100644 index 73b253a..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/read_preference.js +++ /dev/null @@ -1,104 +0,0 @@ -"use strict"; - -/** - * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * - * @example - * var Db = require('mongodb').Db, - * ReplSet = require('mongodb').ReplSet, - * Server = require('mongodb').Server, - * ReadPreference = require('mongodb').ReadPreference, - * test = require('assert'); - * // Connect using ReplSet - * var server = new Server('localhost', 27017); - * var db = new Db('test', new ReplSet([server])); - * db.open(function(err, db) { - * test.equal(null, err); - * // Perform a read - * var cursor = db.collection('t').find({}); - * cursor.setReadPreference(ReadPreference.PRIMARY); - * cursor.toArray(function(err, docs) { - * test.equal(null, err); - * db.close(); - * }); - * }); - */ - -/** - * Creates a new ReadPreference instance - * - * Read Preferences - * - **ReadPreference.PRIMARY**, Read from primary only. All operations produce an error (throw an exception where applicable) if primary is unavailable. Cannot be combined with tags (This is the default.). - * - **ReadPreference.PRIMARY_PREFERRED**, Read from primary if available, otherwise a secondary. - * - **ReadPreference.SECONDARY**, Read from secondary if available, otherwise error. - * - **ReadPreference.SECONDARY_PREFERRED**, Read from a secondary if available, otherwise read from the primary. - * - **ReadPreference.NEAREST**, All modes read from among the nearest candidates, but unlike other modes, NEAREST will include both the primary and all secondaries in the random selection. - * - * @class - * @param {string} mode The ReadPreference mode as listed above. - * @param {object} tags An object representing read preference tags. - * @property {string} mode The ReadPreference mode. - * @property {object} tags The ReadPreference tags. - * @return {ReadPreference} a ReadPreference instance. - */ -var ReadPreference = function(mode, tags) { - if(!(this instanceof ReadPreference)) - return new ReadPreference(mode, tags); - this._type = 'ReadPreference'; - this.mode = mode; - this.tags = tags; -} - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} - */ -ReadPreference.isValid = function(_mode) { - return (_mode == ReadPreference.PRIMARY || _mode == ReadPreference.PRIMARY_PREFERRED - || _mode == ReadPreference.SECONDARY || _mode == ReadPreference.SECONDARY_PREFERRED - || _mode == ReadPreference.NEAREST - || _mode == true || _mode == false || _mode == null); -} - -/** - * Validate if a mode is legal - * - * @method - * @param {string} mode The string representing the read preference mode. - * @return {boolean} - */ -ReadPreference.prototype.isValid = function(mode) { - var _mode = typeof mode == 'string' ? mode : this.mode; - return ReadPreference.isValid(_mode); -} - -/** - * @ignore - */ -ReadPreference.prototype.toObject = function() { - var object = {mode:this.mode}; - - if(this.tags != null) { - object['tags'] = this.tags; - } - - return object; -} - -/** - * @ignore - */ -ReadPreference.PRIMARY = 'primary'; -ReadPreference.PRIMARY_PREFERRED = 'primaryPreferred'; -ReadPreference.SECONDARY = 'secondary'; -ReadPreference.SECONDARY_PREFERRED = 'secondaryPreferred'; -ReadPreference.NEAREST = 'nearest' - -/** - * @ignore - */ -module.exports = ReadPreference; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/lib/replset.js b/util/retroImporter/node_modules/mongodb/lib/replset.js deleted file mode 100644 index 8a71b42..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/replset.js +++ /dev/null @@ -1,555 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , f = require('util').format - , Server = require('./server') - , Mongos = require('./mongos') - , Cursor = require('./cursor') - , AggregationCursor = require('./aggregation_cursor') - , CommandCursor = require('./command_cursor') - , ReadPreference = require('./read_preference') - , MongoCR = require('mongodb-core').MongoCR - , MongoError = require('mongodb-core').MongoError - , ServerCapabilities = require('./topology_base').ServerCapabilities - , Store = require('./topology_base').Store - , Define = require('./metadata') - , CServer = require('mongodb-core').Server - , CReplSet = require('mongodb-core').ReplSet - , CoreReadPreference = require('mongodb-core').ReadPreference - , shallowClone = require('./utils').shallowClone; - -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connections. - * - * **ReplSet Should not be used, use MongoClient.connect** - * @example - * var Db = require('mongodb').Db, - * ReplSet = require('mongodb').ReplSet, - * Server = require('mongodb').Server, - * test = require('assert'); - * // Connect using ReplSet - * var server = new Server('localhost', 27017); - * var db = new Db('test', new ReplSet([server])); - * db.open(function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - -/** - * Creates a new ReplSet instance - * @class - * @deprecated - * @param {Server[]} servers A seedlist of servers participating in the replicaset. - * @param {object} [options=null] Optional settings. - * @param {booelan} [options.ha=true] Turn on high availability monitoring. - * @param {number} [options.haInterval=5000] Time between each replicaset status check. - * @param {string} options.replicaSet The name of the replicaset to connect to. - * @param {number} [options.secondaryAcceptableLatencyMS=15] Sets the range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) - * @param {boolean} [options.connectWithNoPrimary=false] Sets if the driver should connect even if no primary is available - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {object} [options.socketOptions=null] Socket options - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - * @fires ReplSet#fullsetup - * @fires ReplSet#open - * @fires ReplSet#close - * @fires ReplSet#error - * @fires ReplSet#timeout - * @fires ReplSet#parseError - * @return {ReplSet} a ReplSet instance. - */ -var ReplSet = function(servers, options) { - if(!(this instanceof ReplSet)) return new ReplSet(servers, options); - options = options || {}; - var self = this; - - // Ensure all the instances are Server - for(var i = 0; i < servers.length; i++) { - if(!(servers[i] instanceof Server)) { - throw MongoError.create({message: "all seed list instances must be of the Server type", driver:true}); - } - } - - // Store option defaults - var storeOptions = { - force: false - , bufferMaxEntries: -1 - } - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Set up event emitter - EventEmitter.call(this); - - // Debug tag - var tag = options.tag; - - // Build seed list - var seedlist = servers.map(function(x) { - return {host: x.host, port: x.port} - }); - - // Final options - var finalOptions = shallowClone(options); - - // Default values - finalOptions.size = typeof options.poolSize == 'number' ? options.poolSize : 5; - finalOptions.reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; - finalOptions.emitError = typeof options.emitError == 'boolean' ? options.emitError : true; - finalOptions.cursorFactory = Cursor; - - // Add the store - finalOptions.disconnectHandler = store; - - // Socket options passed down - if(options.socketOptions) { - if(options.socketOptions.connectTimeoutMS) { - this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; - finalOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; - } - - if(options.socketOptions.socketTimeoutMS) { - finalOptions.socketTimeout = options.socketOptions.socketTimeoutMS; - } - } - - // Get the name - var replicaSet = options.replicaSet || options.rs_name; - - // Set up options - finalOptions.setName = replicaSet; - - // Are we running in debug mode - var debug = typeof options.debug == 'boolean' ? options.debug : false; - if(debug) { - finalOptions.debug = debug; - } - - // Map keep alive setting - if(options.socketOptions && typeof options.socketOptions.keepAlive == 'number') { - finalOptions.keepAlive = true; - if(typeof options.socketOptions.keepAlive == 'number') { - finalOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; - } - } - - // Connection timeout - if(options.socketOptions && typeof options.socketOptions.connectionTimeout == 'number') { - finalOptions.connectionTimeout = options.socketOptions.connectionTimeout; - } - - // Socket timeout - if(options.socketOptions && typeof options.socketOptions.socketTimeout == 'number') { - finalOptions.socketTimeout = options.socketOptions.socketTimeout; - } - - // noDelay - if(options.socketOptions && typeof options.socketOptions.noDelay == 'boolean') { - finalOptions.noDelay = options.socketOptions.noDelay; - } - - if(typeof options.secondaryAcceptableLatencyMS == 'number') { - finalOptions.acceptableLatency = options.secondaryAcceptableLatencyMS; - } - - if(options.connectWithNoPrimary == true) { - finalOptions.secondaryOnlyConnectionAllowed = true; - } - - // Add the non connection store - finalOptions.disconnectHandler = store; - - // Translate the options - if(options.sslCA) finalOptions.ca = options.sslCA; - if(typeof options.sslValidate == 'boolean') finalOptions.rejectUnauthorized = options.sslValidate; - if(options.sslKey) finalOptions.key = options.sslKey; - if(options.sslCert) finalOptions.cert = options.sslCert; - if(options.sslPass) finalOptions.passphrase = options.sslPass; - - // Create the ReplSet - var replset = new CReplSet(seedlist, finalOptions) - // Server capabilities - var sCapabilities = null; - // Add auth prbufferMaxEntriesoviders - replset.addAuthProvider('mongocr', new MongoCR()); - - // Listen to reconnect event - replset.on('reconnect', function() { - self.emit('reconnect'); - store.execute(); - }); - - // Internal state - this.s = { - // Replicaset - replset: replset - // Server capabilities - , sCapabilities: null - // Debug tag - , tag: options.tag - // Store options - , storeOptions: storeOptions - // Cloned options - , clonedOptions: finalOptions - // Store - , store: store - // Options - , options: options - } - - // Debug - if(debug) { - // Last ismaster - Object.defineProperty(this, 'replset', { - enumerable:true, get: function() { return replset; } - }); - } - - // Last ismaster - Object.defineProperty(this, 'isMasterDoc', { - enumerable:true, get: function() { return replset.lastIsMaster(); } - }); - - // BSON property - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - return replset.bson; - } - }); - - Object.defineProperty(this, 'haInterval', { - enumerable:true, get: function() { return replset.haInterval; } - }); -} - -/** - * @ignore - */ -inherits(ReplSet, EventEmitter); - -var define = ReplSet.define = new Define('ReplSet', ReplSet, false); - -// Ensure the right read Preference object -var translateReadPreference = function(options) { - if(typeof options.readPreference == 'string') { - options.readPreference = new CoreReadPreference(options.readPreference); - } else if(options.readPreference instanceof ReadPreference) { - options.readPreference = new CoreReadPreference(options.readPreference.mode - , options.readPreference.tags); - } - - return options; -} - -ReplSet.prototype.parserType = function() { - return this.s.replset.parserType(); -} - -define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); - -// Connect method -ReplSet.prototype.connect = function(db, _options, callback) { - var self = this; - if('function' === typeof _options) callback = _options, _options = {}; - if(_options == null) _options = {}; - if(!('function' === typeof callback)) callback = null; - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if(event != 'error') { - self.emit(event, err); - } - } - } - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ["timeout", "error", "close"].forEach(function(e) { - self.s.replset.removeAllListeners(e); - }); - - // Set up listeners - self.s.replset.once('timeout', errorHandler('timeout')); - self.s.replset.once('error', errorHandler('error')); - self.s.replset.once('close', errorHandler('close')); - - // relay the event - var relay = function(event) { - return function(t, server) { - self.emit(event, t, server); - } - } - - // Replset events relay - var replsetRelay = function(event) { - return function(t, server) { - self.emit(event, t, server.lastIsMaster(), server); - } - } - - // Relay ha - var relayHa = function(t, state) { - self.emit('ha', t, state); - - if(t == 'start') { - self.emit('ha_connect', t, state); - } else if(t == 'end') { - self.emit('ha_ismaster', t, state); - } - } - - // Set up serverConfig listeners - self.s.replset.on('joined', replsetRelay('joined')); - self.s.replset.on('left', relay('left')); - self.s.replset.on('ping', relay('ping')); - self.s.replset.on('ha', relayHa); - - self.s.replset.on('fullsetup', function(topology) { - self.emit('fullsetup', null, self); - }); - - self.s.replset.on('all', function(topology) { - self.emit('all', null, self); - }); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - - // Error handler - var connectErrorHandler = function(event) { - return function(err) { - ['timeout', 'error', 'close'].forEach(function(e) { - self.s.replset.removeListener(e, connectErrorHandler); - }); - - self.s.replset.removeListener('connect', connectErrorHandler); - // Destroy the replset - self.s.replset.destroy(); - - // Try to callback - try { - callback(err); - } catch(err) { - if(!self.s.replset.isConnected()) - process.nextTick(function() { throw err; }) - } - } - } - - // Set up listeners - self.s.replset.once('timeout', connectErrorHandler('timeout')); - self.s.replset.once('error', connectErrorHandler('error')); - self.s.replset.once('close', connectErrorHandler('close')); - self.s.replset.once('connect', connectHandler); - - // Start connection - self.s.replset.connect(_options); -} - -// Server capabilities -ReplSet.prototype.capabilities = function() { - if(this.s.sCapabilities) return this.s.sCapabilities; - if(this.s.replset.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); - this.s.sCapabilities = new ServerCapabilities(this.s.replset.lastIsMaster()); - return this.s.sCapabilities; -} - -define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); - -// Command -ReplSet.prototype.command = function(ns, cmd, options, callback) { - options = translateReadPreference(options); - this.s.replset.command(ns, cmd, options, callback); -} - -define.classMethod('command', {callback: true, promise:false}); - -// Insert -ReplSet.prototype.insert = function(ns, ops, options, callback) { - this.s.replset.insert(ns, ops, options, callback); -} - -define.classMethod('insert', {callback: true, promise:false}); - -// Update -ReplSet.prototype.update = function(ns, ops, options, callback) { - this.s.replset.update(ns, ops, options, callback); -} - -define.classMethod('update', {callback: true, promise:false}); - -// Remove -ReplSet.prototype.remove = function(ns, ops, options, callback) { - this.s.replset.remove(ns, ops, options, callback); -} - -define.classMethod('remove', {callback: true, promise:false}); - -// IsConnected -ReplSet.prototype.isConnected = function() { - return this.s.replset.isConnected(); -} - -define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); - -ReplSet.prototype.setBSONParserType = function(type) { - return this.s.replset.setBSONParserType(type); -} - -// Insert -ReplSet.prototype.cursor = function(ns, cmd, options) { - options = translateReadPreference(options); - options.disconnectHandler = this.s.store; - return this.s.replset.cursor(ns, cmd, options); -} - -define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); - -ReplSet.prototype.lastIsMaster = function() { - return this.s.replset.lastIsMaster(); -} - -ReplSet.prototype.close = function(forceClosed) { - var self = this; - this.s.replset.destroy(); - // We need to wash out all stored processes - if(forceClosed == true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } - - var events = ['timeout', 'error', 'close', 'joined', 'left']; - events.forEach(function(e) { - self.removeAllListeners(e); - }); -} - -define.classMethod('close', {callback: false, promise:false}); - -ReplSet.prototype.auth = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.replset.auth.apply(this.s.replset, args); -} - -define.classMethod('auth', {callback: true, promise:false}); - -/** - * All raw connections - * @method - * @return {array} - */ -ReplSet.prototype.connections = function() { - return this.s.replset.connections(); -} - -define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -/** - * ReplSet open event, emitted when replicaset can start processing commands. - * - * @event ReplSet#open - * @type {Replset} - */ - -/** - * ReplSet fullsetup event, emitted when all servers in the topology have been connected to. - * - * @event ReplSet#fullsetup - * @type {Replset} - */ - -/** - * ReplSet close event - * - * @event ReplSet#close - * @type {object} - */ - -/** - * ReplSet error event, emitted if there is an error listener. - * - * @event ReplSet#error - * @type {MongoError} - */ - -/** - * ReplSet timeout event - * - * @event ReplSet#timeout - * @type {object} - */ - -/** - * ReplSet parseError event - * - * @event ReplSet#parseError - * @type {object} - */ - -module.exports = ReplSet; diff --git a/util/retroImporter/node_modules/mongodb/lib/server.js b/util/retroImporter/node_modules/mongodb/lib/server.js deleted file mode 100644 index eff7771..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/server.js +++ /dev/null @@ -1,437 +0,0 @@ -"use strict"; - -var EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , CServer = require('mongodb-core').Server - , Cursor = require('./cursor') - , AggregationCursor = require('./aggregation_cursor') - , CommandCursor = require('./command_cursor') - , f = require('util').format - , ServerCapabilities = require('./topology_base').ServerCapabilities - , Store = require('./topology_base').Store - , Define = require('./metadata') - , MongoError = require('mongodb-core').MongoError - , shallowClone = require('./utils').shallowClone; - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * **Server Should not be used, use MongoClient.connect** - * @example - * var Db = require('mongodb').Db, - * Server = require('mongodb').Server, - * test = require('assert'); - * // Connect using single Server - * var db = new Db('test', new Server('localhost', 27017);); - * db.open(function(err, db) { - * // Get an additional db - * db.close(); - * }); - */ - -/** - * Creates a new Server instance - * @class - * @deprecated - * @param {string} host The host for the server, can be either an IP4, IP6 or domain socket style host. - * @param {number} [port] The server port if IP4. - * @param {object} [options=null] Optional settings. - * @param {number} [options.poolSize=5] Number of connections in the connection pool for each server instance, set to 5 as default for legacy reasons. - * @param {boolean} [options.ssl=false] Use ssl connection (needs to have a mongod server with ssl support) - * @param {object} [options.sslValidate=true] Validate mongod server certificate against ca (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {array} [options.sslCA=null] Array of valid certificates either as Buffers or Strings (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslCert=null] String or buffer containing the certificate we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslKey=null] String or buffer containing the certificate private key we wish to present (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {(Buffer|string)} [options.sslPass=null] String or buffer containing the certificate password (needs to have a mongod server with ssl support, 2.4 or higher) - * @param {object} [options.socketOptions=null] Socket options - * @param {boolean} [options.socketOptions.autoReconnect=false] Reconnect on error. - * @param {boolean} [options.socketOptions.noDelay=true] TCP Socket NoDelay option. - * @param {number} [options.socketOptions.keepAlive=0] TCP KeepAlive on the socket with a X ms delay before start. - * @param {number} [options.socketOptions.connectTimeoutMS=0] TCP Connection timeout setting - * @param {number} [options.socketOptions.socketTimeoutMS=0] TCP Socket timeout setting - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - * @return {Server} a Server instance. - */ -var Server = function(host, port, options) { - options = options || {}; - if(!(this instanceof Server)) return new Server(host, port, options); - EventEmitter.call(this); - var self = this; - - // Store option defaults - var storeOptions = { - force: false - , bufferMaxEntries: -1 - } - - // Shared global store - var store = options.store || new Store(self, storeOptions); - - // Detect if we have a socket connection - if(host.indexOf('\/') != -1) { - if(port != null && typeof port == 'object') { - options = port; - port = null; - } - } else if(port == null) { - throw MongoError.create({message: 'port must be specified', driver:true}); - } - - // Clone options - var clonedOptions = shallowClone(options); - clonedOptions.host = host; - clonedOptions.port = port; - - // Reconnect - var reconnect = typeof options.auto_reconnect == 'boolean' ? options.auto_reconnect : true; - reconnect = typeof options.autoReconnect == 'boolean' ? options.autoReconnect : reconnect; - var emitError = typeof options.emitError == 'boolean' ? options.emitError : true; - var poolSize = typeof options.poolSize == 'number' ? options.poolSize : 5; - - // Socket options passed down - if(options.socketOptions) { - if(options.socketOptions.connectTimeoutMS) { - this.connectTimeoutMS = options.socketOptions.connectTimeoutMS; - clonedOptions.connectionTimeout = options.socketOptions.connectTimeoutMS; - } - - if(options.socketOptions.socketTimeoutMS) { - clonedOptions.socketTimeout = options.socketOptions.socketTimeoutMS; - } - - if(typeof options.socketOptions.keepAlive == 'number') { - clonedOptions.keepAliveInitialDelay = options.socketOptions.keepAlive; - clonedOptions.keepAlive = true; - } - - if(typeof options.socketOptions.noDelay == 'boolean') { - clonedOptions.noDelay = options.socketOptions.noDelay; - } - } - - // Add the cursor factory function - clonedOptions.cursorFactory = Cursor; - clonedOptions.reconnect = reconnect; - clonedOptions.emitError = emitError; - clonedOptions.size = poolSize; - - // Translate the options - if(clonedOptions.sslCA) clonedOptions.ca = clonedOptions.sslCA; - if(typeof clonedOptions.sslValidate == 'boolean') clonedOptions.rejectUnauthorized = clonedOptions.sslValidate; - if(clonedOptions.sslKey) clonedOptions.key = clonedOptions.sslKey; - if(clonedOptions.sslCert) clonedOptions.cert = clonedOptions.sslCert; - if(clonedOptions.sslPass) clonedOptions.passphrase = clonedOptions.sslPass; - - // Add the non connection store - clonedOptions.disconnectHandler = store; - - // Create an instance of a server instance from mongodb-core - var server = new CServer(clonedOptions); - // Server capabilities - var sCapabilities = null; - - // Define the internal properties - this.s = { - // Create an instance of a server instance from mongodb-core - server: server - // Server capabilities - , sCapabilities: null - // Cloned options - , clonedOptions: clonedOptions - // Reconnect - , reconnect: reconnect - // Emit error - , emitError: emitError - // Pool size - , poolSize: poolSize - // Store Options - , storeOptions: storeOptions - // Store - , store: store - // Host - , host: host - // Port - , port: port - // Options - , options: options - } - - // BSON property - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - return self.s.server.bson; - } - }); - - // Last ismaster - Object.defineProperty(this, 'isMasterDoc', { - enumerable:true, get: function() { - return self.s.server.lastIsMaster(); - } - }); - - // Last ismaster - Object.defineProperty(this, 'poolSize', { - enumerable:true, get: function() { return self.s.server.connections().length; } - }); - - Object.defineProperty(this, 'autoReconnect', { - enumerable:true, get: function() { return self.s.reconnect; } - }); - - Object.defineProperty(this, 'host', { - enumerable:true, get: function() { return self.s.host; } - }); - - Object.defineProperty(this, 'port', { - enumerable:true, get: function() { return self.s.port; } - }); -} - -inherits(Server, EventEmitter); - -var define = Server.define = new Define('Server', Server, false); - -Server.prototype.parserType = function() { - return this.s.server.parserType(); -} - -define.classMethod('parserType', {callback: false, promise:false, returns: [String]}); - -// Connect -Server.prototype.connect = function(db, _options, callback) { - var self = this; - if('function' === typeof _options) callback = _options, _options = {}; - if(_options == null) _options = {}; - if(!('function' === typeof callback)) callback = null; - self.s.options = _options; - - // Update bufferMaxEntries - self.s.storeOptions.bufferMaxEntries = db.bufferMaxEntries; - - // Error handler - var connectErrorHandler = function(event) { - return function(err) { - // Remove all event handlers - var events = ['timeout', 'error', 'close']; - events.forEach(function(e) { - self.s.server.removeListener(e, connectHandlers[e]); - }); - - self.s.server.removeListener('connect', connectErrorHandler); - - // Try to callback - try { - callback(err); - } catch(err) { - process.nextTick(function() { throw err; }) - } - } - } - - // Actual handler - var errorHandler = function(event) { - return function(err) { - if(event != 'error') { - self.emit(event, err); - } - } - } - - // Error handler - var reconnectHandler = function(err) { - self.emit('reconnect', self); - self.s.store.execute(); - } - - // Destroy called on topology, perform cleanup - var destroyHandler = function() { - self.s.store.flush(); - } - - // Connect handler - var connectHandler = function() { - // Clear out all the current handlers left over - ["timeout", "error", "close"].forEach(function(e) { - self.s.server.removeAllListeners(e); - }); - - // Set up listeners - self.s.server.once('timeout', errorHandler('timeout')); - self.s.server.once('error', errorHandler('error')); - self.s.server.on('close', errorHandler('close')); - // Only called on destroy - self.s.server.once('destroy', destroyHandler); - - // Emit open event - self.emit('open', null, self); - - // Return correctly - try { - callback(null, self); - } catch(err) { - console.log(err.stack) - process.nextTick(function() { throw err; }) - } - } - - // Set up listeners - var connectHandlers = { - timeout: connectErrorHandler('timeout'), - error: connectErrorHandler('error'), - close: connectErrorHandler('close') - }; - - // Add the event handlers - self.s.server.once('timeout', connectHandlers.timeout); - self.s.server.once('error', connectHandlers.error); - self.s.server.once('close', connectHandlers.close); - self.s.server.once('connect', connectHandler); - // Reconnect server - self.s.server.on('reconnect', reconnectHandler); - - // Start connection - self.s.server.connect(_options); -} - -// Server capabilities -Server.prototype.capabilities = function() { - if(this.s.sCapabilities) return this.s.sCapabilities; - if(this.s.server.lastIsMaster() == null) throw MongoError.create({message: 'cannot establish topology capabilities as driver is still in process of connecting', driver:true}); - this.s.sCapabilities = new ServerCapabilities(this.s.server.lastIsMaster()); - return this.s.sCapabilities; -} - -define.classMethod('capabilities', {callback: false, promise:false, returns: [ServerCapabilities]}); - -// Command -Server.prototype.command = function(ns, cmd, options, callback) { - this.s.server.command(ns, cmd, options, callback); -} - -define.classMethod('command', {callback: true, promise:false}); - -// Insert -Server.prototype.insert = function(ns, ops, options, callback) { - this.s.server.insert(ns, ops, options, callback); -} - -define.classMethod('insert', {callback: true, promise:false}); - -// Update -Server.prototype.update = function(ns, ops, options, callback) { - this.s.server.update(ns, ops, options, callback); -} - -define.classMethod('update', {callback: true, promise:false}); - -// Remove -Server.prototype.remove = function(ns, ops, options, callback) { - this.s.server.remove(ns, ops, options, callback); -} - -define.classMethod('remove', {callback: true, promise:false}); - -// IsConnected -Server.prototype.isConnected = function() { - return this.s.server.isConnected(); -} - -define.classMethod('isConnected', {callback: false, promise:false, returns: [Boolean]}); - -// Insert -Server.prototype.cursor = function(ns, cmd, options) { - options.disconnectHandler = this.s.store; - return this.s.server.cursor(ns, cmd, options); -} - -define.classMethod('cursor', {callback: false, promise:false, returns: [Cursor, AggregationCursor, CommandCursor]}); - -Server.prototype.setBSONParserType = function(type) { - return this.s.server.setBSONParserType(type); -} - -Server.prototype.lastIsMaster = function() { - return this.s.server.lastIsMaster(); -} - -Server.prototype.close = function(forceClosed) { - this.s.server.destroy(); - // We need to wash out all stored processes - if(forceClosed == true) { - this.s.storeOptions.force = forceClosed; - this.s.store.flush(); - } -} - -define.classMethod('close', {callback: false, promise:false}); - -Server.prototype.auth = function() { - var args = Array.prototype.slice.call(arguments, 0); - this.s.server.auth.apply(this.s.server, args); -} - -define.classMethod('auth', {callback: true, promise:false}); - -/** - * All raw connections - * @method - * @return {array} - */ -Server.prototype.connections = function() { - return this.s.server.connections(); -} - -define.classMethod('connections', {callback: false, promise:false, returns:[Array]}); - -/** - * Server connect event - * - * @event Server#connect - * @type {object} - */ - -/** - * Server close event - * - * @event Server#close - * @type {object} - */ - -/** - * Server reconnect event - * - * @event Server#reconnect - * @type {object} - */ - -/** - * Server error event - * - * @event Server#error - * @type {MongoError} - */ - -/** - * Server timeout event - * - * @event Server#timeout - * @type {object} - */ - -/** - * Server parseError event - * - * @event Server#parseError - * @type {object} - */ - -module.exports = Server; diff --git a/util/retroImporter/node_modules/mongodb/lib/topology_base.js b/util/retroImporter/node_modules/mongodb/lib/topology_base.js deleted file mode 100644 index 000f7ec..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/topology_base.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; - -var MongoError = require('mongodb-core').MongoError - , f = require('util').format; - -// The store of ops -var Store = function(topology, storeOptions) { - var self = this; - var storedOps = []; - storeOptions = storeOptions || {force:false, bufferMaxEntries: -1} - - // Internal state - this.s = { - storedOps: storedOps - , storeOptions: storeOptions - , topology: topology - } - - Object.defineProperty(this, 'length', { - enumerable:true, get: function() { return self.s.storedOps.length; } - }); -} - -Store.prototype.add = function(opType, ns, ops, options, callback) { - if(this.s.storeOptions.force) { - return callback(MongoError.create({message: "db closed by application", driver:true})); - } - - if(this.s.storeOptions.bufferMaxEntries == 0) { - return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { - while(this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - return; - } - - this.s.storedOps.push({t: opType, n: ns, o: ops, op: options, c: callback}) -} - -Store.prototype.addObjectAndMethod = function(opType, object, method, params, callback) { - if(this.s.storeOptions.force) { - return callback(MongoError.create({message: "db closed by application", driver:true })); - } - - if(this.s.storeOptions.bufferMaxEntries == 0) { - return callback(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - if(this.s.storeOptions.bufferMaxEntries > 0 && this.s.storedOps.length > this.s.storeOptions.bufferMaxEntries) { - while(this.s.storedOps.length > 0) { - var op = this.s.storedOps.shift(); - op.c(MongoError.create({message: f("no connection available for operation and number of stored operation > %s", this.s.storeOptions.bufferMaxEntries), driver:true })); - } - - return; - } - - this.s.storedOps.push({t: opType, m: method, o: object, p: params, c: callback}) -} - -Store.prototype.flush = function() { - while(this.s.storedOps.length > 0) { - this.s.storedOps.shift().c(MongoError.create({message: f("no connection available for operation"), driver:true })); - } -} - -Store.prototype.execute = function() { - // Get current ops - var ops = this.s.storedOps; - // Reset the ops - this.s.storedOps = []; - - // Execute all the stored ops - while(ops.length > 0) { - var op = ops.shift(); - - if(op.t == 'cursor') { - op.o[op.m].apply(op.o, op.p); - } else { - this.s.topology[op.t](op.n, op.o, op.op, op.c); - } - } -} - -Store.prototype.all = function() { - return this.s.storedOps; -} - -// Server capabilities -var ServerCapabilities = function(ismaster) { - var setup_get_property = function(object, name, value) { - Object.defineProperty(object, name, { - enumerable: true - , get: function () { return value; } - }); - } - - // Capabilities - var aggregationCursor = false; - var writeCommands = false; - var textSearch = false; - var authCommands = false; - var listCollections = false; - var listIndexes = false; - var maxNumberOfDocsInBatch = ismaster.maxWriteBatchSize || 1000; - - if(ismaster.minWireVersion >= 0) { - textSearch = true; - } - - if(ismaster.maxWireVersion >= 1) { - aggregationCursor = true; - authCommands = true; - } - - if(ismaster.maxWireVersion >= 2) { - writeCommands = true; - } - - if(ismaster.maxWireVersion >= 3) { - listCollections = true; - listIndexes = true; - } - - // If no min or max wire version set to 0 - if(ismaster.minWireVersion == null) { - ismaster.minWireVersion = 0; - } - - if(ismaster.maxWireVersion == null) { - ismaster.maxWireVersion = 0; - } - - // Map up read only parameters - setup_get_property(this, "hasAggregationCursor", aggregationCursor); - setup_get_property(this, "hasWriteCommands", writeCommands); - setup_get_property(this, "hasTextSearch", textSearch); - setup_get_property(this, "hasAuthCommands", authCommands); - setup_get_property(this, "hasListCollectionsCommand", listCollections); - setup_get_property(this, "hasListIndexesCommand", listIndexes); - setup_get_property(this, "minWireVersion", ismaster.minWireVersion); - setup_get_property(this, "maxWireVersion", ismaster.maxWireVersion); - setup_get_property(this, "maxNumberOfDocsInBatch", maxNumberOfDocsInBatch); -} - -exports.Store = Store; -exports.ServerCapabilities = ServerCapabilities; diff --git a/util/retroImporter/node_modules/mongodb/lib/url_parser.js b/util/retroImporter/node_modules/mongodb/lib/url_parser.js deleted file mode 100644 index eccc1e0..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/url_parser.js +++ /dev/null @@ -1,295 +0,0 @@ -"use strict"; - -var ReadPreference = require('./read_preference'); - -module.exports = function(url, options) { - // Ensure we have a default options object if none set - options = options || {}; - // Variables - var connection_part = ''; - var auth_part = ''; - var query_string_part = ''; - var dbName = 'admin'; - - // Must start with mongodb - if(url.indexOf("mongodb://") != 0) - throw Error("URL must be in the format mongodb://user:pass@host:port/dbname"); - // If we have a ? mark cut the query elements off - if(url.indexOf("?") != -1) { - query_string_part = url.substr(url.indexOf("?") + 1); - connection_part = url.substring("mongodb://".length, url.indexOf("?")) - } else { - connection_part = url.substring("mongodb://".length); - } - - // Check if we have auth params - if(connection_part.indexOf("@") != -1) { - auth_part = connection_part.split("@")[0]; - connection_part = connection_part.split("@")[1]; - } - - // Check if the connection string has a db - if(connection_part.indexOf(".sock") != -1) { - if(connection_part.indexOf(".sock/") != -1) { - dbName = connection_part.split(".sock/")[1]; - connection_part = connection_part.split("/", connection_part.indexOf(".sock") + ".sock".length); - } - } else if(connection_part.indexOf("/") != -1) { - dbName = connection_part.split("/")[1]; - connection_part = connection_part.split("/")[0]; - } - - // Result object - var object = {}; - - // Pick apart the authentication part of the string - var authPart = auth_part || ''; - var auth = authPart.split(':', 2); - - // Decode the URI components - auth[0] = decodeURIComponent(auth[0]); - if(auth[1]){ - auth[1] = decodeURIComponent(auth[1]); - } - - // Add auth to final object if we have 2 elements - if(auth.length == 2) object.auth = {user: auth[0], password: auth[1]}; - - // Variables used for temporary storage - var hostPart; - var urlOptions; - var servers; - var serverOptions = {socketOptions: {}}; - var dbOptions = {read_preference_tags: []}; - var replSetServersOptions = {socketOptions: {}}; - // Add server options to final object - object.server_options = serverOptions; - object.db_options = dbOptions; - object.rs_options = replSetServersOptions; - object.mongos_options = {}; - - // Let's check if we are using a domain socket - if(url.match(/\.sock/)) { - // Split out the socket part - var domainSocket = url.substring( - url.indexOf("mongodb://") + "mongodb://".length - , url.lastIndexOf(".sock") + ".sock".length); - // Clean out any auth stuff if any - if(domainSocket.indexOf("@") != -1) domainSocket = domainSocket.split("@")[1]; - servers = [{domain_socket: domainSocket}]; - } else { - // Split up the db - hostPart = connection_part; - // Deduplicate servers - var deduplicatedServers = {}; - - // Parse all server results - servers = hostPart.split(',').map(function(h) { - var _host, _port, ipv6match; - //check if it matches [IPv6]:port, where the port number is optional - if ((ipv6match = /\[([^\]]+)\](?:\:(.+))?/.exec(h))) { - _host = ipv6match[1]; - _port = parseInt(ipv6match[2], 10) || 27017; - } else { - //otherwise assume it's IPv4, or plain hostname - var hostPort = h.split(':', 2); - _host = hostPort[0] || 'localhost'; - _port = hostPort[1] != null ? parseInt(hostPort[1], 10) : 27017; - // Check for localhost?safe=true style case - if(_host.indexOf("?") != -1) _host = _host.split(/\?/)[0]; - } - - // No entry returned for duplicate servr - if(deduplicatedServers[_host + "_" + _port]) return null; - deduplicatedServers[_host + "_" + _port] = 1; - - // Return the mapped object - return {host: _host, port: _port}; - }).filter(function(x) { - return x != null; - }); - } - - // Get the db name - object.dbName = dbName || 'admin'; - // Split up all the options - urlOptions = (query_string_part || '').split(/[&;]/); - // Ugh, we have to figure out which options go to which constructor manually. - urlOptions.forEach(function(opt) { - if(!opt) return; - var splitOpt = opt.split('='), name = splitOpt[0], value = splitOpt[1]; - // Options implementations - switch(name) { - case 'slaveOk': - case 'slave_ok': - serverOptions.slave_ok = (value == 'true'); - dbOptions.slaveOk = (value == 'true'); - break; - case 'maxPoolSize': - case 'poolSize': - serverOptions.poolSize = parseInt(value, 10); - replSetServersOptions.poolSize = parseInt(value, 10); - break; - case 'autoReconnect': - case 'auto_reconnect': - serverOptions.auto_reconnect = (value == 'true'); - break; - case 'minPoolSize': - throw new Error("minPoolSize not supported"); - case 'maxIdleTimeMS': - throw new Error("maxIdleTimeMS not supported"); - case 'waitQueueMultiple': - throw new Error("waitQueueMultiple not supported"); - case 'waitQueueTimeoutMS': - throw new Error("waitQueueTimeoutMS not supported"); - case 'uuidRepresentation': - throw new Error("uuidRepresentation not supported"); - case 'ssl': - if(value == 'prefer') { - serverOptions.ssl = value; - replSetServersOptions.ssl = value; - break; - } - serverOptions.ssl = (value == 'true'); - replSetServersOptions.ssl = (value == 'true'); - break; - case 'replicaSet': - case 'rs_name': - replSetServersOptions.rs_name = value; - break; - case 'reconnectWait': - replSetServersOptions.reconnectWait = parseInt(value, 10); - break; - case 'retries': - replSetServersOptions.retries = parseInt(value, 10); - break; - case 'readSecondary': - case 'read_secondary': - replSetServersOptions.read_secondary = (value == 'true'); - break; - case 'fsync': - dbOptions.fsync = (value == 'true'); - break; - case 'journal': - dbOptions.j = (value == 'true'); - break; - case 'safe': - dbOptions.safe = (value == 'true'); - break; - case 'nativeParser': - case 'native_parser': - dbOptions.native_parser = (value == 'true'); - break; - case 'readConcernLevel': - dbOptions.readConcern = {level: value}; - break; - case 'connectTimeoutMS': - serverOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.connectTimeoutMS = parseInt(value, 10); - break; - case 'socketTimeoutMS': - serverOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - replSetServersOptions.socketOptions.socketTimeoutMS = parseInt(value, 10); - break; - case 'w': - dbOptions.w = parseInt(value, 10); - if(isNaN(dbOptions.w)) dbOptions.w = value; - break; - case 'authSource': - dbOptions.authSource = value; - break; - case 'gssapiServiceName': - dbOptions.gssapiServiceName = value; - break; - case 'authMechanism': - if(value == 'GSSAPI') { - // If no password provided decode only the principal - if(object.auth == null) { - var urlDecodeAuthPart = decodeURIComponent(authPart); - if(urlDecodeAuthPart.indexOf("@") == -1) throw new Error("GSSAPI requires a provided principal"); - object.auth = {user: urlDecodeAuthPart, password: null}; - } else { - object.auth.user = decodeURIComponent(object.auth.user); - } - } else if(value == 'MONGODB-X509') { - object.auth = {user: decodeURIComponent(authPart)}; - } - - // Only support GSSAPI or MONGODB-CR for now - if(value != 'GSSAPI' - && value != 'MONGODB-X509' - && value != 'MONGODB-CR' - && value != 'DEFAULT' - && value != 'SCRAM-SHA-1' - && value != 'PLAIN') - throw new Error("only DEFAULT, GSSAPI, PLAIN, MONGODB-X509, SCRAM-SHA-1 or MONGODB-CR is supported by authMechanism"); - - // Authentication mechanism - dbOptions.authMechanism = value; - break; - case 'authMechanismProperties': - // Split up into key, value pairs - var values = value.split(','); - var o = {}; - // For each value split into key, value - values.forEach(function(x) { - var v = x.split(':'); - o[v[0]] = v[1]; - }); - - // Set all authMechanismProperties - dbOptions.authMechanismProperties = o; - // Set the service name value - if(typeof o.SERVICE_NAME == 'string') dbOptions.gssapiServiceName = o.SERVICE_NAME; - break; - case 'wtimeoutMS': - dbOptions.wtimeout = parseInt(value, 10); - break; - case 'readPreference': - if(!ReadPreference.isValid(value)) throw new Error("readPreference must be either primary/primaryPreferred/secondary/secondaryPreferred/nearest"); - dbOptions.read_preference = value; - break; - case 'readPreferenceTags': - // Decode the value - value = decodeURIComponent(value); - // Contains the tag object - var tagObject = {}; - if(value == null || value == '') { - dbOptions.read_preference_tags.push(tagObject); - break; - } - - // Split up the tags - var tags = value.split(/\,/); - for(var i = 0; i < tags.length; i++) { - var parts = tags[i].trim().split(/\:/); - tagObject[parts[0]] = parts[1]; - } - - // Set the preferences tags - dbOptions.read_preference_tags.push(tagObject); - break; - default: - break; - } - }); - - // No tags: should be null (not []) - if(dbOptions.read_preference_tags.length === 0) { - dbOptions.read_preference_tags = null; - } - - // Validate if there are an invalid write concern combinations - if((dbOptions.w == -1 || dbOptions.w == 0) && ( - dbOptions.journal == true - || dbOptions.fsync == true - || dbOptions.safe == true)) throw new Error("w set to -1 or 0 cannot be combined with safe/w/journal/fsync") - - // If no read preference set it to primary - if(!dbOptions.read_preference) dbOptions.read_preference = 'primary'; - - // Add servers to result - object.servers = servers; - // Returned parsed object - return object; -} diff --git a/util/retroImporter/node_modules/mongodb/lib/utils.js b/util/retroImporter/node_modules/mongodb/lib/utils.js deleted file mode 100644 index cb20e67..0000000 --- a/util/retroImporter/node_modules/mongodb/lib/utils.js +++ /dev/null @@ -1,234 +0,0 @@ -"use strict"; - -var MongoError = require('mongodb-core').MongoError, - f = require('util').format; - -var shallowClone = function(obj) { - var copy = {}; - for(var name in obj) copy[name] = obj[name]; - return copy; -} - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable:true, - get: function() { - return value - } - }); -} - -var formatSortValue = exports.formatSortValue = function(sortDirection) { - var value = ("" + sortDirection).toLowerCase(); - - switch (value) { - case 'ascending': - case 'asc': - case '1': - return 1; - case 'descending': - case 'desc': - case '-1': - return -1; - default: - throw new Error("Illegal sort clause, must be of the form " - + "[['field1', '(ascending|descending)'], " - + "['field2', '(ascending|descending)']]"); - } -}; - -var formattedOrderClause = exports.formattedOrderClause = function(sortValue) { - var orderBy = {}; - if(sortValue == null) return null; - if (Array.isArray(sortValue)) { - if(sortValue.length === 0) { - return null; - } - - for(var i = 0; i < sortValue.length; i++) { - if(sortValue[i].constructor == String) { - orderBy[sortValue[i]] = 1; - } else { - orderBy[sortValue[i][0]] = formatSortValue(sortValue[i][1]); - } - } - } else if(sortValue != null && typeof sortValue == 'object') { - orderBy = sortValue; - } else if (typeof sortValue == 'string') { - orderBy[sortValue] = 1; - } else { - throw new Error("Illegal sort clause, must be of the form " + - "[['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]"); - } - - return orderBy; -}; - -var checkCollectionName = function checkCollectionName (collectionName) { - if('string' !== typeof collectionName) { - throw Error("collection name must be a String"); - } - - if(!collectionName || collectionName.indexOf('..') != -1) { - throw Error("collection names cannot be empty"); - } - - if(collectionName.indexOf('$') != -1 && - collectionName.match(/((^\$cmd)|(oplog\.\$main))/) == null) { - throw Error("collection names must not contain '$'"); - } - - if(collectionName.match(/^\.|\.$/) != null) { - throw Error("collection names must not start or end with '.'"); - } - - // Validate that we are not passing 0x00 in the colletion name - if(!!~collectionName.indexOf("\x00")) { - throw new Error("collection names cannot contain a null character"); - } -}; - -var handleCallback = function(callback, err, value1, value2) { - try { - if(callback == null) return; - if(value2) return callback(err, value1, value2); - return callback(err, value1); - } catch(err) { - process.nextTick(function() { throw err; }); - return false; - } - - return true; -} - -/** - * Wrap a Mongo error document in an Error instance - * @ignore - * @api private - */ -var toError = function(error) { - if (error instanceof Error) return error; - - var msg = error.err || error.errmsg || error.errMessage || error; - var e = MongoError.create({message: msg, driver:true}); - - // Get all object keys - var keys = typeof error == 'object' - ? Object.keys(error) - : []; - - for(var i = 0; i < keys.length; i++) { - e[keys[i]] = error[keys[i]]; - } - - return e; -} - -/** - * @ignore - */ -var normalizeHintField = function normalizeHintField(hint) { - var finalHint = null; - - if(typeof hint == 'string') { - finalHint = hint; - } else if(Array.isArray(hint)) { - finalHint = {}; - - hint.forEach(function(param) { - finalHint[param] = 1; - }); - } else if(hint != null && typeof hint == 'object') { - finalHint = {}; - for (var name in hint) { - finalHint[name] = hint[name]; - } - } - - return finalHint; -}; - -/** - * Create index name based on field spec - * - * @ignore - * @api private - */ -var parseIndexOptions = function(fieldOrSpec) { - var fieldHash = {}; - var indexes = []; - var keys; - - // Get all the fields accordingly - if('string' == typeof fieldOrSpec) { - // 'type' - indexes.push(fieldOrSpec + '_' + 1); - fieldHash[fieldOrSpec] = 1; - } else if(Array.isArray(fieldOrSpec)) { - fieldOrSpec.forEach(function(f) { - if('string' == typeof f) { - // [{location:'2d'}, 'type'] - indexes.push(f + '_' + 1); - fieldHash[f] = 1; - } else if(Array.isArray(f)) { - // [['location', '2d'],['type', 1]] - indexes.push(f[0] + '_' + (f[1] || 1)); - fieldHash[f[0]] = f[1] || 1; - } else if(isObject(f)) { - // [{location:'2d'}, {type:1}] - keys = Object.keys(f); - keys.forEach(function(k) { - indexes.push(k + '_' + f[k]); - fieldHash[k] = f[k]; - }); - } else { - // undefined (ignore) - } - }); - } else if(isObject(fieldOrSpec)) { - // {location:'2d', type:1} - keys = Object.keys(fieldOrSpec); - keys.forEach(function(key) { - indexes.push(key + '_' + fieldOrSpec[key]); - fieldHash[key] = fieldOrSpec[key]; - }); - } - - return { - name: indexes.join("_"), keys: keys, fieldHash: fieldHash - } -} - -var isObject = exports.isObject = function (arg) { - return '[object Object]' == toString.call(arg) -} - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -var decorateCommand = function(command, options, exclude) { - for(var name in options) { - if(exclude[name] == null) command[name] = options[name]; - } - - return command; -} - -exports.shallowClone = shallowClone; -exports.getSingleProperty = getSingleProperty; -exports.checkCollectionName = checkCollectionName; -exports.toError = toError; -exports.formattedOrderClause = formattedOrderClause; -exports.parseIndexOptions = parseIndexOptions; -exports.normalizeHintField = normalizeHintField; -exports.handleCallback = handleCallback; -exports.decorateCommand = decorateCommand; -exports.isObject = isObject; -exports.debugOptions = debugOptions; diff --git a/util/retroImporter/node_modules/mongodb/load.js b/util/retroImporter/node_modules/mongodb/load.js deleted file mode 100644 index 01b570e..0000000 --- a/util/retroImporter/node_modules/mongodb/load.js +++ /dev/null @@ -1,32 +0,0 @@ -var MongoClient = require('./').MongoClient; - -MongoClient.connect('mongodb://localhost:27017/test', function(err, db) { - var col = db.collection('test'); - col.ensureIndex({dt:-1}, function() { - var docs = []; - for(var i = 0; i < 100; i++) { - docs.push({a:i, dt:i, ot:i}); - } - console.log("------------------------------- 0") - - col.insertMany(docs, function() { - // Start firing finds - - for(var i = 0; i < 100; i++) { - setInterval(function() { - col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) { - console.log("-------------------------------- 1") - }); - }, 10) - } - - // while(true) { - // - // // console.log("------------------------------- 1") - // col.find({}, {_id: 0, ot:0}).limit(2).sort({dt:-1}).toArray(function(err) { - // console.log("-------------------------------- 1") - // }); - // } - }); - }); -}); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md deleted file mode 100644 index e06b496..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/CHANGELOG.md +++ /dev/null @@ -1,9 +0,0 @@ -# Master - -# 2.0.0 - -* re-sync with RSVP. Many large performance improvements and bugfixes. - -# 1.0.0 - -* first subset of RSVP diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE deleted file mode 100644 index 954ec59..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/README.md b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/README.md deleted file mode 100644 index ca8678e..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) - -This is a polyfill of the [ES6 Promise](http://people.mozilla.org/~jorendorff/es6-draft.html#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js), if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js). - -For API details and how to use promises, see the JavaScript Promises HTML5Rocks article. - -## Downloads - -* [es6-promise](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise.js) -* [es6-promise-min](https://raw.githubusercontent.com/jakearchibald/es6-promise/master/dist/es6-promise-min.js) - -## Node.js - -To install: - -```sh -npm install es6-promise -``` - -To use: - -```js -var Promise = require('es6-promise').Promise; -``` - -## Usage in IE<9 - -`catch` is a reserved word in IE<9, meaning `promise.catch(func)` throws a syntax error. To work around this, you can use a string to access the property as shown in the following example. - -However, please remember that such technique is already provided by most common minifiers, making the resulting code safe for old browsers and production: - -```js -promise['catch'](function(err) { - // ... -}); -``` - -Or use `.then` instead: - -```js -promise.then(undefined, function(err) { - // ... -}); -``` - -## Auto-polyfill - -To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet: - -```js -require('es6-promise').polyfill(); -``` - -Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called. - -## Building & Testing - -* `npm run build` to build -* `npm test` to run tests -* `npm start` to run a build watcher, and webserver to test -* `npm run test:server` for a testem test runner and watching builder diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js deleted file mode 100644 index 308f3ac..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.js +++ /dev/null @@ -1,957 +0,0 @@ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 2.1.1 - */ - -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } - - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$toString = {}.toString; - var lib$es6$promise$asap$$vertxNext; - function lib$es6$promise$asap$$asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - lib$es6$promise$asap$$scheduleFlush(); - } - } - - var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function() { - nextTick(lib$es6$promise$asap$$flush); - }; - } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } - - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFullfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$default(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } - } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - var then = lib$es6$promise$$internal$$getThen(maybeThenable); - - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } - } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); - } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } - - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } - } - } else { - lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); - } - } - - lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { - return lib$es6$promise$utils$$isArray(input); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { - this._result = new Array(this.length); - }; - - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (lib$es6$promise$utils$$isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - enumerator._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, enumerator._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } - - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; - } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; - } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - var lib$es6$promise$promise$$counter = 0; - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - if (!lib$es6$promise$utils$$isFunction(resolver)) { - lib$es6$promise$promise$$needsResolver(); - } - - if (!(this instanceof lib$es6$promise$promise$$Promise)) { - lib$es6$promise$promise$$needsNew(); - } - - lib$es6$promise$$internal$$initializePromise(this, resolver); - } - } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$default(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; - } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; - } - - lib$es6$promise$polyfill$$default(); -}).call(this); - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js deleted file mode 100644 index 0552e12..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/es6-promise.min.js +++ /dev/null @@ -1,9 +0,0 @@ -/*! - * @overview es6-promise - a tiny implementation of Promises/A+. - * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) - * @license Licensed under MIT license - * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE - * @version 2.1.1 - */ - -(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;function lib$es6$promise$asap$$asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){lib$es6$promise$asap$$scheduleFlush()}}var lib$es6$promise$asap$$default=lib$es6$promise$asap$$asap;var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){var nextTick=process.nextTick;var version=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);if(Array.isArray(version)&&version[1]==="0"&&version[2]==="10"){nextTick=setImmediate}return function(){nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i -// -// 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. - -// when used in node, this will actually load the util module we depend on -// versus loading the builtin util module as happens otherwise -// this is a bug in node module loading as far as I am concerned -var util = require('util/'); - -var pSlice = Array.prototype.slice; -var hasOwn = Object.prototype.hasOwnProperty; - -// 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 = module.exports = ok; - -// 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.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } - else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = stackStartFunction.name; - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function replacer(key, value) { - if (util.isUndefined(value)) { - return '' + value; - } - if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { - return value.toString(); - } - if (util.isFunction(value) || util.isRegExp(value)) { - return value.toString(); - } - return value; -} - -function truncate(s, n) { - if (util.isString(s)) { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} - -function getMessage(self) { - return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + - self.operator + ' ' + - truncate(JSON.stringify(self.expected, replacer), 128); -} - -// 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);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = 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; - - } else if (util.isBuffer(actual) && util.isBuffer(expected)) { - if (actual.length != expected.length) return false; - - for (var i = 0; i < actual.length; i++) { - if (actual[i] !== expected[i]) return false; - } - - 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 (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if (!util.isObject(actual) && !util.isObject(expected)) { - return actual == expected; - - // 7.5 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 isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b) { - if (util.isNullOrUndefined(a) || util.isNullOrUndefined(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 = objectKeys(a), - kb = objectKeys(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 expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } else if (actual instanceof expected) { - return true; - } else if (expected.call({}, actual) === true) { - return true; - } - - return false; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (util.isString(expected)) { - message = expected; - expected = null; - } - - try { - block(); - } catch (e) { - actual = e; - } - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - if (!shouldThrow && expectedException(actual, expected)) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 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*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function(err) { if (err) {throw err;}}; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; - -},{"util/":6}],3:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],4:[function(require,module,exports){ -// shim for using process in browser - -var process = module.exports = {}; - -process.nextTick = (function () { - var canSetImmediate = typeof window !== 'undefined' - && window.setImmediate; - var canMutationObserver = typeof window !== 'undefined' - && window.MutationObserver; - var canPost = typeof window !== 'undefined' - && window.postMessage && window.addEventListener - ; - - if (canSetImmediate) { - return function (f) { return window.setImmediate(f) }; - } - - var queue = []; - - if (canMutationObserver) { - var hiddenDiv = document.createElement("div"); - var observer = new MutationObserver(function () { - var queueList = queue.slice(); - queue.length = 0; - queueList.forEach(function (fn) { - fn(); - }); - }); - - observer.observe(hiddenDiv, { attributes: true }); - - return function nextTick(fn) { - if (!queue.length) { - hiddenDiv.setAttribute('yes', 'no'); - } - queue.push(fn); - }; - } - - if (canPost) { - window.addEventListener('message', function (ev) { - var source = ev.source; - if ((source === window || source === null) && ev.data === 'process-tick') { - ev.stopPropagation(); - if (queue.length > 0) { - var fn = queue.shift(); - fn(); - } - } - }, true); - - return function nextTick(fn) { - queue.push(fn); - window.postMessage('process-tick', '*'); - }; - } - - return function nextTick(fn) { - setTimeout(fn, 0); - }; -})(); - -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -// TODO(shtylman) -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; - -},{}],5:[function(require,module,exports){ -module.exports = function isBuffer(arg) { - return arg && typeof arg === 'object' - && typeof arg.copy === 'function' - && typeof arg.fill === 'function' - && typeof arg.readUInt8 === 'function'; -} -},{}],6:[function(require,module,exports){ -(function (process,global){ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":5,"_process":4,"inherits":3}],7:[function(require,module,exports){ -require("./tests/2.1.2"); -require("./tests/2.1.3"); -require("./tests/2.2.1"); -require("./tests/2.2.2"); -require("./tests/2.2.3"); -require("./tests/2.2.4"); -require("./tests/2.2.5"); -require("./tests/2.2.6"); -require("./tests/2.2.7"); -require("./tests/2.3.1"); -require("./tests/2.3.2"); -require("./tests/2.3.3"); -require("./tests/2.3.4"); - -},{"./tests/2.1.2":8,"./tests/2.1.3":9,"./tests/2.2.1":10,"./tests/2.2.2":11,"./tests/2.2.3":12,"./tests/2.2.4":13,"./tests/2.2.5":14,"./tests/2.2.6":15,"./tests/2.2.7":16,"./tests/2.3.1":17,"./tests/2.3.2":18,"./tests/2.3.3":19,"./tests/2.3.4":20}],8:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; - -var adapter = global.adapter; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.1.2.1: When fulfilled, a promise: must not transition to any other state.", function () { - testFulfilled(dummy, function (promise, done) { - var onFulfilledCalled = false; - - promise.then(function onFulfilled() { - onFulfilledCalled = true; - }, function onRejected() { - assert.strictEqual(onFulfilledCalled, false); - done(); - }); - - setTimeout(done, 100); - }); - - specify("trying to fulfill then immediately reject", function (done) { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }, function onRejected() { - assert.strictEqual(onFulfilledCalled, false); - done(); - }); - - d.resolve(dummy); - d.reject(dummy); - setTimeout(done, 100); - }); - - specify("trying to fulfill then reject, delayed", function (done) { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }, function onRejected() { - assert.strictEqual(onFulfilledCalled, false); - done(); - }); - - setTimeout(function () { - d.resolve(dummy); - d.reject(dummy); - }, 50); - setTimeout(done, 100); - }); - - specify("trying to fulfill immediately then reject delayed", function (done) { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }, function onRejected() { - assert.strictEqual(onFulfilledCalled, false); - done(); - }); - - d.resolve(dummy); - setTimeout(function () { - d.reject(dummy); - }, 50); - setTimeout(done, 100); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],9:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testRejected = require("./helpers/testThreeCases").testRejected; - -var adapter = global.adapter; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.1.3.1: When rejected, a promise: must not transition to any other state.", function () { - testRejected(dummy, function (promise, done) { - var onRejectedCalled = false; - - promise.then(function onFulfilled() { - assert.strictEqual(onRejectedCalled, false); - done(); - }, function onRejected() { - onRejectedCalled = true; - }); - - setTimeout(done, 100); - }); - - specify("trying to reject then immediately fulfill", function (done) { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(function onFulfilled() { - assert.strictEqual(onRejectedCalled, false); - done(); - }, function onRejected() { - onRejectedCalled = true; - }); - - d.reject(dummy); - d.resolve(dummy); - setTimeout(done, 100); - }); - - specify("trying to reject then fulfill, delayed", function (done) { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(function onFulfilled() { - assert.strictEqual(onRejectedCalled, false); - done(); - }, function onRejected() { - onRejectedCalled = true; - }); - - setTimeout(function () { - d.reject(dummy); - d.resolve(dummy); - }, 50); - setTimeout(done, 100); - }); - - specify("trying to reject immediately then fulfill delayed", function (done) { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(function onFulfilled() { - assert.strictEqual(onRejectedCalled, false); - done(); - }, function onRejected() { - onRejectedCalled = true; - }); - - d.reject(dummy); - setTimeout(function () { - d.resolve(dummy); - }, 50); - setTimeout(done, 100); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],10:[function(require,module,exports){ -(function (global){ -"use strict"; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.2.1: Both `onFulfilled` and `onRejected` are optional arguments.", function () { - describe("2.2.1.1: If `onFulfilled` is not a function, it must be ignored.", function () { - describe("applied to a directly-rejected promise", function () { - function testNonFunction(nonFunction, stringRepresentation) { - specify("`onFulfilled` is " + stringRepresentation, function (done) { - rejected(dummy).then(nonFunction, function () { - done(); - }); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - }); - - describe("applied to a promise rejected and then chained off of", function () { - function testNonFunction(nonFunction, stringRepresentation) { - specify("`onFulfilled` is " + stringRepresentation, function (done) { - rejected(dummy).then(function () { }, undefined).then(nonFunction, function () { - done(); - }); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - }); - }); - - describe("2.2.1.2: If `onRejected` is not a function, it must be ignored.", function () { - describe("applied to a directly-fulfilled promise", function () { - function testNonFunction(nonFunction, stringRepresentation) { - specify("`onRejected` is " + stringRepresentation, function (done) { - resolved(dummy).then(function () { - done(); - }, nonFunction); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - }); - - describe("applied to a promise fulfilled and then chained off of", function () { - function testNonFunction(nonFunction, stringRepresentation) { - specify("`onFulfilled` is " + stringRepresentation, function (done) { - resolved(dummy).then(undefined, function () { }).then(function () { - done(); - }, nonFunction); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],11:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality - -describe("2.2.2: If `onFulfilled` is a function,", function () { - describe("2.2.2.1: it must be called after `promise` is fulfilled, with `promise`’s fulfillment value as its " + - "first argument.", function () { - testFulfilled(sentinel, function (promise, done) { - promise.then(function onFulfilled(value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("2.2.2.2: it must not be called before `promise` is fulfilled", function () { - specify("fulfilled after a delay", function (done) { - var d = deferred(); - var isFulfilled = false; - - d.promise.then(function onFulfilled() { - assert.strictEqual(isFulfilled, true); - done(); - }); - - setTimeout(function () { - d.resolve(dummy); - isFulfilled = true; - }, 50); - }); - - specify("never fulfilled", function (done) { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - done(); - }); - - setTimeout(function () { - assert.strictEqual(onFulfilledCalled, false); - done(); - }, 150); - }); - }); - - describe("2.2.2.3: it must not be called more than once.", function () { - specify("already-fulfilled", function (done) { - var timesCalled = 0; - - resolved(dummy).then(function onFulfilled() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - }); - - specify("trying to fulfill a pending promise more than once, immediately", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - d.resolve(dummy); - d.resolve(dummy); - }); - - specify("trying to fulfill a pending promise more than once, delayed", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - setTimeout(function () { - d.resolve(dummy); - d.resolve(dummy); - }, 50); - }); - - specify("trying to fulfill a pending promise more than once, immediately then delayed", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - d.resolve(dummy); - setTimeout(function () { - d.resolve(dummy); - }, 50); - }); - - specify("when multiple `then` calls are made, spaced apart in time", function (done) { - var d = deferred(); - var timesCalled = [0, 0, 0]; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[0], 1); - }); - - setTimeout(function () { - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[1], 1); - }); - }, 50); - - setTimeout(function () { - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[2], 1); - done(); - }); - }, 100); - - setTimeout(function () { - d.resolve(dummy); - }, 150); - }); - - specify("when `then` is interleaved with fulfillment", function (done) { - var d = deferred(); - var timesCalled = [0, 0]; - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[0], 1); - }); - - d.resolve(dummy); - - d.promise.then(function onFulfilled() { - assert.strictEqual(++timesCalled[1], 1); - done(); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],12:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testRejected = require("./helpers/testThreeCases").testRejected; - -var adapter = global.adapter; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality - -describe("2.2.3: If `onRejected` is a function,", function () { - describe("2.2.3.1: it must be called after `promise` is rejected, with `promise`’s rejection reason as its " + - "first argument.", function () { - testRejected(sentinel, function (promise, done) { - promise.then(null, function onRejected(reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("2.2.3.2: it must not be called before `promise` is rejected", function () { - specify("rejected after a delay", function (done) { - var d = deferred(); - var isRejected = false; - - d.promise.then(null, function onRejected() { - assert.strictEqual(isRejected, true); - done(); - }); - - setTimeout(function () { - d.reject(dummy); - isRejected = true; - }, 50); - }); - - specify("never rejected", function (done) { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(null, function onRejected() { - onRejectedCalled = true; - done(); - }); - - setTimeout(function () { - assert.strictEqual(onRejectedCalled, false); - done(); - }, 150); - }); - }); - - describe("2.2.3.3: it must not be called more than once.", function () { - specify("already-rejected", function (done) { - var timesCalled = 0; - - rejected(dummy).then(null, function onRejected() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - }); - - specify("trying to reject a pending promise more than once, immediately", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - d.reject(dummy); - d.reject(dummy); - }); - - specify("trying to reject a pending promise more than once, delayed", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - setTimeout(function () { - d.reject(dummy); - d.reject(dummy); - }, 50); - }); - - specify("trying to reject a pending promise more than once, immediately then delayed", function (done) { - var d = deferred(); - var timesCalled = 0; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled, 1); - done(); - }); - - d.reject(dummy); - setTimeout(function () { - d.reject(dummy); - }, 50); - }); - - specify("when multiple `then` calls are made, spaced apart in time", function (done) { - var d = deferred(); - var timesCalled = [0, 0, 0]; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[0], 1); - }); - - setTimeout(function () { - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[1], 1); - }); - }, 50); - - setTimeout(function () { - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[2], 1); - done(); - }); - }, 100); - - setTimeout(function () { - d.reject(dummy); - }, 150); - }); - - specify("when `then` is interleaved with rejection", function (done) { - var d = deferred(); - var timesCalled = [0, 0]; - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[0], 1); - }); - - d.reject(dummy); - - d.promise.then(null, function onRejected() { - assert.strictEqual(++timesCalled[1], 1); - done(); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],13:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; -var testRejected = require("./helpers/testThreeCases").testRejected; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.2.4: `onFulfilled` or `onRejected` must not be called until the execution context stack contains only " + - "platform code.", function () { - describe("`then` returns before the promise becomes fulfilled or rejected", function () { - testFulfilled(dummy, function (promise, done) { - var thenHasReturned = false; - - promise.then(function onFulfilled() { - assert.strictEqual(thenHasReturned, true); - done(); - }); - - thenHasReturned = true; - }); - testRejected(dummy, function (promise, done) { - var thenHasReturned = false; - - promise.then(null, function onRejected() { - assert.strictEqual(thenHasReturned, true); - done(); - }); - - thenHasReturned = true; - }); - }); - - describe("Clean-stack execution ordering tests (fulfillment case)", function () { - specify("when `onFulfilled` is added immediately before the promise is fulfilled", - function () { - var d = deferred(); - var onFulfilledCalled = false; - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }); - - d.resolve(dummy); - - assert.strictEqual(onFulfilledCalled, false); - }); - - specify("when `onFulfilled` is added immediately after the promise is fulfilled", - function () { - var d = deferred(); - var onFulfilledCalled = false; - - d.resolve(dummy); - - d.promise.then(function onFulfilled() { - onFulfilledCalled = true; - }); - - assert.strictEqual(onFulfilledCalled, false); - }); - - specify("when one `onFulfilled` is added inside another `onFulfilled`", function (done) { - var promise = resolved(); - var firstOnFulfilledFinished = false; - - promise.then(function () { - promise.then(function () { - assert.strictEqual(firstOnFulfilledFinished, true); - done(); - }); - firstOnFulfilledFinished = true; - }); - }); - - specify("when `onFulfilled` is added inside an `onRejected`", function (done) { - var promise = rejected(); - var promise2 = resolved(); - var firstOnRejectedFinished = false; - - promise.then(null, function () { - promise2.then(function () { - assert.strictEqual(firstOnRejectedFinished, true); - done(); - }); - firstOnRejectedFinished = true; - }); - }); - - specify("when the promise is fulfilled asynchronously", function (done) { - var d = deferred(); - var firstStackFinished = false; - - setTimeout(function () { - d.resolve(dummy); - firstStackFinished = true; - }, 0); - - d.promise.then(function () { - assert.strictEqual(firstStackFinished, true); - done(); - }); - }); - }); - - describe("Clean-stack execution ordering tests (rejection case)", function () { - specify("when `onRejected` is added immediately before the promise is rejected", - function () { - var d = deferred(); - var onRejectedCalled = false; - - d.promise.then(null, function onRejected() { - onRejectedCalled = true; - }); - - d.reject(dummy); - - assert.strictEqual(onRejectedCalled, false); - }); - - specify("when `onRejected` is added immediately after the promise is rejected", - function () { - var d = deferred(); - var onRejectedCalled = false; - - d.reject(dummy); - - d.promise.then(null, function onRejected() { - onRejectedCalled = true; - }); - - assert.strictEqual(onRejectedCalled, false); - }); - - specify("when `onRejected` is added inside an `onFulfilled`", function (done) { - var promise = resolved(); - var promise2 = rejected(); - var firstOnFulfilledFinished = false; - - promise.then(function () { - promise2.then(null, function () { - assert.strictEqual(firstOnFulfilledFinished, true); - done(); - }); - firstOnFulfilledFinished = true; - }); - }); - - specify("when one `onRejected` is added inside another `onRejected`", function (done) { - var promise = rejected(); - var firstOnRejectedFinished = false; - - promise.then(null, function () { - promise.then(null, function () { - assert.strictEqual(firstOnRejectedFinished, true); - done(); - }); - firstOnRejectedFinished = true; - }); - }); - - specify("when the promise is rejected asynchronously", function (done) { - var d = deferred(); - var firstStackFinished = false; - - setTimeout(function () { - d.reject(dummy); - firstStackFinished = true; - }, 0); - - d.promise.then(null, function () { - assert.strictEqual(firstStackFinished, true); - done(); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/testThreeCases":22,"assert":2}],14:[function(require,module,exports){ -(function (global){ -/*jshint strict: false */ - -var assert = require("assert"); - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -function impimentsUseStrictCorrectly() { - "use strict"; - function test() { - /*jshint validthis:true */ - return !this; - } - return test(); -} -describe("2.2.5 `onFulfilled` and `onRejected` must be called as functions (i.e. with no `this` value).", function () { - if (impimentsUseStrictCorrectly()) { - describe("strict mode", function () { - specify("fulfilled", function (done) { - resolved(dummy).then(function onFulfilled() { - "use strict"; - - assert.strictEqual(this, undefined); - done(); - }); - }); - - specify("rejected", function (done) { - rejected(dummy).then(null, function onRejected() { - "use strict"; - - assert.strictEqual(this, undefined); - done(); - }); - }); - }); - } - describe("sloppy mode", function () { - specify("fulfilled", function (done) { - resolved(dummy).then(function onFulfilled() { - assert.strictEqual(this, global); - done(); - }); - }); - - specify("rejected", function (done) { - rejected(dummy).then(null, function onRejected() { - assert.strictEqual(this, global); - done(); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"assert":2}],15:[function(require,module,exports){ -"use strict"; - -var assert = require("assert"); -var sinon = require("sinon"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; -var testRejected = require("./helpers/testThreeCases").testRejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var other = { other: "other" }; // a value we don't want to be strict equal to -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality -var sentinel2 = { sentinel2: "sentinel2" }; -var sentinel3 = { sentinel3: "sentinel3" }; - -function callbackAggregator(times, ultimateCallback) { - var soFar = 0; - return function () { - if (++soFar === times) { - ultimateCallback(); - } - }; -} - -describe("2.2.6: `then` may be called multiple times on the same promise.", function () { - describe("2.2.6.1: If/when `promise` is fulfilled, all respective `onFulfilled` callbacks must execute in the " + - "order of their originating calls to `then`.", function () { - describe("multiple boring fulfillment handlers", function () { - testFulfilled(sentinel, function (promise, done) { - var handler1 = sinon.stub().returns(other); - var handler2 = sinon.stub().returns(other); - var handler3 = sinon.stub().returns(other); - - var spy = sinon.spy(); - promise.then(handler1, spy); - promise.then(handler2, spy); - promise.then(handler3, spy); - - promise.then(function (value) { - assert.strictEqual(value, sentinel); - - sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); - sinon.assert.notCalled(spy); - - done(); - }); - }); - }); - - describe("multiple fulfillment handlers, one of which throws", function () { - testFulfilled(sentinel, function (promise, done) { - var handler1 = sinon.stub().returns(other); - var handler2 = sinon.stub().throws(other); - var handler3 = sinon.stub().returns(other); - - var spy = sinon.spy(); - promise.then(handler1, spy); - promise.then(handler2, spy); - promise.then(handler3, spy); - - promise.then(function (value) { - assert.strictEqual(value, sentinel); - - sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); - sinon.assert.notCalled(spy); - - done(); - }); - }); - }); - - describe("results in multiple branching chains with their own fulfillment values", function () { - testFulfilled(dummy, function (promise, done) { - var semiDone = callbackAggregator(3, done); - - promise.then(function () { - return sentinel; - }).then(function (value) { - assert.strictEqual(value, sentinel); - semiDone(); - }); - - promise.then(function () { - throw sentinel2; - }).then(null, function (reason) { - assert.strictEqual(reason, sentinel2); - semiDone(); - }); - - promise.then(function () { - return sentinel3; - }).then(function (value) { - assert.strictEqual(value, sentinel3); - semiDone(); - }); - }); - }); - - describe("`onFulfilled` handlers are called in the original order", function () { - testFulfilled(dummy, function (promise, done) { - var handler1 = sinon.spy(function handler1() {}); - var handler2 = sinon.spy(function handler2() {}); - var handler3 = sinon.spy(function handler3() {}); - - promise.then(handler1); - promise.then(handler2); - promise.then(handler3); - - promise.then(function () { - sinon.assert.callOrder(handler1, handler2, handler3); - done(); - }); - }); - - describe("even when one handler is added inside another handler", function () { - testFulfilled(dummy, function (promise, done) { - var handler1 = sinon.spy(function handler1() {}); - var handler2 = sinon.spy(function handler2() {}); - var handler3 = sinon.spy(function handler3() {}); - - promise.then(function () { - handler1(); - promise.then(handler3); - }); - promise.then(handler2); - - promise.then(function () { - // Give implementations a bit of extra time to flush their internal queue, if necessary. - setTimeout(function () { - sinon.assert.callOrder(handler1, handler2, handler3); - done(); - }, 15); - }); - }); - }); - }); - }); - - describe("2.2.6.2: If/when `promise` is rejected, all respective `onRejected` callbacks must execute in the " + - "order of their originating calls to `then`.", function () { - describe("multiple boring rejection handlers", function () { - testRejected(sentinel, function (promise, done) { - var handler1 = sinon.stub().returns(other); - var handler2 = sinon.stub().returns(other); - var handler3 = sinon.stub().returns(other); - - var spy = sinon.spy(); - promise.then(spy, handler1); - promise.then(spy, handler2); - promise.then(spy, handler3); - - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - - sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); - sinon.assert.notCalled(spy); - - done(); - }); - }); - }); - - describe("multiple rejection handlers, one of which throws", function () { - testRejected(sentinel, function (promise, done) { - var handler1 = sinon.stub().returns(other); - var handler2 = sinon.stub().throws(other); - var handler3 = sinon.stub().returns(other); - - var spy = sinon.spy(); - promise.then(spy, handler1); - promise.then(spy, handler2); - promise.then(spy, handler3); - - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - - sinon.assert.calledWith(handler1, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler2, sinon.match.same(sentinel)); - sinon.assert.calledWith(handler3, sinon.match.same(sentinel)); - sinon.assert.notCalled(spy); - - done(); - }); - }); - }); - - describe("results in multiple branching chains with their own fulfillment values", function () { - testRejected(sentinel, function (promise, done) { - var semiDone = callbackAggregator(3, done); - - promise.then(null, function () { - return sentinel; - }).then(function (value) { - assert.strictEqual(value, sentinel); - semiDone(); - }); - - promise.then(null, function () { - throw sentinel2; - }).then(null, function (reason) { - assert.strictEqual(reason, sentinel2); - semiDone(); - }); - - promise.then(null, function () { - return sentinel3; - }).then(function (value) { - assert.strictEqual(value, sentinel3); - semiDone(); - }); - }); - }); - - describe("`onRejected` handlers are called in the original order", function () { - testRejected(dummy, function (promise, done) { - var handler1 = sinon.spy(function handler1() {}); - var handler2 = sinon.spy(function handler2() {}); - var handler3 = sinon.spy(function handler3() {}); - - promise.then(null, handler1); - promise.then(null, handler2); - promise.then(null, handler3); - - promise.then(null, function () { - sinon.assert.callOrder(handler1, handler2, handler3); - done(); - }); - }); - - describe("even when one handler is added inside another handler", function () { - testRejected(dummy, function (promise, done) { - var handler1 = sinon.spy(function handler1() {}); - var handler2 = sinon.spy(function handler2() {}); - var handler3 = sinon.spy(function handler3() {}); - - promise.then(null, function () { - handler1(); - promise.then(null, handler3); - }); - promise.then(null, handler2); - - promise.then(null, function () { - // Give implementations a bit of extra time to flush their internal queue, if necessary. - setTimeout(function () { - sinon.assert.callOrder(handler1, handler2, handler3); - done(); - }, 15); - }); - }); - }); - }); - }); -}); - -},{"./helpers/testThreeCases":22,"assert":2,"sinon":24}],16:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; -var testRejected = require("./helpers/testThreeCases").testRejected; -var reasons = require("./helpers/reasons"); - -var adapter = global.adapter; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality -var other = { other: "other" }; // a value we don't want to be strict equal to - -describe("2.2.7: `then` must return a promise: `promise2 = promise1.then(onFulfilled, onRejected)`", function () { - specify("is a promise", function () { - var promise1 = deferred().promise; - var promise2 = promise1.then(); - - assert(typeof promise2 === "object" || typeof promise2 === "function"); - assert.notStrictEqual(promise2, null); - assert.strictEqual(typeof promise2.then, "function"); - }); - - describe("2.2.7.1: If either `onFulfilled` or `onRejected` returns a value `x`, run the Promise Resolution " + - "Procedure `[[Resolve]](promise2, x)`", function () { - specify("see separate 3.3 tests", function () { }); - }); - - describe("2.2.7.2: If either `onFulfilled` or `onRejected` throws an exception `e`, `promise2` must be rejected " + - "with `e` as the reason.", function () { - function testReason(expectedReason, stringRepresentation) { - describe("The reason is " + stringRepresentation, function () { - testFulfilled(dummy, function (promise1, done) { - var promise2 = promise1.then(function onFulfilled() { - throw expectedReason; - }); - - promise2.then(null, function onPromise2Rejected(actualReason) { - assert.strictEqual(actualReason, expectedReason); - done(); - }); - }); - testRejected(dummy, function (promise1, done) { - var promise2 = promise1.then(null, function onRejected() { - throw expectedReason; - }); - - promise2.then(null, function onPromise2Rejected(actualReason) { - assert.strictEqual(actualReason, expectedReason); - done(); - }); - }); - }); - } - - Object.keys(reasons).forEach(function (stringRepresentation) { - testReason(reasons[stringRepresentation], stringRepresentation); - }); - }); - - describe("2.2.7.3: If `onFulfilled` is not a function and `promise1` is fulfilled, `promise2` must be fulfilled " + - "with the same value.", function () { - - function testNonFunction(nonFunction, stringRepresentation) { - describe("`onFulfilled` is " + stringRepresentation, function () { - testFulfilled(sentinel, function (promise1, done) { - var promise2 = promise1.then(nonFunction); - - promise2.then(function onPromise2Fulfilled(value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - testNonFunction([function () { return other; }], "an array containing a function"); - }); - - describe("2.2.7.4: If `onRejected` is not a function and `promise1` is rejected, `promise2` must be rejected " + - "with the same reason.", function () { - - function testNonFunction(nonFunction, stringRepresentation) { - describe("`onRejected` is " + stringRepresentation, function () { - testRejected(sentinel, function (promise1, done) { - var promise2 = promise1.then(null, nonFunction); - - promise2.then(null, function onPromise2Rejected(reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - } - - testNonFunction(undefined, "`undefined`"); - testNonFunction(null, "`null`"); - testNonFunction(false, "`false`"); - testNonFunction(5, "`5`"); - testNonFunction({}, "an object"); - testNonFunction([function () { return other; }], "an array containing a function"); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/reasons":21,"./helpers/testThreeCases":22,"assert":2}],17:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.3.1: If `promise` and `x` refer to the same object, reject `promise` with a `TypeError' as the reason.", - function () { - specify("via return from a fulfilled promise", function (done) { - var promise = resolved(dummy).then(function () { - return promise; - }); - - promise.then(null, function (reason) { - assert(reason instanceof TypeError); - done(); - }); - }); - - specify("via return from a rejected promise", function (done) { - var promise = rejected(dummy).then(null, function () { - return promise; - }); - - promise.then(null, function (reason) { - assert(reason instanceof TypeError); - done(); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"assert":2}],18:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality - -function testPromiseResolution(xFactory, test) { - specify("via return from a fulfilled promise", function (done) { - var promise = resolved(dummy).then(function onBasePromiseFulfilled() { - return xFactory(); - }); - - test(promise, done); - }); - - specify("via return from a rejected promise", function (done) { - var promise = rejected(dummy).then(null, function onBasePromiseRejected() { - return xFactory(); - }); - - test(promise, done); - }); -} - -describe("2.3.2: If `x` is a promise, adopt its state", function () { - describe("2.3.2.1: If `x` is pending, `promise` must remain pending until `x` is fulfilled or rejected.", - function () { - function xFactory() { - return deferred().promise; - } - - testPromiseResolution(xFactory, function (promise, done) { - var wasFulfilled = false; - var wasRejected = false; - - promise.then( - function onPromiseFulfilled() { - wasFulfilled = true; - }, - function onPromiseRejected() { - wasRejected = true; - } - ); - - setTimeout(function () { - assert.strictEqual(wasFulfilled, false); - assert.strictEqual(wasRejected, false); - done(); - }, 100); - }); - }); - - describe("2.3.2.2: If/when `x` is fulfilled, fulfill `promise` with the same value.", function () { - describe("`x` is already-fulfilled", function () { - function xFactory() { - return resolved(sentinel); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function onPromiseFulfilled(value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("`x` is eventually-fulfilled", function () { - var d = null; - - function xFactory() { - d = deferred(); - setTimeout(function () { - d.resolve(sentinel); - }, 50); - return d.promise; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function onPromiseFulfilled(value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - }); - - describe("2.3.2.3: If/when `x` is rejected, reject `promise` with the same reason.", function () { - describe("`x` is already-rejected", function () { - function xFactory() { - return rejected(sentinel); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function onPromiseRejected(reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`x` is eventually-rejected", function () { - var d = null; - - function xFactory() { - d = deferred(); - setTimeout(function () { - d.reject(sentinel); - }, 50); - return d.promise; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function onPromiseRejected(reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"assert":2}],19:[function(require,module,exports){ -(function (global){ -"use strict"; - -var assert = require("assert"); -var thenables = require("./helpers/thenables"); -var reasons = require("./helpers/reasons"); - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it -var sentinel = { sentinel: "sentinel" }; // a sentinel fulfillment value to test for with strict equality -var other = { other: "other" }; // a value we don't want to be strict equal to -var sentinelArray = [sentinel]; // a sentinel fulfillment value to test when we need an array - -function testPromiseResolution(xFactory, test) { - specify("via return from a fulfilled promise", function (done) { - var promise = resolved(dummy).then(function onBasePromiseFulfilled() { - return xFactory(); - }); - - test(promise, done); - }); - - specify("via return from a rejected promise", function (done) { - var promise = rejected(dummy).then(null, function onBasePromiseRejected() { - return xFactory(); - }); - - test(promise, done); - }); -} - -function testCallingResolvePromise(yFactory, stringRepresentation, test) { - describe("`y` is " + stringRepresentation, function () { - describe("`then` calls `resolvePromise` synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - resolvePromise(yFactory()); - } - }; - } - - testPromiseResolution(xFactory, test); - }); - - describe("`then` calls `resolvePromise` asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - setTimeout(function () { - resolvePromise(yFactory()); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, test); - }); - }); -} - -function testCallingRejectPromise(r, stringRepresentation, test) { - describe("`r` is " + stringRepresentation, function () { - describe("`then` calls `rejectPromise` synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(r); - } - }; - } - - testPromiseResolution(xFactory, test); - }); - - describe("`then` calls `rejectPromise` asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - rejectPromise(r); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, test); - }); - }); -} - -function testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, fulfillmentValue) { - testCallingResolvePromise(yFactory, stringRepresentation, function (promise, done) { - promise.then(function onPromiseFulfilled(value) { - assert.strictEqual(value, fulfillmentValue); - done(); - }); - }); -} - -function testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, rejectionReason) { - testCallingResolvePromise(yFactory, stringRepresentation, function (promise, done) { - promise.then(null, function onPromiseRejected(reason) { - assert.strictEqual(reason, rejectionReason); - done(); - }); - }); -} - -function testCallingRejectPromiseRejectsWith(reason, stringRepresentation) { - testCallingRejectPromise(reason, stringRepresentation, function (promise, done) { - promise.then(null, function onPromiseRejected(rejectionReason) { - assert.strictEqual(rejectionReason, reason); - done(); - }); - }); -} - -describe("2.3.3: Otherwise, if `x` is an object or function,", function () { - describe("2.3.3.1: Let `then` be `x.then`", function () { - describe("`x` is an object with null prototype", function () { - var numberOfTimesThenWasRetrieved = null; - - beforeEach(function () { - numberOfTimesThenWasRetrieved = 0; - }); - - function xFactory() { - return Object.create(null, { - then: { - get: function () { - ++numberOfTimesThenWasRetrieved; - return function thenMethodForX(onFulfilled) { - onFulfilled(); - }; - } - } - }); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - assert.strictEqual(numberOfTimesThenWasRetrieved, 1); - done(); - }); - }); - }); - - describe("`x` is an object with normal Object.prototype", function () { - var numberOfTimesThenWasRetrieved = null; - - beforeEach(function () { - numberOfTimesThenWasRetrieved = 0; - }); - - function xFactory() { - return Object.create(Object.prototype, { - then: { - get: function () { - ++numberOfTimesThenWasRetrieved; - return function thenMethodForX(onFulfilled) { - onFulfilled(); - }; - } - } - }); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - assert.strictEqual(numberOfTimesThenWasRetrieved, 1); - done(); - }); - }); - }); - - describe("`x` is a function", function () { - var numberOfTimesThenWasRetrieved = null; - - beforeEach(function () { - numberOfTimesThenWasRetrieved = 0; - }); - - function xFactory() { - function x() { } - - Object.defineProperty(x, "then", { - get: function () { - ++numberOfTimesThenWasRetrieved; - return function thenMethodForX(onFulfilled) { - onFulfilled(); - }; - } - }); - - return x; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - assert.strictEqual(numberOfTimesThenWasRetrieved, 1); - done(); - }); - }); - }); - }); - - describe("2.3.3.2: If retrieving the property `x.then` results in a thrown exception `e`, reject `promise` with " + - "`e` as the reason.", function () { - function testRejectionViaThrowingGetter(e, stringRepresentation) { - function xFactory() { - return Object.create(Object.prototype, { - then: { - get: function () { - throw e; - } - } - }); - } - - describe("`e` is " + stringRepresentation, function () { - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, e); - done(); - }); - }); - }); - } - - Object.keys(reasons).forEach(function (stringRepresentation) { - testRejectionViaThrowingGetter(reasons[stringRepresentation], stringRepresentation); - }); - }); - - describe("2.3.3.3: If `then` is a function, call it with `x` as `this`, first argument `resolvePromise`, and " + - "second argument `rejectPromise`", function () { - describe("Calls with `x` as `this` and two function arguments", function () { - function xFactory() { - var x = { - then: function (onFulfilled, onRejected) { - assert.strictEqual(this, x); - assert.strictEqual(typeof onFulfilled, "function"); - assert.strictEqual(typeof onRejected, "function"); - onFulfilled(); - } - }; - return x; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - done(); - }); - }); - }); - - describe("Uses the original value of `then`", function () { - var numberOfTimesThenWasRetrieved = null; - - beforeEach(function () { - numberOfTimesThenWasRetrieved = 0; - }); - - function xFactory() { - return Object.create(Object.prototype, { - then: { - get: function () { - if (numberOfTimesThenWasRetrieved === 0) { - return function (onFulfilled) { - onFulfilled(); - }; - } - return null; - } - } - }); - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function () { - done(); - }); - }); - }); - - describe("2.3.3.3.1: If/when `resolvePromise` is called with value `y`, run `[[Resolve]](promise, y)`", - function () { - describe("`y` is not a thenable", function () { - testCallingResolvePromiseFulfillsWith(function () { return undefined; }, "`undefined`", undefined); - testCallingResolvePromiseFulfillsWith(function () { return null; }, "`null`", null); - testCallingResolvePromiseFulfillsWith(function () { return false; }, "`false`", false); - testCallingResolvePromiseFulfillsWith(function () { return 5; }, "`5`", 5); - testCallingResolvePromiseFulfillsWith(function () { return sentinel; }, "an object", sentinel); - testCallingResolvePromiseFulfillsWith(function () { return sentinelArray; }, "an array", sentinelArray); - }); - - describe("`y` is a thenable", function () { - Object.keys(thenables.fulfilled).forEach(function (stringRepresentation) { - function yFactory() { - return thenables.fulfilled[stringRepresentation](sentinel); - } - - testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, sentinel); - }); - - Object.keys(thenables.rejected).forEach(function (stringRepresentation) { - function yFactory() { - return thenables.rejected[stringRepresentation](sentinel); - } - - testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, sentinel); - }); - }); - - describe("`y` is a thenable for a thenable", function () { - Object.keys(thenables.fulfilled).forEach(function (outerStringRepresentation) { - var outerThenableFactory = thenables.fulfilled[outerStringRepresentation]; - - Object.keys(thenables.fulfilled).forEach(function (innerStringRepresentation) { - var innerThenableFactory = thenables.fulfilled[innerStringRepresentation]; - - var stringRepresentation = outerStringRepresentation + " for " + innerStringRepresentation; - - function yFactory() { - return outerThenableFactory(innerThenableFactory(sentinel)); - } - - testCallingResolvePromiseFulfillsWith(yFactory, stringRepresentation, sentinel); - }); - - Object.keys(thenables.rejected).forEach(function (innerStringRepresentation) { - var innerThenableFactory = thenables.rejected[innerStringRepresentation]; - - var stringRepresentation = outerStringRepresentation + " for " + innerStringRepresentation; - - function yFactory() { - return outerThenableFactory(innerThenableFactory(sentinel)); - } - - testCallingResolvePromiseRejectsWith(yFactory, stringRepresentation, sentinel); - }); - }); - }); - }); - - describe("2.3.3.3.2: If/when `rejectPromise` is called with reason `r`, reject `promise` with `r`", - function () { - Object.keys(reasons).forEach(function (stringRepresentation) { - testCallingRejectPromiseRejectsWith(reasons[stringRepresentation], stringRepresentation); - }); - }); - - describe("2.3.3.3.3: If both `resolvePromise` and `rejectPromise` are called, or multiple calls to the same " + - "argument are made, the first call takes precedence, and any further calls are ignored.", - function () { - describe("calling `resolvePromise` then `rejectPromise`, both synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(sentinel); - rejectPromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` synchronously then `rejectPromise` asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(sentinel); - - setTimeout(function () { - rejectPromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` then `rejectPromise`, both asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - resolvePromise(sentinel); - }, 0); - - setTimeout(function () { - rejectPromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` with an asynchronously-fulfilled promise, then calling " + - "`rejectPromise`, both synchronously", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.resolve(sentinel); - }, 50); - - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(d.promise); - rejectPromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` with an asynchronously-rejected promise, then calling " + - "`rejectPromise`, both synchronously", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.reject(sentinel); - }, 50); - - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(d.promise); - rejectPromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` then `resolvePromise`, both synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - resolvePromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` synchronously then `resolvePromise` asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - - setTimeout(function () { - resolvePromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` then `resolvePromise`, both asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - rejectPromise(sentinel); - }, 0); - - setTimeout(function () { - resolvePromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` twice synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - resolvePromise(sentinel); - resolvePromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` twice, first synchronously then asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - resolvePromise(sentinel); - - setTimeout(function () { - resolvePromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` twice, both times asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise) { - setTimeout(function () { - resolvePromise(sentinel); - }, 0); - - setTimeout(function () { - resolvePromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` with an asynchronously-fulfilled promise, then calling it again, both " + - "times synchronously", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.resolve(sentinel); - }, 50); - - return { - then: function (resolvePromise) { - resolvePromise(d.promise); - resolvePromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("calling `resolvePromise` with an asynchronously-rejected promise, then calling it again, both " + - "times synchronously", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.reject(sentinel); - }, 50); - - return { - then: function (resolvePromise) { - resolvePromise(d.promise); - resolvePromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` twice synchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - rejectPromise(other); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` twice, first synchronously then asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - - setTimeout(function () { - rejectPromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("calling `rejectPromise` twice, both times asynchronously", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - rejectPromise(sentinel); - }, 0); - - setTimeout(function () { - rejectPromise(other); - }, 0); - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("saving and abusing `resolvePromise` and `rejectPromise`", function () { - var savedResolvePromise, savedRejectPromise; - - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - savedResolvePromise = resolvePromise; - savedRejectPromise = rejectPromise; - } - }; - } - - beforeEach(function () { - savedResolvePromise = null; - savedRejectPromise = null; - }); - - testPromiseResolution(xFactory, function (promise, done) { - var timesFulfilled = 0; - var timesRejected = 0; - - promise.then( - function () { - ++timesFulfilled; - }, - function () { - ++timesRejected; - } - ); - - if (savedResolvePromise && savedRejectPromise) { - savedResolvePromise(dummy); - savedResolvePromise(dummy); - savedRejectPromise(dummy); - savedRejectPromise(dummy); - } - - setTimeout(function () { - savedResolvePromise(dummy); - savedResolvePromise(dummy); - savedRejectPromise(dummy); - savedRejectPromise(dummy); - }, 50); - - setTimeout(function () { - assert.strictEqual(timesFulfilled, 1); - assert.strictEqual(timesRejected, 0); - done(); - }, 100); - }); - }); - }); - - describe("2.3.3.3.4: If calling `then` throws an exception `e`,", function () { - describe("2.3.3.3.4.1: If `resolvePromise` or `rejectPromise` have been called, ignore it.", function () { - describe("`resolvePromise` was called with a non-thenable", function () { - function xFactory() { - return { - then: function (resolvePromise) { - resolvePromise(sentinel); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("`resolvePromise` was called with an asynchronously-fulfilled promise", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.resolve(sentinel); - }, 50); - - return { - then: function (resolvePromise) { - resolvePromise(d.promise); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("`resolvePromise` was called with an asynchronously-rejected promise", function () { - function xFactory() { - var d = deferred(); - setTimeout(function () { - d.reject(sentinel); - }, 50); - - return { - then: function (resolvePromise) { - resolvePromise(d.promise); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`rejectPromise` was called", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`resolvePromise` then `rejectPromise` were called", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - resolvePromise(sentinel); - rejectPromise(other); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, sentinel); - done(); - }); - }); - }); - - describe("`rejectPromise` then `resolvePromise` were called", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - rejectPromise(sentinel); - resolvePromise(other); - throw other; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - }); - - describe("2.3.3.3.4.2: Otherwise, reject `promise` with `e` as the reason.", function () { - describe("straightforward case", function () { - function xFactory() { - return { - then: function () { - throw sentinel; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`resolvePromise` is called asynchronously before the `throw`", function () { - function xFactory() { - return { - then: function (resolvePromise) { - setTimeout(function () { - resolvePromise(other); - }, 0); - throw sentinel; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - - describe("`rejectPromise` is called asynchronously before the `throw`", function () { - function xFactory() { - return { - then: function (resolvePromise, rejectPromise) { - setTimeout(function () { - rejectPromise(other); - }, 0); - throw sentinel; - } - }; - } - - testPromiseResolution(xFactory, function (promise, done) { - promise.then(null, function (reason) { - assert.strictEqual(reason, sentinel); - done(); - }); - }); - }); - }); - }); - }); - - describe("2.3.3.4: If `then` is not a function, fulfill promise with `x`", function () { - function testFulfillViaNonFunction(then, stringRepresentation) { - var x = null; - - beforeEach(function () { - x = { then: then }; - }); - - function xFactory() { - return x; - } - - describe("`then` is " + stringRepresentation, function () { - testPromiseResolution(xFactory, function (promise, done) { - promise.then(function (value) { - assert.strictEqual(value, x); - done(); - }); - }); - }); - } - - testFulfillViaNonFunction(5, "`5`"); - testFulfillViaNonFunction({}, "an object"); - testFulfillViaNonFunction([function () { }], "an array containing a function"); - testFulfillViaNonFunction(/a-b/i, "a regular expression"); - testFulfillViaNonFunction(Object.create(Function.prototype), "an object inheriting from `Function.prototype`"); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./helpers/reasons":21,"./helpers/thenables":23,"assert":2}],20:[function(require,module,exports){ -"use strict"; - -var assert = require("assert"); -var testFulfilled = require("./helpers/testThreeCases").testFulfilled; -var testRejected = require("./helpers/testThreeCases").testRejected; - -var dummy = { dummy: "dummy" }; // we fulfill or reject with this when we don't intend to test against it - -describe("2.3.4: If `x` is not an object or function, fulfill `promise` with `x`", function () { - function testValue(expectedValue, stringRepresentation, beforeEachHook, afterEachHook) { - describe("The value is " + stringRepresentation, function () { - if (typeof beforeEachHook === "function") { - beforeEach(beforeEachHook); - } - if (typeof afterEachHook === "function") { - afterEach(afterEachHook); - } - - testFulfilled(dummy, function (promise1, done) { - var promise2 = promise1.then(function onFulfilled() { - return expectedValue; - }); - - promise2.then(function onPromise2Fulfilled(actualValue) { - assert.strictEqual(actualValue, expectedValue); - done(); - }); - }); - testRejected(dummy, function (promise1, done) { - var promise2 = promise1.then(null, function onRejected() { - return expectedValue; - }); - - promise2.then(function onPromise2Fulfilled(actualValue) { - assert.strictEqual(actualValue, expectedValue); - done(); - }); - }); - }); - } - - testValue(undefined, "`undefined`"); - testValue(null, "`null`"); - testValue(false, "`false`"); - testValue(true, "`true`"); - testValue(0, "`0`"); - - testValue( - true, - "`true` with `Boolean.prototype` modified to have a `then` method", - function () { - Boolean.prototype.then = function () {}; - }, - function () { - delete Boolean.prototype.then; - } - ); - - testValue( - 1, - "`1` with `Number.prototype` modified to have a `then` method", - function () { - Number.prototype.then = function () {}; - }, - function () { - delete Number.prototype.then; - } - ); -}); - -},{"./helpers/testThreeCases":22,"assert":2}],21:[function(require,module,exports){ -(function (global){ -"use strict"; - -// This module exports some valid rejection reason factories, keyed by human-readable versions of their names. - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; - -var dummy = { dummy: "dummy" }; - -exports["`undefined`"] = function () { - return undefined; -}; - -exports["`null`"] = function () { - return null; -}; - -exports["`false`"] = function () { - return false; -}; - -exports["`0`"] = function () { - return 0; -}; - -exports["an error"] = function () { - return new Error(); -}; - -exports["an error without a stack"] = function () { - var error = new Error(); - delete error.stack; - - return error; -}; - -exports["a date"] = function () { - return new Date(); -}; - -exports["an object"] = function () { - return {}; -}; - -exports["an always-pending thenable"] = function () { - return { then: function () { } }; -}; - -exports["a fulfilled promise"] = function () { - return resolved(dummy); -}; - -exports["a rejected promise"] = function () { - return rejected(dummy); -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],22:[function(require,module,exports){ -(function (global){ -"use strict"; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -exports.testFulfilled = function (value, test) { - specify("already-fulfilled", function (done) { - test(resolved(value), done); - }); - - specify("immediately-fulfilled", function (done) { - var d = deferred(); - test(d.promise, done); - d.resolve(value); - }); - - specify("eventually-fulfilled", function (done) { - var d = deferred(); - test(d.promise, done); - setTimeout(function () { - d.resolve(value); - }, 50); - }); -}; - -exports.testRejected = function (reason, test) { - specify("already-rejected", function (done) { - test(rejected(reason), done); - }); - - specify("immediately-rejected", function (done) { - var d = deferred(); - test(d.promise, done); - d.reject(reason); - }); - - specify("eventually-rejected", function (done) { - var d = deferred(); - test(d.promise, done); - setTimeout(function () { - d.reject(reason); - }, 50); - }); -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],23:[function(require,module,exports){ -(function (global){ -"use strict"; - -var adapter = global.adapter; -var resolved = adapter.resolved; -var rejected = adapter.rejected; -var deferred = adapter.deferred; - -var other = { other: "other" }; // a value we don't want to be strict equal to - -exports.fulfilled = { - "a synchronously-fulfilled custom thenable": function (value) { - return { - then: function (onFulfilled) { - onFulfilled(value); - } - }; - }, - - "an asynchronously-fulfilled custom thenable": function (value) { - return { - then: function (onFulfilled) { - setTimeout(function () { - onFulfilled(value); - }, 0); - } - }; - }, - - "a synchronously-fulfilled one-time thenable": function (value) { - var numberOfTimesThenRetrieved = 0; - return Object.create(null, { - then: { - get: function () { - if (numberOfTimesThenRetrieved === 0) { - ++numberOfTimesThenRetrieved; - return function (onFulfilled) { - onFulfilled(value); - }; - } - return null; - } - } - }); - }, - - "a thenable that tries to fulfill twice": function (value) { - return { - then: function (onFulfilled) { - onFulfilled(value); - onFulfilled(other); - } - }; - }, - - "a thenable that fulfills but then throws": function (value) { - return { - then: function (onFulfilled) { - onFulfilled(value); - throw other; - } - }; - }, - - "an already-fulfilled promise": function (value) { - return resolved(value); - }, - - "an eventually-fulfilled promise": function (value) { - var d = deferred(); - setTimeout(function () { - d.resolve(value); - }, 50); - return d.promise; - } -}; - -exports.rejected = { - "a synchronously-rejected custom thenable": function (reason) { - return { - then: function (onFulfilled, onRejected) { - onRejected(reason); - } - }; - }, - - "an asynchronously-rejected custom thenable": function (reason) { - return { - then: function (onFulfilled, onRejected) { - setTimeout(function () { - onRejected(reason); - }, 0); - } - }; - }, - - "a synchronously-rejected one-time thenable": function (reason) { - var numberOfTimesThenRetrieved = 0; - return Object.create(null, { - then: { - get: function () { - if (numberOfTimesThenRetrieved === 0) { - ++numberOfTimesThenRetrieved; - return function (onFulfilled, onRejected) { - onRejected(reason); - }; - } - return null; - } - } - }); - }, - - "a thenable that immediately throws in `then`": function (reason) { - return { - then: function () { - throw reason; - } - }; - }, - - "an object with a throwing `then` accessor": function (reason) { - return Object.create(null, { - then: { - get: function () { - throw reason; - } - } - }); - }, - - "an already-rejected promise": function (reason) { - return rejected(reason); - }, - - "an eventually-rejected promise": function (reason) { - var d = deferred(); - setTimeout(function () { - d.reject(reason); - }, 50); - return d.promise; - } -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],24:[function(require,module,exports){ -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -var sinon = (function () { - var sinon; - var isNode = typeof module !== "undefined" && module.exports && typeof require === "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - sinon = module.exports = require("./sinon/util/core"); - require("./sinon/extend"); - require("./sinon/typeOf"); - require("./sinon/times_in_words"); - require("./sinon/spy"); - require("./sinon/call"); - require("./sinon/behavior"); - require("./sinon/stub"); - require("./sinon/mock"); - require("./sinon/collection"); - require("./sinon/assert"); - require("./sinon/sandbox"); - require("./sinon/test"); - require("./sinon/test_case"); - require("./sinon/match"); - require("./sinon/format"); - require("./sinon/log_error"); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - sinon = module.exports; - } else { - sinon = {}; - } - - return sinon; -}()); - -},{"./sinon/assert":25,"./sinon/behavior":26,"./sinon/call":27,"./sinon/collection":28,"./sinon/extend":29,"./sinon/format":30,"./sinon/log_error":31,"./sinon/match":32,"./sinon/mock":33,"./sinon/sandbox":34,"./sinon/spy":35,"./sinon/stub":36,"./sinon/test":37,"./sinon/test_case":38,"./sinon/times_in_words":39,"./sinon/typeOf":40,"./sinon/util/core":41}],25:[function(require,module,exports){ -(function (global){ -/** - * @depend times_in_words.js - * @depend util/core.js - * @depend match.js - * @depend format.js - */ -/** - * Assertions matching the test spy retrieval interface. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon, global) { - var slice = Array.prototype.slice; - - function makeApi(sinon) { - var assert; - - function verifyIsStub() { - var method; - - for (var i = 0, l = arguments.length; i < l; ++i) { - method = arguments[i]; - - if (!method) { - assert.fail("fake is not a spy"); - } - - if (method.proxy) { - verifyIsStub(method.proxy); - } else { - if (typeof method != "function") { - assert.fail(method + " is not a function"); - } - - if (typeof method.getCall != "function") { - assert.fail(method + " is not stubbed"); - } - } - - } - } - - function failAssertion(object, msg) { - object = object || global; - var failMethod = object.fail || assert.fail; - failMethod.call(object, msg); - } - - function mirrorPropAsAssertion(name, method, message) { - if (arguments.length == 2) { - message = method; - method = name; - } - - assert[name] = function (fake) { - verifyIsStub(fake); - - var args = slice.call(arguments, 1); - var failed = false; - - if (typeof method == "function") { - failed = !method(fake); - } else { - failed = typeof fake[method] == "function" ? - !fake[method].apply(fake, args) : !fake[method]; - } - - if (failed) { - failAssertion(this, (fake.printf || fake.proxy.printf).apply(fake, [message].concat(args))); - } else { - assert.pass(name); - } - }; - } - - function exposedName(prefix, prop) { - return !prefix || /^fail/.test(prop) ? prop : - prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1); - } - - assert = { - failException: "AssertError", - - fail: function fail(message) { - var error = new Error(message); - error.name = this.failException || assert.failException; - - throw error; - }, - - pass: function pass(assertion) {}, - - callOrder: function assertCallOrder() { - verifyIsStub.apply(null, arguments); - var expected = "", actual = ""; - - if (!sinon.calledInOrder(arguments)) { - try { - expected = [].join.call(arguments, ", "); - var calls = slice.call(arguments); - var i = calls.length; - while (i) { - if (!calls[--i].called) { - calls.splice(i, 1); - } - } - actual = sinon.orderByFirstCall(calls).join(", "); - } catch (e) { - // If this fails, we'll just fall back to the blank string - } - - failAssertion(this, "expected " + expected + " to be " + - "called in order but were called as " + actual); - } else { - assert.pass("callOrder"); - } - }, - - callCount: function assertCallCount(method, count) { - verifyIsStub(method); - - if (method.callCount != count) { - var msg = "expected %n to be called " + sinon.timesInWords(count) + - " but was called %c%C"; - failAssertion(this, method.printf(msg)); - } else { - assert.pass("callCount"); - } - }, - - expose: function expose(target, options) { - if (!target) { - throw new TypeError("target is null or undefined"); - } - - var o = options || {}; - var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix; - var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail; - - for (var method in this) { - if (method != "expose" && (includeFail || !/^(fail)/.test(method))) { - target[exposedName(prefix, method)] = this[method]; - } - } - - return target; - }, - - match: function match(actual, expectation) { - var matcher = sinon.match(expectation); - if (matcher.test(actual)) { - assert.pass("match"); - } else { - var formatted = [ - "expected value to match", - " expected = " + sinon.format(expectation), - " actual = " + sinon.format(actual) - ] - failAssertion(this, formatted.join("\n")); - } - } - }; - - mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called"); - mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; }, - "expected %n to not have been called but was called %c%C"); - mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C"); - mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C"); - mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C"); - mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t"); - mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t"); - mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new"); - mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new"); - mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C"); - mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C"); - mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C"); - mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C"); - mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C"); - mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C"); - mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C"); - mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C"); - mirrorPropAsAssertion("threw", "%n did not throw exception%C"); - mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C"); - - sinon.assert = assert; - return assert; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./match"); - require("./format"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } - -}(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./format":30,"./match":32,"./util/core":41}],26:[function(require,module,exports){ -(function (process){ -/** - * @depend util/core.js - * @depend extend.js - */ -/** - * Stub behavior - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Tim Fischbach (mail@timfischbach.de) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - var slice = Array.prototype.slice; - var join = Array.prototype.join; - var useLeftMostCallback = -1; - var useRightMostCallback = -2; - - var nextTick = (function () { - if (typeof process === "object" && typeof process.nextTick === "function") { - return process.nextTick; - } else if (typeof setImmediate === "function") { - return setImmediate; - } else { - return function (callback) { - setTimeout(callback, 0); - }; - } - })(); - - function throwsException(error, message) { - if (typeof error == "string") { - this.exception = new Error(message || ""); - this.exception.name = error; - } else if (!error) { - this.exception = new Error("Error"); - } else { - this.exception = error; - } - - return this; - } - - function getCallback(behavior, args) { - var callArgAt = behavior.callArgAt; - - if (callArgAt >= 0) { - return args[callArgAt]; - } - - var argumentList; - - if (callArgAt === useLeftMostCallback) { - argumentList = args; - } - - if (callArgAt === useRightMostCallback) { - argumentList = slice.call(args).reverse(); - } - - var callArgProp = behavior.callArgProp; - - for (var i = 0, l = argumentList.length; i < l; ++i) { - if (!callArgProp && typeof argumentList[i] == "function") { - return argumentList[i]; - } - - if (callArgProp && argumentList[i] && - typeof argumentList[i][callArgProp] == "function") { - return argumentList[i][callArgProp]; - } - } - - return null; - } - - function makeApi(sinon) { - function getCallbackError(behavior, func, args) { - if (behavior.callArgAt < 0) { - var msg; - - if (behavior.callArgProp) { - msg = sinon.functionName(behavior.stub) + - " expected to yield to '" + behavior.callArgProp + - "', but no object with such a property was passed."; - } else { - msg = sinon.functionName(behavior.stub) + - " expected to yield, but no callback was passed."; - } - - if (args.length > 0) { - msg += " Received [" + join.call(args, ", ") + "]"; - } - - return msg; - } - - return "argument at index " + behavior.callArgAt + " is not a function: " + func; - } - - function callCallback(behavior, args) { - if (typeof behavior.callArgAt == "number") { - var func = getCallback(behavior, args); - - if (typeof func != "function") { - throw new TypeError(getCallbackError(behavior, func, args)); - } - - if (behavior.callbackAsync) { - nextTick(function () { - func.apply(behavior.callbackContext, behavior.callbackArguments); - }); - } else { - func.apply(behavior.callbackContext, behavior.callbackArguments); - } - } - } - - var proto = { - create: function create(stub) { - var behavior = sinon.extend({}, sinon.behavior); - delete behavior.create; - behavior.stub = stub; - - return behavior; - }, - - isPresent: function isPresent() { - return (typeof this.callArgAt == "number" || - this.exception || - typeof this.returnArgAt == "number" || - this.returnThis || - this.returnValueDefined); - }, - - invoke: function invoke(context, args) { - callCallback(this, args); - - if (this.exception) { - throw this.exception; - } else if (typeof this.returnArgAt == "number") { - return args[this.returnArgAt]; - } else if (this.returnThis) { - return context; - } - - return this.returnValue; - }, - - onCall: function onCall(index) { - return this.stub.onCall(index); - }, - - onFirstCall: function onFirstCall() { - return this.stub.onFirstCall(); - }, - - onSecondCall: function onSecondCall() { - return this.stub.onSecondCall(); - }, - - onThirdCall: function onThirdCall() { - return this.stub.onThirdCall(); - }, - - withArgs: function withArgs(/* arguments */) { - throw new Error("Defining a stub by invoking \"stub.onCall(...).withArgs(...)\" is not supported. " + - "Use \"stub.withArgs(...).onCall(...)\" to define sequential behavior for calls with certain arguments."); - }, - - callsArg: function callsArg(pos) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - - this.callArgAt = pos; - this.callbackArguments = []; - this.callbackContext = undefined; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - callsArgOn: function callsArgOn(pos, context) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - if (typeof context != "object") { - throw new TypeError("argument context is not an object"); - } - - this.callArgAt = pos; - this.callbackArguments = []; - this.callbackContext = context; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - callsArgWith: function callsArgWith(pos) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - - this.callArgAt = pos; - this.callbackArguments = slice.call(arguments, 1); - this.callbackContext = undefined; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - callsArgOnWith: function callsArgWith(pos, context) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - if (typeof context != "object") { - throw new TypeError("argument context is not an object"); - } - - this.callArgAt = pos; - this.callbackArguments = slice.call(arguments, 2); - this.callbackContext = context; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - yields: function () { - this.callArgAt = useLeftMostCallback; - this.callbackArguments = slice.call(arguments, 0); - this.callbackContext = undefined; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - yieldsRight: function () { - this.callArgAt = useRightMostCallback; - this.callbackArguments = slice.call(arguments, 0); - this.callbackContext = undefined; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - yieldsOn: function (context) { - if (typeof context != "object") { - throw new TypeError("argument context is not an object"); - } - - this.callArgAt = useLeftMostCallback; - this.callbackArguments = slice.call(arguments, 1); - this.callbackContext = context; - this.callArgProp = undefined; - this.callbackAsync = false; - - return this; - }, - - yieldsTo: function (prop) { - this.callArgAt = useLeftMostCallback; - this.callbackArguments = slice.call(arguments, 1); - this.callbackContext = undefined; - this.callArgProp = prop; - this.callbackAsync = false; - - return this; - }, - - yieldsToOn: function (prop, context) { - if (typeof context != "object") { - throw new TypeError("argument context is not an object"); - } - - this.callArgAt = useLeftMostCallback; - this.callbackArguments = slice.call(arguments, 2); - this.callbackContext = context; - this.callArgProp = prop; - this.callbackAsync = false; - - return this; - }, - - throws: throwsException, - throwsException: throwsException, - - returns: function returns(value) { - this.returnValue = value; - this.returnValueDefined = true; - - return this; - }, - - returnsArg: function returnsArg(pos) { - if (typeof pos != "number") { - throw new TypeError("argument index is not number"); - } - - this.returnArgAt = pos; - - return this; - }, - - returnsThis: function returnsThis() { - this.returnThis = true; - - return this; - } - }; - - // create asynchronous versions of callsArg* and yields* methods - for (var method in proto) { - // need to avoid creating anotherasync versions of the newly added async methods - if (proto.hasOwnProperty(method) && - method.match(/^(callsArg|yields)/) && - !method.match(/Async/)) { - proto[method + "Async"] = (function (syncFnName) { - return function () { - var result = this[syncFnName].apply(this, arguments); - this.callbackAsync = true; - return result; - }; - })(method); - } - } - - sinon.behavior = proto; - return proto; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./extend"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -}).call(this,require('_process')) -},{"./extend":29,"./util/core":41,"_process":4}],27:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend match.js - * @depend format.js - */ -/** - * Spy calls - * - * @author Christian Johansen (christian@cjohansen.no) - * @author Maximilian Antoni (mail@maxantoni.de) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - * Copyright (c) 2013 Maximilian Antoni - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - function throwYieldError(proxy, text, args) { - var msg = sinon.functionName(proxy) + text; - if (args.length) { - msg += " Received [" + slice.call(args).join(", ") + "]"; - } - throw new Error(msg); - } - - var slice = Array.prototype.slice; - - var callProto = { - calledOn: function calledOn(thisValue) { - if (sinon.match && sinon.match.isMatcher(thisValue)) { - return thisValue.test(this.thisValue); - } - return this.thisValue === thisValue; - }, - - calledWith: function calledWith() { - var l = arguments.length; - if (l > this.args.length) { - return false; - } - for (var i = 0; i < l; i += 1) { - if (!sinon.deepEqual(arguments[i], this.args[i])) { - return false; - } - } - - return true; - }, - - calledWithMatch: function calledWithMatch() { - var l = arguments.length; - if (l > this.args.length) { - return false; - } - for (var i = 0; i < l; i += 1) { - var actual = this.args[i]; - var expectation = arguments[i]; - if (!sinon.match || !sinon.match(expectation).test(actual)) { - return false; - } - } - return true; - }, - - calledWithExactly: function calledWithExactly() { - return arguments.length == this.args.length && - this.calledWith.apply(this, arguments); - }, - - notCalledWith: function notCalledWith() { - return !this.calledWith.apply(this, arguments); - }, - - notCalledWithMatch: function notCalledWithMatch() { - return !this.calledWithMatch.apply(this, arguments); - }, - - returned: function returned(value) { - return sinon.deepEqual(value, this.returnValue); - }, - - threw: function threw(error) { - if (typeof error === "undefined" || !this.exception) { - return !!this.exception; - } - - return this.exception === error || this.exception.name === error; - }, - - calledWithNew: function calledWithNew() { - return this.proxy.prototype && this.thisValue instanceof this.proxy; - }, - - calledBefore: function (other) { - return this.callId < other.callId; - }, - - calledAfter: function (other) { - return this.callId > other.callId; - }, - - callArg: function (pos) { - this.args[pos](); - }, - - callArgOn: function (pos, thisValue) { - this.args[pos].apply(thisValue); - }, - - callArgWith: function (pos) { - this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); - }, - - callArgOnWith: function (pos, thisValue) { - var args = slice.call(arguments, 2); - this.args[pos].apply(thisValue, args); - }, - - yield: function () { - this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); - }, - - yieldOn: function (thisValue) { - var args = this.args; - for (var i = 0, l = args.length; i < l; ++i) { - if (typeof args[i] === "function") { - args[i].apply(thisValue, slice.call(arguments, 1)); - return; - } - } - throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); - }, - - yieldTo: function (prop) { - this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); - }, - - yieldToOn: function (prop, thisValue) { - var args = this.args; - for (var i = 0, l = args.length; i < l; ++i) { - if (args[i] && typeof args[i][prop] === "function") { - args[i][prop].apply(thisValue, slice.call(arguments, 2)); - return; - } - } - throwYieldError(this.proxy, " cannot yield to '" + prop + - "' since no callback was passed.", args); - }, - - toString: function () { - var callStr = this.proxy.toString() + "("; - var args = []; - - for (var i = 0, l = this.args.length; i < l; ++i) { - args.push(sinon.format(this.args[i])); - } - - callStr = callStr + args.join(", ") + ")"; - - if (typeof this.returnValue != "undefined") { - callStr += " => " + sinon.format(this.returnValue); - } - - if (this.exception) { - callStr += " !" + this.exception.name; - - if (this.exception.message) { - callStr += "(" + this.exception.message + ")"; - } - } - - return callStr; - } - }; - - callProto.invokeCallback = callProto.yield; - - function createSpyCall(spy, thisValue, args, returnValue, exception, id) { - if (typeof id !== "number") { - throw new TypeError("Call id is not a number"); - } - var proxyCall = sinon.create(callProto); - proxyCall.proxy = spy; - proxyCall.thisValue = thisValue; - proxyCall.args = args; - proxyCall.returnValue = returnValue; - proxyCall.exception = exception; - proxyCall.callId = id; - - return proxyCall; - } - createSpyCall.toString = callProto.toString; // used by mocks - - sinon.spyCall = createSpyCall; - return createSpyCall; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./match"); - require("./format"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./format":30,"./match":32,"./util/core":41}],28:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend spy.js - * @depend stub.js - * @depend mock.js - */ -/** - * Collections of stubs, spies and mocks. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - var push = [].push; - var hasOwnProperty = Object.prototype.hasOwnProperty; - - function getFakes(fakeCollection) { - if (!fakeCollection.fakes) { - fakeCollection.fakes = []; - } - - return fakeCollection.fakes; - } - - function each(fakeCollection, method) { - var fakes = getFakes(fakeCollection); - - for (var i = 0, l = fakes.length; i < l; i += 1) { - if (typeof fakes[i][method] == "function") { - fakes[i][method](); - } - } - } - - function compact(fakeCollection) { - var fakes = getFakes(fakeCollection); - var i = 0; - while (i < fakes.length) { - fakes.splice(i, 1); - } - } - - function makeApi(sinon) { - var collection = { - verify: function resolve() { - each(this, "verify"); - }, - - restore: function restore() { - each(this, "restore"); - compact(this); - }, - - reset: function restore() { - each(this, "reset"); - }, - - verifyAndRestore: function verifyAndRestore() { - var exception; - - try { - this.verify(); - } catch (e) { - exception = e; - } - - this.restore(); - - if (exception) { - throw exception; - } - }, - - add: function add(fake) { - push.call(getFakes(this), fake); - return fake; - }, - - spy: function spy() { - return this.add(sinon.spy.apply(sinon, arguments)); - }, - - stub: function stub(object, property, value) { - if (property) { - var original = object[property]; - - if (typeof original != "function") { - if (!hasOwnProperty.call(object, property)) { - throw new TypeError("Cannot stub non-existent own property " + property); - } - - object[property] = value; - - return this.add({ - restore: function () { - object[property] = original; - } - }); - } - } - if (!property && !!object && typeof object == "object") { - var stubbedObj = sinon.stub.apply(sinon, arguments); - - for (var prop in stubbedObj) { - if (typeof stubbedObj[prop] === "function") { - this.add(stubbedObj[prop]); - } - } - - return stubbedObj; - } - - return this.add(sinon.stub.apply(sinon, arguments)); - }, - - mock: function mock() { - return this.add(sinon.mock.apply(sinon, arguments)); - }, - - inject: function inject(obj) { - var col = this; - - obj.spy = function () { - return col.spy.apply(col, arguments); - }; - - obj.stub = function () { - return col.stub.apply(col, arguments); - }; - - obj.mock = function () { - return col.mock.apply(col, arguments); - }; - - return obj; - } - }; - - sinon.collection = collection; - return collection; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./mock"); - require("./spy"); - require("./stub"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./mock":33,"./spy":35,"./stub":36,"./util/core":41}],29:[function(require,module,exports){ -/** - * @depend util/core.js - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - - // Adapted from https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug - var hasDontEnumBug = (function () { - var obj = { - constructor: function () { - return "0"; - }, - toString: function () { - return "1"; - }, - valueOf: function () { - return "2"; - }, - toLocaleString: function () { - return "3"; - }, - prototype: function () { - return "4"; - }, - isPrototypeOf: function () { - return "5"; - }, - propertyIsEnumerable: function () { - return "6"; - }, - hasOwnProperty: function () { - return "7"; - }, - length: function () { - return "8"; - }, - unique: function () { - return "9" - } - }; - - var result = []; - for (var prop in obj) { - result.push(obj[prop]()); - } - return result.join("") !== "0123456789"; - })(); - - /* Public: Extend target in place with all (own) properties from sources in-order. Thus, last source will - * override properties in previous sources. - * - * target - The Object to extend - * sources - Objects to copy properties from. - * - * Returns the extended target - */ - function extend(target /*, sources */) { - var sources = Array.prototype.slice.call(arguments, 1), - source, i, prop; - - for (i = 0; i < sources.length; i++) { - source = sources[i]; - - for (prop in source) { - if (source.hasOwnProperty(prop)) { - target[prop] = source[prop]; - } - } - - // Make sure we copy (own) toString method even when in JScript with DontEnum bug - // See https://developer.mozilla.org/en/docs/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug - if (hasDontEnumBug && source.hasOwnProperty("toString") && source.toString !== target.toString) { - target.toString = source.toString; - } - } - - return target; - }; - - sinon.extend = extend; - return sinon.extend; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./util/core":41}],30:[function(require,module,exports){ -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -(function (sinon, formatio) { - function makeApi(sinon) { - function valueFormatter(value) { - return "" + value; - } - - function getFormatioFormatter() { - var formatter = formatio.configure({ - quoteStrings: false, - limitChildrenCount: 250 - }); - - function format() { - return formatter.ascii.apply(formatter, arguments); - }; - - return format; - } - - function getNodeFormatter(value) { - function format(value) { - return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; - }; - - try { - var util = require("util"); - } catch (e) { - /* Node, but no util module - would be very old, but better safe than sorry */ - } - - return util ? format : valueFormatter; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function", - formatter; - - if (isNode) { - try { - formatio = require("formatio"); - } catch (e) {} - } - - if (formatio) { - formatter = getFormatioFormatter() - } else if (isNode) { - formatter = getNodeFormatter(); - } else { - formatter = valueFormatter; - } - - sinon.format = formatter; - return sinon.format; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}( - (typeof sinon == "object" && sinon || null), - (typeof formatio == "object" && formatio) -)); - -},{"./util/core":41,"formatio":48,"util":6}],31:[function(require,module,exports){ -/** - * @depend util/core.js - */ -/** - * Logs errors - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -(function (sinon) { - // cache a reference to setTimeout, so that our reference won't be stubbed out - // when using fake timers and errors will still get logged - // https://github.com/cjohansen/Sinon.JS/issues/381 - var realSetTimeout = setTimeout; - - function makeApi(sinon) { - - function log() {} - - function logError(label, err) { - var msg = label + " threw exception: "; - - sinon.log(msg + "[" + err.name + "] " + err.message); - - if (err.stack) { - sinon.log(err.stack); - } - - logError.setTimeout(function () { - err.message = msg + err.message; - throw err; - }, 0); - }; - - // wrap realSetTimeout with something we can stub in tests - logError.setTimeout = function (func, timeout) { - realSetTimeout(func, timeout); - } - - var exports = {}; - exports.log = sinon.log = log; - exports.logError = sinon.logError = logError; - - return exports; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./util/core":41}],32:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend typeOf.js - */ -/*jslint eqeqeq: false, onevar: false, plusplus: false*/ -/*global module, require, sinon*/ -/** - * Match functions - * - * @author Maximilian Antoni (mail@maxantoni.de) - * @license BSD - * - * Copyright (c) 2012 Maximilian Antoni - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - function assertType(value, type, name) { - var actual = sinon.typeOf(value); - if (actual !== type) { - throw new TypeError("Expected type of " + name + " to be " + - type + ", but was " + actual); - } - } - - var matcher = { - toString: function () { - return this.message; - } - }; - - function isMatcher(object) { - return matcher.isPrototypeOf(object); - } - - function matchObject(expectation, actual) { - if (actual === null || actual === undefined) { - return false; - } - for (var key in expectation) { - if (expectation.hasOwnProperty(key)) { - var exp = expectation[key]; - var act = actual[key]; - if (match.isMatcher(exp)) { - if (!exp.test(act)) { - return false; - } - } else if (sinon.typeOf(exp) === "object") { - if (!matchObject(exp, act)) { - return false; - } - } else if (!sinon.deepEqual(exp, act)) { - return false; - } - } - } - return true; - } - - matcher.or = function (m2) { - if (!arguments.length) { - throw new TypeError("Matcher expected"); - } else if (!isMatcher(m2)) { - m2 = match(m2); - } - var m1 = this; - var or = sinon.create(matcher); - or.test = function (actual) { - return m1.test(actual) || m2.test(actual); - }; - or.message = m1.message + ".or(" + m2.message + ")"; - return or; - }; - - matcher.and = function (m2) { - if (!arguments.length) { - throw new TypeError("Matcher expected"); - } else if (!isMatcher(m2)) { - m2 = match(m2); - } - var m1 = this; - var and = sinon.create(matcher); - and.test = function (actual) { - return m1.test(actual) && m2.test(actual); - }; - and.message = m1.message + ".and(" + m2.message + ")"; - return and; - }; - - var match = function (expectation, message) { - var m = sinon.create(matcher); - var type = sinon.typeOf(expectation); - switch (type) { - case "object": - if (typeof expectation.test === "function") { - m.test = function (actual) { - return expectation.test(actual) === true; - }; - m.message = "match(" + sinon.functionName(expectation.test) + ")"; - return m; - } - var str = []; - for (var key in expectation) { - if (expectation.hasOwnProperty(key)) { - str.push(key + ": " + expectation[key]); - } - } - m.test = function (actual) { - return matchObject(expectation, actual); - }; - m.message = "match(" + str.join(", ") + ")"; - break; - case "number": - m.test = function (actual) { - return expectation == actual; - }; - break; - case "string": - m.test = function (actual) { - if (typeof actual !== "string") { - return false; - } - return actual.indexOf(expectation) !== -1; - }; - m.message = "match(\"" + expectation + "\")"; - break; - case "regexp": - m.test = function (actual) { - if (typeof actual !== "string") { - return false; - } - return expectation.test(actual); - }; - break; - case "function": - m.test = expectation; - if (message) { - m.message = message; - } else { - m.message = "match(" + sinon.functionName(expectation) + ")"; - } - break; - default: - m.test = function (actual) { - return sinon.deepEqual(expectation, actual); - }; - } - if (!m.message) { - m.message = "match(" + expectation + ")"; - } - return m; - }; - - match.isMatcher = isMatcher; - - match.any = match(function () { - return true; - }, "any"); - - match.defined = match(function (actual) { - return actual !== null && actual !== undefined; - }, "defined"); - - match.truthy = match(function (actual) { - return !!actual; - }, "truthy"); - - match.falsy = match(function (actual) { - return !actual; - }, "falsy"); - - match.same = function (expectation) { - return match(function (actual) { - return expectation === actual; - }, "same(" + expectation + ")"); - }; - - match.typeOf = function (type) { - assertType(type, "string", "type"); - return match(function (actual) { - return sinon.typeOf(actual) === type; - }, "typeOf(\"" + type + "\")"); - }; - - match.instanceOf = function (type) { - assertType(type, "function", "type"); - return match(function (actual) { - return actual instanceof type; - }, "instanceOf(" + sinon.functionName(type) + ")"); - }; - - function createPropertyMatcher(propertyTest, messagePrefix) { - return function (property, value) { - assertType(property, "string", "property"); - var onlyProperty = arguments.length === 1; - var message = messagePrefix + "(\"" + property + "\""; - if (!onlyProperty) { - message += ", " + value; - } - message += ")"; - return match(function (actual) { - if (actual === undefined || actual === null || - !propertyTest(actual, property)) { - return false; - } - return onlyProperty || sinon.deepEqual(value, actual[property]); - }, message); - }; - } - - match.has = createPropertyMatcher(function (actual, property) { - if (typeof actual === "object") { - return property in actual; - } - return actual[property] !== undefined; - }, "has"); - - match.hasOwn = createPropertyMatcher(function (actual, property) { - return actual.hasOwnProperty(property); - }, "hasOwn"); - - match.bool = match.typeOf("boolean"); - match.number = match.typeOf("number"); - match.string = match.typeOf("string"); - match.object = match.typeOf("object"); - match.func = match.typeOf("function"); - match.array = match.typeOf("array"); - match.regexp = match.typeOf("regexp"); - match.date = match.typeOf("date"); - - sinon.match = match; - return match; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./typeOf"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./typeOf":40,"./util/core":41}],33:[function(require,module,exports){ -/** - * @depend times_in_words.js - * @depend util/core.js - * @depend call.js - * @depend extend.js - * @depend match.js - * @depend spy.js - * @depend stub.js - * @depend format.js - */ -/** - * Mock functions. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - var push = [].push; - var match = sinon.match; - - function mock(object) { - if (!object) { - return sinon.expectation.create("Anonymous mock"); - } - - return mock.create(object); - } - - function each(collection, callback) { - if (!collection) { - return; - } - - for (var i = 0, l = collection.length; i < l; i += 1) { - callback(collection[i]); - } - } - - sinon.extend(mock, { - create: function create(object) { - if (!object) { - throw new TypeError("object is null"); - } - - var mockObject = sinon.extend({}, mock); - mockObject.object = object; - delete mockObject.create; - - return mockObject; - }, - - expects: function expects(method) { - if (!method) { - throw new TypeError("method is falsy"); - } - - if (!this.expectations) { - this.expectations = {}; - this.proxies = []; - } - - if (!this.expectations[method]) { - this.expectations[method] = []; - var mockObject = this; - - sinon.wrapMethod(this.object, method, function () { - return mockObject.invokeMethod(method, this, arguments); - }); - - push.call(this.proxies, method); - } - - var expectation = sinon.expectation.create(method); - push.call(this.expectations[method], expectation); - - return expectation; - }, - - restore: function restore() { - var object = this.object; - - each(this.proxies, function (proxy) { - if (typeof object[proxy].restore == "function") { - object[proxy].restore(); - } - }); - }, - - verify: function verify() { - var expectations = this.expectations || {}; - var messages = [], met = []; - - each(this.proxies, function (proxy) { - each(expectations[proxy], function (expectation) { - if (!expectation.met()) { - push.call(messages, expectation.toString()); - } else { - push.call(met, expectation.toString()); - } - }); - }); - - this.restore(); - - if (messages.length > 0) { - sinon.expectation.fail(messages.concat(met).join("\n")); - } else if (met.length > 0) { - sinon.expectation.pass(messages.concat(met).join("\n")); - } - - return true; - }, - - invokeMethod: function invokeMethod(method, thisValue, args) { - var expectations = this.expectations && this.expectations[method]; - var length = expectations && expectations.length || 0, i; - - for (i = 0; i < length; i += 1) { - if (!expectations[i].met() && - expectations[i].allowsCall(thisValue, args)) { - return expectations[i].apply(thisValue, args); - } - } - - var messages = [], available, exhausted = 0; - - for (i = 0; i < length; i += 1) { - if (expectations[i].allowsCall(thisValue, args)) { - available = available || expectations[i]; - } else { - exhausted += 1; - } - push.call(messages, " " + expectations[i].toString()); - } - - if (exhausted === 0) { - return available.apply(thisValue, args); - } - - messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ - proxy: method, - args: args - })); - - sinon.expectation.fail(messages.join("\n")); - } - }); - - var times = sinon.timesInWords; - var slice = Array.prototype.slice; - - function callCountInWords(callCount) { - if (callCount == 0) { - return "never called"; - } else { - return "called " + times(callCount); - } - } - - function expectedCallCountInWords(expectation) { - var min = expectation.minCalls; - var max = expectation.maxCalls; - - if (typeof min == "number" && typeof max == "number") { - var str = times(min); - - if (min != max) { - str = "at least " + str + " and at most " + times(max); - } - - return str; - } - - if (typeof min == "number") { - return "at least " + times(min); - } - - return "at most " + times(max); - } - - function receivedMinCalls(expectation) { - var hasMinLimit = typeof expectation.minCalls == "number"; - return !hasMinLimit || expectation.callCount >= expectation.minCalls; - } - - function receivedMaxCalls(expectation) { - if (typeof expectation.maxCalls != "number") { - return false; - } - - return expectation.callCount == expectation.maxCalls; - } - - function verifyMatcher(possibleMatcher, arg) { - if (match && match.isMatcher(possibleMatcher)) { - return possibleMatcher.test(arg); - } else { - return true; - } - } - - sinon.expectation = { - minCalls: 1, - maxCalls: 1, - - create: function create(methodName) { - var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); - delete expectation.create; - expectation.method = methodName; - - return expectation; - }, - - invoke: function invoke(func, thisValue, args) { - this.verifyCallAllowed(thisValue, args); - - return sinon.spy.invoke.apply(this, arguments); - }, - - atLeast: function atLeast(num) { - if (typeof num != "number") { - throw new TypeError("'" + num + "' is not number"); - } - - if (!this.limitsSet) { - this.maxCalls = null; - this.limitsSet = true; - } - - this.minCalls = num; - - return this; - }, - - atMost: function atMost(num) { - if (typeof num != "number") { - throw new TypeError("'" + num + "' is not number"); - } - - if (!this.limitsSet) { - this.minCalls = null; - this.limitsSet = true; - } - - this.maxCalls = num; - - return this; - }, - - never: function never() { - return this.exactly(0); - }, - - once: function once() { - return this.exactly(1); - }, - - twice: function twice() { - return this.exactly(2); - }, - - thrice: function thrice() { - return this.exactly(3); - }, - - exactly: function exactly(num) { - if (typeof num != "number") { - throw new TypeError("'" + num + "' is not a number"); - } - - this.atLeast(num); - return this.atMost(num); - }, - - met: function met() { - return !this.failed && receivedMinCalls(this); - }, - - verifyCallAllowed: function verifyCallAllowed(thisValue, args) { - if (receivedMaxCalls(this)) { - this.failed = true; - sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); - } - - if ("expectedThis" in this && this.expectedThis !== thisValue) { - sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + - this.expectedThis); - } - - if (!("expectedArguments" in this)) { - return; - } - - if (!args) { - sinon.expectation.fail(this.method + " received no arguments, expected " + - sinon.format(this.expectedArguments)); - } - - if (args.length < this.expectedArguments.length) { - sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) + - "), expected " + sinon.format(this.expectedArguments)); - } - - if (this.expectsExactArgCount && - args.length != this.expectedArguments.length) { - sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) + - "), expected " + sinon.format(this.expectedArguments)); - } - - for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { - - if (!verifyMatcher(this.expectedArguments[i], args[i])) { - sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + - ", didn't match " + this.expectedArguments.toString()); - } - - if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { - sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + - ", expected " + sinon.format(this.expectedArguments)); - } - } - }, - - allowsCall: function allowsCall(thisValue, args) { - if (this.met() && receivedMaxCalls(this)) { - return false; - } - - if ("expectedThis" in this && this.expectedThis !== thisValue) { - return false; - } - - if (!("expectedArguments" in this)) { - return true; - } - - args = args || []; - - if (args.length < this.expectedArguments.length) { - return false; - } - - if (this.expectsExactArgCount && - args.length != this.expectedArguments.length) { - return false; - } - - for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { - if (!verifyMatcher(this.expectedArguments[i], args[i])) { - return false; - } - - if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { - return false; - } - } - - return true; - }, - - withArgs: function withArgs() { - this.expectedArguments = slice.call(arguments); - return this; - }, - - withExactArgs: function withExactArgs() { - this.withArgs.apply(this, arguments); - this.expectsExactArgCount = true; - return this; - }, - - on: function on(thisValue) { - this.expectedThis = thisValue; - return this; - }, - - toString: function () { - var args = (this.expectedArguments || []).slice(); - - if (!this.expectsExactArgCount) { - push.call(args, "[...]"); - } - - var callStr = sinon.spyCall.toString.call({ - proxy: this.method || "anonymous mock expectation", - args: args - }); - - var message = callStr.replace(", [...", "[, ...") + " " + - expectedCallCountInWords(this); - - if (this.met()) { - return "Expectation met: " + message; - } - - return "Expected " + message + " (" + - callCountInWords(this.callCount) + ")"; - }, - - verify: function verify() { - if (!this.met()) { - sinon.expectation.fail(this.toString()); - } else { - sinon.expectation.pass(this.toString()); - } - - return true; - }, - - pass: function pass(message) { - sinon.assert.pass(message); - }, - - fail: function fail(message) { - var exception = new Error(message); - exception.name = "ExpectationError"; - - throw exception; - } - }; - - sinon.mock = mock; - return mock; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./times_in_words"); - require("./call"); - require("./extend"); - require("./match"); - require("./spy"); - require("./stub"); - require("./format"); - - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./call":27,"./extend":29,"./format":30,"./match":32,"./spy":35,"./stub":36,"./times_in_words":39,"./util/core":41}],34:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend extend.js - * @depend collection.js - * @depend util/fake_timers.js - * @depend util/fake_server_with_clock.js - */ -/** - * Manages fake collections as well as fake utilities such as Sinon's - * timers and fake XHR implementation in one convenient object. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function () { - function makeApi(sinon) { - var push = [].push; - - function exposeValue(sandbox, config, key, value) { - if (!value) { - return; - } - - if (config.injectInto && !(key in config.injectInto)) { - config.injectInto[key] = value; - sandbox.injectedKeys.push(key); - } else { - push.call(sandbox.args, value); - } - } - - function prepareSandboxFromConfig(config) { - var sandbox = sinon.create(sinon.sandbox); - - if (config.useFakeServer) { - if (typeof config.useFakeServer == "object") { - sandbox.serverPrototype = config.useFakeServer; - } - - sandbox.useFakeServer(); - } - - if (config.useFakeTimers) { - if (typeof config.useFakeTimers == "object") { - sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); - } else { - sandbox.useFakeTimers(); - } - } - - return sandbox; - } - - sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { - useFakeTimers: function useFakeTimers() { - this.clock = sinon.useFakeTimers.apply(sinon, arguments); - - return this.add(this.clock); - }, - - serverPrototype: sinon.fakeServer, - - useFakeServer: function useFakeServer() { - var proto = this.serverPrototype || sinon.fakeServer; - - if (!proto || !proto.create) { - return null; - } - - this.server = proto.create(); - return this.add(this.server); - }, - - inject: function (obj) { - sinon.collection.inject.call(this, obj); - - if (this.clock) { - obj.clock = this.clock; - } - - if (this.server) { - obj.server = this.server; - obj.requests = this.server.requests; - } - - obj.match = sinon.match; - - return obj; - }, - - restore: function () { - sinon.collection.restore.apply(this, arguments); - this.restoreContext(); - }, - - restoreContext: function () { - if (this.injectedKeys) { - for (var i = 0, j = this.injectedKeys.length; i < j; i++) { - delete this.injectInto[this.injectedKeys[i]]; - } - this.injectedKeys = []; - } - }, - - create: function (config) { - if (!config) { - return sinon.create(sinon.sandbox); - } - - var sandbox = prepareSandboxFromConfig(config); - sandbox.args = sandbox.args || []; - sandbox.injectedKeys = []; - sandbox.injectInto = config.injectInto; - var prop, value, exposed = sandbox.inject({}); - - if (config.properties) { - for (var i = 0, l = config.properties.length; i < l; i++) { - prop = config.properties[i]; - value = exposed[prop] || prop == "sandbox" && sandbox; - exposeValue(sandbox, config, prop, value); - } - } else { - exposeValue(sandbox, config, "sandbox", value); - } - - return sandbox; - }, - - match: sinon.match - }); - - sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; - - return sinon.sandbox; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./extend"); - require("./util/fake_server_with_clock"); - require("./util/fake_timers"); - require("./collection"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}()); - -},{"./collection":28,"./extend":29,"./util/core":41,"./util/fake_server_with_clock":44,"./util/fake_timers":45}],35:[function(require,module,exports){ -/** - * @depend times_in_words.js - * @depend util/core.js - * @depend extend.js - * @depend call.js - * @depend format.js - */ -/** - * Spy functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - - function makeApi(sinon) { - var push = Array.prototype.push; - var slice = Array.prototype.slice; - var callId = 0; - - function spy(object, property, types) { - if (!property && typeof object == "function") { - return spy.create(object); - } - - if (!object && !property) { - return spy.create(function () { }); - } - - if (types) { - var methodDesc = sinon.getPropertyDescriptor(object, property); - for (var i = 0; i < types.length; i++) { - methodDesc[types[i]] = spy.create(methodDesc[types[i]]); - } - return sinon.wrapMethod(object, property, methodDesc); - } else { - var method = object[property]; - return sinon.wrapMethod(object, property, spy.create(method)); - } - } - - function matchingFake(fakes, args, strict) { - if (!fakes) { - return; - } - - for (var i = 0, l = fakes.length; i < l; i++) { - if (fakes[i].matches(args, strict)) { - return fakes[i]; - } - } - } - - function incrementCallCount() { - this.called = true; - this.callCount += 1; - this.notCalled = false; - this.calledOnce = this.callCount == 1; - this.calledTwice = this.callCount == 2; - this.calledThrice = this.callCount == 3; - } - - function createCallProperties() { - this.firstCall = this.getCall(0); - this.secondCall = this.getCall(1); - this.thirdCall = this.getCall(2); - this.lastCall = this.getCall(this.callCount - 1); - } - - var vars = "a,b,c,d,e,f,g,h,i,j,k,l"; - function createProxy(func, proxyLength) { - // Retain the function length: - var p; - if (proxyLength) { - eval("p = (function proxy(" + vars.substring(0, proxyLength * 2 - 1) + - ") { return p.invoke(func, this, slice.call(arguments)); });"); - } else { - p = function proxy() { - return p.invoke(func, this, slice.call(arguments)); - }; - } - return p; - } - - var uuid = 0; - - // Public API - var spyApi = { - reset: function () { - if (this.invoking) { - var err = new Error("Cannot reset Sinon function while invoking it. " + - "Move the call to .reset outside of the callback."); - err.name = "InvalidResetException"; - throw err; - } - - this.called = false; - this.notCalled = true; - this.calledOnce = false; - this.calledTwice = false; - this.calledThrice = false; - this.callCount = 0; - this.firstCall = null; - this.secondCall = null; - this.thirdCall = null; - this.lastCall = null; - this.args = []; - this.returnValues = []; - this.thisValues = []; - this.exceptions = []; - this.callIds = []; - if (this.fakes) { - for (var i = 0; i < this.fakes.length; i++) { - this.fakes[i].reset(); - } - } - - return this; - }, - - create: function create(func, spyLength) { - var name; - - if (typeof func != "function") { - func = function () { }; - } else { - name = sinon.functionName(func); - } - - if (!spyLength) { - spyLength = func.length; - } - - var proxy = createProxy(func, spyLength); - - sinon.extend(proxy, spy); - delete proxy.create; - sinon.extend(proxy, func); - - proxy.reset(); - proxy.prototype = func.prototype; - proxy.displayName = name || "spy"; - proxy.toString = sinon.functionToString; - proxy.instantiateFake = sinon.spy.create; - proxy.id = "spy#" + uuid++; - - return proxy; - }, - - invoke: function invoke(func, thisValue, args) { - var matching = matchingFake(this.fakes, args); - var exception, returnValue; - - incrementCallCount.call(this); - push.call(this.thisValues, thisValue); - push.call(this.args, args); - push.call(this.callIds, callId++); - - // Make call properties available from within the spied function: - createCallProperties.call(this); - - try { - this.invoking = true; - - if (matching) { - returnValue = matching.invoke(func, thisValue, args); - } else { - returnValue = (this.func || func).apply(thisValue, args); - } - - var thisCall = this.getCall(this.callCount - 1); - if (thisCall.calledWithNew() && typeof returnValue !== "object") { - returnValue = thisValue; - } - } catch (e) { - exception = e; - } finally { - delete this.invoking; - } - - push.call(this.exceptions, exception); - push.call(this.returnValues, returnValue); - - // Make return value and exception available in the calls: - createCallProperties.call(this); - - if (exception !== undefined) { - throw exception; - } - - return returnValue; - }, - - named: function named(name) { - this.displayName = name; - return this; - }, - - getCall: function getCall(i) { - if (i < 0 || i >= this.callCount) { - return null; - } - - return sinon.spyCall(this, this.thisValues[i], this.args[i], - this.returnValues[i], this.exceptions[i], - this.callIds[i]); - }, - - getCalls: function () { - var calls = []; - var i; - - for (i = 0; i < this.callCount; i++) { - calls.push(this.getCall(i)); - } - - return calls; - }, - - calledBefore: function calledBefore(spyFn) { - if (!this.called) { - return false; - } - - if (!spyFn.called) { - return true; - } - - return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; - }, - - calledAfter: function calledAfter(spyFn) { - if (!this.called || !spyFn.called) { - return false; - } - - return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; - }, - - withArgs: function () { - var args = slice.call(arguments); - - if (this.fakes) { - var match = matchingFake(this.fakes, args, true); - - if (match) { - return match; - } - } else { - this.fakes = []; - } - - var original = this; - var fake = this.instantiateFake(); - fake.matchingAguments = args; - fake.parent = this; - push.call(this.fakes, fake); - - fake.withArgs = function () { - return original.withArgs.apply(original, arguments); - }; - - for (var i = 0; i < this.args.length; i++) { - if (fake.matches(this.args[i])) { - incrementCallCount.call(fake); - push.call(fake.thisValues, this.thisValues[i]); - push.call(fake.args, this.args[i]); - push.call(fake.returnValues, this.returnValues[i]); - push.call(fake.exceptions, this.exceptions[i]); - push.call(fake.callIds, this.callIds[i]); - } - } - createCallProperties.call(fake); - - return fake; - }, - - matches: function (args, strict) { - var margs = this.matchingAguments; - - if (margs.length <= args.length && - sinon.deepEqual(margs, args.slice(0, margs.length))) { - return !strict || margs.length == args.length; - } - }, - - printf: function (format) { - var spy = this; - var args = slice.call(arguments, 1); - var formatter; - - return (format || "").replace(/%(.)/g, function (match, specifyer) { - formatter = spyApi.formatters[specifyer]; - - if (typeof formatter == "function") { - return formatter.call(null, spy, args); - } else if (!isNaN(parseInt(specifyer, 10))) { - return sinon.format(args[specifyer - 1]); - } - - return "%" + specifyer; - }); - } - }; - - function delegateToCalls(method, matchAny, actual, notCalled) { - spyApi[method] = function () { - if (!this.called) { - if (notCalled) { - return notCalled.apply(this, arguments); - } - return false; - } - - var currentCall; - var matches = 0; - - for (var i = 0, l = this.callCount; i < l; i += 1) { - currentCall = this.getCall(i); - - if (currentCall[actual || method].apply(currentCall, arguments)) { - matches += 1; - - if (matchAny) { - return true; - } - } - } - - return matches === this.callCount; - }; - } - - delegateToCalls("calledOn", true); - delegateToCalls("alwaysCalledOn", false, "calledOn"); - delegateToCalls("calledWith", true); - delegateToCalls("calledWithMatch", true); - delegateToCalls("alwaysCalledWith", false, "calledWith"); - delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch"); - delegateToCalls("calledWithExactly", true); - delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly"); - delegateToCalls("neverCalledWith", false, "notCalledWith", - function () { return true; }); - delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", - function () { return true; }); - delegateToCalls("threw", true); - delegateToCalls("alwaysThrew", false, "threw"); - delegateToCalls("returned", true); - delegateToCalls("alwaysReturned", false, "returned"); - delegateToCalls("calledWithNew", true); - delegateToCalls("alwaysCalledWithNew", false, "calledWithNew"); - delegateToCalls("callArg", false, "callArgWith", function () { - throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); - }); - spyApi.callArgWith = spyApi.callArg; - delegateToCalls("callArgOn", false, "callArgOnWith", function () { - throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); - }); - spyApi.callArgOnWith = spyApi.callArgOn; - delegateToCalls("yield", false, "yield", function () { - throw new Error(this.toString() + " cannot yield since it was not yet invoked."); - }); - // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. - spyApi.invokeCallback = spyApi.yield; - delegateToCalls("yieldOn", false, "yieldOn", function () { - throw new Error(this.toString() + " cannot yield since it was not yet invoked."); - }); - delegateToCalls("yieldTo", false, "yieldTo", function (property) { - throw new Error(this.toString() + " cannot yield to '" + property + - "' since it was not yet invoked."); - }); - delegateToCalls("yieldToOn", false, "yieldToOn", function (property) { - throw new Error(this.toString() + " cannot yield to '" + property + - "' since it was not yet invoked."); - }); - - spyApi.formatters = { - c: function (spy) { - return sinon.timesInWords(spy.callCount); - }, - - n: function (spy) { - return spy.toString(); - }, - - C: function (spy) { - var calls = []; - - for (var i = 0, l = spy.callCount; i < l; ++i) { - var stringifiedCall = " " + spy.getCall(i).toString(); - if (/\n/.test(calls[i - 1])) { - stringifiedCall = "\n" + stringifiedCall; - } - push.call(calls, stringifiedCall); - } - - return calls.length > 0 ? "\n" + calls.join("\n") : ""; - }, - - t: function (spy) { - var objects = []; - - for (var i = 0, l = spy.callCount; i < l; ++i) { - push.call(objects, sinon.format(spy.thisValues[i])); - } - - return objects.join(", "); - }, - - "*": function (spy, args) { - var formatted = []; - - for (var i = 0, l = args.length; i < l; ++i) { - push.call(formatted, sinon.format(args[i])); - } - - return formatted.join(", "); - } - }; - - sinon.extend(spy, spyApi); - - spy.spyCall = sinon.spyCall; - sinon.spy = spy; - - return spy; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./call"); - require("./extend"); - require("./times_in_words"); - require("./format"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./call":27,"./extend":29,"./format":30,"./times_in_words":39,"./util/core":41}],36:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend extend.js - * @depend spy.js - * @depend behavior.js - */ -/** - * Stub functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - function stub(object, property, func) { - if (!!func && typeof func != "function" && typeof func != "object") { - throw new TypeError("Custom stub should be a function or a property descriptor"); - } - - var wrapper; - - if (func) { - if (typeof func == "function") { - wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; - } else { - wrapper = func; - if (sinon.spy && sinon.spy.create) { - var types = sinon.objectKeys(wrapper); - for (var i = 0; i < types.length; i++) { - wrapper[types[i]] = sinon.spy.create(wrapper[types[i]]); - } - } - } - } else { - var stubLength = 0; - if (typeof object == "object" && typeof object[property] == "function") { - stubLength = object[property].length; - } - wrapper = stub.create(stubLength); - } - - if (!object && typeof property === "undefined") { - return sinon.stub.create(); - } - - if (typeof property === "undefined" && typeof object == "object") { - for (var prop in object) { - if (typeof object[prop] === "function") { - stub(object, prop); - } - } - - return object; - } - - return sinon.wrapMethod(object, property, wrapper); - } - - function getDefaultBehavior(stub) { - return stub.defaultBehavior || getParentBehaviour(stub) || sinon.behavior.create(stub); - } - - function getParentBehaviour(stub) { - return (stub.parent && getCurrentBehavior(stub.parent)); - } - - function getCurrentBehavior(stub) { - var behavior = stub.behaviors[stub.callCount - 1]; - return behavior && behavior.isPresent() ? behavior : getDefaultBehavior(stub); - } - - var uuid = 0; - - var proto = { - create: function create(stubLength) { - var functionStub = function () { - return getCurrentBehavior(functionStub).invoke(this, arguments); - }; - - functionStub.id = "stub#" + uuid++; - var orig = functionStub; - functionStub = sinon.spy.create(functionStub, stubLength); - functionStub.func = orig; - - sinon.extend(functionStub, stub); - functionStub.instantiateFake = sinon.stub.create; - functionStub.displayName = "stub"; - functionStub.toString = sinon.functionToString; - - functionStub.defaultBehavior = null; - functionStub.behaviors = []; - - return functionStub; - }, - - resetBehavior: function () { - var i; - - this.defaultBehavior = null; - this.behaviors = []; - - delete this.returnValue; - delete this.returnArgAt; - this.returnThis = false; - - if (this.fakes) { - for (i = 0; i < this.fakes.length; i++) { - this.fakes[i].resetBehavior(); - } - } - }, - - onCall: function onCall(index) { - if (!this.behaviors[index]) { - this.behaviors[index] = sinon.behavior.create(this); - } - - return this.behaviors[index]; - }, - - onFirstCall: function onFirstCall() { - return this.onCall(0); - }, - - onSecondCall: function onSecondCall() { - return this.onCall(1); - }, - - onThirdCall: function onThirdCall() { - return this.onCall(2); - } - }; - - for (var method in sinon.behavior) { - if (sinon.behavior.hasOwnProperty(method) && - !proto.hasOwnProperty(method) && - method != "create" && - method != "withArgs" && - method != "invoke") { - proto[method] = (function (behaviorMethod) { - return function () { - this.defaultBehavior = this.defaultBehavior || sinon.behavior.create(this); - this.defaultBehavior[behaviorMethod].apply(this.defaultBehavior, arguments); - return this; - }; - }(method)); - } - } - - sinon.extend(stub, proto); - sinon.stub = stub; - - return stub; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./behavior"); - require("./spy"); - require("./extend"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./behavior":26,"./extend":29,"./spy":35,"./util/core":41}],37:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend sandbox.js - */ -/** - * Test function, sandboxes fakes - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - var slice = Array.prototype.slice; - - function test(callback) { - var type = typeof callback; - - if (type != "function") { - throw new TypeError("sinon.test needs to wrap a test function, got " + type); - } - - function sinonSandboxedTest() { - var config = sinon.getConfig(sinon.config); - config.injectInto = config.injectIntoThis && this || config.injectInto; - var sandbox = sinon.sandbox.create(config); - var args = slice.call(arguments); - var oldDone = args.length && args[args.length - 1]; - var exception, result; - - if (typeof oldDone == "function") { - args[args.length - 1] = function sinonDone(result) { - if (result) { - sandbox.restore(); - throw exception; - } else { - sandbox.verifyAndRestore(); - } - oldDone(result); - }; - } - - try { - result = callback.apply(this, args.concat(sandbox.args)); - } catch (e) { - exception = e; - } - - if (typeof oldDone != "function") { - if (typeof exception !== "undefined") { - sandbox.restore(); - throw exception; - } else { - sandbox.verifyAndRestore(); - } - } - - return result; - } - - if (callback.length) { - return function sinonAsyncSandboxedTest(callback) { - return sinonSandboxedTest.apply(this, arguments); - }; - } - - return sinonSandboxedTest; - } - - test.config = { - injectIntoThis: true, - injectInto: null, - properties: ["spy", "stub", "mock", "clock", "server", "requests"], - useFakeTimers: true, - useFakeServer: true - }; - - sinon.test = test; - return test; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./sandbox"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (sinon) { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./sandbox":34,"./util/core":41}],38:[function(require,module,exports){ -/** - * @depend util/core.js - * @depend test.js - */ -/** - * Test case, sandboxes all test functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - function createTest(property, setUp, tearDown) { - return function () { - if (setUp) { - setUp.apply(this, arguments); - } - - var exception, result; - - try { - result = property.apply(this, arguments); - } catch (e) { - exception = e; - } - - if (tearDown) { - tearDown.apply(this, arguments); - } - - if (exception) { - throw exception; - } - - return result; - }; - } - - function makeApi(sinon) { - function testCase(tests, prefix) { - /*jsl:ignore*/ - if (!tests || typeof tests != "object") { - throw new TypeError("sinon.testCase needs an object with test functions"); - } - /*jsl:end*/ - - prefix = prefix || "test"; - var rPrefix = new RegExp("^" + prefix); - var methods = {}, testName, property, method; - var setUp = tests.setUp; - var tearDown = tests.tearDown; - - for (testName in tests) { - if (tests.hasOwnProperty(testName)) { - property = tests[testName]; - - if (/^(setUp|tearDown)$/.test(testName)) { - continue; - } - - if (typeof property == "function" && rPrefix.test(testName)) { - method = property; - - if (setUp || tearDown) { - method = createTest(property, setUp, tearDown); - } - - methods[testName] = sinon.test(method); - } else { - methods[testName] = tests[testName]; - } - } - } - - return methods; - } - - sinon.testCase = testCase; - return testCase; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - require("./test"); - module.exports = makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./test":37,"./util/core":41}],39:[function(require,module,exports){ -/** - * @depend util/core.js - */ -"use strict"; - -(function (sinon) { - function makeApi(sinon) { - - function timesInWords(count) { - switch (count) { - case 1: - return "once"; - case 2: - return "twice"; - case 3: - return "thrice"; - default: - return (count || 0) + " times"; - } - } - - sinon.timesInWords = timesInWords; - return sinon.timesInWords; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{"./util/core":41}],40:[function(require,module,exports){ -/** - * @depend util/core.js - */ -/** - * Format functions - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -(function (sinon, formatio) { - function makeApi(sinon) { - function typeOf(value) { - if (value === null) { - return "null"; - } else if (value === undefined) { - return "undefined"; - } - var string = Object.prototype.toString.call(value); - return string.substring(8, string.length - 1).toLowerCase(); - }; - - sinon.typeOf = typeOf; - return sinon.typeOf; - } - - function loadDependencies(require, exports, module) { - var sinon = require("./util/core"); - module.exports = makeApi(sinon); - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}( - (typeof sinon == "object" && sinon || null), - (typeof formatio == "object" && formatio) -)); - -},{"./util/core":41}],41:[function(require,module,exports){ -/** - * @depend ../../sinon.js - */ -/** - * Sinon core utilities. For internal use only. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (sinon) { - var div = typeof document != "undefined" && document.createElement("div"); - var hasOwn = Object.prototype.hasOwnProperty; - - function isDOMNode(obj) { - var success = false; - - try { - obj.appendChild(div); - success = div.parentNode == obj; - } catch (e) { - return false; - } finally { - try { - obj.removeChild(div); - } catch (e) { - // Remove failed, not much we can do about that - } - } - - return success; - } - - function isElement(obj) { - return div && obj && obj.nodeType === 1 && isDOMNode(obj); - } - - function isFunction(obj) { - return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply); - } - - function isReallyNaN(val) { - return typeof val === "number" && isNaN(val); - } - - function mirrorProperties(target, source) { - for (var prop in source) { - if (!hasOwn.call(target, prop)) { - target[prop] = source[prop]; - } - } - } - - function isRestorable(obj) { - return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon; - } - - // Cheap way to detect if we have ES5 support. - var hasES5Support = "keys" in Object; - - function makeApi(sinon) { - sinon.wrapMethod = function wrapMethod(object, property, method) { - if (!object) { - throw new TypeError("Should wrap property of object"); - } - - if (typeof method != "function" && typeof method != "object") { - throw new TypeError("Method wrapper should be a function or a property descriptor"); - } - - function checkWrappedMethod(wrappedMethod) { - if (!isFunction(wrappedMethod)) { - error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + - property + " as function"); - } else if (wrappedMethod.restore && wrappedMethod.restore.sinon) { - error = new TypeError("Attempted to wrap " + property + " which is already wrapped"); - } else if (wrappedMethod.calledBefore) { - var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; - error = new TypeError("Attempted to wrap " + property + " which is already " + verb); - } - - if (error) { - if (wrappedMethod && wrappedMethod.stackTrace) { - error.stack += "\n--------------\n" + wrappedMethod.stackTrace; - } - throw error; - } - } - - var error, wrappedMethod; - - // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem - // when using hasOwn.call on objects from other frames. - var owned = object.hasOwnProperty ? object.hasOwnProperty(property) : hasOwn.call(object, property); - - if (hasES5Support) { - var methodDesc = (typeof method == "function") ? {value: method} : method, - wrappedMethodDesc = sinon.getPropertyDescriptor(object, property), - i; - - if (!wrappedMethodDesc) { - error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + - property + " as function"); - } else if (wrappedMethodDesc.restore && wrappedMethodDesc.restore.sinon) { - error = new TypeError("Attempted to wrap " + property + " which is already wrapped"); - } - if (error) { - if (wrappedMethodDesc && wrappedMethodDesc.stackTrace) { - error.stack += "\n--------------\n" + wrappedMethodDesc.stackTrace; - } - throw error; - } - - var types = sinon.objectKeys(methodDesc); - for (i = 0; i < types.length; i++) { - wrappedMethod = wrappedMethodDesc[types[i]]; - checkWrappedMethod(wrappedMethod); - } - - mirrorProperties(methodDesc, wrappedMethodDesc); - for (i = 0; i < types.length; i++) { - mirrorProperties(methodDesc[types[i]], wrappedMethodDesc[types[i]]); - } - Object.defineProperty(object, property, methodDesc); - } else { - wrappedMethod = object[property]; - checkWrappedMethod(wrappedMethod); - object[property] = method; - method.displayName = property; - } - - method.displayName = property; - - // Set up a stack trace which can be used later to find what line of - // code the original method was created on. - method.stackTrace = (new Error("Stack Trace for original")).stack; - - method.restore = function () { - // For prototype properties try to reset by delete first. - // If this fails (ex: localStorage on mobile safari) then force a reset - // via direct assignment. - if (!owned) { - try { - delete object[property]; - } catch (e) {} - // For native code functions `delete` fails without throwing an error - // on Chrome < 43, PhantomJS, etc. - // Use strict equality comparison to check failures then force a reset - // via direct assignment. - if (object[property] === method) { - object[property] = wrappedMethod; - } - } else if (hasES5Support) { - Object.defineProperty(object, property, wrappedMethodDesc); - } - - if (!hasES5Support && object[property] === method) { - object[property] = wrappedMethod; - } - }; - - method.restore.sinon = true; - - if (!hasES5Support) { - mirrorProperties(method, wrappedMethod); - } - - return method; - }; - - sinon.create = function create(proto) { - var F = function () {}; - F.prototype = proto; - return new F(); - }; - - sinon.deepEqual = function deepEqual(a, b) { - if (sinon.match && sinon.match.isMatcher(a)) { - return a.test(b); - } - - if (typeof a != "object" || typeof b != "object") { - if (isReallyNaN(a) && isReallyNaN(b)) { - return true; - } else { - return a === b; - } - } - - if (isElement(a) || isElement(b)) { - return a === b; - } - - if (a === b) { - return true; - } - - if ((a === null && b !== null) || (a !== null && b === null)) { - return false; - } - - if (a instanceof RegExp && b instanceof RegExp) { - return (a.source === b.source) && (a.global === b.global) && - (a.ignoreCase === b.ignoreCase) && (a.multiline === b.multiline); - } - - var aString = Object.prototype.toString.call(a); - if (aString != Object.prototype.toString.call(b)) { - return false; - } - - if (aString == "[object Date]") { - return a.valueOf() === b.valueOf(); - } - - var prop, aLength = 0, bLength = 0; - - if (aString == "[object Array]" && a.length !== b.length) { - return false; - } - - for (prop in a) { - aLength += 1; - - if (!(prop in b)) { - return false; - } - - if (!deepEqual(a[prop], b[prop])) { - return false; - } - } - - for (prop in b) { - bLength += 1; - } - - return aLength == bLength; - }; - - sinon.functionName = function functionName(func) { - var name = func.displayName || func.name; - - // Use function decomposition as a last resort to get function - // name. Does not rely on function decomposition to work - if it - // doesn't debugging will be slightly less informative - // (i.e. toString will say 'spy' rather than 'myFunc'). - if (!name) { - var matches = func.toString().match(/function ([^\s\(]+)/); - name = matches && matches[1]; - } - - return name; - }; - - sinon.functionToString = function toString() { - if (this.getCall && this.callCount) { - var thisValue, prop, i = this.callCount; - - while (i--) { - thisValue = this.getCall(i).thisValue; - - for (prop in thisValue) { - if (thisValue[prop] === this) { - return prop; - } - } - } - } - - return this.displayName || "sinon fake"; - }; - - sinon.objectKeys = function objectKeys(obj) { - if (obj !== Object(obj)) { - throw new TypeError("sinon.objectKeys called on a non-object"); - } - - var keys = []; - var key; - for (key in obj) { - if (hasOwn.call(obj, key)) { - keys.push(key); - } - } - - return keys; - }; - - sinon.getPropertyDescriptor = function getPropertyDescriptor(object, property) { - var proto = object, descriptor; - while (proto && !(descriptor = Object.getOwnPropertyDescriptor(proto, property))) { - proto = Object.getPrototypeOf(proto); - } - return descriptor; - } - - sinon.getConfig = function (custom) { - var config = {}; - custom = custom || {}; - var defaults = sinon.defaultConfig; - - for (var prop in defaults) { - if (defaults.hasOwnProperty(prop)) { - config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; - } - } - - return config; - }; - - sinon.defaultConfig = { - injectIntoThis: true, - injectInto: null, - properties: ["spy", "stub", "mock", "clock", "server", "requests"], - useFakeTimers: true, - useFakeServer: true - }; - - sinon.timesInWords = function timesInWords(count) { - return count == 1 && "once" || - count == 2 && "twice" || - count == 3 && "thrice" || - (count || 0) + " times"; - }; - - sinon.calledInOrder = function (spies) { - for (var i = 1, l = spies.length; i < l; i++) { - if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) { - return false; - } - } - - return true; - }; - - sinon.orderByFirstCall = function (spies) { - return spies.sort(function (a, b) { - // uuid, won't ever be equal - var aCall = a.getCall(0); - var bCall = b.getCall(0); - var aId = aCall && aCall.callId || -1; - var bId = bCall && bCall.callId || -1; - - return aId < bId ? -1 : 1; - }); - }; - - sinon.createStubInstance = function (constructor) { - if (typeof constructor !== "function") { - throw new TypeError("The constructor should be a function."); - } - return sinon.stub(sinon.create(constructor.prototype)); - }; - - sinon.restore = function (object) { - if (object !== null && typeof object === "object") { - for (var prop in object) { - if (isRestorable(object[prop])) { - object[prop].restore(); - } - } - } else if (isRestorable(object)) { - object.restore(); - } - }; - - return sinon; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports) { - makeApi(exports); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports); - } else if (!sinon) { - return; - } else { - makeApi(sinon); - } -}(typeof sinon == "object" && sinon || null)); - -},{}],42:[function(require,module,exports){ -/** - * Minimal Event interface implementation - * - * Original implementation by Sven Fuchs: https://gist.github.com/995028 - * Modifications and tests by Christian Johansen. - * - * @author Sven Fuchs (svenfuchs@artweb-design.de) - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2011 Sven Fuchs, Christian Johansen - */ -"use strict"; - -if (typeof sinon == "undefined") { - this.sinon = {}; -} - -(function () { - var push = [].push; - - function makeApi(sinon) { - sinon.Event = function Event(type, bubbles, cancelable, target) { - this.initEvent(type, bubbles, cancelable, target); - }; - - sinon.Event.prototype = { - initEvent: function (type, bubbles, cancelable, target) { - this.type = type; - this.bubbles = bubbles; - this.cancelable = cancelable; - this.target = target; - }, - - stopPropagation: function () {}, - - preventDefault: function () { - this.defaultPrevented = true; - } - }; - - sinon.ProgressEvent = function ProgressEvent(type, progressEventRaw, target) { - this.initEvent(type, false, false, target); - this.loaded = progressEventRaw.loaded || null; - this.total = progressEventRaw.total || null; - this.lengthComputable = !!progressEventRaw.total; - }; - - sinon.ProgressEvent.prototype = new sinon.Event(); - - sinon.ProgressEvent.prototype.constructor = sinon.ProgressEvent; - - sinon.CustomEvent = function CustomEvent(type, customData, target) { - this.initEvent(type, false, false, target); - this.detail = customData.detail || null; - }; - - sinon.CustomEvent.prototype = new sinon.Event(); - - sinon.CustomEvent.prototype.constructor = sinon.CustomEvent; - - sinon.EventTarget = { - addEventListener: function addEventListener(event, listener) { - this.eventListeners = this.eventListeners || {}; - this.eventListeners[event] = this.eventListeners[event] || []; - push.call(this.eventListeners[event], listener); - }, - - removeEventListener: function removeEventListener(event, listener) { - var listeners = this.eventListeners && this.eventListeners[event] || []; - - for (var i = 0, l = listeners.length; i < l; ++i) { - if (listeners[i] == listener) { - return listeners.splice(i, 1); - } - } - }, - - dispatchEvent: function dispatchEvent(event) { - var type = event.type; - var listeners = this.eventListeners && this.eventListeners[type] || []; - - for (var i = 0; i < listeners.length; i++) { - if (typeof listeners[i] == "function") { - listeners[i].call(this, event); - } else { - listeners[i].handleEvent(event); - } - } - - return !!event.defaultPrevented; - } - }; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require) { - var sinon = require("./core"); - makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require); - } else { - makeApi(sinon); - } -}()); - -},{"./core":41}],43:[function(require,module,exports){ -/** - * @depend fake_xdomain_request.js - * @depend fake_xml_http_request.js - * @depend ../format.js - * @depend ../log_error.js - */ -/** - * The Sinon "server" mimics a web server that receives requests from - * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, - * both synchronously and asynchronously. To respond synchronuously, canned - * answers have to be provided upfront. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -if (typeof sinon == "undefined") { - var sinon = {}; -} - -(function () { - var push = [].push; - function F() {} - - function create(proto) { - F.prototype = proto; - return new F(); - } - - function responseArray(handler) { - var response = handler; - - if (Object.prototype.toString.call(handler) != "[object Array]") { - response = [200, {}, handler]; - } - - if (typeof response[2] != "string") { - throw new TypeError("Fake server response body should be string, but was " + - typeof response[2]); - } - - return response; - } - - var wloc = typeof window !== "undefined" ? window.location : {}; - var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); - - function matchOne(response, reqMethod, reqUrl) { - var rmeth = response.method; - var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); - var url = response.url; - var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); - - return matchMethod && matchUrl; - } - - function match(response, request) { - var requestUrl = request.url; - - if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { - requestUrl = requestUrl.replace(rCurrLoc, ""); - } - - if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { - if (typeof response.response == "function") { - var ru = response.url; - var args = [request].concat(ru && typeof ru.exec == "function" ? ru.exec(requestUrl).slice(1) : []); - return response.response.apply(response, args); - } - - return true; - } - - return false; - } - - function makeApi(sinon) { - sinon.fakeServer = { - create: function () { - var server = create(this); - if (!sinon.xhr.supportsCORS) { - this.xhr = sinon.useFakeXDomainRequest(); - } else { - this.xhr = sinon.useFakeXMLHttpRequest(); - } - server.requests = []; - - this.xhr.onCreate = function (xhrObj) { - server.addRequest(xhrObj); - }; - - return server; - }, - - addRequest: function addRequest(xhrObj) { - var server = this; - push.call(this.requests, xhrObj); - - xhrObj.onSend = function () { - server.handleRequest(this); - - if (server.respondImmediately) { - server.respond(); - } else if (server.autoRespond && !server.responding) { - setTimeout(function () { - server.responding = false; - server.respond(); - }, server.autoRespondAfter || 10); - - server.responding = true; - } - }; - }, - - getHTTPMethod: function getHTTPMethod(request) { - if (this.fakeHTTPMethods && /post/i.test(request.method)) { - var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); - return !!matches ? matches[1] : request.method; - } - - return request.method; - }, - - handleRequest: function handleRequest(xhr) { - if (xhr.async) { - if (!this.queue) { - this.queue = []; - } - - push.call(this.queue, xhr); - } else { - this.processRequest(xhr); - } - }, - - log: function log(response, request) { - var str; - - str = "Request:\n" + sinon.format(request) + "\n\n"; - str += "Response:\n" + sinon.format(response) + "\n\n"; - - sinon.log(str); - }, - - respondWith: function respondWith(method, url, body) { - if (arguments.length == 1 && typeof method != "function") { - this.response = responseArray(method); - return; - } - - if (!this.responses) { this.responses = []; } - - if (arguments.length == 1) { - body = method; - url = method = null; - } - - if (arguments.length == 2) { - body = url; - url = method; - method = null; - } - - push.call(this.responses, { - method: method, - url: url, - response: typeof body == "function" ? body : responseArray(body) - }); - }, - - respond: function respond() { - if (arguments.length > 0) { - this.respondWith.apply(this, arguments); - } - - var queue = this.queue || []; - var requests = queue.splice(0, queue.length); - var request; - - while (request = requests.shift()) { - this.processRequest(request); - } - }, - - processRequest: function processRequest(request) { - try { - if (request.aborted) { - return; - } - - var response = this.response || [404, {}, ""]; - - if (this.responses) { - for (var l = this.responses.length, i = l - 1; i >= 0; i--) { - if (match.call(this, this.responses[i], request)) { - response = this.responses[i].response; - break; - } - } - } - - if (request.readyState != 4) { - this.log(response, request); - - request.respond(response[0], response[1], response[2]); - } - } catch (e) { - sinon.logError("Fake server request processing", e); - } - }, - - restore: function restore() { - return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); - } - }; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./core"); - require("./fake_xdomain_request"); - require("./fake_xml_http_request"); - require("../format"); - makeApi(sinon); - module.exports = sinon; - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else { - makeApi(sinon); - } -}()); - -},{"../format":30,"./core":41,"./fake_xdomain_request":46,"./fake_xml_http_request":47}],44:[function(require,module,exports){ -/** - * @depend fake_server.js - * @depend fake_timers.js - */ -/** - * Add-on for sinon.fakeServer that automatically handles a fake timer along with - * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery - * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, - * it polls the object for completion with setInterval. Dispite the direct - * motivation, there is nothing jQuery-specific in this file, so it can be used - * in any environment where the ajax implementation depends on setInterval or - * setTimeout. - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function () { - function makeApi(sinon) { - function Server() {} - Server.prototype = sinon.fakeServer; - - sinon.fakeServerWithClock = new Server(); - - sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { - if (xhr.async) { - if (typeof setTimeout.clock == "object") { - this.clock = setTimeout.clock; - } else { - this.clock = sinon.useFakeTimers(); - this.resetClock = true; - } - - if (!this.longestTimeout) { - var clockSetTimeout = this.clock.setTimeout; - var clockSetInterval = this.clock.setInterval; - var server = this; - - this.clock.setTimeout = function (fn, timeout) { - server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); - - return clockSetTimeout.apply(this, arguments); - }; - - this.clock.setInterval = function (fn, timeout) { - server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); - - return clockSetInterval.apply(this, arguments); - }; - } - } - - return sinon.fakeServer.addRequest.call(this, xhr); - }; - - sinon.fakeServerWithClock.respond = function respond() { - var returnVal = sinon.fakeServer.respond.apply(this, arguments); - - if (this.clock) { - this.clock.tick(this.longestTimeout || 0); - this.longestTimeout = 0; - - if (this.resetClock) { - this.clock.restore(); - this.resetClock = false; - } - } - - return returnVal; - }; - - sinon.fakeServerWithClock.restore = function restore() { - if (this.clock) { - this.clock.restore(); - } - - return sinon.fakeServer.restore.apply(this, arguments); - }; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require) { - var sinon = require("./core"); - require("./fake_server"); - require("./fake_timers"); - makeApi(sinon); - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require); - } else { - makeApi(sinon); - } -}()); - -},{"./core":41,"./fake_server":43,"./fake_timers":45}],45:[function(require,module,exports){ -(function (global){ -/*global lolex */ - -/** - * Fake timer API - * setTimeout - * setInterval - * clearTimeout - * clearInterval - * tick - * reset - * Date - * - * Inspired by jsUnitMockTimeOut from JsUnit - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -if (typeof sinon == "undefined") { - var sinon = {}; -} - -(function (global) { - function makeApi(sinon, lol) { - var llx = typeof lolex !== "undefined" ? lolex : lol; - - sinon.useFakeTimers = function () { - var now, methods = Array.prototype.slice.call(arguments); - - if (typeof methods[0] === "string") { - now = 0; - } else { - now = methods.shift(); - } - - var clock = llx.install(now || 0, methods); - clock.restore = clock.uninstall; - return clock; - }; - - sinon.clock = { - create: function (now) { - return llx.createClock(now); - } - }; - - sinon.timers = { - setTimeout: setTimeout, - clearTimeout: clearTimeout, - setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined), - clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate : undefined), - setInterval: setInterval, - clearInterval: clearInterval, - Date: Date - }; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, epxorts, module, lolex) { - var sinon = require("./core"); - makeApi(sinon, lolex); - module.exports = sinon; - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module, require("lolex")); - } else { - makeApi(sinon); - } -}(typeof global != "undefined" && typeof global !== "function" ? global : this)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./core":41,"lolex":50}],46:[function(require,module,exports){ -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XDomainRequest object - */ -"use strict"; - -if (typeof sinon == "undefined") { - this.sinon = {}; -} - -// wrapper for global -(function (global) { - var xdr = { XDomainRequest: global.XDomainRequest }; - xdr.GlobalXDomainRequest = global.XDomainRequest; - xdr.supportsXDR = typeof xdr.GlobalXDomainRequest != "undefined"; - xdr.workingXDR = xdr.supportsXDR ? xdr.GlobalXDomainRequest : false; - - function makeApi(sinon) { - sinon.xdr = xdr; - - function FakeXDomainRequest() { - this.readyState = FakeXDomainRequest.UNSENT; - this.requestBody = null; - this.requestHeaders = {}; - this.status = 0; - this.timeout = null; - - if (typeof FakeXDomainRequest.onCreate == "function") { - FakeXDomainRequest.onCreate(this); - } - } - - function verifyState(xdr) { - if (xdr.readyState !== FakeXDomainRequest.OPENED) { - throw new Error("INVALID_STATE_ERR"); - } - - if (xdr.sendFlag) { - throw new Error("INVALID_STATE_ERR"); - } - } - - function verifyRequestSent(xdr) { - if (xdr.readyState == FakeXDomainRequest.UNSENT) { - throw new Error("Request not sent"); - } - if (xdr.readyState == FakeXDomainRequest.DONE) { - throw new Error("Request done"); - } - } - - function verifyResponseBodyType(body) { - if (typeof body != "string") { - var error = new Error("Attempted to respond to fake XDomainRequest with " + - body + ", which is not a string."); - error.name = "InvalidBodyException"; - throw error; - } - } - - sinon.extend(FakeXDomainRequest.prototype, sinon.EventTarget, { - open: function open(method, url) { - this.method = method; - this.url = url; - - this.responseText = null; - this.sendFlag = false; - - this.readyStateChange(FakeXDomainRequest.OPENED); - }, - - readyStateChange: function readyStateChange(state) { - this.readyState = state; - var eventName = ""; - switch (this.readyState) { - case FakeXDomainRequest.UNSENT: - break; - case FakeXDomainRequest.OPENED: - break; - case FakeXDomainRequest.LOADING: - if (this.sendFlag) { - //raise the progress event - eventName = "onprogress"; - } - break; - case FakeXDomainRequest.DONE: - if (this.isTimeout) { - eventName = "ontimeout" - } else if (this.errorFlag || (this.status < 200 || this.status > 299)) { - eventName = "onerror"; - } else { - eventName = "onload" - } - break; - } - - // raising event (if defined) - if (eventName) { - if (typeof this[eventName] == "function") { - try { - this[eventName](); - } catch (e) { - sinon.logError("Fake XHR " + eventName + " handler", e); - } - } - } - }, - - send: function send(data) { - verifyState(this); - - if (!/^(get|head)$/i.test(this.method)) { - this.requestBody = data; - } - this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; - - this.errorFlag = false; - this.sendFlag = true; - this.readyStateChange(FakeXDomainRequest.OPENED); - - if (typeof this.onSend == "function") { - this.onSend(this); - } - }, - - abort: function abort() { - this.aborted = true; - this.responseText = null; - this.errorFlag = true; - - if (this.readyState > sinon.FakeXDomainRequest.UNSENT && this.sendFlag) { - this.readyStateChange(sinon.FakeXDomainRequest.DONE); - this.sendFlag = false; - } - }, - - setResponseBody: function setResponseBody(body) { - verifyRequestSent(this); - verifyResponseBodyType(body); - - var chunkSize = this.chunkSize || 10; - var index = 0; - this.responseText = ""; - - do { - this.readyStateChange(FakeXDomainRequest.LOADING); - this.responseText += body.substring(index, index + chunkSize); - index += chunkSize; - } while (index < body.length); - - this.readyStateChange(FakeXDomainRequest.DONE); - }, - - respond: function respond(status, contentType, body) { - // content-type ignored, since XDomainRequest does not carry this - // we keep the same syntax for respond(...) as for FakeXMLHttpRequest to ease - // test integration across browsers - this.status = typeof status == "number" ? status : 200; - this.setResponseBody(body || ""); - }, - - simulatetimeout: function simulatetimeout() { - this.status = 0; - this.isTimeout = true; - // Access to this should actually throw an error - this.responseText = undefined; - this.readyStateChange(FakeXDomainRequest.DONE); - } - }); - - sinon.extend(FakeXDomainRequest, { - UNSENT: 0, - OPENED: 1, - LOADING: 3, - DONE: 4 - }); - - sinon.useFakeXDomainRequest = function useFakeXDomainRequest() { - sinon.FakeXDomainRequest.restore = function restore(keepOnCreate) { - if (xdr.supportsXDR) { - global.XDomainRequest = xdr.GlobalXDomainRequest; - } - - delete sinon.FakeXDomainRequest.restore; - - if (keepOnCreate !== true) { - delete sinon.FakeXDomainRequest.onCreate; - } - }; - if (xdr.supportsXDR) { - global.XDomainRequest = sinon.FakeXDomainRequest; - } - return sinon.FakeXDomainRequest; - }; - - sinon.FakeXDomainRequest = FakeXDomainRequest; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./core"); - require("../extend"); - require("./event"); - require("../log_error"); - makeApi(sinon); - module.exports = sinon; - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else { - makeApi(sinon); - } -})(this); - -},{"../extend":29,"../log_error":31,"./core":41,"./event":42}],47:[function(require,module,exports){ -(function (global){ -/** - * @depend core.js - * @depend ../extend.js - * @depend event.js - * @depend ../log_error.js - */ -/** - * Fake XMLHttpRequest object - * - * @author Christian Johansen (christian@cjohansen.no) - * @license BSD - * - * Copyright (c) 2010-2013 Christian Johansen - */ -"use strict"; - -(function (global) { - - var supportsProgress = typeof ProgressEvent !== "undefined"; - var supportsCustomEvent = typeof CustomEvent !== "undefined"; - var sinonXhr = { XMLHttpRequest: global.XMLHttpRequest }; - sinonXhr.GlobalXMLHttpRequest = global.XMLHttpRequest; - sinonXhr.GlobalActiveXObject = global.ActiveXObject; - sinonXhr.supportsActiveX = typeof sinonXhr.GlobalActiveXObject != "undefined"; - sinonXhr.supportsXHR = typeof sinonXhr.GlobalXMLHttpRequest != "undefined"; - sinonXhr.workingXHR = sinonXhr.supportsXHR ? sinonXhr.GlobalXMLHttpRequest : sinonXhr.supportsActiveX - ? function () { return new sinonXhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; - sinonXhr.supportsCORS = sinonXhr.supportsXHR && "withCredentials" in (new sinonXhr.GlobalXMLHttpRequest()); - - /*jsl:ignore*/ - var unsafeHeaders = { - "Accept-Charset": true, - "Accept-Encoding": true, - Connection: true, - "Content-Length": true, - Cookie: true, - Cookie2: true, - "Content-Transfer-Encoding": true, - Date: true, - Expect: true, - Host: true, - "Keep-Alive": true, - Referer: true, - TE: true, - Trailer: true, - "Transfer-Encoding": true, - Upgrade: true, - "User-Agent": true, - Via: true - }; - /*jsl:end*/ - - function FakeXMLHttpRequest() { - this.readyState = FakeXMLHttpRequest.UNSENT; - this.requestHeaders = {}; - this.requestBody = null; - this.status = 0; - this.statusText = ""; - this.upload = new UploadProgress(); - if (sinonXhr.supportsCORS) { - this.withCredentials = false; - } - - var xhr = this; - var events = ["loadstart", "load", "abort", "loadend"]; - - function addEventListener(eventName) { - xhr.addEventListener(eventName, function (event) { - var listener = xhr["on" + eventName]; - - if (listener && typeof listener == "function") { - listener.call(this, event); - } - }); - } - - for (var i = events.length - 1; i >= 0; i--) { - addEventListener(events[i]); - } - - if (typeof FakeXMLHttpRequest.onCreate == "function") { - FakeXMLHttpRequest.onCreate(this); - } - } - - // An upload object is created for each - // FakeXMLHttpRequest and allows upload - // events to be simulated using uploadProgress - // and uploadError. - function UploadProgress() { - this.eventListeners = { - progress: [], - load: [], - abort: [], - error: [] - } - } - - UploadProgress.prototype.addEventListener = function addEventListener(event, listener) { - this.eventListeners[event].push(listener); - }; - - UploadProgress.prototype.removeEventListener = function removeEventListener(event, listener) { - var listeners = this.eventListeners[event] || []; - - for (var i = 0, l = listeners.length; i < l; ++i) { - if (listeners[i] == listener) { - return listeners.splice(i, 1); - } - } - }; - - UploadProgress.prototype.dispatchEvent = function dispatchEvent(event) { - var listeners = this.eventListeners[event.type] || []; - - for (var i = 0, listener; (listener = listeners[i]) != null; i++) { - listener(event); - } - }; - - function verifyState(xhr) { - if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { - throw new Error("INVALID_STATE_ERR"); - } - - if (xhr.sendFlag) { - throw new Error("INVALID_STATE_ERR"); - } - } - - function getHeader(headers, header) { - header = header.toLowerCase(); - - for (var h in headers) { - if (h.toLowerCase() == header) { - return h; - } - } - - return null; - } - - // filtering to enable a white-list version of Sinon FakeXhr, - // where whitelisted requests are passed through to real XHR - function each(collection, callback) { - if (!collection) { - return; - } - - for (var i = 0, l = collection.length; i < l; i += 1) { - callback(collection[i]); - } - } - function some(collection, callback) { - for (var index = 0; index < collection.length; index++) { - if (callback(collection[index]) === true) { - return true; - } - } - return false; - } - // largest arity in XHR is 5 - XHR#open - var apply = function (obj, method, args) { - switch (args.length) { - case 0: return obj[method](); - case 1: return obj[method](args[0]); - case 2: return obj[method](args[0], args[1]); - case 3: return obj[method](args[0], args[1], args[2]); - case 4: return obj[method](args[0], args[1], args[2], args[3]); - case 5: return obj[method](args[0], args[1], args[2], args[3], args[4]); - } - }; - - FakeXMLHttpRequest.filters = []; - FakeXMLHttpRequest.addFilter = function addFilter(fn) { - this.filters.push(fn) - }; - var IE6Re = /MSIE 6/; - FakeXMLHttpRequest.defake = function defake(fakeXhr, xhrArgs) { - var xhr = new sinonXhr.workingXHR(); - each([ - "open", - "setRequestHeader", - "send", - "abort", - "getResponseHeader", - "getAllResponseHeaders", - "addEventListener", - "overrideMimeType", - "removeEventListener" - ], function (method) { - fakeXhr[method] = function () { - return apply(xhr, method, arguments); - }; - }); - - var copyAttrs = function (args) { - each(args, function (attr) { - try { - fakeXhr[attr] = xhr[attr] - } catch (e) { - if (!IE6Re.test(navigator.userAgent)) { - throw e; - } - } - }); - }; - - var stateChange = function stateChange() { - fakeXhr.readyState = xhr.readyState; - if (xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { - copyAttrs(["status", "statusText"]); - } - if (xhr.readyState >= FakeXMLHttpRequest.LOADING) { - copyAttrs(["responseText", "response"]); - } - if (xhr.readyState === FakeXMLHttpRequest.DONE) { - copyAttrs(["responseXML"]); - } - if (fakeXhr.onreadystatechange) { - fakeXhr.onreadystatechange.call(fakeXhr, { target: fakeXhr }); - } - }; - - if (xhr.addEventListener) { - for (var event in fakeXhr.eventListeners) { - if (fakeXhr.eventListeners.hasOwnProperty(event)) { - each(fakeXhr.eventListeners[event], function (handler) { - xhr.addEventListener(event, handler); - }); - } - } - xhr.addEventListener("readystatechange", stateChange); - } else { - xhr.onreadystatechange = stateChange; - } - apply(xhr, "open", xhrArgs); - }; - FakeXMLHttpRequest.useFilters = false; - - function verifyRequestOpened(xhr) { - if (xhr.readyState != FakeXMLHttpRequest.OPENED) { - throw new Error("INVALID_STATE_ERR - " + xhr.readyState); - } - } - - function verifyRequestSent(xhr) { - if (xhr.readyState == FakeXMLHttpRequest.DONE) { - throw new Error("Request done"); - } - } - - function verifyHeadersReceived(xhr) { - if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { - throw new Error("No headers received"); - } - } - - function verifyResponseBodyType(body) { - if (typeof body != "string") { - var error = new Error("Attempted to respond to fake XMLHttpRequest with " + - body + ", which is not a string."); - error.name = "InvalidBodyException"; - throw error; - } - } - - FakeXMLHttpRequest.parseXML = function parseXML(text) { - var xmlDoc; - - if (typeof DOMParser != "undefined") { - var parser = new DOMParser(); - xmlDoc = parser.parseFromString(text, "text/xml"); - } else { - xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); - xmlDoc.async = "false"; - xmlDoc.loadXML(text); - } - - return xmlDoc; - }; - - FakeXMLHttpRequest.statusCodes = { - 100: "Continue", - 101: "Switching Protocols", - 200: "OK", - 201: "Created", - 202: "Accepted", - 203: "Non-Authoritative Information", - 204: "No Content", - 205: "Reset Content", - 206: "Partial Content", - 207: "Multi-Status", - 300: "Multiple Choice", - 301: "Moved Permanently", - 302: "Found", - 303: "See Other", - 304: "Not Modified", - 305: "Use Proxy", - 307: "Temporary Redirect", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 409: "Conflict", - 410: "Gone", - 411: "Length Required", - 412: "Precondition Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Requested Range Not Satisfiable", - 417: "Expectation Failed", - 422: "Unprocessable Entity", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", - 505: "HTTP Version Not Supported" - }; - - function makeApi(sinon) { - sinon.xhr = sinonXhr; - - sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { - async: true, - - open: function open(method, url, async, username, password) { - this.method = method; - this.url = url; - this.async = typeof async == "boolean" ? async : true; - this.username = username; - this.password = password; - this.responseText = null; - this.responseXML = null; - this.requestHeaders = {}; - this.sendFlag = false; - - if (FakeXMLHttpRequest.useFilters === true) { - var xhrArgs = arguments; - var defake = some(FakeXMLHttpRequest.filters, function (filter) { - return filter.apply(this, xhrArgs) - }); - if (defake) { - return FakeXMLHttpRequest.defake(this, arguments); - } - } - this.readyStateChange(FakeXMLHttpRequest.OPENED); - }, - - readyStateChange: function readyStateChange(state) { - this.readyState = state; - - if (typeof this.onreadystatechange == "function") { - try { - this.onreadystatechange(); - } catch (e) { - sinon.logError("Fake XHR onreadystatechange handler", e); - } - } - - this.dispatchEvent(new sinon.Event("readystatechange")); - - switch (this.readyState) { - case FakeXMLHttpRequest.DONE: - this.dispatchEvent(new sinon.Event("load", false, false, this)); - this.dispatchEvent(new sinon.Event("loadend", false, false, this)); - this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - this.dispatchEvent(new sinon.ProgressEvent("progress", {loaded: 100, total: 100})); - } - break; - } - }, - - setRequestHeader: function setRequestHeader(header, value) { - verifyState(this); - - if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { - throw new Error("Refused to set unsafe header \"" + header + "\""); - } - - if (this.requestHeaders[header]) { - this.requestHeaders[header] += "," + value; - } else { - this.requestHeaders[header] = value; - } - }, - - // Helps testing - setResponseHeaders: function setResponseHeaders(headers) { - verifyRequestOpened(this); - this.responseHeaders = {}; - - for (var header in headers) { - if (headers.hasOwnProperty(header)) { - this.responseHeaders[header] = headers[header]; - } - } - - if (this.async) { - this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); - } else { - this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; - } - }, - - // Currently treats ALL data as a DOMString (i.e. no Document) - send: function send(data) { - verifyState(this); - - if (!/^(get|head)$/i.test(this.method)) { - var contentType = getHeader(this.requestHeaders, "Content-Type"); - if (this.requestHeaders[contentType]) { - var value = this.requestHeaders[contentType].split(";"); - this.requestHeaders[contentType] = value[0] + ";charset=utf-8"; - } else if (!(data instanceof FormData)) { - this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; - } - - this.requestBody = data; - } - - this.errorFlag = false; - this.sendFlag = this.async; - this.readyStateChange(FakeXMLHttpRequest.OPENED); - - if (typeof this.onSend == "function") { - this.onSend(this); - } - - this.dispatchEvent(new sinon.Event("loadstart", false, false, this)); - }, - - abort: function abort() { - this.aborted = true; - this.responseText = null; - this.errorFlag = true; - this.requestHeaders = {}; - - if (this.readyState > FakeXMLHttpRequest.UNSENT && this.sendFlag) { - this.readyStateChange(FakeXMLHttpRequest.DONE); - this.sendFlag = false; - } - - this.readyState = FakeXMLHttpRequest.UNSENT; - - this.dispatchEvent(new sinon.Event("abort", false, false, this)); - - this.upload.dispatchEvent(new sinon.Event("abort", false, false, this)); - - if (typeof this.onerror === "function") { - this.onerror(); - } - }, - - getResponseHeader: function getResponseHeader(header) { - if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { - return null; - } - - if (/^Set-Cookie2?$/i.test(header)) { - return null; - } - - header = getHeader(this.responseHeaders, header); - - return this.responseHeaders[header] || null; - }, - - getAllResponseHeaders: function getAllResponseHeaders() { - if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { - return ""; - } - - var headers = ""; - - for (var header in this.responseHeaders) { - if (this.responseHeaders.hasOwnProperty(header) && - !/^Set-Cookie2?$/i.test(header)) { - headers += header + ": " + this.responseHeaders[header] + "\r\n"; - } - } - - return headers; - }, - - setResponseBody: function setResponseBody(body) { - verifyRequestSent(this); - verifyHeadersReceived(this); - verifyResponseBodyType(body); - - var chunkSize = this.chunkSize || 10; - var index = 0; - this.responseText = ""; - - do { - if (this.async) { - this.readyStateChange(FakeXMLHttpRequest.LOADING); - } - - this.responseText += body.substring(index, index + chunkSize); - index += chunkSize; - } while (index < body.length); - - var type = this.getResponseHeader("Content-Type"); - - if (this.responseText && - (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { - try { - this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); - } catch (e) { - // Unable to parse XML - no biggie - } - } - - this.readyStateChange(FakeXMLHttpRequest.DONE); - }, - - respond: function respond(status, headers, body) { - this.status = typeof status == "number" ? status : 200; - this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; - this.setResponseHeaders(headers || {}); - this.setResponseBody(body || ""); - }, - - uploadProgress: function uploadProgress(progressEventRaw) { - if (supportsProgress) { - this.upload.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw)); - } - }, - - downloadProgress: function downloadProgress(progressEventRaw) { - if (supportsProgress) { - this.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw)); - } - }, - - uploadError: function uploadError(error) { - if (supportsCustomEvent) { - this.upload.dispatchEvent(new sinon.CustomEvent("error", {detail: error})); - } - } - }); - - sinon.extend(FakeXMLHttpRequest, { - UNSENT: 0, - OPENED: 1, - HEADERS_RECEIVED: 2, - LOADING: 3, - DONE: 4 - }); - - sinon.useFakeXMLHttpRequest = function () { - FakeXMLHttpRequest.restore = function restore(keepOnCreate) { - if (sinonXhr.supportsXHR) { - global.XMLHttpRequest = sinonXhr.GlobalXMLHttpRequest; - } - - if (sinonXhr.supportsActiveX) { - global.ActiveXObject = sinonXhr.GlobalActiveXObject; - } - - delete FakeXMLHttpRequest.restore; - - if (keepOnCreate !== true) { - delete FakeXMLHttpRequest.onCreate; - } - }; - if (sinonXhr.supportsXHR) { - global.XMLHttpRequest = FakeXMLHttpRequest; - } - - if (sinonXhr.supportsActiveX) { - global.ActiveXObject = function ActiveXObject(objId) { - if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { - - return new FakeXMLHttpRequest(); - } - - return new sinonXhr.GlobalActiveXObject(objId); - }; - } - - return FakeXMLHttpRequest; - }; - - sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; - } - - var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; - var isAMD = typeof define === "function" && typeof define.amd === "object" && define.amd; - - function loadDependencies(require, exports, module) { - var sinon = require("./core"); - require("../extend"); - require("./event"); - require("../log_error"); - makeApi(sinon); - module.exports = sinon; - } - - if (isAMD) { - define(loadDependencies); - } else if (isNode) { - loadDependencies(require, module.exports, module); - } else if (typeof sinon === "undefined") { - return; - } else { - makeApi(sinon); - } - -})(typeof global !== "undefined" ? global : this); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"../extend":29,"../log_error":31,"./core":41,"./event":42}],48:[function(require,module,exports){ -(function (global){ -((typeof define === "function" && define.amd && function (m) { - define("formatio", ["samsam"], m); -}) || (typeof module === "object" && function (m) { - module.exports = m(require("samsam")); -}) || function (m) { this.formatio = m(this.samsam); } -)(function (samsam) { - "use strict"; - - var formatio = { - excludeConstructors: ["Object", /^.$/], - quoteStrings: true, - limitChildrenCount: 0 - }; - - var hasOwn = Object.prototype.hasOwnProperty; - - var specialObjects = []; - if (typeof global !== "undefined") { - specialObjects.push({ object: global, value: "[object global]" }); - } - if (typeof document !== "undefined") { - specialObjects.push({ - object: document, - value: "[object HTMLDocument]" - }); - } - if (typeof window !== "undefined") { - specialObjects.push({ object: window, value: "[object Window]" }); - } - - function functionName(func) { - if (!func) { return ""; } - if (func.displayName) { return func.displayName; } - if (func.name) { return func.name; } - var matches = func.toString().match(/function\s+([^\(]+)/m); - return (matches && matches[1]) || ""; - } - - function constructorName(f, object) { - var name = functionName(object && object.constructor); - var excludes = f.excludeConstructors || - formatio.excludeConstructors || []; - - var i, l; - for (i = 0, l = excludes.length; i < l; ++i) { - if (typeof excludes[i] === "string" && excludes[i] === name) { - return ""; - } else if (excludes[i].test && excludes[i].test(name)) { - return ""; - } - } - - return name; - } - - function isCircular(object, objects) { - if (typeof object !== "object") { return false; } - var i, l; - for (i = 0, l = objects.length; i < l; ++i) { - if (objects[i] === object) { return true; } - } - return false; - } - - function ascii(f, object, processed, indent) { - if (typeof object === "string") { - var qs = f.quoteStrings; - var quote = typeof qs !== "boolean" || qs; - return processed || quote ? '"' + object + '"' : object; - } - - if (typeof object === "function" && !(object instanceof RegExp)) { - return ascii.func(object); - } - - processed = processed || []; - - if (isCircular(object, processed)) { return "[Circular]"; } - - if (Object.prototype.toString.call(object) === "[object Array]") { - return ascii.array.call(f, object, processed); - } - - if (!object) { return String((1/object) === -Infinity ? "-0" : object); } - if (samsam.isElement(object)) { return ascii.element(object); } - - if (typeof object.toString === "function" && - object.toString !== Object.prototype.toString) { - return object.toString(); - } - - var i, l; - for (i = 0, l = specialObjects.length; i < l; i++) { - if (object === specialObjects[i].object) { - return specialObjects[i].value; - } - } - - return ascii.object.call(f, object, processed, indent); - } - - ascii.func = function (func) { - return "function " + functionName(func) + "() {}"; - }; - - ascii.array = function (array, processed) { - processed = processed || []; - processed.push(array); - var pieces = []; - var i, l; - l = (this.limitChildrenCount > 0) ? - Math.min(this.limitChildrenCount, array.length) : array.length; - - for (i = 0; i < l; ++i) { - pieces.push(ascii(this, array[i], processed)); - } - - if(l < array.length) - pieces.push("[... " + (array.length - l) + " more elements]"); - - return "[" + pieces.join(", ") + "]"; - }; - - ascii.object = function (object, processed, indent) { - processed = processed || []; - processed.push(object); - indent = indent || 0; - var pieces = [], properties = samsam.keys(object).sort(); - var length = 3; - var prop, str, obj, i, k, l; - l = (this.limitChildrenCount > 0) ? - Math.min(this.limitChildrenCount, properties.length) : properties.length; - - for (i = 0; i < l; ++i) { - prop = properties[i]; - obj = object[prop]; - - if (isCircular(obj, processed)) { - str = "[Circular]"; - } else { - str = ascii(this, obj, processed, indent + 2); - } - - str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; - length += str.length; - pieces.push(str); - } - - var cons = constructorName(this, object); - var prefix = cons ? "[" + cons + "] " : ""; - var is = ""; - for (i = 0, k = indent; i < k; ++i) { is += " "; } - - if(l < properties.length) - pieces.push("[... " + (properties.length - l) + " more elements]"); - - if (length + indent > 80) { - return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + - is + "}"; - } - return prefix + "{ " + pieces.join(", ") + " }"; - }; - - ascii.element = function (element) { - var tagName = element.tagName.toLowerCase(); - var attrs = element.attributes, attr, pairs = [], attrName, i, l, val; - - for (i = 0, l = attrs.length; i < l; ++i) { - attr = attrs.item(i); - attrName = attr.nodeName.toLowerCase().replace("html:", ""); - val = attr.nodeValue; - if (attrName !== "contenteditable" || val !== "inherit") { - if (!!val) { pairs.push(attrName + "=\"" + val + "\""); } - } - } - - var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); - var content = element.innerHTML; - - if (content.length > 20) { - content = content.substr(0, 20) + "[...]"; - } - - var res = formatted + pairs.join(" ") + ">" + content + - ""; - - return res.replace(/ contentEditable="inherit"/, ""); - }; - - function Formatio(options) { - for (var opt in options) { - this[opt] = options[opt]; - } - } - - Formatio.prototype = { - functionName: functionName, - - configure: function (options) { - return new Formatio(options); - }, - - constructorName: function (object) { - return constructorName(this, object); - }, - - ascii: function (object, processed, indent) { - return ascii(this, object, processed, indent); - } - }; - - return Formatio.prototype; -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"samsam":49}],49:[function(require,module,exports){ -((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) || - (typeof module === "object" && - function (m) { module.exports = m(); }) || // Node - function (m) { this.samsam = m(); } // Browser globals -)(function () { - var o = Object.prototype; - var div = typeof document !== "undefined" && document.createElement("div"); - - function isNaN(value) { - // Unlike global isNaN, this avoids type coercion - // typeof check avoids IE host object issues, hat tip to - // lodash - var val = value; // JsLint thinks value !== value is "weird" - return typeof value === "number" && value !== val; - } - - function getClass(value) { - // Returns the internal [[Class]] by calling Object.prototype.toString - // with the provided value as this. Return value is a string, naming the - // internal class, e.g. "Array" - return o.toString.call(value).split(/[ \]]/)[1]; - } - - /** - * @name samsam.isArguments - * @param Object object - * - * Returns ``true`` if ``object`` is an ``arguments`` object, - * ``false`` otherwise. - */ - function isArguments(object) { - if (getClass(object) === 'Arguments') { return true; } - if (typeof object !== "object" || typeof object.length !== "number" || - getClass(object) === "Array") { - return false; - } - if (typeof object.callee == "function") { return true; } - try { - object[object.length] = 6; - delete object[object.length]; - } catch (e) { - return true; - } - return false; - } - - /** - * @name samsam.isElement - * @param Object object - * - * Returns ``true`` if ``object`` is a DOM element node. Unlike - * Underscore.js/lodash, this function will return ``false`` if ``object`` - * is an *element-like* object, i.e. a regular object with a ``nodeType`` - * property that holds the value ``1``. - */ - function isElement(object) { - if (!object || object.nodeType !== 1 || !div) { return false; } - try { - object.appendChild(div); - object.removeChild(div); - } catch (e) { - return false; - } - return true; - } - - /** - * @name samsam.keys - * @param Object object - * - * Return an array of own property names. - */ - function keys(object) { - var ks = [], prop; - for (prop in object) { - if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); } - } - return ks; - } - - /** - * @name samsam.isDate - * @param Object value - * - * Returns true if the object is a ``Date``, or *date-like*. Duck typing - * of date objects work by checking that the object has a ``getTime`` - * function whose return value equals the return value from the object's - * ``valueOf``. - */ - function isDate(value) { - return typeof value.getTime == "function" && - value.getTime() == value.valueOf(); - } - - /** - * @name samsam.isNegZero - * @param Object value - * - * Returns ``true`` if ``value`` is ``-0``. - */ - function isNegZero(value) { - return value === 0 && 1 / value === -Infinity; - } - - /** - * @name samsam.equal - * @param Object obj1 - * @param Object obj2 - * - * Returns ``true`` if two objects are strictly equal. Compared to - * ``===`` there are two exceptions: - * - * - NaN is considered equal to NaN - * - -0 and +0 are not considered equal - */ - function identical(obj1, obj2) { - if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) { - return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2); - } - } - - - /** - * @name samsam.deepEqual - * @param Object obj1 - * @param Object obj2 - * - * Deep equal comparison. Two values are "deep equal" if: - * - * - They are equal, according to samsam.identical - * - They are both date objects representing the same time - * - They are both arrays containing elements that are all deepEqual - * - They are objects with the same set of properties, and each property - * in ``obj1`` is deepEqual to the corresponding property in ``obj2`` - * - * Supports cyclic objects. - */ - function deepEqualCyclic(obj1, obj2) { - - // used for cyclic comparison - // contain already visited objects - var objects1 = [], - objects2 = [], - // contain pathes (position in the object structure) - // of the already visited objects - // indexes same as in objects arrays - paths1 = [], - paths2 = [], - // contains combinations of already compared objects - // in the manner: { "$1['ref']$2['ref']": true } - compared = {}; - - /** - * used to check, if the value of a property is an object - * (cyclic logic is only needed for objects) - * only needed for cyclic logic - */ - function isObject(value) { - - if (typeof value === 'object' && value !== null && - !(value instanceof Boolean) && - !(value instanceof Date) && - !(value instanceof Number) && - !(value instanceof RegExp) && - !(value instanceof String)) { - - return true; - } - - return false; - } - - /** - * returns the index of the given object in the - * given objects array, -1 if not contained - * only needed for cyclic logic - */ - function getIndex(objects, obj) { - - var i; - for (i = 0; i < objects.length; i++) { - if (objects[i] === obj) { - return i; - } - } - - return -1; - } - - // does the recursion for the deep equal check - return (function deepEqual(obj1, obj2, path1, path2) { - var type1 = typeof obj1; - var type2 = typeof obj2; - - // == null also matches undefined - if (obj1 === obj2 || - isNaN(obj1) || isNaN(obj2) || - obj1 == null || obj2 == null || - type1 !== "object" || type2 !== "object") { - - return identical(obj1, obj2); - } - - // Elements are only equal if identical(expected, actual) - if (isElement(obj1) || isElement(obj2)) { return false; } - - var isDate1 = isDate(obj1), isDate2 = isDate(obj2); - if (isDate1 || isDate2) { - if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) { - return false; - } - } - - if (obj1 instanceof RegExp && obj2 instanceof RegExp) { - if (obj1.toString() !== obj2.toString()) { return false; } - } - - var class1 = getClass(obj1); - var class2 = getClass(obj2); - var keys1 = keys(obj1); - var keys2 = keys(obj2); - - if (isArguments(obj1) || isArguments(obj2)) { - if (obj1.length !== obj2.length) { return false; } - } else { - if (type1 !== type2 || class1 !== class2 || - keys1.length !== keys2.length) { - return false; - } - } - - var key, i, l, - // following vars are used for the cyclic logic - value1, value2, - isObject1, isObject2, - index1, index2, - newPath1, newPath2; - - for (i = 0, l = keys1.length; i < l; i++) { - key = keys1[i]; - if (!o.hasOwnProperty.call(obj2, key)) { - return false; - } - - // Start of the cyclic logic - - value1 = obj1[key]; - value2 = obj2[key]; - - isObject1 = isObject(value1); - isObject2 = isObject(value2); - - // determine, if the objects were already visited - // (it's faster to check for isObject first, than to - // get -1 from getIndex for non objects) - index1 = isObject1 ? getIndex(objects1, value1) : -1; - index2 = isObject2 ? getIndex(objects2, value2) : -1; - - // determine the new pathes of the objects - // - for non cyclic objects the current path will be extended - // by current property name - // - for cyclic objects the stored path is taken - newPath1 = index1 !== -1 - ? paths1[index1] - : path1 + '[' + JSON.stringify(key) + ']'; - newPath2 = index2 !== -1 - ? paths2[index2] - : path2 + '[' + JSON.stringify(key) + ']'; - - // stop recursion if current objects are already compared - if (compared[newPath1 + newPath2]) { - return true; - } - - // remember the current objects and their pathes - if (index1 === -1 && isObject1) { - objects1.push(value1); - paths1.push(newPath1); - } - if (index2 === -1 && isObject2) { - objects2.push(value2); - paths2.push(newPath2); - } - - // remember that the current objects are already compared - if (isObject1 && isObject2) { - compared[newPath1 + newPath2] = true; - } - - // End of cyclic logic - - // neither value1 nor value2 is a cycle - // continue with next level - if (!deepEqual(value1, value2, newPath1, newPath2)) { - return false; - } - } - - return true; - - }(obj1, obj2, '$1', '$2')); - } - - var match; - - function arrayContains(array, subset) { - if (subset.length === 0) { return true; } - var i, l, j, k; - for (i = 0, l = array.length; i < l; ++i) { - if (match(array[i], subset[0])) { - for (j = 0, k = subset.length; j < k; ++j) { - if (!match(array[i + j], subset[j])) { return false; } - } - return true; - } - } - return false; - } - - /** - * @name samsam.match - * @param Object object - * @param Object matcher - * - * Compare arbitrary value ``object`` with matcher. - */ - match = function match(object, matcher) { - if (matcher && typeof matcher.test === "function") { - return matcher.test(object); - } - - if (typeof matcher === "function") { - return matcher(object) === true; - } - - if (typeof matcher === "string") { - matcher = matcher.toLowerCase(); - var notNull = typeof object === "string" || !!object; - return notNull && - (String(object)).toLowerCase().indexOf(matcher) >= 0; - } - - if (typeof matcher === "number") { - return matcher === object; - } - - if (typeof matcher === "boolean") { - return matcher === object; - } - - if (typeof(matcher) === "undefined") { - return typeof(object) === "undefined"; - } - - if (matcher === null) { - return object === null; - } - - if (getClass(object) === "Array" && getClass(matcher) === "Array") { - return arrayContains(object, matcher); - } - - if (matcher && typeof matcher === "object") { - if (matcher === object) { - return true; - } - var prop; - for (prop in matcher) { - var value = object[prop]; - if (typeof value === "undefined" && - typeof object.getAttribute === "function") { - value = object.getAttribute(prop); - } - if (matcher[prop] === null || typeof matcher[prop] === 'undefined') { - if (value !== matcher[prop]) { - return false; - } - } else if (typeof value === "undefined" || !match(value, matcher[prop])) { - return false; - } - } - return true; - } - - throw new Error("Matcher was not a string, a number, a " + - "function, a boolean or an object"); - }; - - return { - isArguments: isArguments, - isElement: isElement, - isDate: isDate, - isNegZero: isNegZero, - identical: identical, - deepEqual: deepEqualCyclic, - match: match, - keys: keys - }; -}); - -},{}],50:[function(require,module,exports){ -(function (global){ -/*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ -/*global global*/ -/** - * @author Christian Johansen (christian@cjohansen.no) and contributors - * @license BSD - * - * Copyright (c) 2010-2014 Christian Johansen - */ -"use strict"; - -// node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref() -// browsers, a number. -// see https://github.com/cjohansen/Sinon.JS/pull/436 -var timeoutResult = setTimeout(function() {}, 0); -var addTimerReturnsObject = typeof timeoutResult === "object"; -clearTimeout(timeoutResult); - -var NativeDate = Date; -var id = 1; - -/** - * Parse strings like "01:10:00" (meaning 1 hour, 10 minutes, 0 seconds) into - * number of milliseconds. This is used to support human-readable strings passed - * to clock.tick() - */ -function parseTime(str) { - if (!str) { - return 0; - } - - var strings = str.split(":"); - var l = strings.length, i = l; - var ms = 0, parsed; - - if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { - throw new Error("tick only understands numbers and 'h:m:s'"); - } - - while (i--) { - parsed = parseInt(strings[i], 10); - - if (parsed >= 60) { - throw new Error("Invalid time " + str); - } - - ms += parsed * Math.pow(60, (l - i - 1)); - } - - return ms * 1000; -} - -/** - * Used to grok the `now` parameter to createClock. - */ -function getEpoch(epoch) { - if (!epoch) { return 0; } - if (typeof epoch.getTime === "function") { return epoch.getTime(); } - if (typeof epoch === "number") { return epoch; } - throw new TypeError("now should be milliseconds since UNIX epoch"); -} - -function inRange(from, to, timer) { - return timer && timer.callAt >= from && timer.callAt <= to; -} - -function mirrorDateProperties(target, source) { - if (source.now) { - target.now = function now() { - return target.clock.now; - }; - } else { - delete target.now; - } - - if (source.toSource) { - target.toSource = function toSource() { - return source.toSource(); - }; - } else { - delete target.toSource; - } - - target.toString = function toString() { - return source.toString(); - }; - - target.prototype = source.prototype; - target.parse = source.parse; - target.UTC = source.UTC; - target.prototype.toUTCString = source.prototype.toUTCString; - - for (var prop in source) { - if (source.hasOwnProperty(prop)) { - target[prop] = source[prop]; - } - } - - return target; -} - -function createDate() { - function ClockDate(year, month, date, hour, minute, second, ms) { - // Defensive and verbose to avoid potential harm in passing - // explicit undefined when user does not pass argument - switch (arguments.length) { - case 0: - return new NativeDate(ClockDate.clock.now); - case 1: - return new NativeDate(year); - case 2: - return new NativeDate(year, month); - case 3: - return new NativeDate(year, month, date); - case 4: - return new NativeDate(year, month, date, hour); - case 5: - return new NativeDate(year, month, date, hour, minute); - case 6: - return new NativeDate(year, month, date, hour, minute, second); - default: - return new NativeDate(year, month, date, hour, minute, second, ms); - } - } - - return mirrorDateProperties(ClockDate, NativeDate); -} - -function addTimer(clock, timer) { - if (typeof timer.func === "undefined") { - throw new Error("Callback must be provided to timer calls"); - } - - if (!clock.timers) { - clock.timers = {}; - } - - timer.id = id++; - timer.createdAt = clock.now; - timer.callAt = clock.now + (timer.delay || 0); - - clock.timers[timer.id] = timer; - - if (addTimerReturnsObject) { - return { - id: timer.id, - ref: function() {}, - unref: function() {} - }; - } - else { - return timer.id; - } -} - -function firstTimerInRange(clock, from, to) { - var timers = clock.timers, timer = null; - - for (var id in timers) { - if (!inRange(from, to, timers[id])) { - continue; - } - - if (!timer || ~compareTimers(timer, timers[id])) { - timer = timers[id]; - } - } - - return timer; -} - -function compareTimers(a, b) { - // Sort first by absolute timing - if (a.callAt < b.callAt) { - return -1; - } - if (a.callAt > b.callAt) { - return 1; - } - - // Sort next by immediate, immediate timers take precedence - if (a.immediate && !b.immediate) { - return -1; - } - if (!a.immediate && b.immediate) { - return 1; - } - - // Sort next by creation time, earlier-created timers take precedence - if (a.createdAt < b.createdAt) { - return -1; - } - if (a.createdAt > b.createdAt) { - return 1; - } - - // Sort next by id, lower-id timers take precedence - if (a.id < b.id) { - return -1; - } - if (a.id > b.id) { - return 1; - } - - // As timer ids are unique, no fallback `0` is necessary -} - -function callTimer(clock, timer) { - if (typeof timer.interval == "number") { - clock.timers[timer.id].callAt += timer.interval; - } else { - delete clock.timers[timer.id]; - } - - try { - if (typeof timer.func == "function") { - timer.func.apply(null, timer.args); - } else { - eval(timer.func); - } - } catch (e) { - var exception = e; - } - - if (!clock.timers[timer.id]) { - if (exception) { - throw exception; - } - return; - } - - if (exception) { - throw exception; - } -} - -function uninstall(clock, target) { - var method; - - for (var i = 0, l = clock.methods.length; i < l; i++) { - method = clock.methods[i]; - - if (target[method].hadOwnProperty) { - target[method] = clock["_" + method]; - } else { - try { - delete target[method]; - } catch (e) {} - } - } - - // Prevent multiple executions which will completely remove these props - clock.methods = []; -} - -function hijackMethod(target, method, clock) { - clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(target, method); - clock["_" + method] = target[method]; - - if (method == "Date") { - var date = mirrorDateProperties(clock[method], target[method]); - target[method] = date; - } else { - target[method] = function () { - return clock[method].apply(clock, arguments); - }; - - for (var prop in clock[method]) { - if (clock[method].hasOwnProperty(prop)) { - target[method][prop] = clock[method][prop]; - } - } - } - - target[method].clock = clock; -} - -var timers = { - setTimeout: setTimeout, - clearTimeout: clearTimeout, - setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined), - clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate: undefined), - setInterval: setInterval, - clearInterval: clearInterval, - Date: Date -}; - -var keys = Object.keys || function (obj) { - var ks = []; - for (var key in obj) { - ks.push(key); - } - return ks; -}; - -exports.timers = timers; - -var createClock = exports.createClock = function (now) { - var clock = { - now: getEpoch(now), - timeouts: {}, - Date: createDate() - }; - - clock.Date.clock = clock; - - clock.setTimeout = function setTimeout(func, timeout) { - return addTimer(clock, { - func: func, - args: Array.prototype.slice.call(arguments, 2), - delay: timeout - }); - }; - - clock.clearTimeout = function clearTimeout(timerId) { - if (!timerId) { - // null appears to be allowed in most browsers, and appears to be - // relied upon by some libraries, like Bootstrap carousel - return; - } - if (!clock.timers) { - clock.timers = []; - } - // in Node, timerId is an object with .ref()/.unref(), and - // its .id field is the actual timer id. - if (typeof timerId === "object") { - timerId = timerId.id - } - if (timerId in clock.timers) { - delete clock.timers[timerId]; - } - }; - - clock.setInterval = function setInterval(func, timeout) { - return addTimer(clock, { - func: func, - args: Array.prototype.slice.call(arguments, 2), - delay: timeout, - interval: timeout - }); - }; - - clock.clearInterval = function clearInterval(timerId) { - clock.clearTimeout(timerId); - }; - - clock.setImmediate = function setImmediate(func) { - return addTimer(clock, { - func: func, - args: Array.prototype.slice.call(arguments, 1), - immediate: true - }); - }; - - clock.clearImmediate = function clearImmediate(timerId) { - clock.clearTimeout(timerId); - }; - - clock.tick = function tick(ms) { - ms = typeof ms == "number" ? ms : parseTime(ms); - var tickFrom = clock.now, tickTo = clock.now + ms, previous = clock.now; - var timer = firstTimerInRange(clock, tickFrom, tickTo); - - var firstException; - while (timer && tickFrom <= tickTo) { - if (clock.timers[timer.id]) { - tickFrom = clock.now = timer.callAt; - try { - callTimer(clock, timer); - } catch (e) { - firstException = firstException || e; - } - } - - timer = firstTimerInRange(clock, previous, tickTo); - previous = tickFrom; - } - - clock.now = tickTo; - - if (firstException) { - throw firstException; - } - - return clock.now; - }; - - clock.reset = function reset() { - clock.timers = {}; - }; - - return clock; -}; - -exports.install = function install(target, now, toFake) { - if (typeof target === "number") { - toFake = now; - now = target; - target = null; - } - - if (!target) { - target = global; - } - - var clock = createClock(now); - - clock.uninstall = function () { - uninstall(clock, target); - }; - - clock.methods = toFake || []; - - if (clock.methods.length === 0) { - clock.methods = keys(timers); - } - - for (var i = 0, l = clock.methods.length; i < l; i++) { - hijackMethod(target, clock.methods[i], clock); - } - - return clock; -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],51:[function(require,module,exports){ -(function (process,global){ -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } - - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$toString = {}.toString; - var lib$es6$promise$asap$$vertxNext; - function lib$es6$promise$asap$$asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - lib$es6$promise$asap$$scheduleFlush(); - } - } - - var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function() { - nextTick(lib$es6$promise$asap$$flush); - }; - } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } - - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFullfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$default(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } - } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - var then = lib$es6$promise$$internal$$getThen(maybeThenable); - - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } - } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); - } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } - - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } - } - } else { - lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); - } - } - - lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { - return lib$es6$promise$utils$$isArray(input); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { - this._result = new Array(this.length); - }; - - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (lib$es6$promise$utils$$isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - enumerator._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, enumerator._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } - - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; - } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; - } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - var lib$es6$promise$promise$$counter = 0; - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - if (!lib$es6$promise$utils$$isFunction(resolver)) { - lib$es6$promise$promise$$needsResolver(); - } - - if (!(this instanceof lib$es6$promise$promise$$Promise)) { - lib$es6$promise$promise$$needsNew(); - } - - lib$es6$promise$$internal$$initializePromise(this, resolver); - } - } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$default(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; - } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; - } - - lib$es6$promise$polyfill$$default(); -}).call(this); - -//# sourceMappingURL=es6-promise.js.map -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":4}],52:[function(require,module,exports){ -(function (global){ -/*global describe, specify, it, assert */ - -if (typeof Object.getPrototypeOf !== "function") { - Object.getPrototypeOf = "".__proto__ === String.prototype - ? function (object) { - return object.__proto__; - } - : function (object) { - // May break if the constructor has been tampered with - return object.constructor.prototype; - }; -} - -function keysOf(object) { - var results = []; - - for (var key in object) { - if (object.hasOwnProperty(key)) { - results.push(key); - } - } - - return results; -} - -var g = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this; -var Promise = g.adapter.Promise; -var assert = require('assert'); - -function objectEquals(obj1, obj2) { - for (var i in obj1) { - if (obj1.hasOwnProperty(i)) { - if (!obj2.hasOwnProperty(i)) return false; - if (obj1[i] != obj2[i]) return false; - } - } - for (var i in obj2) { - if (obj2.hasOwnProperty(i)) { - if (!obj1.hasOwnProperty(i)) return false; - if (obj1[i] != obj2[i]) return false; - } - } - return true; -} - -describe("extensions", function() { - describe("Promise constructor", function() { - it('should exist and have length 1', function() { - assert(Promise); - assert.equal(Promise.length, 1); - }); - - it('should fulfill if `resolve` is called with a value', function(done) { - var promise = new Promise(function(resolve) { resolve('value'); }); - - promise.then(function(value) { - assert.equal(value, 'value'); - done(); - }); - }); - - it('should reject if `reject` is called with a reason', function(done) { - var promise = new Promise(function(resolve, reject) { reject('reason'); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'reason'); - done(); - }); - }); - - it('should be a constructor', function() { - var promise = new Promise(function() {}); - - assert.equal(Object.getPrototypeOf(promise), Promise.prototype, '[[Prototype]] equals Promise.prototype'); - assert.equal(promise.constructor, Promise, 'constructor property of instances is set correctly'); - assert.equal(Promise.prototype.constructor, Promise, 'constructor property of prototype is set correctly'); - }); - - it('should NOT work without `new`', function() { - assert.throws(function(){ - Promise(function(resolve) { resolve('value'); }); - }, TypeError) - }); - - it('should throw a `TypeError` if not given a function', function() { - assert.throws(function () { - new Promise(); - }, TypeError); - - assert.throws(function () { - new Promise({}); - }, TypeError); - - assert.throws(function () { - new Promise('boo!'); - }, TypeError); - }); - - it('should reject on resolver exception', function(done) { - new Promise(function() { - throw 'error'; - }).then(null, function(e) { - assert.equal(e, 'error'); - done(); - }); - }); - - it('should not resolve multiple times', function(done) { - var resolver, rejector, fulfilled = 0, rejected = 0; - var thenable = { - then: function(resolve, reject) { - resolver = resolve; - rejector = reject; - } - }; - - var promise = new Promise(function(resolve) { - resolve(1); - }); - - promise.then(function(value){ - return thenable; - }).then(function(value){ - fulfilled++; - }, function(reason) { - rejected++; - }); - - setTimeout(function() { - resolver(1); - resolver(1); - rejector(1); - rejector(1); - - setTimeout(function() { - assert.equal(fulfilled, 1); - assert.equal(rejected, 0); - done(); - }, 20); - }, 20); - - }); - - describe('assimilation', function() { - it('should assimilate if `resolve` is called with a fulfilled promise', function(done) { - var originalPromise = new Promise(function(resolve) { resolve('original value'); }); - var promise = new Promise(function(resolve) { resolve(originalPromise); }); - - promise.then(function(value) { - assert.equal(value, 'original value'); - done(); - }); - }); - - it('should assimilate if `resolve` is called with a rejected promise', function(done) { - var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); - var promise = new Promise(function(resolve) { resolve(originalPromise); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'original reason'); - done(); - }); - }); - - it('should assimilate if `resolve` is called with a fulfilled thenable', function(done) { - var originalThenable = { - then: function (onFulfilled) { - setTimeout(function() { onFulfilled('original value'); }, 0); - } - }; - var promise = new Promise(function(resolve) { resolve(originalThenable); }); - - promise.then(function(value) { - assert.equal(value, 'original value'); - done(); - }); - }); - - it('should assimilate if `resolve` is called with a rejected thenable', function(done) { - var originalThenable = { - then: function (onFulfilled, onRejected) { - setTimeout(function() { onRejected('original reason'); }, 0); - } - }; - var promise = new Promise(function(resolve) { resolve(originalThenable); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'original reason'); - done(); - }); - }); - - - it('should assimilate two levels deep, for fulfillment of self fulfilling promises', function(done) { - var originalPromise, promise; - originalPromise = new Promise(function(resolve) { - setTimeout(function() { - resolve(originalPromise); - }, 0) - }); - - promise = new Promise(function(resolve) { - setTimeout(function() { - resolve(originalPromise); - }, 0); - }); - - promise.then(function(value) { - assert(false); - done(); - })['catch'](function(reason) { - assert.equal(reason.message, "You cannot resolve a promise with itself"); - assert(reason instanceof TypeError); - done(); - }); - }); - - it('should assimilate two levels deep, for fulfillment', function(done) { - var originalPromise = new Promise(function(resolve) { resolve('original value'); }); - var nextPromise = new Promise(function(resolve) { resolve(originalPromise); }); - var promise = new Promise(function(resolve) { resolve(nextPromise); }); - - promise.then(function(value) { - assert.equal(value, 'original value'); - done(); - }); - }); - - it('should assimilate two levels deep, for rejection', function(done) { - var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); - var nextPromise = new Promise(function(resolve) { resolve(originalPromise); }); - var promise = new Promise(function(resolve) { resolve(nextPromise); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'original reason'); - done(); - }); - }); - - it('should assimilate three levels deep, mixing thenables and promises (fulfilled case)', function(done) { - var originalPromise = new Promise(function(resolve) { resolve('original value'); }); - var intermediateThenable = { - then: function (onFulfilled) { - setTimeout(function() { onFulfilled(originalPromise); }, 0); - } - }; - var promise = new Promise(function(resolve) { resolve(intermediateThenable); }); - - promise.then(function(value) { - assert.equal(value, 'original value'); - done(); - }); - }); - - it('should assimilate three levels deep, mixing thenables and promises (rejected case)', function(done) { - var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); }); - var intermediateThenable = { - then: function (onFulfilled) { - setTimeout(function() { onFulfilled(originalPromise); }, 0); - } - }; - var promise = new Promise(function(resolve) { resolve(intermediateThenable); }); - - promise.then(function() { - assert(false); - done(); - }, function(reason) { - assert.equal(reason, 'original reason'); - done(); - }); - }); - }); - }); - - describe("Promise.all", function() { - testAll(function(){ - return Promise.all.apply(Promise, arguments); - }); - }); - - function testAll(all) { - it('should exist', function() { - assert(all); - }); - - it('throws when not passed an array', function(done) { - var nothing = assertRejection(all()); - var string = assertRejection(all('')); - var object = assertRejection(all({})); - - Promise.all([ - nothing, - string, - object - ]).then(function(){ done(); }); - }); - - specify('fulfilled only after all of the other promises are fulfilled', function(done) { - var firstResolved, secondResolved, firstResolver, secondResolver; - - var first = new Promise(function(resolve) { - firstResolver = resolve; - }); - first.then(function() { - firstResolved = true; - }); - - var second = new Promise(function(resolve) { - secondResolver = resolve; - }); - second.then(function() { - secondResolved = true; - }); - - setTimeout(function() { - firstResolver(true); - }, 0); - - setTimeout(function() { - secondResolver(true); - }, 0); - - all([first, second]).then(function() { - assert(firstResolved); - assert(secondResolved); - done(); - }); - }); - - specify('rejected as soon as a promise is rejected', function(done) { - var firstResolver, secondResolver; - - var first = new Promise(function(resolve, reject) { - firstResolver = { resolve: resolve, reject: reject }; - }); - - var second = new Promise(function(resolve, reject) { - secondResolver = { resolve: resolve, reject: reject }; - }); - - setTimeout(function() { - firstResolver.reject({}); - }, 0); - - var firstWasRejected, secondCompleted; - - first['catch'](function(){ - firstWasRejected = true; - }); - - second.then(function(){ - secondCompleted = true; - }, function() { - secondCompleted = true; - }); - - all([first, second]).then(function() { - assert(false); - }, function() { - assert(firstWasRejected); - assert(!secondCompleted); - done(); - }); - }); - - specify('passes the resolved values of each promise to the callback in the correct order', function(done) { - var firstResolver, secondResolver, thirdResolver; - - var first = new Promise(function(resolve, reject) { - firstResolver = { resolve: resolve, reject: reject }; - }); - - var second = new Promise(function(resolve, reject) { - secondResolver = { resolve: resolve, reject: reject }; - }); - - var third = new Promise(function(resolve, reject) { - thirdResolver = { resolve: resolve, reject: reject }; - }); - - thirdResolver.resolve(3); - firstResolver.resolve(1); - secondResolver.resolve(2); - - all([first, second, third]).then(function(results) { - assert(results.length === 3); - assert(results[0] === 1); - assert(results[1] === 2); - assert(results[2] === 3); - done(); - }); - }); - - specify('resolves an empty array passed to all()', function(done) { - all([]).then(function(results) { - assert(results.length === 0); - done(); - }); - }); - - specify('works with null', function(done) { - all([null]).then(function(results) { - assert.equal(results[0], null); - done(); - }); - }); - - specify('works with a mix of promises and thenables and non-promises', function(done) { - var promise = new Promise(function(resolve) { resolve(1); }); - var syncThenable = { then: function (onFulfilled) { onFulfilled(2); } }; - var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } }; - var nonPromise = 4; - - all([promise, syncThenable, asyncThenable, nonPromise]).then(function(results) { - assert(objectEquals(results, [1, 2, 3, 4])); - done(); - })['catch'](done); - }); - } - - describe("reject", function(){ - specify("it should exist", function(){ - assert(Promise.reject); - }); - - describe('it rejects', function(){ - var reason = 'the reason', - promise = Promise.reject(reason); - - promise.then(function(){ - assert(false, 'should not fulfill'); - }, function(actualReason){ - assert.equal(reason, actualReason); - }); - }); - }); - - function assertRejection(promise) { - return promise.then(function(){ - assert(false, 'expected rejection, but got fulfillment'); - }, function(reason){ - assert(reason instanceof Error); - }); - } - - describe('race', function() { - it("should exist", function() { - assert(Promise.race); - }); - - it("throws when not passed an array", function(done) { - var nothing = assertRejection(Promise.race()); - var string = assertRejection(Promise.race('')); - var object = assertRejection(Promise.race({})); - - Promise.all([ - nothing, - string, - object - ]).then(function(){ done(); }); - }); - - specify('fulfilled after one of the other promises are fulfilled', function(done) { - var firstResolved, secondResolved, firstResolver, secondResolver; - - var first = new Promise(function(resolve) { - firstResolver = resolve; - }); - first.then(function() { - firstResolved = true; - }); - - var second = new Promise(function(resolve) { - secondResolver = resolve; - }); - second.then(function() { - secondResolved = true; - }); - - setTimeout(function() { - firstResolver(true); - }, 100); - - setTimeout(function() { - secondResolver(true); - }, 0); - - Promise.race([first, second]).then(function() { - assert(secondResolved); - assert.equal(firstResolved, undefined); - done(); - }); - }); - - specify('the race begins on nextTurn and prioritized by array entry', function(done) { - var firstResolver, secondResolver, nonPromise = 5; - - var first = new Promise(function(resolve, reject) { - resolve(true); - }); - - var second = new Promise(function(resolve, reject) { - resolve(false); - }); - - Promise.race([first, second, nonPromise]).then(function(value) { - assert.equal(value, true); - done(); - }); - }); - - specify('rejected as soon as a promise is rejected', function(done) { - var firstResolver, secondResolver; - - var first = new Promise(function(resolve, reject) { - firstResolver = { resolve: resolve, reject: reject }; - }); - - var second = new Promise(function(resolve, reject) { - secondResolver = { resolve: resolve, reject: reject }; - }); - - setTimeout(function() { - firstResolver.reject({}); - }, 0); - - var firstWasRejected, secondCompleted; - - first['catch'](function(){ - firstWasRejected = true; - }); - - second.then(function(){ - secondCompleted = true; - }, function() { - secondCompleted = true; - }); - - Promise.race([first, second]).then(function() { - assert(false); - }, function() { - assert(firstWasRejected); - assert(!secondCompleted); - done(); - }); - }); - - specify('resolves an empty array to forever pending Promise', function(done) { - var foreverPendingPromise = Promise.race([]), - wasSettled = false; - - foreverPendingPromise.then(function() { - wasSettled = true; - }, function() { - wasSettled = true; - }); - - setTimeout(function() { - assert(!wasSettled); - done(); - }, 100); - }); - - specify('works with a mix of promises and thenables', function(done) { - var promise = new Promise(function(resolve) { setTimeout(function() { resolve(1); }, 10); }), - syncThenable = { then: function (onFulfilled) { onFulfilled(2); } }; - - Promise.race([promise, syncThenable]).then(function(result) { - assert(result, 2); - done(); - }); - }); - - specify('works with a mix of thenables and non-promises', function (done) { - var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } }, - nonPromise = 4; - - Promise.race([asyncThenable, nonPromise]).then(function(result) { - assert(result, 4); - done(); - }); - }); - }); - - describe("resolve", function(){ - specify("it should exist", function(){ - assert(Promise.resolve); - }); - - describe("1. If x is a promise, adopt its state ", function(){ - specify("1.1 If x is pending, promise must remain pending until x is fulfilled or rejected.", function(done){ - var expectedValue, resolver, thenable, wrapped; - - expectedValue = 'the value'; - thenable = { - then: function(resolve, reject){ - resolver = resolve; - } - }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(function(value){ - assert(value === expectedValue); - done(); - }); - - setTimeout(function(){ - resolver(expectedValue); - }, 10); - }); - - specify("1.2 If/when x is fulfilled, fulfill promise with the same value.", function(done){ - var expectedValue, thenable, wrapped; - - expectedValue = 'the value'; - thenable = { - then: function(resolve, reject){ - resolve(expectedValue); - } - }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(function(value){ - assert(value === expectedValue); - done(); - }) - }); - - specify("1.3 If/when x is rejected, reject promise with the same reason.", function(done){ - var expectedError, thenable, wrapped; - - expectedError = new Error(); - thenable = { - then: function(resolve, reject){ - reject(expectedError); - } - }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(null, function(error){ - assert(error === expectedError); - done(); - }); - }); - }); - - describe("2. Otherwise, if x is an object or function,", function(){ - specify("2.1 Let then x.then", function(done){ - var accessCount, resolver, wrapped, thenable; - - accessCount = 0; - thenable = { }; - - // we likely don't need to test this, if the browser doesn't support it - if (typeof Object.defineProperty !== "function") { done(); return; } - - Object.defineProperty(thenable, 'then', { - get: function(){ - accessCount++; - - if (accessCount > 1) { - throw new Error(); - } - - return function(){ }; - } - }); - - assert(accessCount === 0); - - wrapped = Promise.resolve(thenable); - - assert(accessCount === 1); - - done(); - }); - - specify("2.2 If retrieving the property x.then results in a thrown exception e, reject promise with e as the reason.", function(done){ - var wrapped, thenable, expectedError; - - expectedError = new Error(); - thenable = { }; - - // we likely don't need to test this, if the browser doesn't support it - if (typeof Object.defineProperty !== "function") { done(); return; } - - Object.defineProperty(thenable, 'then', { - get: function(){ - throw expectedError; - } - }); - - wrapped = Promise.resolve(thenable); - - wrapped.then(null, function(error){ - assert(error === expectedError, 'incorrect exception was thrown'); - done(); - }); - }); - - describe('2.3. If then is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise, where', function(){ - specify('2.3.1 If/when resolvePromise is called with a value y, run Resolve(promise, y)', function(done){ - var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis; - - thenable = { - then: function(resolve, reject){ - calledThis = this; - resolver = resolve; - rejector = reject; - } - }; - - expectedSuccess = 'success'; - wrapped = Promise.resolve(thenable); - - wrapped.then(function(success){ - assert(calledThis === thenable, 'this must be the thenable'); - assert(success === expectedSuccess, 'rejected promise with x'); - done(); - }); - - setTimeout(function() { - resolver(expectedSuccess); - }, 20); - }); - - specify('2.3.2 If/when rejectPromise is called with a reason r, reject promise with r.', function(done){ - var expectedError, resolver, rejector, thenable, wrapped, calledThis; - - thenable = { - then: function(resolve, reject){ - calledThis = this; - resolver = resolve; - rejector = reject; - } - }; - - expectedError = new Error(); - - wrapped = Promise.resolve(thenable); - - wrapped.then(null, function(error){ - assert(error === expectedError, 'rejected promise with x'); - done(); - }); - - setTimeout(function() { - rejector(expectedError); - }, 20); - }); - - specify("2.3.3 If both resolvePromise and rejectPromise are called, or multiple calls to the same argument are made, the first call takes precedence, and any further calls are ignored", function(done){ - var expectedError, expectedSuccess, resolver, rejector, thenable, wrapped, calledThis, - calledRejected, calledResolved; - - calledRejected = 0; - calledResolved = 0; - - thenable = { - then: function(resolve, reject){ - calledThis = this; - resolver = resolve; - rejector = reject; - } - }; - - expectedError = new Error(); - - wrapped = Promise.resolve(thenable); - - wrapped.then(function(){ - calledResolved++; - }, function(error){ - calledRejected++; - assert(calledResolved === 0, 'never resolved'); - assert(calledRejected === 1, 'rejected only once'); - assert(error === expectedError, 'rejected promise with x'); - }); - - setTimeout(function() { - rejector(expectedError); - rejector(expectedError); - - rejector('foo'); - - resolver('bar'); - resolver('baz'); - }, 20); - - setTimeout(function(){ - assert(calledRejected === 1, 'only rejected once'); - assert(calledResolved === 0, 'never resolved'); - done(); - }, 50); - }); - - describe("2.3.4 If calling then throws an exception e", function(){ - specify("2.3.4.1 If resolvePromise or rejectPromise have been called, ignore it.", function(done){ - var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis, - calledRejected, calledResolved; - - expectedSuccess = 'success'; - - thenable = { - then: function(resolve, reject){ - resolve(expectedSuccess); - throw expectedError; - } - }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(function(success){ - assert(success === expectedSuccess, 'resolved not errored'); - done(); - }); - }); - - specify("2.3.4.2 Otherwise, reject promise with e as the reason.", function(done) { - var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount; - - expectedError = new Error(); - callCount = 0; - - thenable = { then: function() { throw expectedError; } }; - - wrapped = Promise.resolve(thenable); - - wrapped.then(null, function(error){ - callCount++; - assert(expectedError === error, 'expected the correct error to be rejected'); - done(); - }); - - assert(callCount === 0, 'expected async, was sync'); - }); - }); - }); - - specify("2.4 If then is not a function, fulfill promise with x", function(done){ - var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount; - - thenable = { then: 3 }; - callCount = 0; - wrapped = Promise.resolve(thenable); - - wrapped.then(function(success){ - callCount++; - assert(thenable === success, 'fulfilled promise with x'); - done(); - }); - - assert(callCount === 0, 'expected async, was sync'); - }); - }); - - describe("3. If x is not an object or function, ", function(){ - specify("fulfill promise with x.", function(done){ - var thenable, callCount, wrapped; - - thenable = null; - callCount = 0; - wrapped = Promise.resolve(thenable); - - wrapped.then(function(success){ - callCount++; - assert(success === thenable, 'fulfilled promise with x'); - done(); - }, function(a){ - assert(false, 'should not also reject'); - }); - - assert(callCount === 0, 'expected async, was sync'); - }); - }); - }); - - if (typeof Worker !== 'undefined') { - describe('web worker', function () { - it('should work', function (done) { - this.timeout(2000); - var worker = new Worker('worker.js'); - worker.addEventListener('error', function(reason) { - done(new Error("Test failed:" + reason)); - }); - worker.addEventListener('message', function (e) { - worker.terminate(); - assert.equal(e.data, 'pong'); - done(); - }); - worker.postMessage('ping'); - }); - }); - } -}); - -// thanks to @wizardwerdna for the test case -> https://github.com/tildeio/rsvp.js/issues/66 -// Only run these tests in node (phantomjs cannot handle them) -if (typeof module !== 'undefined' && module.exports) { - - describe("using reduce to sum integers using promises", function(){ - it("should build the promise pipeline without error", function(){ - var array, iters, pZero, i; - - array = []; - iters = 1000; - - for (i=1; i<=iters; i++) { - array.push(i); - } - - pZero = Promise.resolve(0); - - array.reduce(function(promise, nextVal) { - return promise.then(function(currentVal) { - return Promise.resolve(currentVal + nextVal); - }); - }, pZero); - }); - - it("should get correct answer without blowing the nextTick stack", function(done){ - var pZero, array, iters, result, i; - - pZero = Promise.resolve(0); - - array = []; - iters = 1000; - - for (i=1; i<=iters; i++) { - array.push(i); - } - - result = array.reduce(function(promise, nextVal) { - return promise.then(function(currentVal) { - return Promise.resolve(currentVal + nextVal); - }); - }, pZero); - - result.then(function(value){ - assert.equal(value, (iters*(iters+1)/2)); - done(); - }); - }); - }); -} - -// Kudos to @Octane at https://github.com/getify/native-promise-only/issues/5 for this, and @getify for pinging me. -describe("Thenables should not be able to run code during assimilation", function () { - specify("resolving to a thenable", function () { - var thenCalled = false; - var thenable = { - then: function () { - thenCalled = true; - } - }; - - Promise.resolve(thenable); - assert.strictEqual(thenCalled, false); - }); - - specify("resolving to an evil promise", function () { - var thenCalled = false; - var evilPromise = Promise.resolve(); - evilPromise.then = function () { - thenCalled = true; - }; - - Promise.resolve(evilPromise); - assert.strictEqual(thenCalled, false); - }); -}); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"assert":2}],53:[function(require,module,exports){ -(function (global){ -var assert = require('assert'); -var g = typeof window !== 'undefined' ? - window : typeof global !== 'undefined' ? global : this; - -var Promise = g.ES6Promise || require('./es6-promise').Promise; - -function defer() { - var deferred = {}; - - deferred.promise = new Promise(function(resolve, reject) { - deferred.resolve = resolve; - deferred.reject = reject; - }); - - return deferred; -} -var resolve = Promise.resolve; -var reject = Promise.reject; - - -module.exports = g.adapter = { - resolved: function(a) { return Promise.resolve(a); }, - rejected: function(a) { return Promise.reject(a); }, - deferred: defer, - Promise: Promise -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./es6-promise":51,"assert":2}]},{},[1]); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js deleted file mode 100644 index 5b096d6..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.js +++ /dev/null @@ -1,950 +0,0 @@ -(function() { - "use strict"; - function lib$es6$promise$utils$$objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); - } - - function lib$es6$promise$utils$$isFunction(x) { - return typeof x === 'function'; - } - - function lib$es6$promise$utils$$isMaybeThenable(x) { - return typeof x === 'object' && x !== null; - } - - var lib$es6$promise$utils$$_isArray; - if (!Array.isArray) { - lib$es6$promise$utils$$_isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; - } else { - lib$es6$promise$utils$$_isArray = Array.isArray; - } - - var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray; - var lib$es6$promise$asap$$len = 0; - var lib$es6$promise$asap$$toString = {}.toString; - var lib$es6$promise$asap$$vertxNext; - function lib$es6$promise$asap$$asap(callback, arg) { - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback; - lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg; - lib$es6$promise$asap$$len += 2; - if (lib$es6$promise$asap$$len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - lib$es6$promise$asap$$scheduleFlush(); - } - } - - var lib$es6$promise$asap$$default = lib$es6$promise$asap$$asap; - - var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined; - var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {}; - var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver; - var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - - // test for web worker but not in IE10 - var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - - // node - function lib$es6$promise$asap$$useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function() { - nextTick(lib$es6$promise$asap$$flush); - }; - } - - // vertx - function lib$es6$promise$asap$$useVertxTimer() { - return function() { - lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush); - }; - } - - function lib$es6$promise$asap$$useMutationObserver() { - var iterations = 0; - var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; - } - - // web worker - function lib$es6$promise$asap$$useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = lib$es6$promise$asap$$flush; - return function () { - channel.port2.postMessage(0); - }; - } - - function lib$es6$promise$asap$$useSetTimeout() { - return function() { - setTimeout(lib$es6$promise$asap$$flush, 1); - }; - } - - var lib$es6$promise$asap$$queue = new Array(1000); - function lib$es6$promise$asap$$flush() { - for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) { - var callback = lib$es6$promise$asap$$queue[i]; - var arg = lib$es6$promise$asap$$queue[i+1]; - - callback(arg); - - lib$es6$promise$asap$$queue[i] = undefined; - lib$es6$promise$asap$$queue[i+1] = undefined; - } - - lib$es6$promise$asap$$len = 0; - } - - function lib$es6$promise$asap$$attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext; - return lib$es6$promise$asap$$useVertxTimer(); - } catch(e) { - return lib$es6$promise$asap$$useSetTimeout(); - } - } - - var lib$es6$promise$asap$$scheduleFlush; - // Decide what async method to use to triggering processing of queued callbacks: - if (lib$es6$promise$asap$$isNode) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick(); - } else if (lib$es6$promise$asap$$BrowserMutationObserver) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver(); - } else if (lib$es6$promise$asap$$isWorker) { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel(); - } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertex(); - } else { - lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout(); - } - - function lib$es6$promise$$internal$$noop() {} - - var lib$es6$promise$$internal$$PENDING = void 0; - var lib$es6$promise$$internal$$FULFILLED = 1; - var lib$es6$promise$$internal$$REJECTED = 2; - - var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$selfFullfillment() { - return new TypeError("You cannot resolve a promise with itself"); - } - - function lib$es6$promise$$internal$$cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); - } - - function lib$es6$promise$$internal$$getThen(promise) { - try { - return promise.then; - } catch(error) { - lib$es6$promise$$internal$$GET_THEN_ERROR.error = error; - return lib$es6$promise$$internal$$GET_THEN_ERROR; - } - } - - function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } - } - - function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) { - lib$es6$promise$asap$$default(function(promise) { - var sealed = false; - var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - lib$es6$promise$$internal$$resolve(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - lib$es6$promise$$internal$$reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - lib$es6$promise$$internal$$reject(promise, error); - } - }, promise); - } - - function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) { - if (thenable._state === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, thenable._result); - } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, thenable._result); - } else { - lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) { - lib$es6$promise$$internal$$resolve(promise, value); - }, function(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } - } - - function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable); - } else { - var then = lib$es6$promise$$internal$$getThen(maybeThenable); - - if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error); - } else if (then === undefined) { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } else if (lib$es6$promise$utils$$isFunction(then)) { - lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then); - } else { - lib$es6$promise$$internal$$fulfill(promise, maybeThenable); - } - } - } - - function lib$es6$promise$$internal$$resolve(promise, value) { - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFullfillment()); - } else if (lib$es6$promise$utils$$objectOrFunction(value)) { - lib$es6$promise$$internal$$handleMaybeThenable(promise, value); - } else { - lib$es6$promise$$internal$$fulfill(promise, value); - } - } - - function lib$es6$promise$$internal$$publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - lib$es6$promise$$internal$$publish(promise); - } - - function lib$es6$promise$$internal$$fulfill(promise, value) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - - promise._result = value; - promise._state = lib$es6$promise$$internal$$FULFILLED; - - if (promise._subscribers.length !== 0) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, promise); - } - } - - function lib$es6$promise$$internal$$reject(promise, reason) { - if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; } - promise._state = lib$es6$promise$$internal$$REJECTED; - promise._result = reason; - - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publishRejection, promise); - } - - function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment; - subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection; - - if (length === 0 && parent._state) { - lib$es6$promise$asap$$default(lib$es6$promise$$internal$$publish, parent); - } - } - - function lib$es6$promise$$internal$$publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; - } - - function lib$es6$promise$$internal$$ErrorObject() { - this.error = null; - } - - var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject(); - - function lib$es6$promise$$internal$$tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e; - return lib$es6$promise$$internal$$TRY_CATCH_ERROR; - } - } - - function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) { - var hasCallback = lib$es6$promise$utils$$isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = lib$es6$promise$$internal$$tryCatch(callback, detail); - - if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== lib$es6$promise$$internal$$PENDING) { - // noop - } else if (hasCallback && succeeded) { - lib$es6$promise$$internal$$resolve(promise, value); - } else if (failed) { - lib$es6$promise$$internal$$reject(promise, error); - } else if (settled === lib$es6$promise$$internal$$FULFILLED) { - lib$es6$promise$$internal$$fulfill(promise, value); - } else if (settled === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } - } - - function lib$es6$promise$$internal$$initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - lib$es6$promise$$internal$$resolve(promise, value); - }, function rejectPromise(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - }); - } catch(e) { - lib$es6$promise$$internal$$reject(promise, e); - } - } - - function lib$es6$promise$enumerator$$Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result); - } - } - } else { - lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError()); - } - } - - lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) { - return lib$es6$promise$utils$$isArray(input); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._init = function() { - this._result = new Array(this.length); - }; - - var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator; - - lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (lib$es6$promise$utils$$isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === lib$es6$promise$$internal$$PENDING) { - enumerator._remaining--; - - if (state === lib$es6$promise$$internal$$REJECTED) { - lib$es6$promise$$internal$$reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - lib$es6$promise$$internal$$fulfill(promise, enumerator._result); - } - }; - - lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) { - enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason); - }); - }; - function lib$es6$promise$promise$all$$all(entries) { - return new lib$es6$promise$enumerator$$default(this, entries).promise; - } - var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all; - function lib$es6$promise$promise$race$$race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - - if (!lib$es6$promise$utils$$isArray(entries)) { - lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - lib$es6$promise$$internal$$resolve(promise, value); - } - - function onRejection(reason) { - lib$es6$promise$$internal$$reject(promise, reason); - } - - for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) { - lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; - } - var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race; - function lib$es6$promise$promise$resolve$$resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$resolve(promise, object); - return promise; - } - var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve; - function lib$es6$promise$promise$reject$$reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(lib$es6$promise$$internal$$noop); - lib$es6$promise$$internal$$reject(promise, reason); - return promise; - } - var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject; - - var lib$es6$promise$promise$$counter = 0; - - function lib$es6$promise$promise$$needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); - } - - function lib$es6$promise$promise$$needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); - } - - var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise; - /** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor - */ - function lib$es6$promise$promise$$Promise(resolver) { - this._id = lib$es6$promise$promise$$counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (lib$es6$promise$$internal$$noop !== resolver) { - if (!lib$es6$promise$utils$$isFunction(resolver)) { - lib$es6$promise$promise$$needsResolver(); - } - - if (!(this instanceof lib$es6$promise$promise$$Promise)) { - lib$es6$promise$promise$$needsNew(); - } - - lib$es6$promise$$internal$$initializePromise(this, resolver); - } - } - - lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default; - lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default; - lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default; - lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default; - - lib$es6$promise$promise$$Promise.prototype = { - constructor: lib$es6$promise$promise$$Promise, - - /** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} - */ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(lib$es6$promise$$internal$$noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - lib$es6$promise$asap$$default(function(){ - lib$es6$promise$$internal$$invokeCallback(state, child, callback, result); - }); - } else { - lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - - /** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} - */ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } - }; - function lib$es6$promise$polyfill$$polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = lib$es6$promise$promise$$default; - } - var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill; - - var lib$es6$promise$umd$$ES6Promise = { - 'Promise': lib$es6$promise$promise$$default, - 'polyfill': lib$es6$promise$polyfill$$default - }; - - /* global define:true module:true window: true */ - if (typeof define === 'function' && define['amd']) { - define(function() { return lib$es6$promise$umd$$ES6Promise; }); - } else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = lib$es6$promise$umd$$ES6Promise; - } else if (typeof this !== 'undefined') { - this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise; - } - - lib$es6$promise$polyfill$$default(); -}).call(this); - -//# sourceMappingURL=es6-promise.js.map \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js deleted file mode 100644 index 34a1f52..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/es6-promise.min.js +++ /dev/null @@ -1 +0,0 @@ -(function(){"use strict";function lib$es6$promise$utils$$objectOrFunction(x){return typeof x==="function"||typeof x==="object"&&x!==null}function lib$es6$promise$utils$$isFunction(x){return typeof x==="function"}function lib$es6$promise$utils$$isMaybeThenable(x){return typeof x==="object"&&x!==null}var lib$es6$promise$utils$$_isArray;if(!Array.isArray){lib$es6$promise$utils$$_isArray=function(x){return Object.prototype.toString.call(x)==="[object Array]"}}else{lib$es6$promise$utils$$_isArray=Array.isArray}var lib$es6$promise$utils$$isArray=lib$es6$promise$utils$$_isArray;var lib$es6$promise$asap$$len=0;var lib$es6$promise$asap$$toString={}.toString;var lib$es6$promise$asap$$vertxNext;function lib$es6$promise$asap$$asap(callback,arg){lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len]=callback;lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len+1]=arg;lib$es6$promise$asap$$len+=2;if(lib$es6$promise$asap$$len===2){lib$es6$promise$asap$$scheduleFlush()}}var lib$es6$promise$asap$$default=lib$es6$promise$asap$$asap;var lib$es6$promise$asap$$browserWindow=typeof window!=="undefined"?window:undefined;var lib$es6$promise$asap$$browserGlobal=lib$es6$promise$asap$$browserWindow||{};var lib$es6$promise$asap$$BrowserMutationObserver=lib$es6$promise$asap$$browserGlobal.MutationObserver||lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;var lib$es6$promise$asap$$isNode=typeof process!=="undefined"&&{}.toString.call(process)==="[object process]";var lib$es6$promise$asap$$isWorker=typeof Uint8ClampedArray!=="undefined"&&typeof importScripts!=="undefined"&&typeof MessageChannel!=="undefined";function lib$es6$promise$asap$$useNextTick(){var nextTick=process.nextTick;var version=process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/);if(Array.isArray(version)&&version[1]==="0"&&version[2]==="10"){nextTick=setImmediate}return function(){nextTick(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useVertxTimer(){return function(){lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush)}}function lib$es6$promise$asap$$useMutationObserver(){var iterations=0;var observer=new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);var node=document.createTextNode("");observer.observe(node,{characterData:true});return function(){node.data=iterations=++iterations%2}}function lib$es6$promise$asap$$useMessageChannel(){var channel=new MessageChannel;channel.port1.onmessage=lib$es6$promise$asap$$flush;return function(){channel.port2.postMessage(0)}}function lib$es6$promise$asap$$useSetTimeout(){return function(){setTimeout(lib$es6$promise$asap$$flush,1)}}var lib$es6$promise$asap$$queue=new Array(1e3);function lib$es6$promise$asap$$flush(){for(var i=0;i - - - rsvp.js Tests - - - -
        - - - - - - - - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js deleted file mode 100644 index 4817c9e..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/json3.js +++ /dev/null @@ -1,902 +0,0 @@ -/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */ -;(function () { - // Detect the `define` function exposed by asynchronous module loaders. The - // strict `define` check is necessary for compatibility with `r.js`. - var isLoader = typeof define === "function" && define.amd; - - // A set of types used to distinguish objects from primitives. - var objectTypes = { - "function": true, - "object": true - }; - - // Detect the `exports` object exposed by CommonJS implementations. - var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; - - // Use the `global` object exposed by Node (including Browserify via - // `insert-module-globals`), Narwhal, and Ringo as the default context, - // and the `window` object in browsers. Rhino exports a `global` function - // instead. - var root = objectTypes[typeof window] && window || this, - freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global; - - if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) { - root = freeGlobal; - } - - // Public: Initializes JSON 3 using the given `context` object, attaching the - // `stringify` and `parse` functions to the specified `exports` object. - function runInContext(context, exports) { - context || (context = root["Object"]()); - exports || (exports = root["Object"]()); - - // Native constructor aliases. - var Number = context["Number"] || root["Number"], - String = context["String"] || root["String"], - Object = context["Object"] || root["Object"], - Date = context["Date"] || root["Date"], - SyntaxError = context["SyntaxError"] || root["SyntaxError"], - TypeError = context["TypeError"] || root["TypeError"], - Math = context["Math"] || root["Math"], - nativeJSON = context["JSON"] || root["JSON"]; - - // Delegate to the native `stringify` and `parse` implementations. - if (typeof nativeJSON == "object" && nativeJSON) { - exports.stringify = nativeJSON.stringify; - exports.parse = nativeJSON.parse; - } - - // Convenience aliases. - var objectProto = Object.prototype, - getClass = objectProto.toString, - isProperty, forEach, undef; - - // Test the `Date#getUTC*` methods. Based on work by @Yaffle. - var isExtended = new Date(-3509827334573292); - try { - // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical - // results for certain dates in Opera >= 10.53. - isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 && - // Safari < 2.0.2 stores the internal millisecond time value correctly, - // but clips the values returned by the date methods to the range of - // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]). - isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708; - } catch (exception) {} - - // Internal: Determines whether the native `JSON.stringify` and `parse` - // implementations are spec-compliant. Based on work by Ken Snyder. - function has(name) { - if (has[name] !== undef) { - // Return cached feature test result. - return has[name]; - } - var isSupported; - if (name == "bug-string-char-index") { - // IE <= 7 doesn't support accessing string characters using square - // bracket notation. IE 8 only supports this for primitives. - isSupported = "a"[0] != "a"; - } else if (name == "json") { - // Indicates whether both `JSON.stringify` and `JSON.parse` are - // supported. - isSupported = has("json-stringify") && has("json-parse"); - } else { - var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}'; - // Test `JSON.stringify`. - if (name == "json-stringify") { - var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended; - if (stringifySupported) { - // A test function object with a custom `toJSON` method. - (value = function () { - return 1; - }).toJSON = value; - try { - stringifySupported = - // Firefox 3.1b1 and b2 serialize string, number, and boolean - // primitives as object literals. - stringify(0) === "0" && - // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object - // literals. - stringify(new Number()) === "0" && - stringify(new String()) == '""' && - // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or - // does not define a canonical JSON representation (this applies to - // objects with `toJSON` properties as well, *unless* they are nested - // within an object or array). - stringify(getClass) === undef && - // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and - // FF 3.1b3 pass this test. - stringify(undef) === undef && - // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s, - // respectively, if the value is omitted entirely. - stringify() === undef && - // FF 3.1b1, 2 throw an error if the given value is not a number, - // string, array, object, Boolean, or `null` literal. This applies to - // objects with custom `toJSON` methods as well, unless they are nested - // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON` - // methods entirely. - stringify(value) === "1" && - stringify([value]) == "[1]" && - // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of - // `"[null]"`. - stringify([undef]) == "[null]" && - // YUI 3.0.0b1 fails to serialize `null` literals. - stringify(null) == "null" && - // FF 3.1b1, 2 halts serialization if an array contains a function: - // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3 - // elides non-JSON values from objects and arrays, unless they - // define custom `toJSON` methods. - stringify([undef, getClass, null]) == "[null,null,null]" && - // Simple serialization test. FF 3.1b1 uses Unicode escape sequences - // where character escape codes are expected (e.g., `\b` => `\u0008`). - stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized && - // FF 3.1b1 and b2 ignore the `filter` and `width` arguments. - stringify(null, value) === "1" && - stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" && - // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly - // serialize extended years. - stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' && - // The milliseconds are optional in ES 5, but required in 5.1. - stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' && - // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative - // four-digit years instead of six-digit years. Credits: @Yaffle. - stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' && - // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond - // values less than 1000. Credits: @Yaffle. - stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"'; - } catch (exception) { - stringifySupported = false; - } - } - isSupported = stringifySupported; - } - // Test `JSON.parse`. - if (name == "json-parse") { - var parse = exports.parse; - if (typeof parse == "function") { - try { - // FF 3.1b1, b2 will throw an exception if a bare literal is provided. - // Conforming implementations should also coerce the initial argument to - // a string prior to parsing. - if (parse("0") === 0 && !parse(false)) { - // Simple parsing test. - value = parse(serialized); - var parseSupported = value["a"].length == 5 && value["a"][0] === 1; - if (parseSupported) { - try { - // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings. - parseSupported = !parse('"\t"'); - } catch (exception) {} - if (parseSupported) { - try { - // FF 4.0 and 4.0.1 allow leading `+` signs and leading - // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow - // certain octal literals. - parseSupported = parse("01") !== 1; - } catch (exception) {} - } - if (parseSupported) { - try { - // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal - // points. These environments, along with FF 3.1b1 and 2, - // also allow trailing commas in JSON objects and arrays. - parseSupported = parse("1.") !== 1; - } catch (exception) {} - } - } - } - } catch (exception) { - parseSupported = false; - } - } - isSupported = parseSupported; - } - } - return has[name] = !!isSupported; - } - - if (!has("json")) { - // Common `[[Class]]` name aliases. - var functionClass = "[object Function]", - dateClass = "[object Date]", - numberClass = "[object Number]", - stringClass = "[object String]", - arrayClass = "[object Array]", - booleanClass = "[object Boolean]"; - - // Detect incomplete support for accessing string characters by index. - var charIndexBuggy = has("bug-string-char-index"); - - // Define additional utility methods if the `Date` methods are buggy. - if (!isExtended) { - var floor = Math.floor; - // A mapping between the months of the year and the number of days between - // January 1st and the first of the respective month. - var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; - // Internal: Calculates the number of days between the Unix epoch and the - // first day of the given month. - var getDay = function (year, month) { - return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400); - }; - } - - // Internal: Determines if a property is a direct property of the given - // object. Delegates to the native `Object#hasOwnProperty` method. - if (!(isProperty = objectProto.hasOwnProperty)) { - isProperty = function (property) { - var members = {}, constructor; - if ((members.__proto__ = null, members.__proto__ = { - // The *proto* property cannot be set multiple times in recent - // versions of Firefox and SeaMonkey. - "toString": 1 - }, members).toString != getClass) { - // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but - // supports the mutable *proto* property. - isProperty = function (property) { - // Capture and break the object's prototype chain (see section 8.6.2 - // of the ES 5.1 spec). The parenthesized expression prevents an - // unsafe transformation by the Closure Compiler. - var original = this.__proto__, result = property in (this.__proto__ = null, this); - // Restore the original prototype chain. - this.__proto__ = original; - return result; - }; - } else { - // Capture a reference to the top-level `Object` constructor. - constructor = members.constructor; - // Use the `constructor` property to simulate `Object#hasOwnProperty` in - // other environments. - isProperty = function (property) { - var parent = (this.constructor || constructor).prototype; - return property in this && !(property in parent && this[property] === parent[property]); - }; - } - members = null; - return isProperty.call(this, property); - }; - } - - // Internal: Normalizes the `for...in` iteration algorithm across - // environments. Each enumerated key is yielded to a `callback` function. - forEach = function (object, callback) { - var size = 0, Properties, members, property; - - // Tests for bugs in the current environment's `for...in` algorithm. The - // `valueOf` property inherits the non-enumerable flag from - // `Object.prototype` in older versions of IE, Netscape, and Mozilla. - (Properties = function () { - this.valueOf = 0; - }).prototype.valueOf = 0; - - // Iterate over a new instance of the `Properties` class. - members = new Properties(); - for (property in members) { - // Ignore all properties inherited from `Object.prototype`. - if (isProperty.call(members, property)) { - size++; - } - } - Properties = members = null; - - // Normalize the iteration algorithm. - if (!size) { - // A list of non-enumerable properties inherited from `Object.prototype`. - members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"]; - // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable - // properties. - forEach = function (object, callback) { - var isFunction = getClass.call(object) == functionClass, property, length; - var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty; - for (property in object) { - // Gecko <= 1.0 enumerates the `prototype` property of functions under - // certain conditions; IE does not. - if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) { - callback(property); - } - } - // Manually invoke the callback for each non-enumerable property. - for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property)); - }; - } else if (size == 2) { - // Safari <= 2.0.4 enumerates shadowed properties twice. - forEach = function (object, callback) { - // Create a set of iterated properties. - var members = {}, isFunction = getClass.call(object) == functionClass, property; - for (property in object) { - // Store each property name to prevent double enumeration. The - // `prototype` property of functions is not enumerated due to cross- - // environment inconsistencies. - if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) { - callback(property); - } - } - }; - } else { - // No bugs detected; use the standard `for...in` algorithm. - forEach = function (object, callback) { - var isFunction = getClass.call(object) == functionClass, property, isConstructor; - for (property in object) { - if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) { - callback(property); - } - } - // Manually invoke the callback for the `constructor` property due to - // cross-environment inconsistencies. - if (isConstructor || isProperty.call(object, (property = "constructor"))) { - callback(property); - } - }; - } - return forEach(object, callback); - }; - - // Public: Serializes a JavaScript `value` as a JSON string. The optional - // `filter` argument may specify either a function that alters how object and - // array members are serialized, or an array of strings and numbers that - // indicates which properties should be serialized. The optional `width` - // argument may be either a string or number that specifies the indentation - // level of the output. - if (!has("json-stringify")) { - // Internal: A map of control characters and their escaped equivalents. - var Escapes = { - 92: "\\\\", - 34: '\\"', - 8: "\\b", - 12: "\\f", - 10: "\\n", - 13: "\\r", - 9: "\\t" - }; - - // Internal: Converts `value` into a zero-padded string such that its - // length is at least equal to `width`. The `width` must be <= 6. - var leadingZeroes = "000000"; - var toPaddedString = function (width, value) { - // The `|| 0` expression is necessary to work around a bug in - // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`. - return (leadingZeroes + (value || 0)).slice(-width); - }; - - // Internal: Double-quotes a string `value`, replacing all ASCII control - // characters (characters with code unit values between 0 and 31) with - // their escaped equivalents. This is an implementation of the - // `Quote(value)` operation defined in ES 5.1 section 15.12.3. - var unicodePrefix = "\\u00"; - var quote = function (value) { - var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10; - var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value); - for (; index < length; index++) { - var charCode = value.charCodeAt(index); - // If the character is a control character, append its Unicode or - // shorthand escape sequence; otherwise, append the character as-is. - switch (charCode) { - case 8: case 9: case 10: case 12: case 13: case 34: case 92: - result += Escapes[charCode]; - break; - default: - if (charCode < 32) { - result += unicodePrefix + toPaddedString(2, charCode.toString(16)); - break; - } - result += useCharIndex ? symbols[index] : value.charAt(index); - } - } - return result + '"'; - }; - - // Internal: Recursively serializes an object. Implements the - // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations. - var serialize = function (property, object, callback, properties, whitespace, indentation, stack) { - var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result; - try { - // Necessary for host object support. - value = object[property]; - } catch (exception) {} - if (typeof value == "object" && value) { - className = getClass.call(value); - if (className == dateClass && !isProperty.call(value, "toJSON")) { - if (value > -1 / 0 && value < 1 / 0) { - // Dates are serialized according to the `Date#toJSON` method - // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15 - // for the ISO 8601 date time string format. - if (getDay) { - // Manually compute the year, month, date, hours, minutes, - // seconds, and milliseconds if the `getUTC*` methods are - // buggy. Adapted from @Yaffle's `date-shim` project. - date = floor(value / 864e5); - for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++); - for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++); - date = 1 + date - getDay(year, month); - // The `time` value specifies the time within the day (see ES - // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used - // to compute `A modulo B`, as the `%` operator does not - // correspond to the `modulo` operation for negative numbers. - time = (value % 864e5 + 864e5) % 864e5; - // The hours, minutes, seconds, and milliseconds are obtained by - // decomposing the time within the day. See section 15.9.1.10. - hours = floor(time / 36e5) % 24; - minutes = floor(time / 6e4) % 60; - seconds = floor(time / 1e3) % 60; - milliseconds = time % 1e3; - } else { - year = value.getUTCFullYear(); - month = value.getUTCMonth(); - date = value.getUTCDate(); - hours = value.getUTCHours(); - minutes = value.getUTCMinutes(); - seconds = value.getUTCSeconds(); - milliseconds = value.getUTCMilliseconds(); - } - // Serialize extended years correctly. - value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) + - "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) + - // Months, dates, hours, minutes, and seconds should have two - // digits; milliseconds should have three. - "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) + - // Milliseconds are optional in ES 5.0, but required in 5.1. - "." + toPaddedString(3, milliseconds) + "Z"; - } else { - value = null; - } - } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) { - // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the - // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3 - // ignores all `toJSON` methods on these objects unless they are - // defined directly on an instance. - value = value.toJSON(property); - } - } - if (callback) { - // If a replacement function was provided, call it to obtain the value - // for serialization. - value = callback.call(object, property, value); - } - if (value === null) { - return "null"; - } - className = getClass.call(value); - if (className == booleanClass) { - // Booleans are represented literally. - return "" + value; - } else if (className == numberClass) { - // JSON numbers must be finite. `Infinity` and `NaN` are serialized as - // `"null"`. - return value > -1 / 0 && value < 1 / 0 ? "" + value : "null"; - } else if (className == stringClass) { - // Strings are double-quoted and escaped. - return quote("" + value); - } - // Recursively serialize objects and arrays. - if (typeof value == "object") { - // Check for cyclic structures. This is a linear search; performance - // is inversely proportional to the number of unique nested objects. - for (length = stack.length; length--;) { - if (stack[length] === value) { - // Cyclic structures cannot be serialized by `JSON.stringify`. - throw TypeError(); - } - } - // Add the object to the stack of traversed objects. - stack.push(value); - results = []; - // Save the current indentation level and indent one additional level. - prefix = indentation; - indentation += whitespace; - if (className == arrayClass) { - // Recursively serialize array elements. - for (index = 0, length = value.length; index < length; index++) { - element = serialize(index, value, callback, properties, whitespace, indentation, stack); - results.push(element === undef ? "null" : element); - } - result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]"; - } else { - // Recursively serialize object members. Members are selected from - // either a user-specified list of property names, or the object - // itself. - forEach(properties || value, function (property) { - var element = serialize(property, value, callback, properties, whitespace, indentation, stack); - if (element !== undef) { - // According to ES 5.1 section 15.12.3: "If `gap` {whitespace} - // is not the empty string, let `member` {quote(property) + ":"} - // be the concatenation of `member` and the `space` character." - // The "`space` character" refers to the literal space - // character, not the `space` {width} argument provided to - // `JSON.stringify`. - results.push(quote(property) + ":" + (whitespace ? " " : "") + element); - } - }); - result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}"; - } - // Remove the object from the traversed object stack. - stack.pop(); - return result; - } - }; - - // Public: `JSON.stringify`. See ES 5.1 section 15.12.3. - exports.stringify = function (source, filter, width) { - var whitespace, callback, properties, className; - if (objectTypes[typeof filter] && filter) { - if ((className = getClass.call(filter)) == functionClass) { - callback = filter; - } else if (className == arrayClass) { - // Convert the property names array into a makeshift set. - properties = {}; - for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1)); - } - } - if (width) { - if ((className = getClass.call(width)) == numberClass) { - // Convert the `width` to an integer and create a string containing - // `width` number of space characters. - if ((width -= width % 1) > 0) { - for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " "); - } - } else if (className == stringClass) { - whitespace = width.length <= 10 ? width : width.slice(0, 10); - } - } - // Opera <= 7.54u2 discards the values associated with empty string keys - // (`""`) only if they are used directly within an object member list - // (e.g., `!("" in { "": 1})`). - return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []); - }; - } - - // Public: Parses a JSON source string. - if (!has("json-parse")) { - var fromCharCode = String.fromCharCode; - - // Internal: A map of escaped control characters and their unescaped - // equivalents. - var Unescapes = { - 92: "\\", - 34: '"', - 47: "/", - 98: "\b", - 116: "\t", - 110: "\n", - 102: "\f", - 114: "\r" - }; - - // Internal: Stores the parser state. - var Index, Source; - - // Internal: Resets the parser state and throws a `SyntaxError`. - var abort = function () { - Index = Source = null; - throw SyntaxError(); - }; - - // Internal: Returns the next token, or `"$"` if the parser has reached - // the end of the source string. A token may be a string, number, `null` - // literal, or Boolean literal. - var lex = function () { - var source = Source, length = source.length, value, begin, position, isSigned, charCode; - while (Index < length) { - charCode = source.charCodeAt(Index); - switch (charCode) { - case 9: case 10: case 13: case 32: - // Skip whitespace tokens, including tabs, carriage returns, line - // feeds, and space characters. - Index++; - break; - case 123: case 125: case 91: case 93: case 58: case 44: - // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at - // the current position. - value = charIndexBuggy ? source.charAt(Index) : source[Index]; - Index++; - return value; - case 34: - // `"` delimits a JSON string; advance to the next character and - // begin parsing the string. String tokens are prefixed with the - // sentinel `@` character to distinguish them from punctuators and - // end-of-string tokens. - for (value = "@", Index++; Index < length;) { - charCode = source.charCodeAt(Index); - if (charCode < 32) { - // Unescaped ASCII control characters (those with a code unit - // less than the space character) are not permitted. - abort(); - } else if (charCode == 92) { - // A reverse solidus (`\`) marks the beginning of an escaped - // control character (including `"`, `\`, and `/`) or Unicode - // escape sequence. - charCode = source.charCodeAt(++Index); - switch (charCode) { - case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114: - // Revive escaped control characters. - value += Unescapes[charCode]; - Index++; - break; - case 117: - // `\u` marks the beginning of a Unicode escape sequence. - // Advance to the first character and validate the - // four-digit code point. - begin = ++Index; - for (position = Index + 4; Index < position; Index++) { - charCode = source.charCodeAt(Index); - // A valid sequence comprises four hexdigits (case- - // insensitive) that form a single hexadecimal value. - if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) { - // Invalid Unicode escape sequence. - abort(); - } - } - // Revive the escaped character. - value += fromCharCode("0x" + source.slice(begin, Index)); - break; - default: - // Invalid escape sequence. - abort(); - } - } else { - if (charCode == 34) { - // An unescaped double-quote character marks the end of the - // string. - break; - } - charCode = source.charCodeAt(Index); - begin = Index; - // Optimize for the common case where a string is valid. - while (charCode >= 32 && charCode != 92 && charCode != 34) { - charCode = source.charCodeAt(++Index); - } - // Append the string as-is. - value += source.slice(begin, Index); - } - } - if (source.charCodeAt(Index) == 34) { - // Advance to the next character and return the revived string. - Index++; - return value; - } - // Unterminated string. - abort(); - default: - // Parse numbers and literals. - begin = Index; - // Advance past the negative sign, if one is specified. - if (charCode == 45) { - isSigned = true; - charCode = source.charCodeAt(++Index); - } - // Parse an integer or floating-point value. - if (charCode >= 48 && charCode <= 57) { - // Leading zeroes are interpreted as octal literals. - if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) { - // Illegal octal literal. - abort(); - } - isSigned = false; - // Parse the integer component. - for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++); - // Floats cannot contain a leading decimal point; however, this - // case is already accounted for by the parser. - if (source.charCodeAt(Index) == 46) { - position = ++Index; - // Parse the decimal component. - for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); - if (position == Index) { - // Illegal trailing decimal. - abort(); - } - Index = position; - } - // Parse exponents. The `e` denoting the exponent is - // case-insensitive. - charCode = source.charCodeAt(Index); - if (charCode == 101 || charCode == 69) { - charCode = source.charCodeAt(++Index); - // Skip past the sign following the exponent, if one is - // specified. - if (charCode == 43 || charCode == 45) { - Index++; - } - // Parse the exponential component. - for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++); - if (position == Index) { - // Illegal empty exponent. - abort(); - } - Index = position; - } - // Coerce the parsed value to a JavaScript number. - return +source.slice(begin, Index); - } - // A negative sign may only precede numbers. - if (isSigned) { - abort(); - } - // `true`, `false`, and `null` literals. - if (source.slice(Index, Index + 4) == "true") { - Index += 4; - return true; - } else if (source.slice(Index, Index + 5) == "false") { - Index += 5; - return false; - } else if (source.slice(Index, Index + 4) == "null") { - Index += 4; - return null; - } - // Unrecognized token. - abort(); - } - } - // Return the sentinel `$` character if the parser has reached the end - // of the source string. - return "$"; - }; - - // Internal: Parses a JSON `value` token. - var get = function (value) { - var results, hasMembers; - if (value == "$") { - // Unexpected end of input. - abort(); - } - if (typeof value == "string") { - if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") { - // Remove the sentinel `@` character. - return value.slice(1); - } - // Parse object and array literals. - if (value == "[") { - // Parses a JSON array, returning a new JavaScript array. - results = []; - for (;; hasMembers || (hasMembers = true)) { - value = lex(); - // A closing square bracket marks the end of the array literal. - if (value == "]") { - break; - } - // If the array literal contains elements, the current token - // should be a comma separating the previous element from the - // next. - if (hasMembers) { - if (value == ",") { - value = lex(); - if (value == "]") { - // Unexpected trailing `,` in array literal. - abort(); - } - } else { - // A `,` must separate each array element. - abort(); - } - } - // Elisions and leading commas are not permitted. - if (value == ",") { - abort(); - } - results.push(get(value)); - } - return results; - } else if (value == "{") { - // Parses a JSON object, returning a new JavaScript object. - results = {}; - for (;; hasMembers || (hasMembers = true)) { - value = lex(); - // A closing curly brace marks the end of the object literal. - if (value == "}") { - break; - } - // If the object literal contains members, the current token - // should be a comma separator. - if (hasMembers) { - if (value == ",") { - value = lex(); - if (value == "}") { - // Unexpected trailing `,` in object literal. - abort(); - } - } else { - // A `,` must separate each object member. - abort(); - } - } - // Leading commas are not permitted, object property names must be - // double-quoted strings, and a `:` must separate each property - // name and value. - if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") { - abort(); - } - results[value.slice(1)] = get(lex()); - } - return results; - } - // Unexpected token encountered. - abort(); - } - return value; - }; - - // Internal: Updates a traversed object member. - var update = function (source, property, callback) { - var element = walk(source, property, callback); - if (element === undef) { - delete source[property]; - } else { - source[property] = element; - } - }; - - // Internal: Recursively traverses a parsed JSON object, invoking the - // `callback` function for each value. This is an implementation of the - // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2. - var walk = function (source, property, callback) { - var value = source[property], length; - if (typeof value == "object" && value) { - // `forEach` can't be used to traverse an array in Opera <= 8.54 - // because its `Object#hasOwnProperty` implementation returns `false` - // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`). - if (getClass.call(value) == arrayClass) { - for (length = value.length; length--;) { - update(value, length, callback); - } - } else { - forEach(value, function (property) { - update(value, property, callback); - }); - } - } - return callback.call(source, property, value); - }; - - // Public: `JSON.parse`. See ES 5.1 section 15.12.2. - exports.parse = function (source, callback) { - var result, value; - Index = 0; - Source = "" + source; - result = get(lex()); - // If a JSON string contains multiple tokens, it is invalid. - if (lex() != "$") { - abort(); - } - // Reset the parser state. - Index = Source = null; - return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result; - }; - } - } - - exports["runInContext"] = runInContext; - return exports; - } - - if (freeExports && !isLoader) { - // Export for CommonJS environments. - runInContext(root, freeExports); - } else { - // Export for web browsers and JavaScript engines. - var nativeJSON = root.JSON, - previousJSON = root["JSON3"], - isRestored = false; - - var JSON3 = runInContext(root, (root["JSON3"] = { - // Public: Restores the original value of the global `JSON` object and - // returns a reference to the `JSON3` object. - "noConflict": function () { - if (!isRestored) { - isRestored = true; - root.JSON = nativeJSON; - root["JSON3"] = previousJSON; - nativeJSON = previousJSON = null; - } - return JSON3; - } - })); - - root.JSON = { - "parse": JSON3.parse, - "stringify": JSON3.stringify - }; - } - - // Export for asynchronous module loaders. - if (isLoader) { - define(function () { - return JSON3; - }); - } -}).call(this); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css deleted file mode 100644 index 42b9798..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.css +++ /dev/null @@ -1,270 +0,0 @@ -@charset "utf-8"; - -body { - margin:0; -} - -#mocha { - font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; - margin: 60px 50px; -} - -#mocha ul, -#mocha li { - margin: 0; - padding: 0; -} - -#mocha ul { - list-style: none; -} - -#mocha h1, -#mocha h2 { - margin: 0; -} - -#mocha h1 { - margin-top: 15px; - font-size: 1em; - font-weight: 200; -} - -#mocha h1 a { - text-decoration: none; - color: inherit; -} - -#mocha h1 a:hover { - text-decoration: underline; -} - -#mocha .suite .suite h1 { - margin-top: 0; - font-size: .8em; -} - -#mocha .hidden { - display: none; -} - -#mocha h2 { - font-size: 12px; - font-weight: normal; - cursor: pointer; -} - -#mocha .suite { - margin-left: 15px; -} - -#mocha .test { - margin-left: 15px; - overflow: hidden; -} - -#mocha .test.pending:hover h2::after { - content: '(pending)'; - font-family: arial, sans-serif; -} - -#mocha .test.pass.medium .duration { - background: #c09853; -} - -#mocha .test.pass.slow .duration { - background: #b94a48; -} - -#mocha .test.pass::before { - content: '✓'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; - color: #00d6b2; -} - -#mocha .test.pass .duration { - font-size: 9px; - margin-left: 5px; - padding: 2px 5px; - color: #fff; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - box-shadow: inset 0 1px 1px rgba(0,0,0,.2); - -webkit-border-radius: 5px; - -moz-border-radius: 5px; - -ms-border-radius: 5px; - -o-border-radius: 5px; - border-radius: 5px; -} - -#mocha .test.pass.fast .duration { - display: none; -} - -#mocha .test.pending { - color: #0b97c4; -} - -#mocha .test.pending::before { - content: '◦'; - color: #0b97c4; -} - -#mocha .test.fail { - color: #c00; -} - -#mocha .test.fail pre { - color: black; -} - -#mocha .test.fail::before { - content: '✖'; - font-size: 12px; - display: block; - float: left; - margin-right: 5px; - color: #c00; -} - -#mocha .test pre.error { - color: #c00; - max-height: 300px; - overflow: auto; -} - -/** - * (1): approximate for browsers not supporting calc - * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border) - * ^^ seriously - */ -#mocha .test pre { - display: block; - float: left; - clear: left; - font: 12px/1.5 monaco, monospace; - margin: 5px; - padding: 15px; - border: 1px solid #eee; - max-width: 85%; /*(1)*/ - max-width: calc(100% - 42px); /*(2)*/ - word-wrap: break-word; - border-bottom-color: #ddd; - -webkit-border-radius: 3px; - -webkit-box-shadow: 0 1px 3px #eee; - -moz-border-radius: 3px; - -moz-box-shadow: 0 1px 3px #eee; - border-radius: 3px; -} - -#mocha .test h2 { - position: relative; -} - -#mocha .test a.replay { - position: absolute; - top: 3px; - right: 0; - text-decoration: none; - vertical-align: middle; - display: block; - width: 15px; - height: 15px; - line-height: 15px; - text-align: center; - background: #eee; - font-size: 15px; - -moz-border-radius: 15px; - border-radius: 15px; - -webkit-transition: opacity 200ms; - -moz-transition: opacity 200ms; - transition: opacity 200ms; - opacity: 0.3; - color: #888; -} - -#mocha .test:hover a.replay { - opacity: 1; -} - -#mocha-report.pass .test.fail { - display: none; -} - -#mocha-report.fail .test.pass { - display: none; -} - -#mocha-report.pending .test.pass, -#mocha-report.pending .test.fail { - display: none; -} -#mocha-report.pending .test.pass.pending { - display: block; -} - -#mocha-error { - color: #c00; - font-size: 1.5em; - font-weight: 100; - letter-spacing: 1px; -} - -#mocha-stats { - position: fixed; - top: 15px; - right: 10px; - font-size: 12px; - margin: 0; - color: #888; - z-index: 1; -} - -#mocha-stats .progress { - float: right; - padding-top: 0; -} - -#mocha-stats em { - color: black; -} - -#mocha-stats a { - text-decoration: none; - color: inherit; -} - -#mocha-stats a:hover { - border-bottom: 1px solid #eee; -} - -#mocha-stats li { - display: inline-block; - margin: 0 5px; - list-style: none; - padding-top: 11px; -} - -#mocha-stats canvas { - width: 40px; - height: 40px; -} - -#mocha code .comment { color: #ddd; } -#mocha code .init { color: #2f6fad; } -#mocha code .string { color: #5890ad; } -#mocha code .keyword { color: #8a6343; } -#mocha code .number { color: #2f6fad; } - -@media screen and (max-device-width: 480px) { - #mocha { - margin: 60px 0px; - } - - #mocha #stats { - position: absolute; - } -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js deleted file mode 100644 index e8bee79..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/mocha.js +++ /dev/null @@ -1,6095 +0,0 @@ -;(function(){ - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p.charAt(0)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("browser/debug.js", function(module, exports, require){ - -module.exports = function(type){ - return function(){ - } -}; - -}); // module: browser/debug.js - -require.register("browser/diff.js", function(module, exports, require){ -/* See LICENSE file for terms of use */ - -/* - * Text diff implementation. - * - * This library supports the following APIS: - * JsDiff.diffChars: Character by character diff - * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace - * JsDiff.diffLines: Line based diff - * - * JsDiff.diffCss: Diff targeted at CSS content - * - * These methods are based on the implementation proposed in - * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 - */ -var JsDiff = (function() { - /*jshint maxparams: 5*/ - function clonePath(path) { - return { newPos: path.newPos, components: path.components.slice(0) }; - } - function removeEmpty(array) { - var ret = []; - for (var i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } - } - return ret; - } - function escapeHTML(s) { - var n = s; - n = n.replace(/&/g, '&'); - n = n.replace(//g, '>'); - n = n.replace(/"/g, '"'); - - return n; - } - - var Diff = function(ignoreWhitespace) { - this.ignoreWhitespace = ignoreWhitespace; - }; - Diff.prototype = { - diff: function(oldString, newString) { - // Handle the identity case (this is due to unrolling editLength == 0 - if (newString === oldString) { - return [{ value: newString }]; - } - if (!newString) { - return [{ value: oldString, removed: true }]; - } - if (!oldString) { - return [{ value: newString, added: true }]; - } - - newString = this.tokenize(newString); - oldString = this.tokenize(oldString); - - var newLen = newString.length, oldLen = oldString.length; - var maxEditLength = newLen + oldLen; - var bestPath = [{ newPos: -1, components: [] }]; - - // Seed editLength = 0 - var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); - if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) { - return bestPath[0].components; - } - - for (var editLength = 1; editLength <= maxEditLength; editLength++) { - for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) { - var basePath; - var addPath = bestPath[diagonalPath-1], - removePath = bestPath[diagonalPath+1]; - oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; - if (addPath) { - // No one else is going to attempt to use this value, clear it - bestPath[diagonalPath-1] = undefined; - } - - var canAdd = addPath && addPath.newPos+1 < newLen; - var canRemove = removePath && 0 <= oldPos && oldPos < oldLen; - if (!canAdd && !canRemove) { - bestPath[diagonalPath] = undefined; - continue; - } - - // Select the diagonal that we want to branch from. We select the prior - // path whose position in the new string is the farthest from the origin - // and does not pass the bounds of the diff graph - if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { - basePath = clonePath(removePath); - this.pushComponent(basePath.components, oldString[oldPos], undefined, true); - } else { - basePath = clonePath(addPath); - basePath.newPos++; - this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined); - } - - var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath); - - if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) { - return basePath.components; - } else { - bestPath[diagonalPath] = basePath; - } - } - } - }, - - pushComponent: function(components, value, added, removed) { - var last = components[components.length-1]; - if (last && last.added === added && last.removed === removed) { - // We need to clone here as the component clone operation is just - // as shallow array clone - components[components.length-1] = - {value: this.join(last.value, value), added: added, removed: removed }; - } else { - components.push({value: value, added: added, removed: removed }); - } - }, - extractCommon: function(basePath, newString, oldString, diagonalPath) { - var newLen = newString.length, - oldLen = oldString.length, - newPos = basePath.newPos, - oldPos = newPos - diagonalPath; - while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) { - newPos++; - oldPos++; - - this.pushComponent(basePath.components, newString[newPos], undefined, undefined); - } - basePath.newPos = newPos; - return oldPos; - }, - - equals: function(left, right) { - var reWhitespace = /\S/; - if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) { - return true; - } else { - return left === right; - } - }, - join: function(left, right) { - return left + right; - }, - tokenize: function(value) { - return value; - } - }; - - var CharDiff = new Diff(); - - var WordDiff = new Diff(true); - var WordWithSpaceDiff = new Diff(); - WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { - return removeEmpty(value.split(/(\s+|\b)/)); - }; - - var CssDiff = new Diff(true); - CssDiff.tokenize = function(value) { - return removeEmpty(value.split(/([{}:;,]|\s+)/)); - }; - - var LineDiff = new Diff(); - LineDiff.tokenize = function(value) { - var retLines = [], - lines = value.split(/^/m); - - for(var i = 0; i < lines.length; i++) { - var line = lines[i], - lastLine = lines[i - 1]; - - // Merge lines that may contain windows new lines - if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') { - retLines[retLines.length - 1] += '\n'; - } else if (line) { - retLines.push(line); - } - } - - return retLines; - }; - - return { - Diff: Diff, - - diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); }, - diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); }, - diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); }, - diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); }, - - diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); }, - - createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { - var ret = []; - - ret.push('Index: ' + fileName); - ret.push('==================================================================='); - ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); - ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); - - var diff = LineDiff.diff(oldStr, newStr); - if (!diff[diff.length-1].value) { - diff.pop(); // Remove trailing newline add - } - diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier - - function contextLines(lines) { - return lines.map(function(entry) { return ' ' + entry; }); - } - function eofNL(curRange, i, current) { - var last = diff[diff.length-2], - isLast = i === diff.length-2, - isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed); - - // Figure out if this is the last line for the given file and missing NL - if (!/\n$/.test(current.value) && (isLast || isLastOfType)) { - curRange.push('\\ No newline at end of file'); - } - } - - var oldRangeStart = 0, newRangeStart = 0, curRange = [], - oldLine = 1, newLine = 1; - for (var i = 0; i < diff.length; i++) { - var current = diff[i], - lines = current.lines || current.value.replace(/\n$/, '').split('\n'); - current.lines = lines; - - if (current.added || current.removed) { - if (!oldRangeStart) { - var prev = diff[i-1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - - if (prev) { - curRange = contextLines(prev.lines.slice(-4)); - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } - curRange.push.apply(curRange, lines.map(function(entry) { return (current.added?'+':'-') + entry; })); - eofNL(curRange, i, current); - - if (current.added) { - newLine += lines.length; - } else { - oldLine += lines.length; - } - } else { - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= 8 && i < diff.length-2) { - // Overlapping - curRange.push.apply(curRange, contextLines(lines)); - } else { - // end the range and output - var contextSize = Math.min(lines.length, 4); - ret.push( - '@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize) - + ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize) - + ' @@'); - ret.push.apply(ret, curRange); - ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); - if (lines.length <= 4) { - eofNL(ret, i, current); - } - - oldRangeStart = 0; newRangeStart = 0; curRange = []; - } - } - oldLine += lines.length; - newLine += lines.length; - } - } - - return ret.join('\n') + '\n'; - }, - - applyPatch: function(oldStr, uniDiff) { - var diffstr = uniDiff.split('\n'); - var diff = []; - var remEOFNL = false, - addEOFNL = false; - - for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) { - if(diffstr[i][0] === '@') { - var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); - diff.unshift({ - start:meh[3], - oldlength:meh[2], - oldlines:[], - newlength:meh[4], - newlines:[] - }); - } else if(diffstr[i][0] === '+') { - diff[0].newlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === '-') { - diff[0].oldlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === ' ') { - diff[0].newlines.push(diffstr[i].substr(1)); - diff[0].oldlines.push(diffstr[i].substr(1)); - } else if(diffstr[i][0] === '\\') { - if (diffstr[i-1][0] === '+') { - remEOFNL = true; - } else if(diffstr[i-1][0] === '-') { - addEOFNL = true; - } - } - } - - var str = oldStr.split('\n'); - for (var i = diff.length - 1; i >= 0; i--) { - var d = diff[i]; - for (var j = 0; j < d.oldlength; j++) { - if(str[d.start-1+j] !== d.oldlines[j]) { - return false; - } - } - Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines)); - } - - if (remEOFNL) { - while (!str[str.length-1]) { - str.pop(); - } - } else if (addEOFNL) { - str.push(''); - } - return str.join('\n'); - }, - - convertChangesToXML: function(changes){ - var ret = []; - for ( var i = 0; i < changes.length; i++) { - var change = changes[i]; - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); - } - - ret.push(escapeHTML(change.value)); - - if (change.added) { - ret.push(''); - } else if (change.removed) { - ret.push(''); - } - } - return ret.join(''); - }, - - // See: http://code.google.com/p/google-diff-match-patch/wiki/API - convertChangesToDMP: function(changes){ - var ret = [], change; - for ( var i = 0; i < changes.length; i++) { - change = changes[i]; - ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]); - } - return ret; - } - }; -})(); - -if (typeof module !== 'undefined') { - module.exports = JsDiff; -} - -}); // module: browser/diff.js - -require.register("browser/escape-string-regexp.js", function(module, exports, require){ -'use strict'; - -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; - -module.exports = function (str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - return str.replace(matchOperatorsRe, '\\$&'); -}; - -}); // module: browser/escape-string-regexp.js - -require.register("browser/events.js", function(module, exports, require){ - -/** - * Module exports. - */ - -exports.EventEmitter = EventEmitter; - -/** - * Check if `obj` is an array. - */ - -function isArray(obj) { - return '[object Array]' == {}.toString.call(obj); -} - -/** - * Event emitter constructor. - * - * @api public - */ - -function EventEmitter(){}; - -/** - * Adds a listener. - * - * @api public - */ - -EventEmitter.prototype.on = function (name, fn) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = fn; - } else if (isArray(this.$events[name])) { - this.$events[name].push(fn); - } else { - this.$events[name] = [this.$events[name], fn]; - } - - return this; -}; - -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -/** - * Adds a volatile listener. - * - * @api public - */ - -EventEmitter.prototype.once = function (name, fn) { - var self = this; - - function on () { - self.removeListener(name, on); - fn.apply(this, arguments); - }; - - on.listener = fn; - this.on(name, on); - - return this; -}; - -/** - * Removes a listener. - * - * @api public - */ - -EventEmitter.prototype.removeListener = function (name, fn) { - if (this.$events && this.$events[name]) { - var list = this.$events[name]; - - if (isArray(list)) { - var pos = -1; - - for (var i = 0, l = list.length; i < l; i++) { - if (list[i] === fn || (list[i].listener && list[i].listener === fn)) { - pos = i; - break; - } - } - - if (pos < 0) { - return this; - } - - list.splice(pos, 1); - - if (!list.length) { - delete this.$events[name]; - } - } else if (list === fn || (list.listener && list.listener === fn)) { - delete this.$events[name]; - } - } - - return this; -}; - -/** - * Removes all listeners for an event. - * - * @api public - */ - -EventEmitter.prototype.removeAllListeners = function (name) { - if (name === undefined) { - this.$events = {}; - return this; - } - - if (this.$events && this.$events[name]) { - this.$events[name] = null; - } - - return this; -}; - -/** - * Gets all listeners for a certain event. - * - * @api public - */ - -EventEmitter.prototype.listeners = function (name) { - if (!this.$events) { - this.$events = {}; - } - - if (!this.$events[name]) { - this.$events[name] = []; - } - - if (!isArray(this.$events[name])) { - this.$events[name] = [this.$events[name]]; - } - - return this.$events[name]; -}; - -/** - * Emits an event. - * - * @api public - */ - -EventEmitter.prototype.emit = function (name) { - if (!this.$events) { - return false; - } - - var handler = this.$events[name]; - - if (!handler) { - return false; - } - - var args = [].slice.call(arguments, 1); - - if ('function' == typeof handler) { - handler.apply(this, args); - } else if (isArray(handler)) { - var listeners = handler.slice(); - - for (var i = 0, l = listeners.length; i < l; i++) { - listeners[i].apply(this, args); - } - } else { - return false; - } - - return true; -}; -}); // module: browser/events.js - -require.register("browser/fs.js", function(module, exports, require){ - -}); // module: browser/fs.js - -require.register("browser/glob.js", function(module, exports, require){ - -}); // module: browser/glob.js - -require.register("browser/path.js", function(module, exports, require){ - -}); // module: browser/path.js - -require.register("browser/progress.js", function(module, exports, require){ -/** - * Expose `Progress`. - */ - -module.exports = Progress; - -/** - * Initialize a new `Progress` indicator. - */ - -function Progress() { - this.percent = 0; - this.size(0); - this.fontSize(11); - this.font('helvetica, arial, sans-serif'); -} - -/** - * Set progress size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.size = function(n){ - this._size = n; - return this; -}; - -/** - * Set text to `str`. - * - * @param {String} str - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.text = function(str){ - this._text = str; - return this; -}; - -/** - * Set font size to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - * @api public - */ - -Progress.prototype.fontSize = function(n){ - this._fontSize = n; - return this; -}; - -/** - * Set font `family`. - * - * @param {String} family - * @return {Progress} for chaining - */ - -Progress.prototype.font = function(family){ - this._font = family; - return this; -}; - -/** - * Update percentage to `n`. - * - * @param {Number} n - * @return {Progress} for chaining - */ - -Progress.prototype.update = function(n){ - this.percent = n; - return this; -}; - -/** - * Draw on `ctx`. - * - * @param {CanvasRenderingContext2d} ctx - * @return {Progress} for chaining - */ - -Progress.prototype.draw = function(ctx){ - try { - var percent = Math.min(this.percent, 100) - , size = this._size - , half = size / 2 - , x = half - , y = half - , rad = half - 1 - , fontSize = this._fontSize; - - ctx.font = fontSize + 'px ' + this._font; - - var angle = Math.PI * 2 * (percent / 100); - ctx.clearRect(0, 0, size, size); - - // outer circle - ctx.strokeStyle = '#9f9f9f'; - ctx.beginPath(); - ctx.arc(x, y, rad, 0, angle, false); - ctx.stroke(); - - // inner circle - ctx.strokeStyle = '#eee'; - ctx.beginPath(); - ctx.arc(x, y, rad - 1, 0, angle, true); - ctx.stroke(); - - // text - var text = this._text || (percent | 0) + '%' - , w = ctx.measureText(text).width; - - ctx.fillText( - text - , x - w / 2 + 1 - , y + fontSize / 2 - 1); - } catch (ex) {} //don't fail if we can't render progress - return this; -}; - -}); // module: browser/progress.js - -require.register("browser/tty.js", function(module, exports, require){ - -exports.isatty = function(){ - return true; -}; - -exports.getWindowSize = function(){ - if ('innerHeight' in global) { - return [global.innerHeight, global.innerWidth]; - } else { - // In a Web Worker, the DOM Window is not available. - return [640, 480]; - } -}; - -}); // module: browser/tty.js - -require.register("context.js", function(module, exports, require){ - -/** - * Expose `Context`. - */ - -module.exports = Context; - -/** - * Initialize a new `Context`. - * - * @api private - */ - -function Context(){} - -/** - * Set or get the context `Runnable` to `runnable`. - * - * @param {Runnable} runnable - * @return {Context} - * @api private - */ - -Context.prototype.runnable = function(runnable){ - if (0 == arguments.length) return this._runnable; - this.test = this._runnable = runnable; - return this; -}; - -/** - * Set test timeout `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.timeout = function(ms){ - if (arguments.length === 0) return this.runnable().timeout(); - this.runnable().timeout(ms); - return this; -}; - -/** - * Set test timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Context} self - * @api private - */ - -Context.prototype.enableTimeouts = function (enabled) { - this.runnable().enableTimeouts(enabled); - return this; -}; - - -/** - * Set test slowness threshold `ms`. - * - * @param {Number} ms - * @return {Context} self - * @api private - */ - -Context.prototype.slow = function(ms){ - this.runnable().slow(ms); - return this; -}; - -/** - * Inspect the context void of `._runnable`. - * - * @return {String} - * @api private - */ - -Context.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_runnable' == key) return; - if ('test' == key) return; - return val; - }, 2); -}; - -}); // module: context.js - -require.register("hook.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Hook`. - */ - -module.exports = Hook; - -/** - * Initialize a new `Hook` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Hook(title, fn) { - Runnable.call(this, title, fn); - this.type = 'hook'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Hook.prototype = new F; -Hook.prototype.constructor = Hook; - - -/** - * Get or set the test `err`. - * - * @param {Error} err - * @return {Error} - * @api public - */ - -Hook.prototype.error = function(err){ - if (0 == arguments.length) { - var err = this._error; - this._error = null; - return err; - } - - this._error = err; -}; - -}); // module: hook.js - -require.register("interfaces/bdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , utils = require('../utils') - , escapeRe = require('browser/escape-string-regexp'); - -/** - * BDD-style interface: - * - * describe('Array', function(){ - * describe('#indexOf()', function(){ - * it('should return -1 when not present', function(){ - * - * }); - * - * it('should return the index when present', function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before running tests. - */ - - context.before = function(name, fn){ - suites[0].beforeAll(name, fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(name, fn){ - suites[0].afterAll(name, fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(name, fn){ - suites[0].beforeEach(name, fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(name, fn){ - suites[0].afterEach(name, fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.describe = context.context = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending describe. - */ - - context.xdescribe = - context.xcontext = - context.describe.skip = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive suite. - */ - - context.describe.only = function(title, fn){ - var suite = context.describe(title, fn); - mocha.grep(suite.fullTitle()); - return suite; - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.it = context.specify = function(title, fn){ - var suite = suites[0]; - if (suite.pending) fn = null; - var test = new Test(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.it.only = function(title, fn){ - var test = context.it(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - return test; - }; - - /** - * Pending test case. - */ - - context.xit = - context.xspecify = - context.it.skip = function(title){ - context.it(title); - }; - }); -}; - -}); // module: interfaces/bdd.js - -require.register("interfaces/exports.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test'); - -/** - * TDD-style interface: - * - * exports.Array = { - * '#indexOf()': { - * 'should return -1 when the value is not present': function(){ - * - * }, - * - * 'should return the correct index when the value is present': function(){ - * - * } - * } - * }; - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('require', visit); - - function visit(obj, file) { - var suite; - for (var key in obj) { - if ('function' == typeof obj[key]) { - var fn = obj[key]; - switch (key) { - case 'before': - suites[0].beforeAll(fn); - break; - case 'after': - suites[0].afterAll(fn); - break; - case 'beforeEach': - suites[0].beforeEach(fn); - break; - case 'afterEach': - suites[0].afterEach(fn); - break; - default: - var test = new Test(key, fn); - test.file = file; - suites[0].addTest(test); - } - } else { - suite = Suite.create(suites[0], key); - suites.unshift(suite); - visit(obj[key]); - suites.shift(); - } - } - } -}; - -}); // module: interfaces/exports.js - -require.register("interfaces/index.js", function(module, exports, require){ - -exports.bdd = require('./bdd'); -exports.tdd = require('./tdd'); -exports.qunit = require('./qunit'); -exports.exports = require('./exports'); - -}); // module: interfaces/index.js - -require.register("interfaces/qunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , escapeRe = require('browser/escape-string-regexp') - , utils = require('../utils'); - -/** - * QUnit-style interface: - * - * suite('Array'); - * - * test('#length', function(){ - * var arr = [1,2,3]; - * ok(arr.length == 3); - * }); - * - * test('#indexOf()', function(){ - * var arr = [1,2,3]; - * ok(arr.indexOf(1) == 0); - * ok(arr.indexOf(2) == 1); - * ok(arr.indexOf(3) == 2); - * }); - * - * suite('String'); - * - * test('#length', function(){ - * ok('foo'.length == 3); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before running tests. - */ - - context.before = function(name, fn){ - suites[0].beforeAll(name, fn); - }; - - /** - * Execute after running tests. - */ - - context.after = function(name, fn){ - suites[0].afterAll(name, fn); - }; - - /** - * Execute before each test case. - */ - - context.beforeEach = function(name, fn){ - suites[0].beforeEach(name, fn); - }; - - /** - * Execute after each test case. - */ - - context.afterEach = function(name, fn){ - suites[0].afterEach(name, fn); - }; - - /** - * Describe a "suite" with the given `title`. - */ - - context.suite = function(title){ - if (suites.length > 1) suites.shift(); - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - return suite; - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var test = new Test(title, fn); - test.file = file; - suites[0].addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; - - /** - * Pending test case. - */ - - context.test.skip = function(title){ - context.test(title); - }; - }); -}; - -}); // module: interfaces/qunit.js - -require.register("interfaces/tdd.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Suite = require('../suite') - , Test = require('../test') - , escapeRe = require('browser/escape-string-regexp') - , utils = require('../utils'); - -/** - * TDD-style interface: - * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * suiteSetup(function(){ - * - * }); - * - * test('should return -1 when not present', function(){ - * - * }); - * - * test('should return the index when present', function(){ - * - * }); - * - * suiteTeardown(function(){ - * - * }); - * }); - * }); - * - */ - -module.exports = function(suite){ - var suites = [suite]; - - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before each test case. - */ - - context.setup = function(name, fn){ - suites[0].beforeEach(name, fn); - }; - - /** - * Execute after each test case. - */ - - context.teardown = function(name, fn){ - suites[0].afterEach(name, fn); - }; - - /** - * Execute before the suite. - */ - - context.suiteSetup = function(name, fn){ - suites[0].beforeAll(name, fn); - }; - - /** - * Execute after the suite. - */ - - context.suiteTeardown = function(name, fn){ - suites[0].afterAll(name, fn); - }; - - /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. - */ - - context.suite = function(title, fn){ - var suite = Suite.create(suites[0], title); - suite.file = file; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - return suite; - }; - - /** - * Pending suite. - */ - context.suite.skip = function(title, fn) { - var suite = Suite.create(suites[0], title); - suite.pending = true; - suites.unshift(suite); - fn.call(suite); - suites.shift(); - }; - - /** - * Exclusive test-case. - */ - - context.suite.only = function(title, fn){ - var suite = context.suite(title, fn); - mocha.grep(suite.fullTitle()); - }; - - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - var suite = suites[0]; - if (suite.pending) fn = null; - var test = new Test(title, fn); - test.file = file; - suite.addTest(test); - return test; - }; - - /** - * Exclusive test-case. - */ - - context.test.only = function(title, fn){ - var test = context.test(title, fn); - var reString = '^' + escapeRe(test.fullTitle()) + '$'; - mocha.grep(new RegExp(reString)); - }; - - /** - * Pending test case. - */ - - context.test.skip = function(title){ - context.test(title); - }; - }); -}; - -}); // module: interfaces/tdd.js - -require.register("mocha.js", function(module, exports, require){ -/*! - * mocha - * Copyright(c) 2011 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var path = require('browser/path') - , escapeRe = require('browser/escape-string-regexp') - , utils = require('./utils'); - -/** - * Expose `Mocha`. - */ - -exports = module.exports = Mocha; - -/** - * To require local UIs and reporters when running in node. - */ - -if (typeof process !== 'undefined' && typeof process.cwd === 'function') { - var join = path.join - , cwd = process.cwd(); - module.paths.push(cwd, join(cwd, 'node_modules')); -} - -/** - * Expose internals. - */ - -exports.utils = utils; -exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); -exports.Runnable = require('./runnable'); -exports.Context = require('./context'); -exports.Runner = require('./runner'); -exports.Suite = require('./suite'); -exports.Hook = require('./hook'); -exports.Test = require('./test'); - -/** - * Return image `name` path. - * - * @param {String} name - * @return {String} - * @api private - */ - -function image(name) { - return __dirname + '/../images/' + name + '.png'; -} - -/** - * Setup mocha with `options`. - * - * Options: - * - * - `ui` name "bdd", "tdd", "exports" etc - * - `reporter` reporter instance, defaults to `mocha.reporters.spec` - * - `globals` array of accepted globals - * - `timeout` timeout in milliseconds - * - `bail` bail on the first test failure - * - `slow` milliseconds to wait before considering a test slow - * - `ignoreLeaks` ignore global leaks - * - `grep` string or regexp to filter tests with - * - * @param {Object} options - * @api public - */ - -function Mocha(options) { - options = options || {}; - this.files = []; - this.options = options; - this.grep(options.grep); - this.suite = new exports.Suite('', new exports.Context); - this.ui(options.ui); - this.bail(options.bail); - this.reporter(options.reporter); - if (null != options.timeout) this.timeout(options.timeout); - this.useColors(options.useColors) - if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts); - if (options.slow) this.slow(options.slow); - - this.suite.on('pre-require', function (context) { - exports.afterEach = context.afterEach || context.teardown; - exports.after = context.after || context.suiteTeardown; - exports.beforeEach = context.beforeEach || context.setup; - exports.before = context.before || context.suiteSetup; - exports.describe = context.describe || context.suite; - exports.it = context.it || context.test; - exports.setup = context.setup || context.beforeEach; - exports.suiteSetup = context.suiteSetup || context.before; - exports.suiteTeardown = context.suiteTeardown || context.after; - exports.suite = context.suite || context.describe; - exports.teardown = context.teardown || context.afterEach; - exports.test = context.test || context.it; - }); -} - -/** - * Enable or disable bailing on the first failure. - * - * @param {Boolean} [bail] - * @api public - */ - -Mocha.prototype.bail = function(bail){ - if (0 == arguments.length) bail = true; - this.suite.bail(bail); - return this; -}; - -/** - * Add test `file`. - * - * @param {String} file - * @api public - */ - -Mocha.prototype.addFile = function(file){ - this.files.push(file); - return this; -}; - -/** - * Set reporter to `reporter`, defaults to "spec". - * - * @param {String|Function} reporter name or constructor - * @api public - */ - -Mocha.prototype.reporter = function(reporter){ - if ('function' == typeof reporter) { - this._reporter = reporter; - } else { - reporter = reporter || 'spec'; - var _reporter; - try { _reporter = require('./reporters/' + reporter); } catch (err) {}; - if (!_reporter) try { _reporter = require(reporter); } catch (err) {}; - if (!_reporter && reporter === 'teamcity') - console.warn('The Teamcity reporter was moved to a package named ' + - 'mocha-teamcity-reporter ' + - '(https://npmjs.org/package/mocha-teamcity-reporter).'); - if (!_reporter) throw new Error('invalid reporter "' + reporter + '"'); - this._reporter = _reporter; - } - return this; -}; - -/** - * Set test UI `name`, defaults to "bdd". - * - * @param {String} bdd - * @api public - */ - -Mocha.prototype.ui = function(name){ - name = name || 'bdd'; - this._ui = exports.interfaces[name]; - if (!this._ui) try { this._ui = require(name); } catch (err) {}; - if (!this._ui) throw new Error('invalid interface "' + name + '"'); - this._ui = this._ui(this.suite); - return this; -}; - -/** - * Load registered files. - * - * @api private - */ - -Mocha.prototype.loadFiles = function(fn){ - var self = this; - var suite = this.suite; - var pending = this.files.length; - this.files.forEach(function(file){ - file = path.resolve(file); - suite.emit('pre-require', global, file, self); - suite.emit('require', require(file), file, self); - suite.emit('post-require', global, file, self); - --pending || (fn && fn()); - }); -}; - -/** - * Enable growl support. - * - * @api private - */ - -Mocha.prototype._growl = function(runner, reporter) { - var notify = require('growl'); - - runner.on('end', function(){ - var stats = reporter.stats; - if (stats.failures) { - var msg = stats.failures + ' of ' + runner.total + ' tests failed'; - notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); - } else { - notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: image('ok') - }); - } - }); -}; - -/** - * Add regexp to grep, if `re` is a string it is escaped. - * - * @param {RegExp|String} re - * @return {Mocha} - * @api public - */ - -Mocha.prototype.grep = function(re){ - this.options.grep = 'string' == typeof re - ? new RegExp(escapeRe(re)) - : re; - return this; -}; - -/** - * Invert `.grep()` matches. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.invert = function(){ - this.options.invert = true; - return this; -}; - -/** - * Ignore global leaks. - * - * @param {Boolean} ignore - * @return {Mocha} - * @api public - */ - -Mocha.prototype.ignoreLeaks = function(ignore){ - this.options.ignoreLeaks = !!ignore; - return this; -}; - -/** - * Enable global leak checking. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.checkLeaks = function(){ - this.options.ignoreLeaks = false; - return this; -}; - -/** - * Enable growl support. - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.growl = function(){ - this.options.growl = true; - return this; -}; - -/** - * Ignore `globals` array or string. - * - * @param {Array|String} globals - * @return {Mocha} - * @api public - */ - -Mocha.prototype.globals = function(globals){ - this.options.globals = (this.options.globals || []).concat(globals); - return this; -}; - -/** - * Emit color output. - * - * @param {Boolean} colors - * @return {Mocha} - * @api public - */ - -Mocha.prototype.useColors = function(colors){ - this.options.useColors = arguments.length && colors != undefined - ? colors - : true; - return this; -}; - -/** - * Use inline diffs rather than +/-. - * - * @param {Boolean} inlineDiffs - * @return {Mocha} - * @api public - */ - -Mocha.prototype.useInlineDiffs = function(inlineDiffs) { - this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined - ? inlineDiffs - : false; - return this; -}; - -/** - * Set the timeout in milliseconds. - * - * @param {Number} timeout - * @return {Mocha} - * @api public - */ - -Mocha.prototype.timeout = function(timeout){ - this.suite.timeout(timeout); - return this; -}; - -/** - * Set slowness threshold in milliseconds. - * - * @param {Number} slow - * @return {Mocha} - * @api public - */ - -Mocha.prototype.slow = function(slow){ - this.suite.slow(slow); - return this; -}; - -/** - * Enable timeouts. - * - * @param {Boolean} enabled - * @return {Mocha} - * @api public - */ - -Mocha.prototype.enableTimeouts = function(enabled) { - this.suite.enableTimeouts(arguments.length && enabled !== undefined - ? enabled - : true); - return this -}; - -/** - * Makes all tests async (accepting a callback) - * - * @return {Mocha} - * @api public - */ - -Mocha.prototype.asyncOnly = function(){ - this.options.asyncOnly = true; - return this; -}; - -/** - * Disable syntax highlighting (in browser). - * @returns {Mocha} - * @api public - */ -Mocha.prototype.noHighlighting = function() { - this.options.noHighlighting = true; - return this; -}; - -/** - * Run tests and invoke `fn()` when complete. - * - * @param {Function} fn - * @return {Runner} - * @api public - */ - -Mocha.prototype.run = function(fn){ - if (this.files.length) this.loadFiles(); - var suite = this.suite; - var options = this.options; - options.files = this.files; - var runner = new exports.Runner(suite); - var reporter = new this._reporter(runner, options); - runner.ignoreLeaks = false !== options.ignoreLeaks; - runner.asyncOnly = options.asyncOnly; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - exports.reporters.Base.useColors = options.useColors; - exports.reporters.Base.inlineDiffs = options.useInlineDiffs; - return runner.run(fn); -}; - -}); // module: mocha.js - -require.register("ms.js", function(module, exports, require){ -/** - * Helpers. - */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} options - * @return {String|Number} - * @api public - */ - -module.exports = function(val, options){ - options = options || {}; - if ('string' == typeof val) return parse(val); - return options['long'] ? longFormat(val) : shortFormat(val); -}; - -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!match) return; - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 's': - return n * s; - case 'ms': - return n; - } -} - -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function shortFormat(ms) { - if (ms >= d) return Math.round(ms / d) + 'd'; - if (ms >= h) return Math.round(ms / h) + 'h'; - if (ms >= m) return Math.round(ms / m) + 'm'; - if (ms >= s) return Math.round(ms / s) + 's'; - return ms + 'ms'; -} - -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ - -function longFormat(ms) { - return plural(ms, d, 'day') - || plural(ms, h, 'hour') - || plural(ms, m, 'minute') - || plural(ms, s, 'second') - || ms + ' ms'; -} - -/** - * Pluralization helper. - */ - -function plural(ms, n, name) { - if (ms < n) return; - if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; - return Math.ceil(ms / n) + ' ' + name + 's'; -} - -}); // module: ms.js - -require.register("reporters/base.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var tty = require('browser/tty') - , diff = require('browser/diff') - , ms = require('../ms') - , utils = require('../utils'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Check if both stdio streams are associated with a tty. - */ - -var isatty = tty.isatty(1) && tty.isatty(2); - -/** - * Expose `Base`. - */ - -exports = module.exports = Base; - -/** - * Enable coloring by default. - */ - -exports.useColors = isatty || (process.env.MOCHA_COLORS !== undefined); - -/** - * Inline diffs instead of +/- - */ - -exports.inlineDiffs = false; - -/** - * Default color map. - */ - -exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': 0 - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 - , 'diff gutter': 90 - , 'diff added': 42 - , 'diff removed': 41 -}; - -/** - * Default symbol map. - */ - -exports.symbols = { - ok: '✓', - err: '✖', - dot: '․' -}; - -// With node.js on Windows: use symbols available in terminal default fonts -if ('win32' == process.platform) { - exports.symbols.ok = '\u221A'; - exports.symbols.err = '\u00D7'; - exports.symbols.dot = '.'; -} - -/** - * Color `str` with the given `type`, - * allowing colors to be disabled, - * as well as user-defined color - * schemes. - * - * @param {String} type - * @param {String} str - * @return {String} - * @api private - */ - -var color = exports.color = function(type, str) { - if (!exports.useColors) return str; - return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; -}; - -/** - * Expose term window size, with some - * defaults for when stderr is not a tty. - */ - -exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 -}; - -/** - * Expose some basic cursor interactions - * that are common among reporters. - */ - -exports.cursor = { - hide: function(){ - isatty && process.stdout.write('\u001b[?25l'); - }, - - show: function(){ - isatty && process.stdout.write('\u001b[?25h'); - }, - - deleteLine: function(){ - isatty && process.stdout.write('\u001b[2K'); - }, - - beginningOfLine: function(){ - isatty && process.stdout.write('\u001b[0G'); - }, - - CR: function(){ - if (isatty) { - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); - } else { - process.stdout.write('\r'); - } - } -}; - -/** - * Outut the given `failures` as a list. - * - * @param {Array} failures - * @api public - */ - -exports.list = function(failures){ - console.error(); - failures.forEach(function(test, i){ - // format - var fmt = color('error title', ' %s) %s:\n') - + color('error message', ' %s') - + color('error stack', '\n%s\n'); - - // msg - var err = test.err - , message = err.message || '' - , stack = err.stack || message - , index = stack.indexOf(message) + message.length - , msg = stack.slice(0, index) - , actual = err.actual - , expected = err.expected - , escape = true; - - // uncaught - if (err.uncaught) { - msg = 'Uncaught ' + msg; - } - - // explicitly show diff - if (err.showDiff && sameType(actual, expected)) { - escape = false; - err.actual = actual = utils.stringify(actual); - err.expected = expected = utils.stringify(expected); - } - - // actual / expected diff - if (err.showDiff && 'string' == typeof actual && 'string' == typeof expected) { - fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); - var match = message.match(/^([^:]+): expected/); - msg = '\n ' + color('error message', match ? match[1] : msg); - - if (exports.inlineDiffs) { - msg += inlineDiff(err, escape); - } else { - msg += unifiedDiff(err, escape); - } - } - - // indent stack trace without msg - stack = stack.slice(index ? index + 1 : index) - .replace(/^/gm, ' '); - - console.error(fmt, (i + 1), test.fullTitle(), msg, stack); - }); -}; - -/** - * Initialize a new `Base` reporter. - * - * All other reporters generally - * inherit from this reporter, providing - * stats such as test duration, number - * of tests passed / failed etc. - * - * @param {Runner} runner - * @api public - */ - -function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } - , failures = this.failures = []; - - if (!runner) return; - this.runner = runner; - - runner.stats = stats; - - runner.on('start', function(){ - stats.start = new Date; - }); - - runner.on('suite', function(suite){ - stats.suites = stats.suites || 0; - suite.root || stats.suites++; - }); - - runner.on('test end', function(test){ - stats.tests = stats.tests || 0; - stats.tests++; - }); - - runner.on('pass', function(test){ - stats.passes = stats.passes || 0; - - var medium = test.slow() / 2; - test.speed = test.duration > test.slow() - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; - - stats.passes++; - }); - - runner.on('fail', function(test, err){ - stats.failures = stats.failures || 0; - stats.failures++; - test.err = err; - failures.push(test); - }); - - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; - }); - - runner.on('pending', function(){ - stats.pending++; - }); -} - -/** - * Output common epilogue used by many of - * the bundled reporters. - * - * @api public - */ - -Base.prototype.epilogue = function(){ - var stats = this.stats; - var tests; - var fmt; - - console.log(); - - // passes - fmt = color('bright pass', ' ') - + color('green', ' %d passing') - + color('light', ' (%s)'); - - console.log(fmt, - stats.passes || 0, - ms(stats.duration)); - - // pending - if (stats.pending) { - fmt = color('pending', ' ') - + color('pending', ' %d pending'); - - console.log(fmt, stats.pending); - } - - // failures - if (stats.failures) { - fmt = color('fail', ' %d failing'); - - console.error(fmt, - stats.failures); - - Base.list(this.failures); - console.error(); - } - - console.log(); -}; - -/** - * Pad the given `str` to `len`. - * - * @param {String} str - * @param {String} len - * @return {String} - * @api private - */ - -function pad(str, len) { - str = String(str); - return Array(len - str.length + 1).join(' ') + str; -} - - -/** - * Returns an inline diff between 2 strings with coloured ANSI output - * - * @param {Error} Error with actual/expected - * @return {String} Diff - * @api private - */ - -function inlineDiff(err, escape) { - var msg = errorDiff(err, 'WordsWithSpace', escape); - - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); - } - - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; - - // indent - msg = msg.replace(/^/gm, ' '); - return msg; -} - -/** - * Returns a unified diff between 2 strings - * - * @param {Error} Error with actual/expected - * @return {String} Diff - * @api private - */ - -function unifiedDiff(err, escape) { - var indent = ' '; - function cleanUp(line) { - if (escape) { - line = escapeInvisibles(line); - } - if (line[0] === '+') return indent + colorLines('diff added', line); - if (line[0] === '-') return indent + colorLines('diff removed', line); - if (line.match(/\@\@/)) return null; - if (line.match(/\\ No newline/)) return null; - else return indent + line; - } - function notBlank(line) { - return line != null; - } - msg = diff.createPatch('string', err.actual, err.expected); - var lines = msg.split('\n').splice(4); - return '\n ' - + colorLines('diff added', '+ expected') + ' ' - + colorLines('diff removed', '- actual') - + '\n\n' - + lines.map(cleanUp).filter(notBlank).join('\n'); -} - -/** - * Return a character diff for `err`. - * - * @param {Error} err - * @return {String} - * @api private - */ - -function errorDiff(err, type, escape) { - var actual = escape ? escapeInvisibles(err.actual) : err.actual; - var expected = escape ? escapeInvisibles(err.expected) : err.expected; - return diff['diff' + type](actual, expected).map(function(str){ - if (str.added) return colorLines('diff added', str.value); - if (str.removed) return colorLines('diff removed', str.value); - return str.value; - }).join(''); -} - -/** - * Returns a string with all invisible characters in plain text - * - * @param {String} line - * @return {String} - * @api private - */ -function escapeInvisibles(line) { - return line.replace(/\t/g, '') - .replace(/\r/g, '') - .replace(/\n/g, '\n'); -} - -/** - * Color lines for `str`, using the color `name`. - * - * @param {String} name - * @param {String} str - * @return {String} - * @api private - */ - -function colorLines(name, str) { - return str.split('\n').map(function(str){ - return color(name, str); - }).join('\n'); -} - -/** - * Check that a / b have the same type. - * - * @param {Object} a - * @param {Object} b - * @return {Boolean} - * @api private - */ - -function sameType(a, b) { - a = Object.prototype.toString.call(a); - b = Object.prototype.toString.call(b); - return a == b; -} - -}); // module: reporters/base.js - -require.register("reporters/doc.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Doc`. - */ - -exports = module.exports = Doc; - -/** - * Initialize a new `Doc` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Doc(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; - - function indent() { - return Array(indents).join(' '); - } - - runner.on('suite', function(suite){ - if (suite.root) return; - ++indents; - console.log('%s
        ', indent()); - ++indents; - console.log('%s

        %s

        ', indent(), utils.escape(suite.title)); - console.log('%s
        ', indent()); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - console.log('%s
        ', indent()); - --indents; - console.log('%s
        ', indent()); - --indents; - }); - - runner.on('pass', function(test){ - console.log('%s
        %s
        ', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
        %s
        ', indent(), code); - }); - - runner.on('fail', function(test, err){ - console.log('%s
        %s
        ', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); - console.log('%s
        %s
        ', indent(), code); - console.log('%s
        %s
        ', indent(), utils.escape(err)); - }); -} - -}); // module: reporters/doc.js - -require.register("reporters/dot.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = Dot; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Dot(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , n = -1; - - runner.on('start', function(){ - process.stdout.write('\n '); - }); - - runner.on('pending', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('pending', Base.symbols.dot)); - }); - - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', Base.symbols.dot)); - } else { - process.stdout.write(color(test.speed, Base.symbols.dot)); - } - }); - - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', Base.symbols.dot)); - }); - - runner.on('end', function(){ - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Dot.prototype = new F; -Dot.prototype.constructor = Dot; - - -}); // module: reporters/dot.js - -require.register("reporters/html-cov.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var JSONCov = require('./json-cov') - , fs = require('browser/fs'); - -/** - * Expose `HTMLCov`. - */ - -exports = module.exports = HTMLCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTMLCov(runner) { - var jade = require('jade') - , file = __dirname + '/templates/coverage.jade' - , str = fs.readFileSync(file, 'utf8') - , fn = jade.compile(str, { filename: file }) - , self = this; - - JSONCov.call(this, runner, false); - - runner.on('end', function(){ - process.stdout.write(fn({ - cov: self.cov - , coverageClass: coverageClass - })); - }); -} - -/** - * Return coverage class for `n`. - * - * @return {String} - * @api private - */ - -function coverageClass(n) { - if (n >= 75) return 'high'; - if (n >= 50) return 'medium'; - if (n >= 25) return 'low'; - return 'terrible'; -} -}); // module: reporters/html-cov.js - -require.register("reporters/html.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , Progress = require('../browser/progress') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `HTML`. - */ - -exports = module.exports = HTML; - -/** - * Stats template. - */ - -var statsTemplate = ''; - -/** - * Initialize a new `HTML` reporter. - * - * @param {Runner} runner - * @api public - */ - -function HTML(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total - , stat = fragment(statsTemplate) - , items = stat.getElementsByTagName('li') - , passes = items[1].getElementsByTagName('em')[0] - , passesLink = items[1].getElementsByTagName('a')[0] - , failures = items[2].getElementsByTagName('em')[0] - , failuresLink = items[2].getElementsByTagName('a')[0] - , duration = items[3].getElementsByTagName('em')[0] - , canvas = stat.getElementsByTagName('canvas')[0] - , report = fragment('
          ') - , stack = [report] - , progress - , ctx - , root = document.getElementById('mocha'); - - if (canvas.getContext) { - var ratio = window.devicePixelRatio || 1; - canvas.style.width = canvas.width; - canvas.style.height = canvas.height; - canvas.width *= ratio; - canvas.height *= ratio; - ctx = canvas.getContext('2d'); - ctx.scale(ratio, ratio); - progress = new Progress; - } - - if (!root) return error('#mocha div missing, add it to your document'); - - // pass toggle - on(passesLink, 'click', function(){ - unhide(); - var name = /pass/.test(report.className) ? '' : ' pass'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test pass'); - }); - - // failure toggle - on(failuresLink, 'click', function(){ - unhide(); - var name = /fail/.test(report.className) ? '' : ' fail'; - report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test fail'); - }); - - root.appendChild(stat); - root.appendChild(report); - - if (progress) progress.size(40); - - runner.on('suite', function(suite){ - if (suite.root) return; - - // suite - var url = self.suiteURL(suite); - var el = fragment('
        • %s

        • ', url, escape(suite.title)); - - // container - stack[0].appendChild(el); - stack.unshift(document.createElement('ul')); - el.appendChild(stack[0]); - }); - - runner.on('suite end', function(suite){ - if (suite.root) return; - stack.shift(); - }); - - runner.on('fail', function(test, err){ - if ('hook' == test.type) runner.emit('test end', test); - }); - - runner.on('test end', function(test){ - // TODO: add to stats - var percent = stats.tests / this.total * 100 | 0; - if (progress) progress.update(percent).draw(ctx); - - // update stats - var ms = new Date - stats.start; - text(passes, stats.passes); - text(failures, stats.failures); - text(duration, (ms / 1000).toFixed(2)); - - // test - if ('passed' == test.state) { - var url = self.testURL(test); - var el = fragment('
        • %e%ems

        • ', test.speed, test.title, test.duration, url); - } else if (test.pending) { - var el = fragment('
        • %e

        • ', test.title); - } else { - var el = fragment('
        • %e

        • ', test.title, encodeURIComponent(test.fullTitle())); - var str = test.err.stack || test.err.toString(); - - // FF / Opera do not add the message - if (!~str.indexOf(test.err.message)) { - str = test.err.message + '\n' + str; - } - - // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - if ('[object Error]' == str) str = test.err.message; - - // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { - str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; - } - - el.appendChild(fragment('
          %e
          ', str)); - } - - // toggle code - // TODO: defer - if (!test.pending) { - var h2 = el.getElementsByTagName('h2')[0]; - - on(h2, 'click', function(){ - pre.style.display = 'none' == pre.style.display - ? 'block' - : 'none'; - }); - - var pre = fragment('
          %e
          ', utils.clean(test.fn.toString())); - el.appendChild(pre); - pre.style.display = 'none'; - } - - // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. - if (stack[0]) stack[0].appendChild(el); - }); -} - -/** - * Provide suite URL - * - * @param {Object} [suite] - */ - -HTML.prototype.suiteURL = function(suite){ - return '?grep=' + encodeURIComponent(suite.fullTitle()); -}; - -/** - * Provide test URL - * - * @param {Object} [test] - */ - -HTML.prototype.testURL = function(test){ - return '?grep=' + encodeURIComponent(test.fullTitle()); -}; - -/** - * Display error `msg`. - */ - -function error(msg) { - document.body.appendChild(fragment('
          %s
          ', msg)); -} - -/** - * Return a DOM fragment from `html`. - */ - -function fragment(html) { - var args = arguments - , div = document.createElement('div') - , i = 1; - - div.innerHTML = html.replace(/%([se])/g, function(_, type){ - switch (type) { - case 's': return String(args[i++]); - case 'e': return escape(args[i++]); - } - }); - - return div.firstChild; -} - -/** - * Check for suites that do not have elements - * with `classname`, and hide them. - */ - -function hideSuitesWithout(classname) { - var suites = document.getElementsByClassName('suite'); - for (var i = 0; i < suites.length; i++) { - var els = suites[i].getElementsByClassName(classname); - if (0 == els.length) suites[i].className += ' hidden'; - } -} - -/** - * Unhide .hidden suites. - */ - -function unhide() { - var els = document.getElementsByClassName('suite hidden'); - for (var i = 0; i < els.length; ++i) { - els[i].className = els[i].className.replace('suite hidden', 'suite'); - } -} - -/** - * Set `el` text to `str`. - */ - -function text(el, str) { - if (el.textContent) { - el.textContent = str; - } else { - el.innerText = str; - } -} - -/** - * Listen on `event` with callback `fn`. - */ - -function on(el, event, fn) { - if (el.addEventListener) { - el.addEventListener(event, fn, false); - } else { - el.attachEvent('on' + event, fn); - } -} - -}); // module: reporters/html.js - -require.register("reporters/index.js", function(module, exports, require){ - -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Min = require('./min'); -exports.Spec = require('./spec'); -exports.Nyan = require('./nyan'); -exports.XUnit = require('./xunit'); -exports.Markdown = require('./markdown'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONCov = require('./json-cov'); -exports.HTMLCov = require('./html-cov'); -exports.JSONStream = require('./json-stream'); - -}); // module: reporters/index.js - -require.register("reporters/json-cov.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `JSONCov`. - */ - -exports = module.exports = JSONCov; - -/** - * Initialize a new `JsCoverage` reporter. - * - * @param {Runner} runner - * @param {Boolean} output - * @api public - */ - -function JSONCov(runner, output) { - var self = this - , output = 1 == arguments.length ? true : output; - - Base.call(this, runner); - - var tests = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('end', function(){ - var cov = global._$jscoverage || {}; - var result = self.cov = map(cov); - result.stats = self.stats; - result.tests = tests.map(clean); - result.failures = failures.map(clean); - result.passes = passes.map(clean); - if (!output) return; - process.stdout.write(JSON.stringify(result, null, 2 )); - }); -} - -/** - * Map jscoverage data to a JSON structure - * suitable for reporting. - * - * @param {Object} cov - * @return {Object} - * @api private - */ - -function map(cov) { - var ret = { - instrumentation: 'node-jscoverage' - , sloc: 0 - , hits: 0 - , misses: 0 - , coverage: 0 - , files: [] - }; - - for (var filename in cov) { - var data = coverage(filename, cov[filename]); - ret.files.push(data); - ret.hits += data.hits; - ret.misses += data.misses; - ret.sloc += data.sloc; - } - - ret.files.sort(function(a, b) { - return a.filename.localeCompare(b.filename); - }); - - if (ret.sloc > 0) { - ret.coverage = (ret.hits / ret.sloc) * 100; - } - - return ret; -} - -/** - * Map jscoverage data for a single source file - * to a JSON structure suitable for reporting. - * - * @param {String} filename name of the source file - * @param {Object} data jscoverage coverage data - * @return {Object} - * @api private - */ - -function coverage(filename, data) { - var ret = { - filename: filename, - coverage: 0, - hits: 0, - misses: 0, - sloc: 0, - source: {} - }; - - data.source.forEach(function(line, num){ - num++; - - if (data[num] === 0) { - ret.misses++; - ret.sloc++; - } else if (data[num] !== undefined) { - ret.hits++; - ret.sloc++; - } - - ret.source[num] = { - source: line - , coverage: data[num] === undefined - ? '' - : data[num] - }; - }); - - ret.coverage = ret.hits / ret.sloc * 100; - - return ret; -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} - -}); // module: reporters/json-cov.js - -require.register("reporters/json-stream.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , total = runner.total; - - runner.on('start', function(){ - console.log(JSON.stringify(['start', { total: total }])); - }); - - runner.on('pass', function(test){ - console.log(JSON.stringify(['pass', clean(test)])); - }); - - runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); - }); - - runner.on('end', function(){ - process.stdout.write(JSON.stringify(['end', self.stats])); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } -} -}); // module: reporters/json-stream.js - -require.register("reporters/json.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `JSON`. - */ - -exports = module.exports = JSONReporter; - -/** - * Initialize a new `JSON` reporter. - * - * @param {Runner} runner - * @api public - */ - -function JSONReporter(runner) { - var self = this; - Base.call(this, runner); - - var tests = [] - , pending = [] - , failures = [] - , passes = []; - - runner.on('test end', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - passes.push(test); - }); - - runner.on('fail', function(test){ - failures.push(test); - }); - - runner.on('pending', function(test){ - pending.push(test); - }); - - runner.on('end', function(){ - var obj = { - stats: self.stats, - tests: tests.map(clean), - pending: pending.map(clean), - failures: failures.map(clean), - passes: passes.map(clean) - }; - - runner.testResults = obj; - - process.stdout.write(JSON.stringify(obj, null, 2)); - }); -} - -/** - * Return a plain-object representation of `test` - * free of cyclic properties etc. - * - * @param {Object} test - * @return {Object} - * @api private - */ - -function clean(test) { - return { - title: test.title, - fullTitle: test.fullTitle(), - duration: test.duration, - err: errorJSON(test.err || {}) - } -} - -/** - * Transform `error` into a JSON object. - * @param {Error} err - * @return {Object} - */ - -function errorJSON(err) { - var res = {}; - Object.getOwnPropertyNames(err).forEach(function(key) { - res[key] = err[key]; - }, err); - return res; -} - -}); // module: reporters/json.js - -require.register("reporters/landing.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Landing`. - */ - -exports = module.exports = Landing; - -/** - * Airplane color. - */ - -Base.colors.plane = 0; - -/** - * Airplane crash color. - */ - -Base.colors['plane crash'] = 31; - -/** - * Runway color. - */ - -Base.colors.runway = 90; - -/** - * Initialize a new `Landing` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Landing(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; - - function runway() { - var buf = Array(width).join('-'); - return ' ' + color('runway', buf); - } - - runner.on('start', function(){ - stream.write('\n '); - cursor.hide(); - }); - - runner.on('test end', function(test){ - // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; - - // show the crash - if ('failed' == test.state) { - plane = color('plane crash', '✈'); - crashed = col; - } - - // render landing strip - stream.write('\u001b[4F\n\n'); - stream.write(runway()); - stream.write('\n '); - stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) - stream.write(color('runway', Array(width - col).join('⋅') + '\n')); - stream.write(runway()); - stream.write('\u001b[0m'); - }); - - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Landing.prototype = new F; -Landing.prototype.constructor = Landing; - -}); // module: reporters/landing.js - -require.register("reporters/list.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `List`. - */ - -exports = module.exports = List; - -/** - * Initialize a new `List` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function List(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 0; - - runner.on('start', function(){ - console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); - }); - - runner.on('pending', function(test){ - var fmt = color('checkmark', ' -') - + color('pending', ' %s'); - console.log(fmt, test.fullTitle()); - }); - - runner.on('pass', function(test){ - var fmt = color('checkmark', ' '+Base.symbols.dot) - + color('pass', ' %s: ') - + color(test.speed, '%dms'); - cursor.CR(); - console.log(fmt, test.fullTitle(), test.duration); - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -List.prototype = new F; -List.prototype.constructor = List; - - -}); // module: reporters/list.js - -require.register("reporters/markdown.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils'); - -/** - * Expose `Markdown`. - */ - -exports = module.exports = Markdown; - -/** - * Initialize a new `Markdown` reporter. - * - * @param {Runner} runner - * @api public - */ - -function Markdown(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , level = 0 - , buf = ''; - - function title(str) { - return Array(level).join('#') + ' ' + str; - } - - function indent() { - return Array(level).join(' '); - } - - function mapTOC(suite, obj) { - var ret = obj; - obj = obj[suite.title] = obj[suite.title] || { suite: suite }; - suite.suites.forEach(function(suite){ - mapTOC(suite, obj); - }); - return ret; - } - - function stringifyTOC(obj, level) { - ++level; - var buf = ''; - var link; - for (var key in obj) { - if ('suite' == key) continue; - if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; - if (key) buf += Array(level).join(' ') + link; - buf += stringifyTOC(obj[key], level); - } - --level; - return buf; - } - - function generateTOC(suite) { - var obj = mapTOC(suite, {}); - return stringifyTOC(obj, 0); - } - - generateTOC(runner.suite); - - runner.on('suite', function(suite){ - ++level; - var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; - buf += title(suite.title) + '\n'; - }); - - runner.on('suite end', function(suite){ - --level; - }); - - runner.on('pass', function(test){ - var code = utils.clean(test.fn.toString()); - buf += test.title + '.\n'; - buf += '\n```js\n'; - buf += code + '\n'; - buf += '```\n\n'; - }); - - runner.on('end', function(){ - process.stdout.write('# TOC\n'); - process.stdout.write(generateTOC(runner.suite)); - process.stdout.write(buf); - }); -} -}); // module: reporters/markdown.js - -require.register("reporters/min.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base'); - -/** - * Expose `Min`. - */ - -exports = module.exports = Min; - -/** - * Initialize a new `Min` minimal test reporter (best used with --watch). - * - * @param {Runner} runner - * @api public - */ - -function Min(runner) { - Base.call(this, runner); - - runner.on('start', function(){ - // clear screen - process.stdout.write('\u001b[2J'); - // set cursor position - process.stdout.write('\u001b[1;3H'); - }); - - runner.on('end', this.epilogue.bind(this)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Min.prototype = new F; -Min.prototype.constructor = Min; - - -}); // module: reporters/min.js - -require.register("reporters/nyan.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , color = Base.color; - -/** - * Expose `Dot`. - */ - -exports = module.exports = NyanCat; - -/** - * Initialize a new `Dot` matrix test reporter. - * - * @param {Runner} runner - * @api public - */ - -function NyanCat(runner) { - Base.call(this, runner); - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , rainbowColors = this.rainbowColors = self.generateColors() - , colorIndex = this.colorIndex = 0 - , numerOfLines = this.numberOfLines = 4 - , trajectories = this.trajectories = [[], [], [], []] - , nyanCatWidth = this.nyanCatWidth = 11 - , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) - , scoreboardWidth = this.scoreboardWidth = 5 - , tick = this.tick = 0 - , n = 0; - - runner.on('start', function(){ - Base.cursor.hide(); - self.draw(); - }); - - runner.on('pending', function(test){ - self.draw(); - }); - - runner.on('pass', function(test){ - self.draw(); - }); - - runner.on('fail', function(test, err){ - self.draw(); - }); - - runner.on('end', function(){ - Base.cursor.show(); - for (var i = 0; i < self.numberOfLines; i++) write('\n'); - self.epilogue(); - }); -} - -/** - * Draw the nyan cat - * - * @api private - */ - -NyanCat.prototype.draw = function(){ - this.appendRainbow(); - this.drawScoreboard(); - this.drawRainbow(); - this.drawNyanCat(); - this.tick = !this.tick; -}; - -/** - * Draw the "scoreboard" showing the number - * of passes, failures and pending tests. - * - * @api private - */ - -NyanCat.prototype.drawScoreboard = function(){ - var stats = this.stats; - var colors = Base.colors; - - function draw(color, n) { - write(' '); - write('\u001b[' + color + 'm' + n + '\u001b[0m'); - write('\n'); - } - - draw(colors.green, stats.passes); - draw(colors.fail, stats.failures); - draw(colors.pending, stats.pending); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Append the rainbow. - * - * @api private - */ - -NyanCat.prototype.appendRainbow = function(){ - var segment = this.tick ? '_' : '-'; - var rainbowified = this.rainbowify(segment); - - for (var index = 0; index < this.numberOfLines; index++) { - var trajectory = this.trajectories[index]; - if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); - trajectory.push(rainbowified); - } -}; - -/** - * Draw the rainbow. - * - * @api private - */ - -NyanCat.prototype.drawRainbow = function(){ - var self = this; - - this.trajectories.forEach(function(line, index) { - write('\u001b[' + self.scoreboardWidth + 'C'); - write(line.join('')); - write('\n'); - }); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw the nyan cat - * - * @api private - */ - -NyanCat.prototype.drawNyanCat = function() { - var self = this; - var startWidth = this.scoreboardWidth + this.trajectories[0].length; - var color = '\u001b[' + startWidth + 'C'; - var padding = ''; - - write(color); - write('_,------,'); - write('\n'); - - write(color); - padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - - write(color); - padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - write(tail + '|' + padding + this.face() + ' '); - write('\n'); - - write(color); - padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - - this.cursorUp(this.numberOfLines); -}; - -/** - * Draw nyan cat face. - * - * @return {String} - * @api private - */ - -NyanCat.prototype.face = function() { - var stats = this.stats; - if (stats.failures) { - return '( x .x)'; - } else if (stats.pending) { - return '( o .o)'; - } else if(stats.passes) { - return '( ^ .^)'; - } else { - return '( - .-)'; - } -}; - -/** - * Move cursor up `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorUp = function(n) { - write('\u001b[' + n + 'A'); -}; - -/** - * Move cursor down `n`. - * - * @param {Number} n - * @api private - */ - -NyanCat.prototype.cursorDown = function(n) { - write('\u001b[' + n + 'B'); -}; - -/** - * Generate rainbow colors. - * - * @return {Array} - * @api private - */ - -NyanCat.prototype.generateColors = function(){ - var colors = []; - - for (var i = 0; i < (6 * 7); i++) { - var pi3 = Math.floor(Math.PI / 3); - var n = (i * (1.0 / 6)); - var r = Math.floor(3 * Math.sin(n) + 3); - var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3); - var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3); - colors.push(36 * r + 6 * g + b + 16); - } - - return colors; -}; - -/** - * Apply rainbow to the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -NyanCat.prototype.rainbowify = function(str){ - var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; - this.colorIndex += 1; - return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; -}; - -/** - * Stdout helper. - */ - -function write(string) { - process.stdout.write(string); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -NyanCat.prototype = new F; -NyanCat.prototype.constructor = NyanCat; - - -}); // module: reporters/nyan.js - -require.register("reporters/progress.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Progress`. - */ - -exports = module.exports = Progress; - -/** - * General progress bar color. - */ - -Base.colors.progress = 90; - -/** - * Initialize a new `Progress` bar test reporter. - * - * @param {Runner} runner - * @param {Object} options - * @api public - */ - -function Progress(runner, options) { - Base.call(this, runner); - - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max - , lastN = -1; - - // default chars - options.open = options.open || '['; - options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || Base.symbols.dot; - options.close = options.close || ']'; - options.verbose = false; - - // tests started - runner.on('start', function(){ - console.log(); - cursor.hide(); - }); - - // tests complete - runner.on('test end', function(){ - complete++; - var incomplete = total - complete - , percent = complete / total - , n = width * percent | 0 - , i = width - n; - - if (lastN === n && !options.verbose) { - // Don't re-render the line if it hasn't changed - return; - } - lastN = n; - - cursor.CR(); - process.stdout.write('\u001b[J'); - process.stdout.write(color('progress', ' ' + options.open)); - process.stdout.write(Array(n).join(options.complete)); - process.stdout.write(Array(i).join(options.incomplete)); - process.stdout.write(color('progress', options.close)); - if (options.verbose) { - process.stdout.write(color('progress', ' ' + complete + ' of ' + total)); - } - }); - - // tests are complete, output some stats - // and the failures if any - runner.on('end', function(){ - cursor.show(); - console.log(); - self.epilogue(); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Progress.prototype = new F; -Progress.prototype.constructor = Progress; - - -}); // module: reporters/progress.js - -require.register("reporters/spec.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `Spec`. - */ - -exports = module.exports = Spec; - -/** - * Initialize a new `Spec` test reporter. - * - * @param {Runner} runner - * @api public - */ - -function Spec(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , indents = 0 - , n = 0; - - function indent() { - return Array(indents).join(' ') - } - - runner.on('start', function(){ - console.log(); - }); - - runner.on('suite', function(suite){ - ++indents; - console.log(color('suite', '%s%s'), indent(), suite.title); - }); - - runner.on('suite end', function(suite){ - --indents; - if (1 == indents) console.log(); - }); - - runner.on('pending', function(test){ - var fmt = indent() + color('pending', ' - %s'); - console.log(fmt, test.title); - }); - - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s '); - cursor.CR(); - console.log(fmt, test.title); - } else { - var fmt = indent() - + color('checkmark', ' ' + Base.symbols.ok) - + color('pass', ' %s ') - + color(test.speed, '(%dms)'); - cursor.CR(); - console.log(fmt, test.title, test.duration); - } - }); - - runner.on('fail', function(test, err){ - cursor.CR(); - console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); - }); - - runner.on('end', self.epilogue.bind(self)); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -Spec.prototype = new F; -Spec.prototype.constructor = Spec; - - -}); // module: reporters/spec.js - -require.register("reporters/tap.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; - -/** - * Expose `TAP`. - */ - -exports = module.exports = TAP; - -/** - * Initialize a new `TAP` reporter. - * - * @param {Runner} runner - * @api public - */ - -function TAP(runner) { - Base.call(this, runner); - - var self = this - , stats = this.stats - , n = 1 - , passes = 0 - , failures = 0; - - runner.on('start', function(){ - var total = runner.grepTotal(runner.suite); - console.log('%d..%d', 1, total); - }); - - runner.on('test end', function(){ - ++n; - }); - - runner.on('pending', function(test){ - console.log('ok %d %s # SKIP -', n, title(test)); - }); - - runner.on('pass', function(test){ - passes++; - console.log('ok %d %s', n, title(test)); - }); - - runner.on('fail', function(test, err){ - failures++; - console.log('not ok %d %s', n, title(test)); - if (err.stack) console.log(err.stack.replace(/^/gm, ' ')); - }); - - runner.on('end', function(){ - console.log('# tests ' + (passes + failures)); - console.log('# pass ' + passes); - console.log('# fail ' + failures); - }); -} - -/** - * Return a TAP-safe title of `test` - * - * @param {Object} test - * @return {String} - * @api private - */ - -function title(test) { - return test.fullTitle().replace(/#/g, ''); -} - -}); // module: reporters/tap.js - -require.register("reporters/xunit.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Base = require('./base') - , utils = require('../utils') - , escape = utils.escape; - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Expose `XUnit`. - */ - -exports = module.exports = XUnit; - -/** - * Initialize a new `XUnit` reporter. - * - * @param {Runner} runner - * @api public - */ - -function XUnit(runner) { - Base.call(this, runner); - var stats = this.stats - , tests = [] - , self = this; - - runner.on('pending', function(test){ - tests.push(test); - }); - - runner.on('pass', function(test){ - tests.push(test); - }); - - runner.on('fail', function(test){ - tests.push(test); - }); - - runner.on('end', function(){ - console.log(tag('testsuite', { - name: 'Mocha Tests' - , tests: stats.tests - , failures: stats.failures - , errors: stats.failures - , skipped: stats.tests - stats.failures - stats.passes - , timestamp: (new Date).toUTCString() - , time: (stats.duration / 1000) || 0 - }, false)); - - tests.forEach(test); - console.log(''); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -function F(){}; -F.prototype = Base.prototype; -XUnit.prototype = new F; -XUnit.prototype.constructor = XUnit; - - -/** - * Output tag for the given `test.` - */ - -function test(test) { - var attrs = { - classname: test.parent.fullTitle() - , name: test.title - , time: (test.duration / 1000) || 0 - }; - - if ('failed' == test.state) { - var err = test.err; - console.log(tag('testcase', attrs, false, tag('failure', {}, false, cdata(escape(err.message) + "\n" + err.stack)))); - } else if (test.pending) { - console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - console.log(tag('testcase', attrs, true) ); - } -} - -/** - * HTML tag helper. - */ - -function tag(name, attrs, close, content) { - var end = close ? '/>' : '>' - , pairs = [] - , tag; - - for (var key in attrs) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } - - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - if (content) tag += content + ''; -} - -}); // module: reporters/xunit.js - -require.register("runnable.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runnable') - , milliseconds = require('./ms'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; - -/** - * Object#toString(). - */ - -var toString = Object.prototype.toString; - -/** - * Expose `Runnable`. - */ - -module.exports = Runnable; - -/** - * Initialize a new `Runnable` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Runnable(title, fn) { - this.title = title; - this.fn = fn; - this.async = fn && fn.length; - this.sync = ! this.async; - this._timeout = 2000; - this._slow = 75; - this._enableTimeouts = true; - this.timedOut = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runnable.prototype = new F; -Runnable.prototype.constructor = Runnable; - - -/** - * Set & get timeout `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if (ms === 0) this._enableTimeouts = false; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = ms; - if (this.timer) this.resetTimeout(); - return this; -}; - -/** - * Set & get slow `ms`. - * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self - * @api private - */ - -Runnable.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._slow = ms; - return this; -}; - -/** - * Set and & get timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Runnable|Boolean} enabled or self - * @api private - */ - -Runnable.prototype.enableTimeouts = function(enabled){ - if (arguments.length === 0) return this._enableTimeouts; - debug('enableTimeouts %s', enabled); - this._enableTimeouts = enabled; - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Runnable.prototype.fullTitle = function(){ - return this.parent.fullTitle() + ' ' + this.title; -}; - -/** - * Clear the timeout. - * - * @api private - */ - -Runnable.prototype.clearTimeout = function(){ - clearTimeout(this.timer); -}; - -/** - * Inspect the runnable void of private properties. - * - * @return {String} - * @api private - */ - -Runnable.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_' == key[0]) return; - if ('parent' == key) return '#'; - if ('ctx' == key) return '#'; - return val; - }, 2); -}; - -/** - * Reset the timeout. - * - * @api private - */ - -Runnable.prototype.resetTimeout = function(){ - var self = this; - var ms = this.timeout() || 1e9; - - if (!this._enableTimeouts) return; - this.clearTimeout(); - this.timer = setTimeout(function(){ - if (!self._enableTimeouts) return; - self.callback(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); -}; - -/** - * Whitelist these globals for this test run - * - * @api private - */ -Runnable.prototype.globals = function(arr){ - var self = this; - this._allowedGlobals = arr; -}; - -/** - * Run the test and invoke `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runnable.prototype.run = function(fn){ - var self = this - , start = new Date - , ctx = this.ctx - , finished - , emitted; - - // Some times the ctx exists but it is not runnable - if (ctx && ctx.runnable) ctx.runnable(this); - - // called multiple times - function multiple(err) { - if (emitted) return; - emitted = true; - self.emit('error', err || new Error('done() called multiple times')); - } - - // finished - function done(err) { - var ms = self.timeout(); - if (self.timedOut) return; - if (finished) return multiple(err); - self.clearTimeout(); - self.duration = new Date - start; - finished = true; - if (!err && self.duration > ms && self._enableTimeouts) err = new Error('timeout of ' + ms + 'ms exceeded'); - fn(err); - } - - // for .resetTimeout() - this.callback = done; - - // explicit async with `done` argument - if (this.async) { - this.resetTimeout(); - - try { - this.fn.call(ctx, function(err){ - if (err instanceof Error || toString.call(err) === "[object Error]") return done(err); - if (null != err) { - if (Object.prototype.toString.call(err) === '[object Object]') { - return done(new Error('done() invoked with non-Error: ' + JSON.stringify(err))); - } else { - return done(new Error('done() invoked with non-Error: ' + err)); - } - } - done(); - }); - } catch (err) { - done(err); - } - return; - } - - if (this.asyncOnly) { - return done(new Error('--async-only option in use without declaring `done()`')); - } - - // sync or promise-returning - try { - if (this.pending) { - done(); - } else { - callFn(this.fn); - } - } catch (err) { - done(err); - } - - function callFn(fn) { - var result = fn.call(ctx); - if (result && typeof result.then === 'function') { - self.resetTimeout(); - result - .then(function() { - done() - }, - function(reason) { - done(reason || new Error('Promise rejected with no or falsy reason')) - }); - } else { - done(); - } - } -}; - -}); // module: runnable.js - -require.register("runner.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runner') - , Test = require('./test') - , utils = require('./utils') - , filter = utils.filter - , keys = utils.keys; - -/** - * Non-enumerable globals. - */ - -var globals = [ - 'setTimeout', - 'clearTimeout', - 'setInterval', - 'clearInterval', - 'XMLHttpRequest', - 'Date' -]; - -/** - * Expose `Runner`. - */ - -module.exports = Runner; - -/** - * Initialize a `Runner` for the given `suite`. - * - * Events: - * - * - `start` execution started - * - `end` execution complete - * - `suite` (suite) test suite execution started - * - `suite end` (suite) all tests (and sub-suites) have finished - * - `test` (test) test execution started - * - `test end` (test) test completed - * - `hook` (hook) hook execution started - * - `hook end` (hook) hook complete - * - `pass` (test) test passed - * - `fail` (test, err) test failed - * - `pending` (test) test pending - * - * @api public - */ - -function Runner(suite) { - var self = this; - this._globals = []; - this._abort = false; - this.suite = suite; - this.total = suite.total(); - this.failures = 0; - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); - this.globals(this.globalProps().concat(extraGlobals())); -} - -/** - * Wrapper for setImmediate, process.nextTick, or browser polyfill. - * - * @param {Function} fn - * @api private - */ - -Runner.immediately = global.setImmediate || process.nextTick; - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Runner.prototype = new F; -Runner.prototype.constructor = Runner; - - -/** - * Run tests with full titles matching `re`. Updates runner.total - * with number of tests matched. - * - * @param {RegExp} re - * @param {Boolean} invert - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.grep = function(re, invert){ - debug('grep %s', re); - this._grep = re; - this._invert = invert; - this.total = this.grepTotal(this.suite); - return this; -}; - -/** - * Returns the number of tests matching the grep search for the - * given suite. - * - * @param {Suite} suite - * @return {Number} - * @api public - */ - -Runner.prototype.grepTotal = function(suite) { - var self = this; - var total = 0; - - suite.eachTest(function(test){ - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (match) total++; - }); - - return total; -}; - -/** - * Return a list of global properties. - * - * @return {Array} - * @api private - */ - -Runner.prototype.globalProps = function() { - var props = utils.keys(global); - - // non-enumerables - for (var i = 0; i < globals.length; ++i) { - if (~utils.indexOf(props, globals[i])) continue; - props.push(globals[i]); - } - - return props; -}; - -/** - * Allow the given `arr` of globals. - * - * @param {Array} arr - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.globals = function(arr){ - if (0 == arguments.length) return this._globals; - debug('globals %j', arr); - this._globals = this._globals.concat(arr); - return this; -}; - -/** - * Check for global variable leaks. - * - * @api private - */ - -Runner.prototype.checkGlobals = function(test){ - if (this.ignoreLeaks) return; - var ok = this._globals; - - var globals = this.globalProps(); - var leaks; - - if (test) { - ok = ok.concat(test._allowedGlobals || []); - } - - if(this.prevGlobalsLength == globals.length) return; - this.prevGlobalsLength = globals.length; - - leaks = filterLeaks(ok, globals); - this._globals = this._globals.concat(leaks); - - if (leaks.length > 1) { - this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + '')); - } else if (leaks.length) { - this.fail(test, new Error('global leak detected: ' + leaks[0])); - } -}; - -/** - * Fail the given `test`. - * - * @param {Test} test - * @param {Error} err - * @api private - */ - -Runner.prototype.fail = function(test, err){ - ++this.failures; - test.state = 'failed'; - - if ('string' == typeof err) { - err = new Error('the string "' + err + '" was thrown, throw an Error :)'); - } - - this.emit('fail', test, err); -}; - -/** - * Fail the given `hook` with `err`. - * - * Hook failures work in the following pattern: - * - If bail, then exit - * - Failed `before` hook skips all tests in a suite and subsuites, - * but jumps to corresponding `after` hook - * - Failed `before each` hook skips remaining tests in a - * suite and jumps to corresponding `after each` hook, - * which is run only once - * - Failed `after` hook does not alter - * execution order - * - Failed `after each` hook skips remaining tests in a - * suite and subsuites, but executes other `after each` - * hooks - * - * @param {Hook} hook - * @param {Error} err - * @api private - */ - -Runner.prototype.failHook = function(hook, err){ - this.fail(hook, err); - if (this.suite.bail()) { - this.emit('end'); - } -}; - -/** - * Run hook `name` callbacks and then invoke `fn()`. - * - * @param {String} name - * @param {Function} function - * @api private - */ - -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , self = this - , timer; - - function next(i) { - var hook = hooks[i]; - if (!hook) return fn(); - if (self.failures && suite.bail()) return fn(); - self.currentRunnable = hook; - - hook.ctx.currentTest = self.test; - - self.emit('hook', hook); - - hook.on('error', function(err){ - self.failHook(hook, err); - }); - - hook.run(function(err){ - hook.removeAllListeners('error'); - var testError = hook.error(); - if (testError) self.fail(self.test, testError); - if (err) { - self.failHook(hook, err); - - // stop executing hooks, notify callee of hook err - return fn(err); - } - self.emit('hook end', hook); - delete hook.ctx.currentTest; - next(++i); - }); - } - - Runner.immediately(function(){ - next(0); - }); -}; - -/** - * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err, errSuite)`. - * - * @param {String} name - * @param {Array} suites - * @param {Function} fn - * @api private - */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; - - function next(suite) { - self.suite = suite; - - if (!suite) { - self.suite = orig; - return fn(); - } - - self.hook(name, function(err){ - if (err) { - var errSuite = self.suite; - self.suite = orig; - return fn(err, errSuite); - } - - next(suites.pop()); - }); - } - - next(suites.pop()); -}; - -/** - * Run hooks from the top level down. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookUp = function(name, fn){ - var suites = [this.suite].concat(this.parents()).reverse(); - this.hooks(name, suites, fn); -}; - -/** - * Run hooks from the bottom up. - * - * @param {String} name - * @param {Function} fn - * @api private - */ - -Runner.prototype.hookDown = function(name, fn){ - var suites = [this.suite].concat(this.parents()); - this.hooks(name, suites, fn); -}; - -/** - * Return an array of parent Suites from - * closest to furthest. - * - * @return {Array} - * @api private - */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); - return suites; -}; - -/** - * Run the current test and callback `fn(err)`. - * - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; - - if (this.asyncOnly) test.asyncOnly = true; - - try { - test.on('error', function(err){ - self.fail(test, err); - }); - test.run(fn); - } catch (err) { - fn(err); - } -}; - -/** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests.slice() - , test; - - - function hookErr(err, errSuite, after) { - // before/after Each hook for errSuite failed: - var orig = self.suite; - - // for failed 'after each' hook start from errSuite parent, - // otherwise start from errSuite itself - self.suite = after ? errSuite.parent : errSuite; - - if (self.suite) { - // call hookUp afterEach - self.hookUp('afterEach', function(err2, errSuite2) { - self.suite = orig; - // some hooks may fail even now - if (err2) return hookErr(err2, errSuite2, true); - // report error suite - fn(errSuite); - }); - } else { - // there is no need calling other 'after each' hooks - self.suite = orig; - fn(errSuite); - } - } - - function next(err, errSuite) { - // if we bail after first err - if (self.failures && suite._bail) return fn(); - - if (self._abort) return fn(); - - if (err) return hookErr(err, errSuite, true); - - // next test - test = tests.shift(); - - // all done - if (!test) return fn(); - - // grep - var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (!match) return next(); - - // pending - if (test.pending) { - self.emit('pending', test); - self.emit('test end', test); - return next(); - } - - // execute test and hook(s) - self.emit('test', self.test = test); - self.hookDown('beforeEach', function(err, errSuite){ - - if (err) return hookErr(err, errSuite, false); - - self.currentRunnable = self.test; - self.runTest(function(err){ - test = self.test; - - if (err) { - self.fail(test, err); - self.emit('test end', test); - return self.hookUp('afterEach', next); - } - - test.state = 'passed'; - self.emit('pass', test); - self.emit('test end', test); - self.hookUp('afterEach', next); - }); - }); - } - - this.next = next; - next(); -}; - -/** - * Run the given `suite` and invoke the - * callback `fn()` when complete. - * - * @param {Suite} suite - * @param {Function} fn - * @api private - */ - -Runner.prototype.runSuite = function(suite, fn){ - var total = this.grepTotal(suite) - , self = this - , i = 0; - - debug('run suite %s', suite.fullTitle()); - - if (!total) return fn(); - - this.emit('suite', this.suite = suite); - - function next(errSuite) { - if (errSuite) { - // current suite failed on a hook from errSuite - if (errSuite == suite) { - // if errSuite is current suite - // continue to the next sibling suite - return done(); - } else { - // errSuite is among the parents of current suite - // stop execution of errSuite and all sub-suites - return done(errSuite); - } - } - - if (self._abort) return done(); - - var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); - } - - function done(errSuite) { - self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(errSuite); - }); - } - - this.hook('beforeAll', function(err){ - if (err) return done(); - self.runTests(suite, next); - }); -}; - -/** - * Handle uncaught exceptions. - * - * @param {Error} err - * @api private - */ - -Runner.prototype.uncaught = function(err){ - if (err) { - debug('uncaught exception %s', err !== function () { - return this; - }.call(err) ? err : ( err.message || err )); - } else { - debug('uncaught undefined exception'); - err = new Error('Caught undefined error, did you throw without specifying what?'); - } - err.uncaught = true; - - var runnable = this.currentRunnable; - if (!runnable) return; - - var wasAlreadyDone = runnable.state; - this.fail(runnable, err); - - runnable.clearTimeout(); - - if (wasAlreadyDone) return; - - // recover from test - if ('test' == runnable.type) { - this.emit('test end', runnable); - this.hookUp('afterEach', this.next); - return; - } - - // bail on hooks - this.emit('end'); -}; - -/** - * Run the root suite and invoke `fn(failures)` - * on completion. - * - * @param {Function} fn - * @return {Runner} for chaining - * @api public - */ - -Runner.prototype.run = function(fn){ - var self = this - , fn = fn || function(){}; - - function uncaught(err){ - self.uncaught(err); - } - - debug('start'); - - // callback - this.on('end', function(){ - debug('end'); - process.removeListener('uncaughtException', uncaught); - fn(self.failures); - }); - - // run suites - this.emit('start'); - this.runSuite(this.suite, function(){ - debug('finished running'); - self.emit('end'); - }); - - // uncaught exception - process.on('uncaughtException', uncaught); - - return this; -}; - -/** - * Cleanly abort execution - * - * @return {Runner} for chaining - * @api public - */ -Runner.prototype.abort = function(){ - debug('aborting'); - this._abort = true; -}; - -/** - * Filter leaks with the given globals flagged as `ok`. - * - * @param {Array} ok - * @param {Array} globals - * @return {Array} - * @api private - */ - -function filterLeaks(ok, globals) { - return filter(globals, function(key){ - // Firefox and Chrome exposes iframes as index inside the window object - if (/^d+/.test(key)) return false; - - // in firefox - // if runner runs in an iframe, this iframe's window.getInterface method not init at first - // it is assigned in some seconds - if (global.navigator && /^getInterface/.test(key)) return false; - - // an iframe could be approached by window[iframeIndex] - // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak - if (global.navigator && /^\d+/.test(key)) return false; - - // Opera and IE expose global variables for HTML element IDs (issue #243) - if (/^mocha-/.test(key)) return false; - - var matched = filter(ok, function(ok){ - if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); - return key == ok; - }); - return matched.length == 0 && (!global.navigator || 'onerror' !== key); - }); -} - -/** - * Array of globals dependent on the environment. - * - * @return {Array} - * @api private - */ - - function extraGlobals() { - if (typeof(process) === 'object' && - typeof(process.version) === 'string') { - - var nodeVersion = process.version.split('.').reduce(function(a, v) { - return a << 8 | v; - }); - - // 'errno' was renamed to process._errno in v0.9.11. - - if (nodeVersion < 0x00090B) { - return ['errno']; - } - } - - return []; - } - -}); // module: runner.js - -require.register("suite.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:suite') - , milliseconds = require('./ms') - , utils = require('./utils') - , Hook = require('./hook'); - -/** - * Expose `Suite`. - */ - -exports = module.exports = Suite; - -/** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. - * - * @param {Suite} parent - * @param {String} title - * @return {Suite} - * @api public - */ - -exports.create = function(parent, title){ - var suite = new Suite(title, parent.ctx); - suite.parent = parent; - if (parent.pending) suite.pending = true; - title = suite.fullTitle(); - parent.addSuite(suite); - return suite; -}; - -/** - * Initialize a new `Suite` with the given - * `title` and `ctx`. - * - * @param {String} title - * @param {Context} ctx - * @api private - */ - -function Suite(title, parentContext) { - this.title = title; - var context = function() {}; - context.prototype = parentContext; - this.ctx = new context(); - this.suites = []; - this.tests = []; - this.pending = false; - this._beforeEach = []; - this._beforeAll = []; - this._afterEach = []; - this._afterAll = []; - this.root = !title; - this._timeout = 2000; - this._enableTimeouts = true; - this._slow = 75; - this._bail = false; -} - -/** - * Inherit from `EventEmitter.prototype`. - */ - -function F(){}; -F.prototype = EventEmitter.prototype; -Suite.prototype = new F; -Suite.prototype.constructor = Suite; - - -/** - * Return a clone of this `Suite`. - * - * @return {Suite} - * @api private - */ - -Suite.prototype.clone = function(){ - var suite = new Suite(this.title); - debug('clone'); - suite.ctx = this.ctx; - suite.timeout(this.timeout()); - suite.enableTimeouts(this.enableTimeouts()); - suite.slow(this.slow()); - suite.bail(this.bail()); - return suite; -}; - -/** - * Set timeout `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if (ms === 0) this._enableTimeouts = false; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('timeout %d', ms); - this._timeout = parseInt(ms, 10); - return this; -}; - -/** - * Set timeout `enabled`. - * - * @param {Boolean} enabled - * @return {Suite|Boolean} self or enabled - * @api private - */ - -Suite.prototype.enableTimeouts = function(enabled){ - if (arguments.length === 0) return this._enableTimeouts; - debug('enableTimeouts %s', enabled); - this._enableTimeouts = enabled; - return this; -}; - -/** - * Set slow `ms` or short-hand such as "2s". - * - * @param {Number|String} ms - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); - debug('slow %d', ms); - this._slow = ms; - return this; -}; - -/** - * Sets whether to bail after first error. - * - * @parma {Boolean} bail - * @return {Suite|Number} for chaining - * @api private - */ - -Suite.prototype.bail = function(bail){ - if (0 == arguments.length) return this._bail; - debug('bail %s', bail); - this._bail = bail; - return this; -}; - -/** - * Run `fn(test[, done])` before running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeAll.push(hook); - this.emit('beforeAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after running tests. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterAll = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after all" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterAll.push(hook); - this.emit('afterAll', hook); - return this; -}; - -/** - * Run `fn(test[, done])` before each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.beforeEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"before each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._beforeEach.push(hook); - this.emit('beforeEach', hook); - return this; -}; - -/** - * Run `fn(test[, done])` after each test case. - * - * @param {Function} fn - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.afterEach = function(title, fn){ - if (this.pending) return this; - if ('function' === typeof title) { - fn = title; - title = fn.name; - } - title = '"after each" hook' + (title ? ': ' + title : ''); - - var hook = new Hook(title, fn); - hook.parent = this; - hook.timeout(this.timeout()); - hook.enableTimeouts(this.enableTimeouts()); - hook.slow(this.slow()); - hook.ctx = this.ctx; - this._afterEach.push(hook); - this.emit('afterEach', hook); - return this; -}; - -/** - * Add a test `suite`. - * - * @param {Suite} suite - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addSuite = function(suite){ - suite.parent = this; - suite.timeout(this.timeout()); - suite.enableTimeouts(this.enableTimeouts()); - suite.slow(this.slow()); - suite.bail(this.bail()); - this.suites.push(suite); - this.emit('suite', suite); - return this; -}; - -/** - * Add a `test` to this suite. - * - * @param {Test} test - * @return {Suite} for chaining - * @api private - */ - -Suite.prototype.addTest = function(test){ - test.parent = this; - test.timeout(this.timeout()); - test.enableTimeouts(this.enableTimeouts()); - test.slow(this.slow()); - test.ctx = this.ctx; - this.tests.push(test); - this.emit('test', test); - return this; -}; - -/** - * Return the full title generated by recursively - * concatenating the parent's full title. - * - * @return {String} - * @api public - */ - -Suite.prototype.fullTitle = function(){ - if (this.parent) { - var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; - } - return this.title; -}; - -/** - * Return the total number of tests. - * - * @return {Number} - * @api public - */ - -Suite.prototype.total = function(){ - return utils.reduce(this.suites, function(sum, suite){ - return sum + suite.total(); - }, 0) + this.tests.length; -}; - -/** - * Iterates through each suite recursively to find - * all tests. Applies a function in the format - * `fn(test)`. - * - * @param {Function} fn - * @return {Suite} - * @api private - */ - -Suite.prototype.eachTest = function(fn){ - utils.forEach(this.tests, fn); - utils.forEach(this.suites, function(suite){ - suite.eachTest(fn); - }); - return this; -}; - -}); // module: suite.js - -require.register("test.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var Runnable = require('./runnable'); - -/** - * Expose `Test`. - */ - -module.exports = Test; - -/** - * Initialize a new `Test` with the given `title` and callback `fn`. - * - * @param {String} title - * @param {Function} fn - * @api private - */ - -function Test(title, fn) { - Runnable.call(this, title, fn); - this.pending = !fn; - this.type = 'test'; -} - -/** - * Inherit from `Runnable.prototype`. - */ - -function F(){}; -F.prototype = Runnable.prototype; -Test.prototype = new F; -Test.prototype.constructor = Test; - - -}); // module: test.js - -require.register("utils.js", function(module, exports, require){ -/** - * Module dependencies. - */ - -var fs = require('browser/fs') - , path = require('browser/path') - , basename = path.basename - , exists = fs.existsSync || path.existsSync - , glob = require('browser/glob') - , join = path.join - , debug = require('browser/debug')('mocha:watch'); - -/** - * Ignored directories. - */ - -var ignore = ['node_modules', '.git']; - -/** - * Escape special characters in the given string of html. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&/g, '&') - .replace(/"/g, '"') - .replace(//g, '>'); -}; - -/** - * Array#forEach (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.forEach = function(arr, fn, scope){ - for (var i = 0, l = arr.length; i < l; i++) - fn.call(scope, arr[i], i); -}; - -/** - * Array#map (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} scope - * @api private - */ - -exports.map = function(arr, fn, scope){ - var result = []; - for (var i = 0, l = arr.length; i < l; i++) - result.push(fn.call(scope, arr[i], i)); - return result; -}; - -/** - * Array#indexOf (<=IE8) - * - * @parma {Array} arr - * @param {Object} obj to find index of - * @param {Number} start - * @api private - */ - -exports.indexOf = function(arr, obj, start){ - for (var i = start || 0, l = arr.length; i < l; i++) { - if (arr[i] === obj) - return i; - } - return -1; -}; - -/** - * Array#reduce (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} initial value - * @api private - */ - -exports.reduce = function(arr, fn, val){ - var rval = val; - - for (var i = 0, l = arr.length; i < l; i++) { - rval = fn(rval, arr[i], i, arr); - } - - return rval; -}; - -/** - * Array#filter (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @api private - */ - -exports.filter = function(arr, fn){ - var ret = []; - - for (var i = 0, l = arr.length; i < l; i++) { - var val = arr[i]; - if (fn(val, i, arr)) ret.push(val); - } - - return ret; -}; - -/** - * Object.keys (<=IE8) - * - * @param {Object} obj - * @return {Array} keys - * @api private - */ - -exports.keys = Object.keys || function(obj) { - var keys = [] - , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 - - for (var key in obj) { - if (has.call(obj, key)) { - keys.push(key); - } - } - - return keys; -}; - -/** - * Watch the given `files` for changes - * and invoke `fn(file)` on modification. - * - * @param {Array} files - * @param {Function} fn - * @api private - */ - -exports.watch = function(files, fn){ - var options = { interval: 100 }; - files.forEach(function(file){ - debug('file %s', file); - fs.watchFile(file, options, function(curr, prev){ - if (prev.mtime < curr.mtime) fn(file); - }); - }); -}; - -/** - * Ignored files. - */ - -function ignored(path){ - return !~ignore.indexOf(path); -} - -/** - * Lookup files in the given `dir`. - * - * @return {Array} - * @api private - */ - -exports.files = function(dir, ext, ret){ - ret = ret || []; - ext = ext || ['js']; - - var re = new RegExp('\\.(' + ext.join('|') + ')$'); - - fs.readdirSync(dir) - .filter(ignored) - .forEach(function(path){ - path = join(dir, path); - if (fs.statSync(path).isDirectory()) { - exports.files(path, ext, ret); - } else if (path.match(re)) { - ret.push(path); - } - }); - - return ret; -}; - -/** - * Compute a slug from the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.slug = function(str){ - return str - .toLowerCase() - .replace(/ +/g, '-') - .replace(/[^-\w]/g, ''); -}; - -/** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. - */ - -exports.clean = function(str) { - str = str - .replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, '') - .replace(/^function *\(.*\) *{|\(.*\) *=> *{?/, '') - .replace(/\s+\}$/, ''); - - var spaces = str.match(/^\n?( *)/)[1].length - , tabs = str.match(/^\n?(\t*)/)[1].length - , re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm'); - - str = str.replace(re, ''); - - return exports.trim(str); -}; - -/** - * Trim the given `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.trim = function(str){ - return str.replace(/^\s+|\s+$/g, ''); -}; - -/** - * Parse the given `qs`. - * - * @param {String} qs - * @return {Object} - * @api private - */ - -exports.parseQuery = function(qs){ - return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); - - obj[key] = decodeURIComponent(val); - return obj; - }, {}); -}; - -/** - * Highlight the given string of `js`. - * - * @param {String} js - * @return {String} - * @api private - */ - -function highlight(js) { - return js - .replace(//g, '>') - .replace(/\/\/(.*)/gm, '//$1') - .replace(/('.*?')/gm, '$1') - .replace(/(\d+\.\d+)/gm, '$1') - .replace(/(\d+)/gm, '$1') - .replace(/\bnew[ \t]+(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') -} - -/** - * Highlight the contents of tag `name`. - * - * @param {String} name - * @api private - */ - -exports.highlightTags = function(name) { - var code = document.getElementById('mocha').getElementsByTagName(name); - for (var i = 0, len = code.length; i < len; ++i) { - code[i].innerHTML = highlight(code[i].innerHTML); - } -}; - - -/** - * Stringify `obj`. - * - * @param {Object} obj - * @return {String} - * @api private - */ - -exports.stringify = function(obj) { - if (obj instanceof RegExp) return obj.toString(); - return JSON.stringify(exports.canonicalize(obj), null, 2).replace(/,(\n|$)/g, '$1'); -}; - -/** - * Return a new object that has the keys in sorted order. - * @param {Object} obj - * @param {Array} [stack] - * @return {Object} - * @api private - */ - -exports.canonicalize = function(obj, stack) { - stack = stack || []; - - if (exports.indexOf(stack, obj) !== -1) return '[Circular]'; - - var canonicalizedObj; - - if ({}.toString.call(obj) === '[object Array]') { - stack.push(obj); - canonicalizedObj = exports.map(obj, function (item) { - return exports.canonicalize(item, stack); - }); - stack.pop(); - } else if (typeof obj === 'object' && obj !== null) { - stack.push(obj); - canonicalizedObj = {}; - exports.forEach(exports.keys(obj).sort(), function (key) { - canonicalizedObj[key] = exports.canonicalize(obj[key], stack); - }); - stack.pop(); - } else { - canonicalizedObj = obj; - } - - return canonicalizedObj; - }; - -/** - * Lookup file names at the given `path`. - */ -exports.lookupFiles = function lookupFiles(path, extensions, recursive) { - var files = []; - var re = new RegExp('\\.(' + extensions.join('|') + ')$'); - - if (!exists(path)) { - if (exists(path + '.js')) { - path += '.js'; - } else { - files = glob.sync(path); - if (!files.length) throw new Error("cannot resolve path (or pattern) '" + path + "'"); - return files; - } - } - - try { - var stat = fs.statSync(path); - if (stat.isFile()) return path; - } - catch (ignored) { - return; - } - - fs.readdirSync(path).forEach(function(file){ - file = join(path, file); - try { - var stat = fs.statSync(file); - if (stat.isDirectory()) { - if (recursive) { - files = files.concat(lookupFiles(file, extensions, recursive)); - } - return; - } - } - catch (ignored) { - return; - } - if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') return; - files.push(file); - }); - - return files; -}; - -}); // module: utils.js -// The global object is "self" in Web Workers. -var global = (function() { return this; })(); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date; -var setTimeout = global.setTimeout; -var setInterval = global.setInterval; -var clearTimeout = global.clearTimeout; -var clearInterval = global.clearInterval; - -/** - * Node shims. - * - * These are meant only to allow - * mocha.js to run untouched, not - * to allow running node code in - * the browser. - */ - -var process = {}; -process.exit = function(status){}; -process.stdout = {}; - -var uncaughtExceptionHandlers = []; - -var originalOnerrorHandler = global.onerror; - -/** - * Remove uncaughtException listener. - * Revert to original onerror handler if previously defined. - */ - -process.removeListener = function(e, fn){ - if ('uncaughtException' == e) { - if (originalOnerrorHandler) { - global.onerror = originalOnerrorHandler; - } else { - global.onerror = function() {}; - } - var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn); - if (i != -1) { uncaughtExceptionHandlers.splice(i, 1); } - } -}; - -/** - * Implements uncaughtException listener. - */ - -process.on = function(e, fn){ - if ('uncaughtException' == e) { - global.onerror = function(err, url, line){ - fn(new Error(err + ' (' + url + ':' + line + ')')); - return true; - }; - uncaughtExceptionHandlers.push(fn); - } -}; - -/** - * Expose mocha. - */ - -var Mocha = global.Mocha = require('mocha'), - mocha = global.mocha = new Mocha({ reporter: 'html' }); - -// The BDD UI is registered by default, but no UI will be functional in the -// browser without an explicit call to the overridden `mocha.ui` (see below). -// Ensure that this default UI does not expose its methods to the global scope. -mocha.suite.removeAllListeners('pre-require'); - -var immediateQueue = [] - , immediateTimeout; - -function timeslice() { - var immediateStart = new Date().getTime(); - while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) { - immediateQueue.shift()(); - } - if (immediateQueue.length) { - immediateTimeout = setTimeout(timeslice, 0); - } else { - immediateTimeout = null; - } -} - -/** - * High-performance override of Runner.immediately. - */ - -Mocha.Runner.immediately = function(callback) { - immediateQueue.push(callback); - if (!immediateTimeout) { - immediateTimeout = setTimeout(timeslice, 0); - } -}; - -/** - * Function to allow assertion libraries to throw errors directly into mocha. - * This is useful when running tests in a browser because window.onerror will - * only receive the 'message' attribute of the Error. - */ -mocha.throwError = function(err) { - Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) { - fn(err); - }); - throw err; -}; - -/** - * Override ui to ensure that the ui functions are initialized. - * Normally this would happen in Mocha.prototype.loadFiles. - */ - -mocha.ui = function(ui){ - Mocha.prototype.ui.call(this, ui); - this.suite.emit('pre-require', global, null, this); - return this; -}; - -/** - * Setup mocha with the given setting options. - */ - -mocha.setup = function(opts){ - if ('string' == typeof opts) opts = { ui: opts }; - for (var opt in opts) this[opt](opts[opt]); - return this; -}; - -/** - * Run mocha, returning the Runner. - */ - -mocha.run = function(fn){ - var options = mocha.options; - mocha.globals('location'); - - var query = Mocha.utils.parseQuery(global.location.search || ''); - if (query.grep) mocha.grep(query.grep); - if (query.invert) mocha.invert(); - - return Mocha.prototype.run.call(mocha, function(err){ - // The DOM Document is not available in Web Workers. - var document = global.document; - if (document && document.getElementById('mocha') && options.noHighlighting !== true) { - Mocha.utils.highlightTags('code'); - } - if (fn) fn(err); - }); -}; - -/** - * Expose the process shim. - */ - -Mocha.process = process; -})(); \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js deleted file mode 100644 index 7ad9f8a..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/dist/test/worker.js +++ /dev/null @@ -1,16 +0,0 @@ -importScripts('es6-promise.js'); -new ES6Promise.Promise(function(resolve, reject) { - self.onmessage = function (e) { - if (e.data === 'ping') { - resolve('pong'); - } else { - reject(new Error('wrong message')); - } - }; -}).then(function (result) { - self.postMessage(result); -}, function (err){ - setTimeout(function () { - throw err; - }); -}); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js deleted file mode 100644 index 5984f70..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise.umd.js +++ /dev/null @@ -1,18 +0,0 @@ -import Promise from './es6-promise/promise'; -import polyfill from './es6-promise/polyfill'; - -var ES6Promise = { - 'Promise': Promise, - 'polyfill': polyfill -}; - -/* global define:true module:true window: true */ -if (typeof define === 'function' && define['amd']) { - define(function() { return ES6Promise; }); -} else if (typeof module !== 'undefined' && module['exports']) { - module['exports'] = ES6Promise; -} else if (typeof this !== 'undefined') { - this['ES6Promise'] = ES6Promise; -} - -polyfill(); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js deleted file mode 100644 index daee2c3..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/-internal.js +++ /dev/null @@ -1,250 +0,0 @@ -import { - objectOrFunction, - isFunction -} from './utils'; - -import asap from './asap'; - -function noop() {} - -var PENDING = void 0; -var FULFILLED = 1; -var REJECTED = 2; - -var GET_THEN_ERROR = new ErrorObject(); - -function selfFullfillment() { - return new TypeError("You cannot resolve a promise with itself"); -} - -function cannotReturnOwn() { - return new TypeError('A promises callback cannot return that same promise.'); -} - -function getThen(promise) { - try { - return promise.then; - } catch(error) { - GET_THEN_ERROR.error = error; - return GET_THEN_ERROR; - } -} - -function tryThen(then, value, fulfillmentHandler, rejectionHandler) { - try { - then.call(value, fulfillmentHandler, rejectionHandler); - } catch(e) { - return e; - } -} - -function handleForeignThenable(promise, thenable, then) { - asap(function(promise) { - var sealed = false; - var error = tryThen(then, thenable, function(value) { - if (sealed) { return; } - sealed = true; - if (thenable !== value) { - resolve(promise, value); - } else { - fulfill(promise, value); - } - }, function(reason) { - if (sealed) { return; } - sealed = true; - - reject(promise, reason); - }, 'Settle: ' + (promise._label || ' unknown promise')); - - if (!sealed && error) { - sealed = true; - reject(promise, error); - } - }, promise); -} - -function handleOwnThenable(promise, thenable) { - if (thenable._state === FULFILLED) { - fulfill(promise, thenable._result); - } else if (thenable._state === REJECTED) { - reject(promise, thenable._result); - } else { - subscribe(thenable, undefined, function(value) { - resolve(promise, value); - }, function(reason) { - reject(promise, reason); - }); - } -} - -function handleMaybeThenable(promise, maybeThenable) { - if (maybeThenable.constructor === promise.constructor) { - handleOwnThenable(promise, maybeThenable); - } else { - var then = getThen(maybeThenable); - - if (then === GET_THEN_ERROR) { - reject(promise, GET_THEN_ERROR.error); - } else if (then === undefined) { - fulfill(promise, maybeThenable); - } else if (isFunction(then)) { - handleForeignThenable(promise, maybeThenable, then); - } else { - fulfill(promise, maybeThenable); - } - } -} - -function resolve(promise, value) { - if (promise === value) { - reject(promise, selfFullfillment()); - } else if (objectOrFunction(value)) { - handleMaybeThenable(promise, value); - } else { - fulfill(promise, value); - } -} - -function publishRejection(promise) { - if (promise._onerror) { - promise._onerror(promise._result); - } - - publish(promise); -} - -function fulfill(promise, value) { - if (promise._state !== PENDING) { return; } - - promise._result = value; - promise._state = FULFILLED; - - if (promise._subscribers.length !== 0) { - asap(publish, promise); - } -} - -function reject(promise, reason) { - if (promise._state !== PENDING) { return; } - promise._state = REJECTED; - promise._result = reason; - - asap(publishRejection, promise); -} - -function subscribe(parent, child, onFulfillment, onRejection) { - var subscribers = parent._subscribers; - var length = subscribers.length; - - parent._onerror = null; - - subscribers[length] = child; - subscribers[length + FULFILLED] = onFulfillment; - subscribers[length + REJECTED] = onRejection; - - if (length === 0 && parent._state) { - asap(publish, parent); - } -} - -function publish(promise) { - var subscribers = promise._subscribers; - var settled = promise._state; - - if (subscribers.length === 0) { return; } - - var child, callback, detail = promise._result; - - for (var i = 0; i < subscribers.length; i += 3) { - child = subscribers[i]; - callback = subscribers[i + settled]; - - if (child) { - invokeCallback(settled, child, callback, detail); - } else { - callback(detail); - } - } - - promise._subscribers.length = 0; -} - -function ErrorObject() { - this.error = null; -} - -var TRY_CATCH_ERROR = new ErrorObject(); - -function tryCatch(callback, detail) { - try { - return callback(detail); - } catch(e) { - TRY_CATCH_ERROR.error = e; - return TRY_CATCH_ERROR; - } -} - -function invokeCallback(settled, promise, callback, detail) { - var hasCallback = isFunction(callback), - value, error, succeeded, failed; - - if (hasCallback) { - value = tryCatch(callback, detail); - - if (value === TRY_CATCH_ERROR) { - failed = true; - error = value.error; - value = null; - } else { - succeeded = true; - } - - if (promise === value) { - reject(promise, cannotReturnOwn()); - return; - } - - } else { - value = detail; - succeeded = true; - } - - if (promise._state !== PENDING) { - // noop - } else if (hasCallback && succeeded) { - resolve(promise, value); - } else if (failed) { - reject(promise, error); - } else if (settled === FULFILLED) { - fulfill(promise, value); - } else if (settled === REJECTED) { - reject(promise, value); - } -} - -function initializePromise(promise, resolver) { - try { - resolver(function resolvePromise(value){ - resolve(promise, value); - }, function rejectPromise(reason) { - reject(promise, reason); - }); - } catch(e) { - reject(promise, e); - } -} - -export { - noop, - resolve, - reject, - fulfill, - subscribe, - publish, - publishRejection, - initializePromise, - invokeCallback, - FULFILLED, - REJECTED, - PENDING -}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js deleted file mode 100644 index 4f7dcee..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/asap.js +++ /dev/null @@ -1,111 +0,0 @@ -var len = 0; -var toString = {}.toString; -var vertxNext; -export default function asap(callback, arg) { - queue[len] = callback; - queue[len + 1] = arg; - len += 2; - if (len === 2) { - // If len is 2, that means that we need to schedule an async flush. - // If additional callbacks are queued before the queue is flushed, they - // will be processed by this flush that we are scheduling. - scheduleFlush(); - } -} - -var browserWindow = (typeof window !== 'undefined') ? window : undefined; -var browserGlobal = browserWindow || {}; -var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; -var isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; - -// test for web worker but not in IE10 -var isWorker = typeof Uint8ClampedArray !== 'undefined' && - typeof importScripts !== 'undefined' && - typeof MessageChannel !== 'undefined'; - -// node -function useNextTick() { - var nextTick = process.nextTick; - // node version 0.10.x displays a deprecation warning when nextTick is used recursively - // setImmediate should be used instead instead - var version = process.versions.node.match(/^(?:(\d+)\.)?(?:(\d+)\.)?(\*|\d+)$/); - if (Array.isArray(version) && version[1] === '0' && version[2] === '10') { - nextTick = setImmediate; - } - return function() { - nextTick(flush); - }; -} - -// vertx -function useVertxTimer() { - return function() { - vertxNext(flush); - }; -} - -function useMutationObserver() { - var iterations = 0; - var observer = new BrowserMutationObserver(flush); - var node = document.createTextNode(''); - observer.observe(node, { characterData: true }); - - return function() { - node.data = (iterations = ++iterations % 2); - }; -} - -// web worker -function useMessageChannel() { - var channel = new MessageChannel(); - channel.port1.onmessage = flush; - return function () { - channel.port2.postMessage(0); - }; -} - -function useSetTimeout() { - return function() { - setTimeout(flush, 1); - }; -} - -var queue = new Array(1000); -function flush() { - for (var i = 0; i < len; i+=2) { - var callback = queue[i]; - var arg = queue[i+1]; - - callback(arg); - - queue[i] = undefined; - queue[i+1] = undefined; - } - - len = 0; -} - -function attemptVertex() { - try { - var r = require; - var vertx = r('vertx'); - vertxNext = vertx.runOnLoop || vertx.runOnContext; - return useVertxTimer(); - } catch(e) { - return useSetTimeout(); - } -} - -var scheduleFlush; -// Decide what async method to use to triggering processing of queued callbacks: -if (isNode) { - scheduleFlush = useNextTick(); -} else if (BrowserMutationObserver) { - scheduleFlush = useMutationObserver(); -} else if (isWorker) { - scheduleFlush = useMessageChannel(); -} else if (browserWindow === undefined && typeof require === 'function') { - scheduleFlush = attemptVertex(); -} else { - scheduleFlush = useSetTimeout(); -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js deleted file mode 100644 index 03fdf8c..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/enumerator.js +++ /dev/null @@ -1,113 +0,0 @@ -import { - isArray, - isMaybeThenable -} from './utils'; - -import { - noop, - reject, - fulfill, - subscribe, - FULFILLED, - REJECTED, - PENDING -} from './-internal'; - -function Enumerator(Constructor, input) { - var enumerator = this; - - enumerator._instanceConstructor = Constructor; - enumerator.promise = new Constructor(noop); - - if (enumerator._validateInput(input)) { - enumerator._input = input; - enumerator.length = input.length; - enumerator._remaining = input.length; - - enumerator._init(); - - if (enumerator.length === 0) { - fulfill(enumerator.promise, enumerator._result); - } else { - enumerator.length = enumerator.length || 0; - enumerator._enumerate(); - if (enumerator._remaining === 0) { - fulfill(enumerator.promise, enumerator._result); - } - } - } else { - reject(enumerator.promise, enumerator._validationError()); - } -} - -Enumerator.prototype._validateInput = function(input) { - return isArray(input); -}; - -Enumerator.prototype._validationError = function() { - return new Error('Array Methods must be provided an Array'); -}; - -Enumerator.prototype._init = function() { - this._result = new Array(this.length); -}; - -export default Enumerator; - -Enumerator.prototype._enumerate = function() { - var enumerator = this; - - var length = enumerator.length; - var promise = enumerator.promise; - var input = enumerator._input; - - for (var i = 0; promise._state === PENDING && i < length; i++) { - enumerator._eachEntry(input[i], i); - } -}; - -Enumerator.prototype._eachEntry = function(entry, i) { - var enumerator = this; - var c = enumerator._instanceConstructor; - - if (isMaybeThenable(entry)) { - if (entry.constructor === c && entry._state !== PENDING) { - entry._onerror = null; - enumerator._settledAt(entry._state, i, entry._result); - } else { - enumerator._willSettleAt(c.resolve(entry), i); - } - } else { - enumerator._remaining--; - enumerator._result[i] = entry; - } -}; - -Enumerator.prototype._settledAt = function(state, i, value) { - var enumerator = this; - var promise = enumerator.promise; - - if (promise._state === PENDING) { - enumerator._remaining--; - - if (state === REJECTED) { - reject(promise, value); - } else { - enumerator._result[i] = value; - } - } - - if (enumerator._remaining === 0) { - fulfill(promise, enumerator._result); - } -}; - -Enumerator.prototype._willSettleAt = function(promise, i) { - var enumerator = this; - - subscribe(promise, undefined, function(value) { - enumerator._settledAt(FULFILLED, i, value); - }, function(reason) { - enumerator._settledAt(REJECTED, i, reason); - }); -}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js deleted file mode 100644 index 6696dfc..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/polyfill.js +++ /dev/null @@ -1,26 +0,0 @@ -/*global self*/ -import Promise from './promise'; - -export default function polyfill() { - var local; - - if (typeof global !== 'undefined') { - local = global; - } else if (typeof self !== 'undefined') { - local = self; - } else { - try { - local = Function('return this')(); - } catch (e) { - throw new Error('polyfill failed because global object is unavailable in this environment'); - } - } - - var P = local.Promise; - - if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) { - return; - } - - local.Promise = Promise; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js deleted file mode 100644 index 78fe2ca..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise.js +++ /dev/null @@ -1,408 +0,0 @@ -import { - isFunction -} from './utils'; - -import { - noop, - subscribe, - initializePromise, - invokeCallback, - FULFILLED, - REJECTED -} from './-internal'; - -import asap from './asap'; - -import all from './promise/all'; -import race from './promise/race'; -import Resolve from './promise/resolve'; -import Reject from './promise/reject'; - -var counter = 0; - -function needsResolver() { - throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); -} - -function needsNew() { - throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); -} - -export default Promise; -/** - Promise objects represent the eventual result of an asynchronous operation. The - primary way of interacting with a promise is through its `then` method, which - registers callbacks to receive either a promise’s eventual value or the reason - why the promise cannot be fulfilled. - - Terminology - ----------- - - - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - - `thenable` is an object or function that defines a `then` method. - - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - - `exception` is a value that is thrown using the throw statement. - - `reason` is a value that indicates why a promise was rejected. - - `settled` the final resting state of a promise, fulfilled or rejected. - - A promise can be in one of three states: pending, fulfilled, or rejected. - - Promises that are fulfilled have a fulfillment value and are in the fulfilled - state. Promises that are rejected have a rejection reason and are in the - rejected state. A fulfillment value is never a thenable. - - Promises can also be said to *resolve* a value. If this value is also a - promise, then the original promise's settled state will match the value's - settled state. So a promise that *resolves* a promise that rejects will - itself reject, and a promise that *resolves* a promise that fulfills will - itself fulfill. - - - Basic Usage: - ------------ - - ```js - var promise = new Promise(function(resolve, reject) { - // on success - resolve(value); - - // on failure - reject(reason); - }); - - promise.then(function(value) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Advanced Usage: - --------------- - - Promises shine when abstracting away asynchronous interactions such as - `XMLHttpRequest`s. - - ```js - function getJSON(url) { - return new Promise(function(resolve, reject){ - var xhr = new XMLHttpRequest(); - - xhr.open('GET', url); - xhr.onreadystatechange = handler; - xhr.responseType = 'json'; - xhr.setRequestHeader('Accept', 'application/json'); - xhr.send(); - - function handler() { - if (this.readyState === this.DONE) { - if (this.status === 200) { - resolve(this.response); - } else { - reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); - } - } - }; - }); - } - - getJSON('/posts.json').then(function(json) { - // on fulfillment - }, function(reason) { - // on rejection - }); - ``` - - Unlike callbacks, promises are great composable primitives. - - ```js - Promise.all([ - getJSON('/posts'), - getJSON('/comments') - ]).then(function(values){ - values[0] // => postsJSON - values[1] // => commentsJSON - - return values; - }); - ``` - - @class Promise - @param {function} resolver - Useful for tooling. - @constructor -*/ -function Promise(resolver) { - this._id = counter++; - this._state = undefined; - this._result = undefined; - this._subscribers = []; - - if (noop !== resolver) { - if (!isFunction(resolver)) { - needsResolver(); - } - - if (!(this instanceof Promise)) { - needsNew(); - } - - initializePromise(this, resolver); - } -} - -Promise.all = all; -Promise.race = race; -Promise.resolve = Resolve; -Promise.reject = Reject; - -Promise.prototype = { - constructor: Promise, - -/** - The primary way of interacting with a promise is through its `then` method, - which registers callbacks to receive either a promise's eventual value or the - reason why the promise cannot be fulfilled. - - ```js - findUser().then(function(user){ - // user is available - }, function(reason){ - // user is unavailable, and you are given the reason why - }); - ``` - - Chaining - -------- - - The return value of `then` is itself a promise. This second, 'downstream' - promise is resolved with the return value of the first promise's fulfillment - or rejection handler, or rejected if the handler throws an exception. - - ```js - findUser().then(function (user) { - return user.name; - }, function (reason) { - return 'default name'; - }).then(function (userName) { - // If `findUser` fulfilled, `userName` will be the user's name, otherwise it - // will be `'default name'` - }); - - findUser().then(function (user) { - throw new Error('Found user, but still unhappy'); - }, function (reason) { - throw new Error('`findUser` rejected and we're unhappy'); - }).then(function (value) { - // never reached - }, function (reason) { - // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. - // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. - }); - ``` - If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. - - ```js - findUser().then(function (user) { - throw new PedagogicalException('Upstream error'); - }).then(function (value) { - // never reached - }).then(function (value) { - // never reached - }, function (reason) { - // The `PedgagocialException` is propagated all the way down to here - }); - ``` - - Assimilation - ------------ - - Sometimes the value you want to propagate to a downstream promise can only be - retrieved asynchronously. This can be achieved by returning a promise in the - fulfillment or rejection handler. The downstream promise will then be pending - until the returned promise is settled. This is called *assimilation*. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // The user's comments are now available - }); - ``` - - If the assimliated promise rejects, then the downstream promise will also reject. - - ```js - findUser().then(function (user) { - return findCommentsByAuthor(user); - }).then(function (comments) { - // If `findCommentsByAuthor` fulfills, we'll have the value here - }, function (reason) { - // If `findCommentsByAuthor` rejects, we'll have the reason here - }); - ``` - - Simple Example - -------------- - - Synchronous Example - - ```javascript - var result; - - try { - result = findResult(); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - findResult(function(result, err){ - if (err) { - // failure - } else { - // success - } - }); - ``` - - Promise Example; - - ```javascript - findResult().then(function(result){ - // success - }, function(reason){ - // failure - }); - ``` - - Advanced Example - -------------- - - Synchronous Example - - ```javascript - var author, books; - - try { - author = findAuthor(); - books = findBooksByAuthor(author); - // success - } catch(reason) { - // failure - } - ``` - - Errback Example - - ```js - - function foundBooks(books) { - - } - - function failure(reason) { - - } - - findAuthor(function(author, err){ - if (err) { - failure(err); - // failure - } else { - try { - findBoooksByAuthor(author, function(books, err) { - if (err) { - failure(err); - } else { - try { - foundBooks(books); - } catch(reason) { - failure(reason); - } - } - }); - } catch(error) { - failure(err); - } - // success - } - }); - ``` - - Promise Example; - - ```javascript - findAuthor(). - then(findBooksByAuthor). - then(function(books){ - // found books - }).catch(function(reason){ - // something went wrong - }); - ``` - - @method then - @param {Function} onFulfilled - @param {Function} onRejected - Useful for tooling. - @return {Promise} -*/ - then: function(onFulfillment, onRejection) { - var parent = this; - var state = parent._state; - - if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { - return this; - } - - var child = new this.constructor(noop); - var result = parent._result; - - if (state) { - var callback = arguments[state - 1]; - asap(function(){ - invokeCallback(state, child, callback, result); - }); - } else { - subscribe(parent, child, onFulfillment, onRejection); - } - - return child; - }, - -/** - `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same - as the catch block of a try/catch statement. - - ```js - function findAuthor(){ - throw new Error('couldn't find that author'); - } - - // synchronous - try { - findAuthor(); - } catch(reason) { - // something went wrong - } - - // async with promises - findAuthor().catch(function(reason){ - // something went wrong - }); - ``` - - @method catch - @param {Function} onRejection - Useful for tooling. - @return {Promise} -*/ - 'catch': function(onRejection) { - return this.then(null, onRejection); - } -}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js deleted file mode 100644 index 03033f0..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/all.js +++ /dev/null @@ -1,52 +0,0 @@ -import Enumerator from '../enumerator'; - -/** - `Promise.all` accepts an array of promises, and returns a new promise which - is fulfilled with an array of fulfillment values for the passed promises, or - rejected with the reason of the first passed promise to be rejected. It casts all - elements of the passed iterable to promises as it runs this algorithm. - - Example: - - ```javascript - var promise1 = resolve(1); - var promise2 = resolve(2); - var promise3 = resolve(3); - var promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // The array here would be [ 1, 2, 3 ]; - }); - ``` - - If any of the `promises` given to `all` are rejected, the first promise - that is rejected will be given as an argument to the returned promises's - rejection handler. For example: - - Example: - - ```javascript - var promise1 = resolve(1); - var promise2 = reject(new Error("2")); - var promise3 = reject(new Error("3")); - var promises = [ promise1, promise2, promise3 ]; - - Promise.all(promises).then(function(array){ - // Code here never runs because there are rejected promises! - }, function(error) { - // error.message === "2" - }); - ``` - - @method all - @static - @param {Array} entries array of promises - @param {String} label optional string for labeling the promise. - Useful for tooling. - @return {Promise} promise that is fulfilled when all `promises` have been - fulfilled, or rejected if any of them become rejected. - @static -*/ -export default function all(entries) { - return new Enumerator(this, entries).promise; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js deleted file mode 100644 index 0d7ff13..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/race.js +++ /dev/null @@ -1,104 +0,0 @@ -import { - isArray -} from "../utils"; - -import { - noop, - resolve, - reject, - subscribe, - PENDING -} from '../-internal'; - -/** - `Promise.race` returns a new promise which is settled in the same way as the - first passed promise to settle. - - Example: - - ```javascript - var promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - var promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 2'); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // result === 'promise 2' because it was resolved before promise1 - // was resolved. - }); - ``` - - `Promise.race` is deterministic in that only the state of the first - settled promise matters. For example, even if other promises given to the - `promises` array argument are resolved, but the first settled promise has - become rejected before the other promises became fulfilled, the returned - promise will become rejected: - - ```javascript - var promise1 = new Promise(function(resolve, reject){ - setTimeout(function(){ - resolve('promise 1'); - }, 200); - }); - - var promise2 = new Promise(function(resolve, reject){ - setTimeout(function(){ - reject(new Error('promise 2')); - }, 100); - }); - - Promise.race([promise1, promise2]).then(function(result){ - // Code here never runs - }, function(reason){ - // reason.message === 'promise 2' because promise 2 became rejected before - // promise 1 became fulfilled - }); - ``` - - An example real-world use case is implementing timeouts: - - ```javascript - Promise.race([ajax('foo.json'), timeout(5000)]) - ``` - - @method race - @static - @param {Array} promises array of promises to observe - Useful for tooling. - @return {Promise} a promise which settles in the same way as the first passed - promise to settle. -*/ -export default function race(entries) { - /*jshint validthis:true */ - var Constructor = this; - - var promise = new Constructor(noop); - - if (!isArray(entries)) { - reject(promise, new TypeError('You must pass an array to race.')); - return promise; - } - - var length = entries.length; - - function onFulfillment(value) { - resolve(promise, value); - } - - function onRejection(reason) { - reject(promise, reason); - } - - for (var i = 0; promise._state === PENDING && i < length; i++) { - subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); - } - - return promise; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js deleted file mode 100644 index 63b86cb..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/reject.js +++ /dev/null @@ -1,46 +0,0 @@ -import { - noop, - reject as _reject -} from '../-internal'; - -/** - `Promise.reject` returns a promise rejected with the passed `reason`. - It is shorthand for the following: - - ```javascript - var promise = new Promise(function(resolve, reject){ - reject(new Error('WHOOPS')); - }); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = Promise.reject(new Error('WHOOPS')); - - promise.then(function(value){ - // Code here doesn't run because the promise is rejected! - }, function(reason){ - // reason.message === 'WHOOPS' - }); - ``` - - @method reject - @static - @param {Any} reason value that the returned promise will be rejected with. - Useful for tooling. - @return {Promise} a promise rejected with the given `reason`. -*/ -export default function reject(reason) { - /*jshint validthis:true */ - var Constructor = this; - var promise = new Constructor(noop); - _reject(promise, reason); - return promise; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js deleted file mode 100644 index 201a545..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/promise/resolve.js +++ /dev/null @@ -1,48 +0,0 @@ -import { - noop, - resolve as _resolve -} from '../-internal'; - -/** - `Promise.resolve` returns a promise that will become resolved with the - passed `value`. It is shorthand for the following: - - ```javascript - var promise = new Promise(function(resolve, reject){ - resolve(1); - }); - - promise.then(function(value){ - // value === 1 - }); - ``` - - Instead of writing the above, your code now simply becomes the following: - - ```javascript - var promise = Promise.resolve(1); - - promise.then(function(value){ - // value === 1 - }); - ``` - - @method resolve - @static - @param {Any} value value that the returned promise will be resolved with - Useful for tooling. - @return {Promise} a promise that will become fulfilled with the given - `value` -*/ -export default function resolve(object) { - /*jshint validthis:true */ - var Constructor = this; - - if (object && typeof object === 'object' && object.constructor === Constructor) { - return object; - } - - var promise = new Constructor(noop); - _resolve(promise, object); - return promise; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js deleted file mode 100644 index 31ec6f9..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/lib/es6-promise/utils.js +++ /dev/null @@ -1,22 +0,0 @@ -export function objectOrFunction(x) { - return typeof x === 'function' || (typeof x === 'object' && x !== null); -} - -export function isFunction(x) { - return typeof x === 'function'; -} - -export function isMaybeThenable(x) { - return typeof x === 'object' && x !== null; -} - -var _isArray; -if (!Array.isArray) { - _isArray = function (x) { - return Object.prototype.toString.call(x) === '[object Array]'; - }; -} else { - _isArray = Array.isArray; -} - -export var isArray = _isArray; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/package.json b/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/package.json deleted file mode 100644 index 6fc9a80..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/es6-promise/package.json +++ /dev/null @@ -1,88 +0,0 @@ -{ - "name": "es6-promise", - "namespace": "es6-promise", - "version": "2.1.1", - "description": "A lightweight library that provides tools for organizing asynchronous code", - "main": "dist/es6-promise.js", - "directories": { - "lib": "lib" - }, - "files": [ - "dist", - "lib" - ], - "devDependencies": { - "bower": "^1.3.9", - "brfs": "0.0.8", - "broccoli-es3-safe-recast": "0.0.8", - "broccoli-es6-module-transpiler": "^0.5.0", - "broccoli-jshint": "^0.5.1", - "broccoli-merge-trees": "^0.1.4", - "broccoli-replace": "^0.2.0", - "broccoli-stew": "0.0.6", - "broccoli-uglify-js": "^0.1.3", - "broccoli-watchify": "^0.2.0", - "ember-cli": "^0.2.2", - "ember-publisher": "0.0.7", - "git-repo-version": "0.0.2", - "json3": "^3.3.2", - "minimatch": "^2.0.1", - "mocha": "^1.20.1", - "promises-aplus-tests-phantom": "^2.1.0-revise", - "release-it": "0.0.10" - }, - "scripts": { - "build": "ember build", - "start": "ember s", - "test": "ember test", - "test:server": "ember test --server", - "test:node": "ember build && mocha ./dist/test/browserify", - "lint": "jshint lib", - "prepublish": "ember build --environment production", - "dry-run-release": "ember build --environment production && release-it --dry-run --non-interactive" - }, - "repository": { - "type": "git", - "url": "git://github.com/jakearchibald/ES6-Promises.git" - }, - "bugs": { - "url": "https://github.com/jakearchibald/ES6-Promises/issues" - }, - "browser": { - "vertx": false - }, - "keywords": [ - "promises", - "futures" - ], - "author": { - "name": "Yehuda Katz, Tom Dale, Stefan Penner and contributors", - "url": "Conversion to ES6 API by Jake Archibald" - }, - "license": "MIT", - "spm": { - "main": "dist/es6-promise.js" - }, - "gitHead": "02cf697c50856f0cd3785f425a2cf819af0e521c", - "homepage": "https://github.com/jakearchibald/ES6-Promises", - "_id": "es6-promise@2.1.1", - "_shasum": "03e8f3c7297928e5478d6ab1d0643251507bdedd", - "_from": "es6-promise@2.1.1", - "_npmVersion": "2.5.1", - "_nodeVersion": "0.12.1", - "_npmUser": { - "name": "jaffathecake", - "email": "jaffathecake@gmail.com" - }, - "maintainers": [ - { - "name": "jaffathecake", - "email": "jaffathecake@gmail.com" - } - ], - "dist": { - "shasum": "03e8f3c7297928e5478d6ab1d0643251507bdedd", - "tarball": "http://registry.npmjs.org/es6-promise/-/es6-promise-2.1.1.tgz" - }, - "_resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-2.1.1.tgz" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md deleted file mode 100644 index a21da87..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/HISTORY.md +++ /dev/null @@ -1,246 +0,0 @@ -1.2.14 09-28-2015 ------------------ -- NODE-547 only emit error if there are any listeners. -- Fixed APM issue with issuing readConcern. - -1.2.13 09-18-2015 ------------------ -- Added BSON serializer ignoreUndefined option for insert/update/remove/command/cursor. - -1.2.12 09-08-2015 ------------------ -- NODE-541 Added initial support for readConcern. - -1.2.11 08-31-2015 ------------------ -- NODE-535 If connectWithNoPrimary is true then primary-only connection is not allowed. -- NODE-534 Passive secondaries are not allowed for secondaryOnlyConnectionAllowed. -- Fixed filtering bug for logging (Issue 30, https://github.com/christkv/mongodb-core/issues/30). - -1.2.10 08-14-2015 ------------------ -- Added missing Mongos.prototype.parserType function. - -1.2.9 08-05-2015 ----------------- -- NODE-525 Reset connectionTimeout after it's overwritten by tls.connect. -- NODE-518 connectTimeoutMS is doubled in 2.0.39. - -1.2.8 07-24-2015 ------------------ -- Minor fix to handle 2.4.x errors better by correctly return driver layer issues. - -1.2.7 07-16-2015 ------------------ -- Refactoring to allow to tap into find/getmore/killcursor in cursors for APM monitoring in driver. - -1.2.6 07-14-2015 ------------------ -- NODE-505 Query fails to find records that have a 'result' property with an array value. - -1.2.5 07-14-2015 ------------------ -- NODE-492 correctly handle hanging replicaset monitoring connections when server is unavailable due to network partitions or firewalls dropping packets, configureable using the connectionTimeoutMS setting. - -1.2.4 07-07-2015 ------------------ -- NODE-493 staggering the socket connections to avoid overwhelming the mongod process. - -1.2.3 06-26-2015 ------------------ -- Minor bug fixes. - -1.2.2 06-22-2015 ------------------ -- Fix issue with SCRAM authentication causing authentication to return true on failed authentication (Issue 26, https://github.com/cglass17). - -1.2.1 06-17-2015 ------------------ -- Ensure serializeFunctions passed down correctly to wire protocol. - -1.2.0 06-17-2015 ------------------ -- Switching to using the 0.4.x pure JS serializer, removing dependency on C++ parser. -- Refactoring wire protocol messages to avoid expensive size calculations of documents in favor of writing out an array of buffers to the sockets. -- NODE-486 fixed issue related to limit and skip when calling toArray in 2.0 driver. -- NODE-483 throw error if capabilities of topology is queries before topology has performed connection setup. -- NODE-487 fixed issue where killcursor command was not being sent correctly on limit and skip queries. - -1.1.33 05-31-2015 ------------------ -- NODE-478 Work around authentication race condition in mongos authentication due to multi step authentication methods like SCRAM. - -1.1.32 05-20-2015 ------------------ -- After reconnect, it updates the allowable reconnect retries to the option settings (Issue #23, https://github.com/owenallenaz) - -1.1.31 05-19-2015 ------------------ -- Minor fixes for issues with re-authentication of mongos. - -1.1.30 05-18-2015 ------------------ -- Correctly emit 'all' event when primary + all secondaries have connected. - -1.1.29 05-17-2015 ------------------ -- NODE-464 Only use a single socket against arbiters and hidden servers. -- Ensure we filter out hidden servers from any server queries. - -1.1.28 05-12-2015 ------------------ -- Fixed buffer compare for electionId for < node 12.0.2 - -1.1.27 05-12-2015 ------------------ -- NODE-455 Update SDAM specification support to cover electionId and Mongos load balancing. - -1.1.26 05-06-2015 ------------------ -- NODE-456 Allow mongodb-core to pipeline commands (ex findAndModify+GLE) along the same connection and handle the returned results. -- Fixes to make mongodb-core work for node 0.8.x when using scram and setImmediate. - -1.1.25 04-24-2015 ------------------ -- Handle lack of callback in crud operations when returning error on application closed. - -1.1.24 04-22-2015 ------------------ -- Error out when topology has been destroyed either by connection retries being exhausted or destroy called on topology. - -1.1.23 04-15-2015 ------------------ -- Standardizing mongoErrors and its API (Issue #14) -- Creating a new connection is slow because of 100ms setTimeout() (Issue #17, https://github.com/vkarpov15) -- remove mkdirp and rimraf dependencies (Issue #12) -- Updated default value of param options.rejectUnauthorized to match documentation (Issue #16) -- ISSUE: NODE-417 Resolution. Improving behavior of thrown errors (Issue #14, https://github.com/owenallenaz) -- Fix cursor hanging when next() called on exhausted cursor (Issue #18, https://github.com/vkarpov15) - -1.1.22 04-10-2015 ------------------ -- Minor refactorings in cursor code to make extending the cursor simpler. -- NODE-417 Resolution. Improving behavior of thrown errors using Error.captureStackTrace. - -1.1.21 03-26-2015 ------------------ -- Updated bson module to 0.3.0 that extracted the c++ parser into bson-ext and made it an optional dependency. - -1.1.20 03-24-2015 ------------------ -- NODE-395 Socket Not Closing, db.close called before full set finished initalizing leading to server connections in progress not being closed properly. - -1.1.19 03-21-2015 ------------------ -- Made kerberos module ~0.0 to allow for quicker releases due to io.js of kerberos module. - -1.1.18 03-17-2015 ------------------ -- Added support for minHeartbeatFrequencyMS on server reconnect according to the SDAM specification. - -1.1.17 03-16-2015 ------------------ -- NODE-377, fixed issue where tags would correctly be checked on secondary and nearest to filter out eligible server candidates. - -1.1.16 03-06-2015 ------------------ -- rejectUnauthorized parameter is set to true for ssl certificates by default instead of false. - -1.1.15 03-04-2015 ------------------ -- Removed check for type in replset pickserver function. - -1.1.14 02-26-2015 ------------------ -- NODE-374 correctly adding passive secondaries to the list of eligable servers for reads - -1.1.13 02-24-2015 ------------------ -- NODE-365 mongoDB native node.js driver infinite reconnect attempts (fixed issue around handling of retry attempts) - -1.1.12 02-16-2015 ------------------ -- Fixed cursor transforms for buffered document reads from cursor. - -1.1.11 02-02-2015 ------------------ -- Remove the required setName for replicaset connections, if not set it will pick the first setName returned. - -1.1.10 31-01-2015 ------------------ -- Added tranforms.doc option to cursor to allow for pr. document transformations. - -1.1.9 21-01-2015 ----------------- -- Updated BSON dependency to 0.2.18 to fix issues with io.js and node. -- Updated Kerberos dependency to 0.0.8 to fix issues with io.js and node. -- Don't treat findOne() as a command cursor. -- Refactored out state changes into methods to simplify read the next method. - -1.1.8 09-12-2015 ----------------- -- Stripped out Object.defineProperty for performance reasons -- Applied more performance optimizations. -- properties cursorBatchSize, cursorSkip, cursorLimit are not methods setCursorBatchSize/cursorBatchSize, setCursorSkip/cursorSkip, setCursorLimit/cursorLimit - -1.1.7 18-12-2014 ----------------- -- Use ns variable for getMore commands for command cursors to work properly with cursor version of listCollections and listIndexes. - -1.1.6 18-12-2014 ----------------- -- Server manager fixed to support 2.2.X servers for travis test matrix. - -1.1.5 17-12-2014 ----------------- -- Fall back to errmsg when creating MongoError for command errors - -1.1.4 17-12-2014 ----------------- -- Added transform method support for cursor (initially just for initial query results) to support listCollections/listIndexes in 2.8. -- Fixed variable leak in scram. -- Fixed server manager to deal better with killing processes. -- Bumped bson to 0.2.16. - -1.1.3 01-12-2014 ----------------- -- Fixed error handling issue with nonce generation in mongocr. -- Fixed issues with restarting servers when using ssl. -- Using strict for all classes. -- Cleaned up any escaping global variables. - -1.1.2 20-11-2014 ----------------- -- Correctly encoding UTF8 collection names on wire protocol messages. -- Added emitClose parameter to topology destroy methods to allow users to specify that they wish the topology to emit the close event to any listeners. - -1.1.1 14-11-2014 ----------------- -- Refactored code to use prototype instead of privileged methods. -- Fixed issue with auth where a runtime condition could leave replicaset members without proper authentication. -- Several deopt optimizations for v8 to improve performance and reduce GC pauses. - -1.0.5 29-10-2014 ----------------- -- Fixed issue with wrong namespace being created for command cursors. - -1.0.4 24-10-2014 ----------------- -- switched from using shift for the cursor due to bad slowdown on big batchSizes as shift causes entire array to be copied on each call. - -1.0.3 21-10-2014 ----------------- -- fixed error issuing problem on cursor.next when iterating over a huge dataset with a very small batchSize. - -1.0.2 07-10-2014 ----------------- -- fullsetup is now defined as a primary and secondary being available allowing for all read preferences to be satisfied. -- fixed issue with replset_state logging. - -1.0.1 07-10-2014 ----------------- -- Dependency issue solved - -1.0.0 07-10-2014 ----------------- -- Initial release of mongodb-core diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE deleted file mode 100644 index ad410e1..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ -Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - 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. \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile deleted file mode 100644 index 36e1202..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -NODE = node -NPM = npm -JSDOC = jsdoc -name = all - -generate_docs: - # cp -R ./HISTORY.md ./docs/content/meta/release-notes.md - hugo -s docs/reference -d ../../public - $(JSDOC) -c conf.json -t docs/jsdoc-template/ -d ./public/api - cp -R ./public/api/scripts ./public/. - cp -R ./public/api/styles ./public/. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/README.md deleted file mode 100644 index 1c9e4c8..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/README.md +++ /dev/null @@ -1,225 +0,0 @@ -# Description - -The MongoDB Core driver is the low level part of the 2.0 or higher MongoDB driver and is meant for library developers not end users. It does not contain any abstractions or helpers outside of the basic management of MongoDB topology connections, CRUD operations and authentication. - -## MongoDB Node.JS Core Driver - -| what | where | -|---------------|------------------------------------------------| -| documentation | http://mongodb.github.io/node-mongodb-native/ | -| apidoc | http://mongodb.github.io/node-mongodb-native/ | -| source | https://github.com/christkv/mongodb-core | -| mongodb | http://www.mongodb.org/ | - -### Blogs of Engineers involved in the driver -- Christian Kvalheim [@christkv](https://twitter.com/christkv) - -### Bugs / Feature Requests - -Think you’ve found a bug? Want to see a new feature in node-mongodb-native? Please open a -case in our issue management tool, JIRA: - -- Create an account and login . -- Navigate to the NODE project . -- Click **Create Issue** - Please provide as much information as possible about the issue type and how to reproduce it. - -Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the -Core Server (i.e. SERVER) project are **public**. - -### Questions and Bug Reports - - * mailing list: https://groups.google.com/forum/#!forum/node-mongodb-native - * jira: http://jira.mongodb.org/ - -### Change Log - -http://jira.mongodb.org/browse/NODE - -# QuickStart - -The quick start guide will show you how to set up a simple application using Core driver and MongoDB. It scope is only how to set up the driver and perform the simple crud operations. For more inn depth coverage we encourage reading the tutorials. - -## Create the package.json file - -Let's create a directory where our application will live. In our case we will put this under our projects directory. - -``` -mkdir myproject -cd myproject -``` - -Create a **package.json** using your favorite text editor and fill it in. - -```json -{ - "name": "myproject", - "version": "1.0.0", - "description": "My first project", - "main": "index.js", - "repository": { - "type": "git", - "url": "git://github.com/christkv/myfirstproject.git" - }, - "dependencies": { - "mongodb-core": "~1.0" - }, - "author": "Christian Kvalheim", - "license": "Apache 2.0", - "bugs": { - "url": "https://github.com/christkv/myfirstproject/issues" - }, - "homepage": "https://github.com/christkv/myfirstproject" -} -``` - -Save the file and return to the shell or command prompt and use **NPM** to install all the dependencies. - -``` -npm install -``` - -You should see **NPM** download a lot of files. Once it's done you'll find all the downloaded packages under the **node_modules** directory. - -Booting up a MongoDB Server ---------------------------- -Let's boot up a MongoDB server instance. Download the right MongoDB version from [MongoDB](http://www.mongodb.org), open a new shell or command line and ensure the **mongod** command is in the shell or command line path. Now let's create a database directory (in our case under **/data**). - -``` -mongod --dbpath=/data --port 27017 -``` - -You should see the **mongod** process start up and print some status information. - -## Connecting to MongoDB - -Let's create a new **app.js** file that we will use to show the basic CRUD operations using the MongoDB driver. - -First let's add code to connect to the server. Notice that there is no concept of a database here and we use the topology directly to perform the connection. - -```js -var Server = require('mongodb-core').Server - , assert = require('assert'); - -// Set up server connection -var server = new Server({ - host: 'localhost' - , port: 27017 - , reconnect: true - , reconnectInterval: 50 -}); - -// Add event listeners -server.on('connect', function(_server) { - console.log('connected'); - test.done(); -}); - -server.on('close', function() { - console.log('closed'); -}); - -server.on('reconnect', function() { - console.log('reconnect'); -}); - -// Start connection -server.connect(); -``` - -To connect to a replicaset we would use the `ReplSet` class and for a set of Mongos proxies we use the `Mongos` class. Each topology class offer the same CRUD operations and you operate on the topology directly. Let's look at an example exercising all the different available CRUD operations. - -```js -var Server = require('mongodb-core').Server - , assert = require('assert'); - -// Set up server connection -var server = new Server({ - host: 'localhost' - , port: 27017 - , reconnect: true - , reconnectInterval: 50 -}); - -// Add event listeners -server.on('connect', function(_server) { - console.log('connected'); - - // Execute the ismaster command - _server.command('system.$cmd', {ismaster: true}, function(err, result) { - - // Perform a document insert - _server.insert('myproject.inserts1', [{a:1}, {a:2}], { - writeConcern: {w:1}, ordered:true - }, function(err, results) { - assert.equal(null, err); - assert.equal(2, results.result.n); - - // Perform a document update - _server.update('myproject.inserts1', [{ - q: {a: 1}, u: {'$set': {b:1}} - }], { - writeConcern: {w:1}, ordered:true - }, function(err, results) { - assert.equal(null, err); - assert.equal(1, results.result.n); - - // Remove a document - _server.remove('myproject.inserts1', [{ - q: {a: 1}, limit: 1 - }], { - writeConcern: {w:1}, ordered:true - }, function(err, results) { - assert.equal(null, err); - assert.equal(1, results.result.n); - - // Get a document - var cursor = _server.cursor('integration_tests.inserts_example4', { - find: 'integration_tests.example4' - , query: {a:1} - }); - - // Get the first document - cursor.next(function(err, doc) { - assert.equal(null, err); - assert.equal(2, doc.a); - - // Execute the ismaster command - _server.command("system.$cmd" - , {ismaster: true}, function(err, result) { - assert.equal(null, err) - _server.destroy(); - }); - }); - }); - }); - - test.done(); - }); -}); - -server.on('close', function() { - console.log('closed'); -}); - -server.on('reconnect', function() { - console.log('reconnect'); -}); - -// Start connection -server.connect(); -``` - -The core driver does not contain any helpers or abstractions only the core crud operations. These consist of the following commands. - -* `insert`, Insert takes an array of 1 or more documents to be inserted against the topology and allows you to specify a write concern and if you wish to execute the inserts in order or out of order. -* `update`, Update takes an array of 1 or more update commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the updates in order or out of order. -* `remove`, Remove takes an array of 1 or more remove commands to be executed against the server topology and also allows you to specify a write concern and if you wish to execute the removes in order or out of order. -* `cursor`, Returns you a cursor for either the 'virtual' `find` command, a command that returns a cursor id or a plain cursor id. Read the cursor tutorial for more inn depth coverage. -* `command`, Executes a command against MongoDB and returns the result. -* `auth`, Authenticates the current topology using a supported authentication scheme. - -The Core Driver is a building block for library builders and is not meant for usage by end users as it lacks a lot of features the end user might need such as automatic buffering of operations when a primary is changing in a replicaset or the db and collections abstraction. - -## Next steps - -The next step is to get more in depth information about how the different aspects of the core driver works and how to leverage them to extend the functionality of the cursors. Please view the tutorials for more detailed information. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md deleted file mode 100644 index fe03ea0..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/TESTING.md +++ /dev/null @@ -1,18 +0,0 @@ -Testing setup -============= - -Single Server -------------- -mongod --dbpath=./db - -Replicaset ----------- -mongo --nodb -var x = new ReplSetTest({"useHostName":"false", "nodes" : {node0 : {}, node1 : {}, node2 : {}}}) -x.startSet(); -var config = x.getReplSetConfig() -x.initiate(config); - -Mongos ------- -var s = new ShardingTest( "auth1", 1 , 0 , 2 , {rs: true, noChunkSize : true}); \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json deleted file mode 100644 index c5eca92..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/conf.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "plugins": ["plugins/markdown", "docs/lib/jsdoc/examples_plugin.js"], - "source": { - "include": [ - "test/tests/functional/operation_example_tests.js", - "lib/topologies/mongos.js", - "lib/topologies/command_result.js", - "lib/topologies/read_preference.js", - "lib/topologies/replset.js", - "lib/topologies/server.js", - "lib/topologies/session.js", - "lib/topologies/replset_state.js", - "lib/connection/logger.js", - "lib/connection/connection.js", - "lib/cursor.js", - "lib/error.js", - "node_modules/bson/lib/bson/binary.js", - "node_modules/bson/lib/bson/code.js", - "node_modules/bson/lib/bson/db_ref.js", - "node_modules/bson/lib/bson/double.js", - "node_modules/bson/lib/bson/long.js", - "node_modules/bson/lib/bson/objectid.js", - "node_modules/bson/lib/bson/symbol.js", - "node_modules/bson/lib/bson/timestamp.js", - "node_modules/bson/lib/bson/max_key.js", - "node_modules/bson/lib/bson/min_key.js" - ] - }, - "templates": { - "cleverLinks": true, - "monospaceLinks": true, - "default": { - "outputSourceFiles" : true - }, - "applicationName": "Node.js MongoDB Driver API", - "disqus": true, - "googleAnalytics": "UA-29229787-1", - "openGraph": { - "title": "", - "type": "website", - "image": "", - "site_name": "", - "url": "" - }, - "meta": { - "title": "", - "description": "", - "keyword": "" - }, - "linenums": true - }, - "markdown": { - "parser": "gfm", - "hardwrap": true, - "tags": ["examples"] - }, - "examples": { - "indent": 4 - } -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/index.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/index.js deleted file mode 100644 index 8f10860..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/index.js +++ /dev/null @@ -1,18 +0,0 @@ -module.exports = { - MongoError: require('./lib/error') - , Server: require('./lib/topologies/server') - , ReplSet: require('./lib/topologies/replset') - , Mongos: require('./lib/topologies/mongos') - , Logger: require('./lib/connection/logger') - , Cursor: require('./lib/cursor') - , ReadPreference: require('./lib/topologies/read_preference') - , BSON: require('bson') - // Raw operations - , Query: require('./lib/connection/commands').Query - // Auth mechanisms - , MongoCR: require('./lib/auth/mongocr') - , X509: require('./lib/auth/x509') - , Plain: require('./lib/auth/plain') - , GSSAPI: require('./lib/auth/gssapi') - , ScramSHA1: require('./lib/auth/scram') -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js deleted file mode 100644 index c442b9b..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/gssapi.js +++ /dev/null @@ -1,244 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , MongoError = require('../error'); - -var AuthSession = function(db, username, password, options) { - this.db = db; - this.username = username; - this.password = password; - this.options = options; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; - -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -/** - * Creates a new GSSAPI authentication mechanism - * @class - * @return {GSSAPI} A cursor instance - */ -var GSSAPI = function() { - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -GSSAPI.prototype.auth = function(server, pool, db, username, password, options, callback) { - var self = this; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Start Auth process for a connection - GSSAPIInitialize(db, username, password, db, gssapiServiceName, server, connection, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password, options)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - // Get the connection - execute(connections.shift()); - } -} - -// -// Initialize step -var GSSAPIInitialize = function(db, username, password, authdb, gssapiServiceName, server, connection, callback) { - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); - - // Perform initialization - mongo_auth_process.init(username, password, function(err, context) { - if(err) return callback(err, false); - - // Perform the first step - mongo_auth_process.transition('', function(err, payload) { - if(err) return callback(err, false); - - // Call the next db step - MongoDBGSSAPIFirstStep(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPIFirstStep = function(mongo_auth_process, payload, db, username, password, authdb, server, connection, callback) { - // Build the sasl start command - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: payload - , autoAuthorize: 1 - }; - - // Execute first sasl step - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - // Execute mongodb transition - mongo_auth_process.transition(r.result.payload, function(err, payload) { - if(err) return callback(err, false); - - // MongoDB API Second Step - MongoDBGSSAPISecondStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); - }); - }); -} - -// -// Perform first step against mongodb -var MongoDBGSSAPISecondStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - // Call next transition for kerberos - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err, false); - - // Call the last and third step - MongoDBGSSAPIThirdStep(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback); - }); - }); -} - -var MongoDBGSSAPIThirdStep = function(mongo_auth_process, payload, doc, db, username, password, authdb, server, connection, callback) { - // Build final command - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - mongo_auth_process.transition(null, function(err, payload) { - if(err) return callback(err, null); - callback(null, r); - }); - }); -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -GSSAPI.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = GSSAPI; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js deleted file mode 100644 index d0e9f59..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/mongocr.js +++ /dev/null @@ -1,160 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new MongoCR authentication mechanism - * @class - * @return {MongoCR} A cursor instance - */ -var MongoCR = function() { - this.authStore = []; -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -MongoCR.prototype.auth = function(server, pool, db, username, password, callback) { - var self = this; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var executeMongoCR = function(connection) { - // Let's start the process - server.command(f("%s.$cmd", db) - , { getnonce: 1 } - , { connection: connection }, function(err, r) { - var nonce = null; - var key = null; - - // Adjust the number of connections left - // Get nonce - if(err == null) { - nonce = r.result.nonce; - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - var hash_password = md5.digest('hex'); - // Final key - md5 = crypto.createHash('md5'); - md5.update(nonce + username + hash_password); - key = md5.digest('hex'); - } - - // Execute command - server.command(f("%s.$cmd", db) - , { authenticate: 1, user: username, nonce: nonce, key:key} - , { connection: connection }, function(err, r) { - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - }); - } - - // Get the connection - executeMongoCR(connections.shift()); - } -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -MongoCR.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = MongoCR; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js deleted file mode 100644 index 31ce872..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/plain.js +++ /dev/null @@ -1,150 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , Binary = require('bson').Binary - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new Plain authentication mechanism - * @class - * @return {Plain} A cursor instance - */ -var Plain = function() { - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -Plain.prototype.auth = function(server, pool, db, username, password, callback) { - var self = this; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Create payload - var payload = new Binary(f("\x00%s\x00%s", username, password)); - - // Let's start the sasl process - var command = { - saslStart: 1 - , mechanism: 'PLAIN' - , payload: payload - , autoAuthorize: 1 - }; - - // Let's start the process - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - // Get the connection - execute(connections.shift()); - } -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -Plain.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = Plain; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js deleted file mode 100644 index fe96637..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/scram.js +++ /dev/null @@ -1,317 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , Binary = require('bson').Binary - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new ScramSHA1 authentication mechanism - * @class - * @return {ScramSHA1} A cursor instance - */ -var ScramSHA1 = function() { - this.authStore = []; -} - -var parsePayload = function(payload) { - var dict = {}; - var parts = payload.split(','); - - for(var i = 0; i < parts.length; i++) { - var valueParts = parts[i].split('='); - dict[valueParts[0]] = valueParts[1]; - } - - return dict; -} - -var passwordDigest = function(username, password) { - if(typeof username != 'string') throw new MongoError("username must be a string"); - if(typeof password != 'string') throw new MongoError("password must be a string"); - if(password.length == 0) throw new MongoError("password cannot be empty"); - // Use node md5 generator - var md5 = crypto.createHash('md5'); - // Generate keys used for authentication - md5.update(username + ":mongo:" + password); - return md5.digest('hex'); -} - -// XOR two buffers -var xor = function(a, b) { - if (!Buffer.isBuffer(a)) a = new Buffer(a) - if (!Buffer.isBuffer(b)) b = new Buffer(b) - var res = [] - if (a.length > b.length) { - for (var i = 0; i < b.length; i++) { - res.push(a[i] ^ b[i]) - } - } else { - for (var i = 0; i < a.length; i++) { - res.push(a[i] ^ b[i]) - } - } - return new Buffer(res); -} - -// Create a final digest -var hi = function(data, salt, iterations) { - // Create digest - var digest = function(msg) { - var hmac = crypto.createHmac('sha1', data); - hmac.update(msg); - return new Buffer(hmac.digest('base64'), 'base64'); - } - - // Create variables - salt = Buffer.concat([salt, new Buffer('\x00\x00\x00\x01')]) - var ui = digest(salt); - var u1 = ui; - - for(var i = 0; i < iterations - 1; i++) { - u1 = digest(u1); - ui = xor(ui, u1); - } - - return ui; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -ScramSHA1.prototype.auth = function(server, pool, db, username, password, callback) { - var self = this; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var executeScram = function(connection) { - // Clean up the user - username = username.replace('=', "=3D").replace(',', '=2C'); - - // Create a random nonce - var nonce = crypto.randomBytes(24).toString('base64'); - // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc' - var firstBare = f("n=%s,r=%s", username, nonce); - - // Build command structure - var cmd = { - saslStart: 1 - , mechanism: 'SCRAM-SHA-1' - , payload: new Binary(f("n,,%s", firstBare)) - , autoAuthorize: 1 - } - - // Handle the error - var handleError = function(err, r) { - if(err) { - numberOfValidConnections = numberOfValidConnections - 1; - errorObject = err; return false; - } else if(r.result['$err']) { - errorObject = r.result; return false; - } else if(r.result['errmsg']) { - errorObject = r.result; return false; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - return true - } - - // Finish up - var finish = function(_count, _numberOfValidConnections) { - if(_count == 0 && _numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - return callback(null, true); - } else if(_count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); - return callback(errorObject, false); - } - } - - var handleEnd = function(_err, _r) { - // Handle any error - handleError(_err, _r) - // Adjust the number of connections - count = count - 1; - // Execute the finish - finish(count, numberOfValidConnections); - } - - // Execute start sasl command - server.command(f("%s.$cmd", db) - , cmd, { connection: connection }, function(err, r) { - - // Do we have an error, handle it - if(handleError(err, r) == false) { - count = count - 1; - - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - return callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram")); - return callback(errorObject, false); - } - - return; - } - - // Get the dictionary - var dict = parsePayload(r.result.payload.value()) - - // Unpack dictionary - var iterations = parseInt(dict.i, 10); - var salt = dict.s; - var rnonce = dict.r; - - // Set up start of proof - var withoutProof = f("c=biws,r=%s", rnonce); - var passwordDig = passwordDigest(username, password); - var saltedPassword = hi(passwordDig - , new Buffer(salt, 'base64') - , iterations); - - // Create the client key - var hmac = crypto.createHmac('sha1', saltedPassword); - hmac.update(new Buffer("Client Key")); - var clientKey = new Buffer(hmac.digest('base64'), 'base64'); - - // Create the stored key - var hash = crypto.createHash('sha1'); - hash.update(clientKey); - var storedKey = new Buffer(hash.digest('base64'), 'base64'); - - // Create the authentication message - var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(','); - - // Create client signature - var hmac = crypto.createHmac('sha1', storedKey); - hmac.update(new Buffer(authMsg)); - var clientSig = new Buffer(hmac.digest('base64'), 'base64'); - - // Create client proof - var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64')); - - // Create client final - var clientFinal = [withoutProof, clientProof].join(','); - - // Generate server key - var hmac = crypto.createHmac('sha1', saltedPassword); - hmac.update(new Buffer('Server Key')) - var serverKey = new Buffer(hmac.digest('base64'), 'base64'); - - // Generate server signature - var hmac = crypto.createHmac('sha1', serverKey); - hmac.update(new Buffer(authMsg)) - var serverSig = new Buffer(hmac.digest('base64'), 'base64'); - - // - // Create continue message - var cmd = { - saslContinue: 1 - , conversationId: r.result.conversationId - , payload: new Binary(new Buffer(clientFinal)) - } - - // - // Execute sasl continue - server.command(f("%s.$cmd", db) - , cmd, { connection: connection }, function(err, r) { - if(r && r.result.done == false) { - var cmd = { - saslContinue: 1 - , conversationId: r.result.conversationId - , payload: new Buffer(0) - } - - server.command(f("%s.$cmd", db) - , cmd, { connection: connection }, function(err, r) { - handleEnd(err, r); - }); - } else { - handleEnd(err, r); - } - }); - }); - } - - // Get the connection - executeScram(connections.shift()); - } -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -ScramSHA1.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - - -module.exports = ScramSHA1; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js deleted file mode 100644 index 177ede5..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/sspi.js +++ /dev/null @@ -1,234 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , MongoError = require('../error'); - -var AuthSession = function(db, username, password, options) { - this.db = db; - this.username = username; - this.password = password; - this.options = options; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -// Kerberos class -var Kerberos = null; -var MongoAuthProcess = null; - -// Try to grab the Kerberos class -try { - Kerberos = require('kerberos').Kerberos - // Authentication process for Mongo - MongoAuthProcess = require('kerberos').processes.MongoAuthProcess -} catch(err) {} - -/** - * Creates a new SSPI authentication mechanism - * @class - * @return {SSPI} A cursor instance - */ -var SSPI = function() { - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -SSPI.prototype.auth = function(server, pool, db, username, password, options, callback) { - var self = this; - // We don't have the Kerberos library - if(Kerberos == null) return callback(new Error("Kerberos library is not installed")); - var gssapiServiceName = options['gssapiServiceName'] || 'mongodb'; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Start Auth process for a connection - SSIPAuthenticate(username, password, gssapiServiceName, server, connection, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r && typeof r == 'object' && r.result['$err']) { - errorObject = r.result; - } else if(r && typeof r == 'object' && r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password, options)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - // Get the connection - execute(connections.shift()); - } -} - -var SSIPAuthenticate = function(username, password, gssapiServiceName, server, connection, callback) { - // Build Authentication command to send to MongoDB - var command = { - saslStart: 1 - , mechanism: 'GSSAPI' - , payload: '' - , autoAuthorize: 1 - }; - - // Create authenticator - var mongo_auth_process = new MongoAuthProcess(connection.host, connection.port, gssapiServiceName); - - // Execute first sasl step - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - mongo_auth_process.init(username, password, function(err) { - if(err) return callback(err); - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - if(err) return callback(err); - - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - mongo_auth_process.transition(doc.payload, function(err, payload) { - // Perform the next step against mongod - var command = { - saslContinue: 1 - , conversationId: doc.conversationId - , payload: payload - }; - - // Execute the command - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - if(err) return callback(err, false); - var doc = r.result; - - if(doc.done) return callback(null, true); - callback(new Error("Authentication failed"), false); - }); - }); - }); - }); - }); - }); - }); - }); -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -SSPI.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, this.authStore[i].options, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = SSPI; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js deleted file mode 100644 index 641990e..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/auth/x509.js +++ /dev/null @@ -1,145 +0,0 @@ -"use strict"; - -var f = require('util').format - , crypto = require('crypto') - , MongoError = require('../error'); - -var AuthSession = function(db, username, password) { - this.db = db; - this.username = username; - this.password = password; -} - -AuthSession.prototype.equal = function(session) { - return session.db == this.db - && session.username == this.username - && session.password == this.password; -} - -/** - * Creates a new X509 authentication mechanism - * @class - * @return {X509} A cursor instance - */ -var X509 = function() { - this.authStore = []; -} - -/** - * Authenticate - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {string} db Name of the database - * @param {string} username Username - * @param {string} password Password - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -X509.prototype.auth = function(server, pool, db, username, password, callback) { - var self = this; - // Get all the connections - var connections = pool.getAll(); - // Total connections - var count = connections.length; - if(count == 0) return callback(null, null); - - // Valid connections - var numberOfValidConnections = 0; - var credentialsValid = false; - var errorObject = null; - - // For each connection we need to authenticate - while(connections.length > 0) { - // Execute MongoCR - var execute = function(connection) { - // Let's start the sasl process - var command = { - authenticate: 1 - , mechanism: 'MONGODB-X509' - , user: username - }; - - // Let's start the process - server.command("$external.$cmd" - , command - , { connection: connection }, function(err, r) { - // Adjust count - count = count - 1; - - // If we have an error - if(err) { - errorObject = err; - } else if(r.result['$err']) { - errorObject = r.result; - } else if(r.result['errmsg']) { - errorObject = r.result; - } else { - credentialsValid = true; - numberOfValidConnections = numberOfValidConnections + 1; - } - - // We have authenticated all connections - if(count == 0 && numberOfValidConnections > 0) { - // Store the auth details - addAuthSession(self.authStore, new AuthSession(db, username, password)); - // Return correct authentication - callback(null, true); - } else if(count == 0) { - if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using mongocr")); - callback(errorObject, false); - } - }); - } - - // Get the connection - execute(connections.shift()); - } -} - -// Add to store only if it does not exist -var addAuthSession = function(authStore, session) { - var found = false; - - for(var i = 0; i < authStore.length; i++) { - if(authStore[i].equal(session)) { - found = true; - break; - } - } - - if(!found) authStore.push(session); -} - -/** - * Re authenticate pool - * @method - * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on - * @param {Pool} pool Connection pool for this topology - * @param {authResultCallback} callback The callback to return the result from the authentication - * @return {object} - */ -X509.prototype.reauthenticate = function(server, pool, callback) { - var count = this.authStore.length; - if(count == 0) return callback(null, null); - // Iterate over all the auth details stored - for(var i = 0; i < this.authStore.length; i++) { - this.auth(server, pool, this.authStore[i].db, this.authStore[i].username, this.authStore[i].password, function(err, r) { - count = count - 1; - // Done re-authenticating - if(count == 0) { - callback(null, null); - } - }); - } -} - -/** - * This is a result from a authentication strategy - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {boolean} result The result of the authentication process - */ - -module.exports = X509; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js deleted file mode 100644 index 05023b4..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/commands.js +++ /dev/null @@ -1,519 +0,0 @@ -"use strict"; - -var f = require('util').format - , Long = require('bson').Long - , setProperty = require('./utils').setProperty - , getProperty = require('./utils').getProperty - , getSingleProperty = require('./utils').getSingleProperty; - -// Incrementing request id -var _requestId = 0; - -// Wire command operation ids -var OP_QUERY = 2004; -var OP_GETMORE = 2005; -var OP_KILL_CURSORS = 2007; - -// Query flags -var OPTS_NONE = 0; -var OPTS_TAILABLE_CURSOR = 2; -var OPTS_SLAVE = 4; -var OPTS_OPLOG_REPLAY = 8; -var OPTS_NO_CURSOR_TIMEOUT = 16; -var OPTS_AWAIT_DATA = 32; -var OPTS_EXHAUST = 64; -var OPTS_PARTIAL = 128; - -// Response flags -var CURSOR_NOT_FOUND = 0; -var QUERY_FAILURE = 2; -var SHARD_CONFIG_STALE = 4; -var AWAIT_CAPABLE = 8; - -/************************************************************** - * QUERY - **************************************************************/ -var Query = function(bson, ns, query, options) { - var self = this; - // Basic options needed to be passed in - if(ns == null) throw new Error("ns must be specified for query"); - if(query == null) throw new Error("query must be specified for query"); - - // Validate that we are not passing 0x00 in the colletion name - if(!!~ns.indexOf("\x00")) { - throw new Error("namespace cannot contain a null character"); - } - - // Basic options - this.bson = bson; - this.ns = ns; - this.query = query; - - // Ensure empty options - this.options = options || {}; - - // Additional options - this.numberToSkip = options.numberToSkip || 0; - this.numberToReturn = options.numberToReturn || 0; - this.returnFieldSelector = options.returnFieldSelector || null; - this.requestId = _requestId++; - - // Serialization option - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.maxBsonSize = options.maxBsonSize || 1024 * 1024 * 16; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; - this.batchSize = self.numberToReturn; - - // Flags - this.tailable = false; - this.slaveOk = false; - this.oplogReply = false; - this.noCursorTimeout = false; - this.awaitData = false; - this.exhaust = false; - this.partial = false; -} - -// -// Assign a new request Id -Query.prototype.incRequestId = function() { - this.requestId = _requestId++; -} - -// -// Assign a new request Id -Query.nextRequestId = function() { - return _requestId + 1; -} - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -Query.prototype.toBin = function() { - var self = this; - var buffers = []; - var projection = null; - - // Set up the flags - var flags = 0; - if(this.tailable) flags |= OPTS_TAILABLE_CURSOR; - if(this.slaveOk) flags |= OPTS_SLAVE; - if(this.oplogReply) flags |= OPTS_OPLOG_REPLAY; - if(this.noCursorTimeout) flags |= OPTS_NO_CURSOR_TIMEOUT; - if(this.awaitData) flags |= OPTS_AWAIT_DATA; - if(this.exhaust) flags |= OPTS_EXHAUST; - if(this.partial) flags |= OPTS_PARTIAL; - - // If batchSize is different to self.numberToReturn - if(self.batchSize != self.numberToReturn) self.numberToReturn = self.batchSize; - - // Allocate write protocol header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // Flags - + Buffer.byteLength(self.ns) + 1 // namespace - + 4 // numberToSkip - + 4 // numberToReturn - ); - - // Add header to buffers - buffers.push(header); - - // Serialize the query - var query = self.bson.serialize(this.query - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - - // Add query document - buffers.push(query); - - if(self.returnFieldSelector && Object.keys(self.returnFieldSelector).length > 0) { - // Serialize the projection document - projection = self.bson.serialize(this.returnFieldSelector, this.checkKeys, true, this.serializeFunctions, this.ignoreUndefined); - // Add projection document - buffers.push(projection); - } - - // Total message size - var totalLength = header.length + query.length + (projection ? projection.length : 0); - - // Set up the index - var index = 4; - - // Write total document length - header[3] = (totalLength >> 24) & 0xff; - header[2] = (totalLength >> 16) & 0xff; - header[1] = (totalLength >> 8) & 0xff; - header[0] = (totalLength) & 0xff; - - // Write header information requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // Write header information responseTo - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Write header information OP_QUERY - header[index + 3] = (OP_QUERY >> 24) & 0xff; - header[index + 2] = (OP_QUERY >> 16) & 0xff; - header[index + 1] = (OP_QUERY >> 8) & 0xff; - header[index] = (OP_QUERY) & 0xff; - index = index + 4; - - // Write header information flags - header[index + 3] = (flags >> 24) & 0xff; - header[index + 2] = (flags >> 16) & 0xff; - header[index + 1] = (flags >> 8) & 0xff; - header[index] = (flags) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write header information flags numberToSkip - header[index + 3] = (this.numberToSkip >> 24) & 0xff; - header[index + 2] = (this.numberToSkip >> 16) & 0xff; - header[index + 1] = (this.numberToSkip >> 8) & 0xff; - header[index] = (this.numberToSkip) & 0xff; - index = index + 4; - - // Write header information flags numberToReturn - header[index + 3] = (this.numberToReturn >> 24) & 0xff; - header[index + 2] = (this.numberToReturn >> 16) & 0xff; - header[index + 1] = (this.numberToReturn >> 8) & 0xff; - header[index] = (this.numberToReturn) & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -} - -Query.getRequestId = function() { - return ++_requestId; -} - -/************************************************************** - * GETMORE - **************************************************************/ -var GetMore = function(bson, ns, cursorId, opts) { - opts = opts || {}; - this.numberToReturn = opts.numberToReturn || 0; - this.requestId = _requestId++; - this.bson = bson; - this.ns = ns; - this.cursorId = cursorId; -} - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -GetMore.prototype.toBin = function() { - var length = 4 + Buffer.byteLength(this.ns) + 1 + 4 + 8 + (4 * 4); - // Create command buffer - var index = 0; - // Allocate buffer - var _buffer = new Buffer(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = (length) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = (this.requestId) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_GETMORE); - _buffer[index + 3] = (OP_GETMORE >> 24) & 0xff; - _buffer[index + 2] = (OP_GETMORE >> 16) & 0xff; - _buffer[index + 1] = (OP_GETMORE >> 8) & 0xff; - _buffer[index] = (OP_GETMORE) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // Write collection name - index = index + _buffer.write(this.ns, index, 'utf8') + 1; - _buffer[index - 1] = 0; - - // Write batch size - // index = write32bit(index, _buffer, numberToReturn); - _buffer[index + 3] = (this.numberToReturn >> 24) & 0xff; - _buffer[index + 2] = (this.numberToReturn >> 16) & 0xff; - _buffer[index + 1] = (this.numberToReturn >> 8) & 0xff; - _buffer[index] = (this.numberToReturn) & 0xff; - index = index + 4; - - // Write cursor id - // index = write32bit(index, _buffer, cursorId.getLowBits()); - _buffer[index + 3] = (this.cursorId.getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getLowBits() >> 8) & 0xff; - _buffer[index] = (this.cursorId.getLowBits()) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorId.getHighBits()); - _buffer[index + 3] = (this.cursorId.getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorId.getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorId.getHighBits() >> 8) & 0xff; - _buffer[index] = (this.cursorId.getHighBits()) & 0xff; - index = index + 4; - - // Return buffer - return _buffer; -} - -/************************************************************** - * KILLCURSOR - **************************************************************/ -var KillCursor = function(bson, cursorIds) { - this.requestId = _requestId++; - this.cursorIds = cursorIds; -} - -// -// Uses a single allocated buffer for the process, avoiding multiple memory allocations -KillCursor.prototype.toBin = function() { - var length = 4 + 4 + (4 * 4) + (this.cursorIds.length * 8); - - // Create command buffer - var index = 0; - var _buffer = new Buffer(length); - - // Write header information - // index = write32bit(index, _buffer, length); - _buffer[index + 3] = (length >> 24) & 0xff; - _buffer[index + 2] = (length >> 16) & 0xff; - _buffer[index + 1] = (length >> 8) & 0xff; - _buffer[index] = (length) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, requestId); - _buffer[index + 3] = (this.requestId >> 24) & 0xff; - _buffer[index + 2] = (this.requestId >> 16) & 0xff; - _buffer[index + 1] = (this.requestId >> 8) & 0xff; - _buffer[index] = (this.requestId) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, OP_KILL_CURSORS); - _buffer[index + 3] = (OP_KILL_CURSORS >> 24) & 0xff; - _buffer[index + 2] = (OP_KILL_CURSORS >> 16) & 0xff; - _buffer[index + 1] = (OP_KILL_CURSORS >> 8) & 0xff; - _buffer[index] = (OP_KILL_CURSORS) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, 0); - _buffer[index + 3] = (0 >> 24) & 0xff; - _buffer[index + 2] = (0 >> 16) & 0xff; - _buffer[index + 1] = (0 >> 8) & 0xff; - _buffer[index] = (0) & 0xff; - index = index + 4; - - // Write batch size - // index = write32bit(index, _buffer, this.cursorIds.length); - _buffer[index + 3] = (this.cursorIds.length >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds.length >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds.length >> 8) & 0xff; - _buffer[index] = (this.cursorIds.length) & 0xff; - index = index + 4; - - // Write all the cursor ids into the array - for(var i = 0; i < this.cursorIds.length; i++) { - // Write cursor id - // index = write32bit(index, _buffer, cursorIds[i].getLowBits()); - _buffer[index + 3] = (this.cursorIds[i].getLowBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getLowBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getLowBits() >> 8) & 0xff; - _buffer[index] = (this.cursorIds[i].getLowBits()) & 0xff; - index = index + 4; - - // index = write32bit(index, _buffer, cursorIds[i].getHighBits()); - _buffer[index + 3] = (this.cursorIds[i].getHighBits() >> 24) & 0xff; - _buffer[index + 2] = (this.cursorIds[i].getHighBits() >> 16) & 0xff; - _buffer[index + 1] = (this.cursorIds[i].getHighBits() >> 8) & 0xff; - _buffer[index] = (this.cursorIds[i].getHighBits()) & 0xff; - index = index + 4; - } - - // Return buffer - return _buffer; -} - -var Response = function(bson, data, opts) { - opts = opts || {promoteLongs: true}; - this.parsed = false; - - // - // Parse Header - // - this.index = 0; - this.raw = data; - this.data = data; - this.bson = bson; - this.opts = opts; - - // Read the message length - this.length = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Fetch the request id for this reply - this.requestId = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Fetch the id of the request that triggered the response - this.responseTo = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Skip op-code field - this.index = this.index + 4; - - // Unpack flags - this.responseFlags = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Unpack the cursor - var lowBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - var highBits = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - // Create long object - this.cursorId = new Long(lowBits, highBits); - - // Unpack the starting from - this.startingFrom = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Unpack the number of objects returned - this.numberReturned = data[this.index] | data[this.index + 1] << 8 | data[this.index + 2] << 16 | data[this.index + 3] << 24; - this.index = this.index + 4; - - // Preallocate document array - this.documents = new Array(this.numberReturned); - - // Flag values - this.cursorNotFound = (this.responseFlags & CURSOR_NOT_FOUND) != 0; - this.queryFailure = (this.responseFlags & QUERY_FAILURE) != 0; - this.shardConfigStale = (this.responseFlags & SHARD_CONFIG_STALE) != 0; - this.awaitCapable = (this.responseFlags & AWAIT_CAPABLE) != 0; - this.promoteLongs = typeof opts.promoteLongs == 'boolean' ? opts.promoteLongs : true; -} - -Response.prototype.isParsed = function() { - return this.parsed; -} - -// Validation buffers -var firstBatch = new Buffer('firstBatch', 'utf8'); -var nextBatch = new Buffer('nextBatch', 'utf8'); -var cursorId = new Buffer('id', 'utf8').toString('hex'); - -var documentBuffers = { - firstBatch: firstBatch.toString('hex'), - nextBatch: nextBatch.toString('hex') -}; - -Response.prototype.parse = function(options) { - // Don't parse again if not needed - if(this.parsed) return; - options = options || {}; - - // Allow the return of raw documents instead of parsing - var raw = options.raw || false; - var documentsReturnedIn = options.documentsReturnedIn || null; - - // - // Single document and documentsReturnedIn set - // - if(this.numberReturned == 1 && documentsReturnedIn != null && raw) { - // Calculate the bson size - var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; - // Slice out the buffer containing the command result document - var document = this.data.slice(this.index, this.index + bsonSize); - // Set up field we wish to keep as raw - var fieldsAsRaw = {} - fieldsAsRaw[documentsReturnedIn] = true; - // Set up the options - var _options = {promoteLongs: this.opts.promoteLongs, fieldsAsRaw: fieldsAsRaw}; - - // Deserialize but keep the array of documents in non-parsed form - var doc = this.bson.deserialize(document, _options); - - // Get the documents - this.documents = doc.cursor[documentsReturnedIn]; - this.numberReturned = this.documents.length; - // Ensure we have a Long valie cursor id - this.cursorId = typeof doc.cursor.id == 'number' - ? Long.fromNumber(doc.cursor.id) - : doc.cursor.id; - - // Adjust the index - this.index = this.index + bsonSize; - - // Set as parsed - this.parsed = true - return; - } - - // - // Parse Body - // - for(var i = 0; i < this.numberReturned; i++) { - var bsonSize = this.data[this.index] | this.data[this.index + 1] << 8 | this.data[this.index + 2] << 16 | this.data[this.index + 3] << 24; - // Parse options - var _options = {promoteLongs: this.opts.promoteLongs}; - - // If we have raw results specified slice the return document - if(raw) { - this.documents[i] = this.data.slice(this.index, this.index + bsonSize); - } else { - this.documents[i] = this.bson.deserialize(this.data.slice(this.index, this.index + bsonSize), _options); - } - - // Adjust the index - this.index = this.index + bsonSize; - } - - // Set parsed - this.parsed = true; -} - -module.exports = { - Query: Query - , GetMore: GetMore - , Response: Response - , KillCursor: KillCursor -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js deleted file mode 100644 index 217e58a..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js +++ /dev/null @@ -1,462 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , EventEmitter = require('events').EventEmitter - , net = require('net') - , tls = require('tls') - , f = require('util').format - , getSingleProperty = require('./utils').getSingleProperty - , debugOptions = require('./utils').debugOptions - , Response = require('./commands').Response - , MongoError = require('../error') - , Logger = require('./logger'); - -var _id = 0; -var debugFields = ['host', 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay' - , 'connectionTimeout', 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert' - , 'rejectUnauthorized', 'promoteLongs']; - -/** - * Creates a new Connection instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @fires Connection#connect - * @fires Connection#close - * @fires Connection#error - * @fires Connection#timeout - * @fires Connection#parseError - * @return {Connection} A cursor instance - */ -var Connection = function(options) { - // Add event listener - EventEmitter.call(this); - // Set empty if no options passed - this.options = options || {}; - // Identification information - this.id = _id++; - // Logger instance - this.logger = Logger('Connection', options); - // No bson parser passed in - if(!options.bson) throw new Error("must pass in valid bson parser"); - // Get bson parser - this.bson = options.bson; - // Grouping tag used for debugging purposes - this.tag = options.tag; - // Message handler - this.messageHandler = options.messageHandler; - - // Max BSON message size - this.maxBsonMessageSize = options.maxBsonMessageSize || (1024 * 1024 * 16 * 4); - // Debug information - if(this.logger.isDebug()) this.logger.debug(f('creating connection %s with options [%s]', this.id, JSON.stringify(debugOptions(debugFields, options)))); - - // Default options - this.port = options.port || 27017; - this.host = options.host || 'localhost'; - this.keepAlive = typeof options.keepAlive == 'boolean' ? options.keepAlive : true; - this.keepAliveInitialDelay = options.keepAliveInitialDelay || 0; - this.noDelay = typeof options.noDelay == 'boolean' ? options.noDelay : true; - this.connectionTimeout = options.connectionTimeout || 0; - this.socketTimeout = options.socketTimeout || 0; - - // If connection was destroyed - this.destroyed = false; - - // Check if we have a domain socket - this.domainSocket = this.host.indexOf('\/') != -1; - - // Serialize commands using function - this.singleBufferSerializtion = typeof options.singleBufferSerializtion == 'boolean' ? options.singleBufferSerializtion : true; - this.serializationFunction = this.singleBufferSerializtion ? 'toBinUnified' : 'toBin'; - - // SSL options - this.ca = options.ca || null; - this.cert = options.cert || null; - this.key = options.key || null; - this.passphrase = options.passphrase || null; - this.ssl = typeof options.ssl == 'boolean' ? options.ssl : false; - this.rejectUnauthorized = typeof options.rejectUnauthorized == 'boolean' ? options.rejectUnauthorized : true - - // If ssl not enabled - if(!this.ssl) this.rejectUnauthorized = false; - - // Response options - this.responseOptions = { - promoteLongs: typeof options.promoteLongs == 'boolean' ? options.promoteLongs : true - } - - // Flushing - this.flushing = false; - this.queue = []; - - // Internal state - this.connection = null; - this.writeStream = null; -} - -inherits(Connection, EventEmitter); - -// -// Connection handlers -var errorHandler = function(self) { - return function(err) { - // Debug information - if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] errored out with [%s]', self.id, self.host, self.port, JSON.stringify(err))); - // Emit the error - if(self.listeners('error').length > 0) self.emit("error", MongoError.create(err), self); - } -} - -var timeoutHandler = function(self) { - return function() { - // Debug information - if(self.logger.isDebug()) self.logger.debug(f('connection %s for [%s:%s] timed out', self.id, self.host, self.port)); - // Emit timeout error - self.emit("timeout" - , MongoError.create(f("connection %s to %s:%s timed out", self.id, self.host, self.port)) - , self); - } -} - -var closeHandler = function(self) { - return function(hadError) { - // Debug information - if(self.logger.isDebug()) self.logger.debug(f('connection %s with for [%s:%s] closed', self.id, self.host, self.port)); - // Emit close event - if(!hadError) { - self.emit("close" - , MongoError.create(f("connection %s to %s:%s closed", self.id, self.host, self.port)) - , self); - } - } -} - -var dataHandler = function(self) { - return function(data) { - // Parse until we are done with the data - while(data.length > 0) { - // If we still have bytes to read on the current message - if(self.bytesRead > 0 && self.sizeOfMessage > 0) { - // Calculate the amount of remaining bytes - var remainingBytesToRead = self.sizeOfMessage - self.bytesRead; - // Check if the current chunk contains the rest of the message - if(remainingBytesToRead > data.length) { - // Copy the new data into the exiting buffer (should have been allocated when we know the message size) - data.copy(self.buffer, self.bytesRead); - // Adjust the number of bytes read so it point to the correct index in the buffer - self.bytesRead = self.bytesRead + data.length; - - // Reset state of buffer - data = new Buffer(0); - } else { - // Copy the missing part of the data into our current buffer - data.copy(self.buffer, self.bytesRead, 0, remainingBytesToRead); - // Slice the overflow into a new buffer that we will then re-parse - data = data.slice(remainingBytesToRead); - - // Emit current complete message - try { - var emitBuffer = self.buffer; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Emit the buffer - self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); - } catch(err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } - } else { - // Stub buffer is kept in case we don't get enough bytes to determine the - // size of the message (< 4 bytes) - if(self.stubBuffer != null && self.stubBuffer.length > 0) { - // If we have enough bytes to determine the message size let's do it - if(self.stubBuffer.length + data.length > 4) { - // Prepad the data - var newData = new Buffer(self.stubBuffer.length + data.length); - self.stubBuffer.copy(newData, 0); - data.copy(newData, self.stubBuffer.length); - // Reassign for parsing - data = newData; - - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - - } else { - - // Add the the bytes to the stub buffer - var newStubBuffer = new Buffer(self.stubBuffer.length + data.length); - // Copy existing stub buffer - self.stubBuffer.copy(newStubBuffer, 0); - // Copy missing part of the data - data.copy(newStubBuffer, self.stubBuffer.length); - // Exit parsing loop - data = new Buffer(0); - } - } else { - if(data.length > 4) { - // Retrieve the message size - // var sizeOfMessage = data.readUInt32LE(0); - var sizeOfMessage = data[0] | data[1] << 8 | data[2] << 16 | data[3] << 24; - // If we have a negative sizeOfMessage emit error and return - if(sizeOfMessage < 0 || sizeOfMessage > self.maxBsonMessageSize) { - var errorObject = {err:"socketHandler", trace:'', bin:self.buffer, parseState:{ - sizeOfMessage: sizeOfMessage, - bytesRead: self.bytesRead, - stubBuffer: self.stubBuffer}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - return; - } - - // Ensure that the size of message is larger than 0 and less than the max allowed - if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage > data.length) { - self.buffer = new Buffer(sizeOfMessage); - // Copy all the data into the buffer - data.copy(self.buffer, 0); - // Update bytes read - self.bytesRead = data.length; - // Update sizeOfMessage - self.sizeOfMessage = sizeOfMessage; - // Ensure stub buffer is null - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - - } else if(sizeOfMessage > 4 && sizeOfMessage < self.maxBsonMessageSize && sizeOfMessage == data.length) { - try { - var emitBuffer = data; - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - // Emit the message - self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); - } catch (err) { - var errorObject = {err:"socketHandler", trace:err, bin:self.buffer, parseState:{ - sizeOfMessage:self.sizeOfMessage, - bytesRead:self.bytesRead, - stubBuffer:self.stubBuffer}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - } - } else if(sizeOfMessage <= 4 || sizeOfMessage > self.maxBsonMessageSize) { - var errorObject = {err:"socketHandler", trace:null, bin:data, parseState:{ - sizeOfMessage:sizeOfMessage, - bytesRead:0, - buffer:null, - stubBuffer:null}}; - // We got a parse Error fire it off then keep going - self.emit("parseError", errorObject, self); - - // Clear out the state of the parser - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Exit parsing loop - data = new Buffer(0); - } else { - var emitBuffer = data.slice(0, sizeOfMessage); - // Reset state of buffer - self.buffer = null; - self.sizeOfMessage = 0; - self.bytesRead = 0; - self.stubBuffer = null; - // Copy rest of message - data = data.slice(sizeOfMessage); - // Emit the message - self.messageHandler(new Response(self.bson, emitBuffer, self.responseOptions), self); - } - } else { - // Create a buffer that contains the space for the non-complete message - self.stubBuffer = new Buffer(data.length) - // Copy the data to the stub buffer - data.copy(self.stubBuffer, 0); - // Exit parsing loop - data = new Buffer(0); - } - } - } - } - } -} - -/** - * Connect - * @method - */ -Connection.prototype.connect = function(_options) { - var self = this; - _options = _options || {}; - // Check if we are overriding the promoteLongs - if(typeof _options.promoteLongs == 'boolean') { - self.responseOptions.promoteLongs = _options.promoteLongs; - } - - // Create new connection instance - self.connection = self.domainSocket - ? net.createConnection(self.host) - : net.createConnection(self.port, self.host); - - // Set the options for the connection - self.connection.setKeepAlive(self.keepAlive, self.keepAliveInitialDelay); - self.connection.setTimeout(self.connectionTimeout); - self.connection.setNoDelay(self.noDelay); - - // If we have ssl enabled - if(self.ssl) { - var sslOptions = { - socket: self.connection - , rejectUnauthorized: self.rejectUnauthorized - } - - if(self.ca) sslOptions.ca = self.ca; - if(self.cert) sslOptions.cert = self.cert; - if(self.key) sslOptions.key = self.key; - if(self.passphrase) sslOptions.passphrase = self.passphrase; - - // Attempt SSL connection - self.connection = tls.connect(self.port, self.host, sslOptions, function() { - // Error on auth or skip - if(self.connection.authorizationError && self.rejectUnauthorized) { - return self.emit("error", self.connection.authorizationError, self, {ssl:true}); - } - - // Set socket timeout instead of connection timeout - self.connection.setTimeout(self.socketTimeout); - // We are done emit connect - self.emit('connect', self); - }); - self.connection.setTimeout(self.connectionTimeout); - } else { - self.connection.on('connect', function() { - // Set socket timeout instead of connection timeout - self.connection.setTimeout(self.socketTimeout); - // Emit connect event - self.emit('connect', self); - }); - } - - // Add handlers for events - self.connection.once('error', errorHandler(self)); - self.connection.once('timeout', timeoutHandler(self)); - self.connection.once('close', closeHandler(self)); - self.connection.on('data', dataHandler(self)); -} - -/** - * Destroy connection - * @method - */ -Connection.prototype.destroy = function() { - if(this.connection) this.connection.destroy(); - this.destroyed = true; -} - -/** - * Write to connection - * @method - * @param {Command} command Command to write out need to implement toBin and toBinUnified - */ -Connection.prototype.write = function(buffer) { - // Debug log - if(this.logger.isDebug()) this.logger.debug(f('writing buffer [%s] to %s:%s', buffer.toString('hex'), this.host, this.port)); - // Write out the command - if(!Array.isArray(buffer)) return this.connection.write(buffer, 'binary'); - // Iterate over all buffers and write them in order to the socket - for(var i = 0; i < buffer.length; i++) this.connection.write(buffer[i], 'binary'); -} - -/** - * Return id of connection as a string - * @method - * @return {string} - */ -Connection.prototype.toString = function() { - return "" + this.id; -} - -/** - * Return json object of connection - * @method - * @return {object} - */ -Connection.prototype.toJSON = function() { - return {id: this.id, host: this.host, port: this.port}; -} - -/** - * Is the connection connected - * @method - * @return {boolean} - */ -Connection.prototype.isConnected = function() { - if(this.destroyed) return false; - return !this.connection.destroyed && this.connection.writable; -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Connection#connect - * @type {Connection} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Connection#close - * @type {Connection} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Connection#error - * @type {Connection} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Connection#timeout - * @type {Connection} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Connection#parseError - * @type {Connection} - */ - -module.exports = Connection; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js deleted file mode 100644 index 69c6f93..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/logger.js +++ /dev/null @@ -1,196 +0,0 @@ -"use strict"; - -var f = require('util').format - , MongoError = require('../error'); - -// Filters for classes -var classFilters = {}; -var filteredClasses = {}; -var level = null; -// Save the process id -var pid = process.pid; -// current logger -var currentLogger = null; - -/** - * Creates a new Logger instance - * @class - * @param {string} className The Class name associated with the logging instance - * @param {object} [options=null] Optional settings. - * @param {Function} [options.logger=null] Custom logger function; - * @param {string} [options.loggerLevel=error] Override default global log level. - * @return {Logger} a Logger instance. - */ -var Logger = function(className, options) { - if(!(this instanceof Logger)) return new Logger(className, options); - options = options || {}; - - // Current reference - var self = this; - this.className = className; - - // Current logger - if(currentLogger == null && options.logger) { - currentLogger = options.logger; - } else if(currentLogger == null) { - currentLogger = console.log; - } - - // Set level of logging, default is error - if(level == null) { - level = options.loggerLevel || 'error'; - } - - // Add all class names - if(filteredClasses[this.className] == null) classFilters[this.className] = true; -} - -/** - * Log a message at the debug level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.debug = function(message, object) { - if(this.isDebug() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); - var state = { - type: 'debug', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -} - -/** - * Log a message at the info level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.info = function(message, object) { - if(this.isInfo() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); - var state = { - type: 'info', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -}, - -/** - * Log a message at the error level - * @method - * @param {string} message The message to log - * @param {object} object additional meta data to log - * @return {null} - */ -Logger.prototype.error = function(message, object) { - if(this.isError() - && ((Object.keys(filteredClasses).length > 0 && filteredClasses[this.className]) - || (Object.keys(filteredClasses).length == 0 && classFilters[this.className]))) { - var dateTime = new Date().getTime(); - var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); - var state = { - type: 'error', message: message, className: this.className, pid: pid, date: dateTime - }; - if(object) state.meta = object; - currentLogger(msg, state); - } -}, - -/** - * Is the logger set at info level - * @method - * @return {boolean} - */ -Logger.prototype.isInfo = function() { - return level == 'info' || level == 'debug'; -}, - -/** - * Is the logger set at error level - * @method - * @return {boolean} - */ -Logger.prototype.isError = function() { - return level == 'error' || level == 'info' || level == 'debug'; -}, - -/** - * Is the logger set at debug level - * @method - * @return {boolean} - */ -Logger.prototype.isDebug = function() { - return level == 'debug'; -} - -/** - * Resets the logger to default settings, error and no filtered classes - * @method - * @return {null} - */ -Logger.reset = function() { - level = 'error'; - filteredClasses = {}; -} - -/** - * Get the current logger function - * @method - * @return {function} - */ -Logger.currentLogger = function() { - return currentLogger; -} - -/** - * Set the current logger function - * @method - * @param {function} logger Logger function. - * @return {null} - */ -Logger.setCurrentLogger = function(logger) { - if(typeof logger != 'function') throw new MongoError("current logger must be a function"); - currentLogger = logger; -} - -/** - * Set what classes to log. - * @method - * @param {string} type The type of filter (currently only class) - * @param {string[]} values The filters to apply - * @return {null} - */ -Logger.filter = function(type, values) { - if(type == 'class' && Array.isArray(values)) { - filteredClasses = {}; - - values.forEach(function(x) { - filteredClasses[x] = true; - }); - } -} - -/** - * Set the current log level - * @method - * @param {string} level Set current log level (debug, info, error) - * @return {null} - */ -Logger.setLevel = function(_level) { - if(_level != 'info' && _level != 'error' && _level != 'debug') throw new Error(f("%s is an illegal logging level", _level)); - level = _level; -} - -module.exports = Logger; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js deleted file mode 100644 index dd13707..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js +++ /dev/null @@ -1,275 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , EventEmitter = require('events').EventEmitter - , Connection = require('./connection') - , Query = require('./commands').Query - , Logger = require('./logger') - , f = require('util').format; - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -var _id = 0; - -/** - * Creates a new Pool instance - * @class - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passPhrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=false] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @fires Pool#connect - * @fires Pool#close - * @fires Pool#error - * @fires Pool#timeout - * @fires Pool#parseError - * @return {Pool} A cursor instance - */ -var Pool = function(options) { - var self = this; - // Add event listener - EventEmitter.call(this); - // Set empty if no options passed - this.options = options || {}; - this.size = typeof options.size == 'number' ? options.size : 5; - // Message handler - this.messageHandler = options.messageHandler; - // No bson parser passed in - if(!options.bson) throw new Error("must pass in valid bson parser"); - // Contains all connections - this.connections = []; - this.state = DISCONNECTED; - // Round robin index - this.index = 0; - this.dead = false; - // Logger instance - this.logger = Logger('Pool', options); - // Pool id - this.id = _id++; - // Grouping tag used for debugging purposes - this.tag = options.tag; -} - -inherits(Pool, EventEmitter); - -var errorHandler = function(self) { - return function(err, connection) { - if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); - if(!self.dead) { - self.state = DISCONNECTED; - self.dead = true; - self.destroy(); - self.emit('error', err, self); - } - } -} - -var timeoutHandler = function(self) { - return function(err, connection) { - if(self.logger.isDebug()) self.logger.debug(f('pool [%s] timed out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); - if(!self.dead) { - self.state = DISCONNECTED; - self.dead = true; - self.destroy(); - self.emit('timeout', err, self); - } - } -} - -var closeHandler = function(self) { - return function(err, connection) { - if(self.logger.isDebug()) self.logger.debug(f('pool [%s] closed [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); - if(!self.dead) { - self.state = DISCONNECTED; - self.dead = true; - self.destroy(); - self.emit('close', err, self); - } - } -} - -var parseErrorHandler = function(self) { - return function(err, connection) { - if(self.logger.isDebug()) self.logger.debug(f('pool [%s] errored out [%s] with connection [%s]', this.dead, JSON.stringify(err), JSON.stringify(connection))); - if(!self.dead) { - self.state = DISCONNECTED; - self.dead = true; - self.destroy(); - self.emit('parseError', err, self); - } - } -} - -var connectHandler = function(self) { - return function(connection) { - self.connections.push(connection); - // We have connected to all servers - if(self.connections.length == self.size) { - self.state = CONNECTED; - // Done connecting - self.emit("connect", self); - } - } -} - -/** - * Destroy pool - * @method - */ -Pool.prototype.destroy = function() { - this.state = DESTROYED; - // Set dead - this.dead = true; - // Destroy all the connections - this.connections.forEach(function(c) { - // Destroy all event emitters - ["close", "message", "error", "timeout", "parseError", "connect"].forEach(function(e) { - c.removeAllListeners(e); - }); - - // Destroy the connection - c.destroy(); - }); -} - -var execute = null; - -try { - execute = setImmediate; -} catch(err) { - execute = process.nextTick; -} - -/** - * Connect pool - * @method - */ -Pool.prototype.connect = function(_options) { - var self = this; - // Set to connecting - this.state = CONNECTING - // No dead - this.dead = false; - - // Ensure we allow for a little time to setup connections - var wait = 1; - - // Connect all sockets - for(var i = 0; i < this.size; i++) { - setTimeout(function() { - execute(function() { - self.options.messageHandler = self.messageHandler; - var connection = new Connection(self.options); - - // Add all handlers - connection.once('close', closeHandler(self)); - connection.once('error', errorHandler(self)); - connection.once('timeout', timeoutHandler(self)); - connection.once('parseError', parseErrorHandler(self)); - connection.on('connect', connectHandler(self)); - - // Start connection - connection.connect(_options); - }); - }, wait); - - // wait for 1 miliseconds before attempting to connect, spacing out connections - wait = wait + 1; - } -} - -/** - * Get a pool connection (round-robin) - * @method - * @return {Connection} - */ -Pool.prototype.get = function() { - // if(this.dead) return null; - var connection = this.connections[this.index++]; - this.index = this.index % this.connections.length; - return connection; -} - -/** - * Get all pool connections - * @method - * @return {array} - */ -Pool.prototype.getAll = function() { - return this.connections.slice(0); -} - -/** - * Is the pool connected - * @method - * @return {boolean} - */ -Pool.prototype.isConnected = function() { - for(var i = 0; i < this.connections.length; i++) { - if(!this.connections[i].isConnected()) return false; - } - - return this.state == CONNECTED; -} - -/** - * Was the pool destroyed - * @method - * @return {boolean} - */ -Pool.prototype.isDestroyed = function() { - return this.state == DESTROYED; -} - - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Pool#connect - * @type {Pool} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Pool#close - * @type {Pool} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Pool#error - * @type {Pool} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Pool#timeout - * @type {Pool} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Pool#parseError - * @type {Pool} - */ - -module.exports = Pool; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js deleted file mode 100644 index 7f0b89d..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/connection/utils.js +++ /dev/null @@ -1,77 +0,0 @@ -"use strict"; - -// Set property function -var setProperty = function(obj, prop, flag, values) { - Object.defineProperty(obj, prop.name, { - enumerable:true, - set: function(value) { - if(typeof value != 'boolean') throw new Error(f("%s required a boolean", prop.name)); - // Flip the bit to 1 - if(value == true) values.flags |= flag; - // Flip the bit to 0 if it's set, otherwise ignore - if(value == false && (values.flags & flag) == flag) values.flags ^= flag; - prop.value = value; - } - , get: function() { return prop.value; } - }); -} - -// Set property function -var getProperty = function(obj, propName, fieldName, values, func) { - Object.defineProperty(obj, propName, { - enumerable:true, - get: function() { - // Not parsed yet, parse it - if(values[fieldName] == null && obj.isParsed && !obj.isParsed()) { - obj.parse(); - } - - // Do we have a post processing function - if(typeof func == 'function') return func(values[fieldName]); - // Return raw value - return values[fieldName]; - } - }); -} - -// Set simple property -var getSingleProperty = function(obj, name, value) { - Object.defineProperty(obj, name, { - enumerable:true, - get: function() { - return value - } - }); -} - -// Shallow copy -var copy = function(fObj, tObj) { - tObj = tObj || {}; - for(var name in fObj) tObj[name] = fObj[name]; - return tObj; -} - -var debugOptions = function(debugFields, options) { - var finaloptions = {}; - debugFields.forEach(function(n) { - finaloptions[n] = options[n]; - }); - - return finaloptions; -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) return callback; - return domain.bind(callback); -} - -exports.setProperty = setProperty; -exports.getProperty = getProperty; -exports.getSingleProperty = getSingleProperty; -exports.copy = copy; -exports.bindToCurrentDomain = bindToCurrentDomain; -exports.debugOptions = debugOptions; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js deleted file mode 100644 index ab82818..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/cursor.js +++ /dev/null @@ -1,756 +0,0 @@ -"use strict"; - -var Long = require('bson').Long - , Logger = require('./connection/logger') - , MongoError = require('./error') - , f = require('util').format; - -/** - * This is a cursor results callback - * - * @callback resultCallback - * @param {error} error An error object. Set to null if no error present - * @param {object} document - */ - -/** - * @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB - * allowing for iteration over the results returned from the underlying query. - * - * **CURSORS Cannot directly be instantiated** - * @example - * var Server = require('mongodb-core').Server - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new Server({host: 'localhost', port: 27017}); - * // Wait for the connection event - * server.on('connect', function(server) { - * assert.equal(null, err); - * - * // Execute the write - * var cursor = _server.cursor('integration_tests.inserts_example4', { - * find: 'integration_tests.example4' - * , query: {a:1} - * }, { - * readPreference: new ReadPreference('secondary'); - * }); - * - * // Get the first document - * cursor.next(function(err, doc) { - * assert.equal(null, err); - * server.destroy(); - * }); - * }); - * - * // Start connecting - * server.connect(); - */ - -/** - * Creates a new Cursor, not to be used directly - * @class - * @param {object} bson An instance of the BSON parser - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|Long} cmd The selector (can be a command or a cursorId) - * @param {object} [options=null] Optional settings. - * @param {object} [options.batchSize=1000] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {object} [options.transforms=null] Transform methods for the cursor results - * @param {function} [options.transforms.query] Transform the value returned from the initial query - * @param {function} [options.transforms.doc] Transform each document returned from Cursor.prototype.next - * @param {object} topology The server topology instance. - * @param {object} topologyOptions The server topology options. - * @return {Cursor} A cursor instance - * @property {number} cursorBatchSize The current cursorBatchSize for the cursor - * @property {number} cursorLimit The current cursorLimit for the cursor - * @property {number} cursorSkip The current cursorSkip for the cursor - */ -var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) { - options = options || {}; - // Cursor reference - var self = this; - // Initial query - var query = null; - - // Cursor connection - this.connection = null; - // Cursor server - this.server = null; - - // Do we have a not connected handler - this.disconnectHandler = options.disconnectHandler; - - // Set local values - this.bson = bson; - this.ns = ns; - this.cmd = cmd; - this.options = options; - this.topology = topology; - - // All internal state - this.cursorState = { - cursorId: null - , cmd: cmd - , documents: options.documents || [] - , cursorIndex: 0 - , dead: false - , killed: false - , init: false - , notified: false - , limit: options.limit || cmd.limit || 0 - , skip: options.skip || cmd.skip || 0 - , batchSize: options.batchSize || cmd.batchSize || 1000 - , currentLimit: 0 - // Result field name if not a cursor (contains the array of results) - , transforms: options.transforms - } - - // Callback controller - this.callbacks = null; - - // Logger - this.logger = Logger('Cursor', options); - - // - // Did we pass in a cursor id - if(typeof cmd == 'number') { - this.cursorState.cursorId = Long.fromNumber(cmd); - } else if(cmd instanceof Long) { - this.cursorState.cursorId = cmd; - } -} - -Cursor.prototype.setCursorBatchSize = function(value) { - this.cursorState.batchSize = value; -} - -Cursor.prototype.cursorBatchSize = function() { - return this.cursorState.batchSize; -} - -Cursor.prototype.setCursorLimit = function(value) { - this.cursorState.limit = value; -} - -Cursor.prototype.cursorLimit = function() { - return this.cursorState.limit; -} - -Cursor.prototype.setCursorSkip = function(value) { - this.cursorState.skip = value; -} - -Cursor.prototype.cursorSkip = function() { - return this.cursorState.skip; -} - -// // -// // Execute getMore command -// var execGetMore = function(self, callback) { -// } - -// -// Execute the first query -var execInitialQuery = function(self, query, cmd, options, cursorState, connection, logger, callbacks, callback) { - if(logger.isDebug()) { - logger.debug(f("issue initial query [%s] with flags [%s]" - , JSON.stringify(cmd) - , JSON.stringify(query))); - } - - var queryCallback = function(err, result) { - if(err) return callback(err); - - if(result.queryFailure) { - return callback(MongoError.create(result.documents[0]), null); - } - - // Check if we have a command cursor - if(Array.isArray(result.documents) && result.documents.length == 1 - && (!cmd.find || (cmd.find && cmd.virtual == false)) - && (result.documents[0].cursor != 'string' - || result.documents[0]['$err'] - || result.documents[0]['errmsg'] - || Array.isArray(result.documents[0].result)) - ) { - - // We have a an error document return the error - if(result.documents[0]['$err'] - || result.documents[0]['errmsg']) { - return callback(MongoError.create(result.documents[0]), null); - } - - // We have a cursor document - if(result.documents[0].cursor != null - && typeof result.documents[0].cursor != 'string') { - var id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if(result.documents[0].cursor.ns) { - self.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; - // If we have a firstBatch set it - if(Array.isArray(result.documents[0].cursor.firstBatch)) { - cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); - } - - // Return after processing command cursor - return callback(null, null); - } - - if(Array.isArray(result.documents[0].result)) { - cursorState.documents = result.documents[0].result; - cursorState.cursorId = Long.ZERO; - return callback(null, null); - } - } - - // Otherwise fall back to regular find path - cursorState.cursorId = result.cursorId; - cursorState.documents = result.documents; - - // Transform the results with passed in transformation method if provided - if(cursorState.transforms && typeof cursorState.transforms.query == 'function') { - cursorState.documents = cursorState.transforms.query(result); - } - - // Return callback - callback(null, null); - } - - // If we have a raw query decorate the function - if(options.raw || cmd.raw) { - queryCallback.raw = options.raw || cmd.raw; - } - - // Do we have documentsReturnedIn set on the query - if(typeof query.documentsReturnedIn == 'string') { - queryCallback.documentsReturnedIn = query.documentsReturnedIn; - } - - // Set up callback - callbacks.register(query.requestId, queryCallback); - - // Write the initial command out - connection.write(query.toBin()); -} - -// -// Handle callback (including any exceptions thrown) -var handleCallback = function(callback, err, result) { - try { - callback(err, result); - } catch(err) { - process.nextTick(function() { - throw err; - }); - } -} - - -// Internal methods -Cursor.prototype._find = function(callback) { - var self = this; - // execInitialQuery(self, self.query, self.cmd, self.options, self.cursorState, self.connection, self.logger, self.callbacks, function(err, r) { - if(self.logger.isDebug()) { - self.logger.debug(f("issue initial query [%s] with flags [%s]" - , JSON.stringify(self.cmd) - , JSON.stringify(self.query))); - } - - var queryCallback = function(err, result) { - if(err) return callback(err); - - if(result.queryFailure) { - return callback(MongoError.create(result.documents[0]), null); - } - - // Check if we have a command cursor - if(Array.isArray(result.documents) && result.documents.length == 1 - && (!self.cmd.find || (self.cmd.find && self.cmd.virtual == false)) - && (result.documents[0].cursor != 'string' - || result.documents[0]['$err'] - || result.documents[0]['errmsg'] - || Array.isArray(result.documents[0].result)) - ) { - - // We have a an error document return the error - if(result.documents[0]['$err'] - || result.documents[0]['errmsg']) { - return callback(MongoError.create(result.documents[0]), null); - } - - // We have a cursor document - if(result.documents[0].cursor != null - && typeof result.documents[0].cursor != 'string') { - var id = result.documents[0].cursor.id; - // If we have a namespace change set the new namespace for getmores - if(result.documents[0].cursor.ns) { - self.ns = result.documents[0].cursor.ns; - } - // Promote id to long if needed - self.cursorState.cursorId = typeof id == 'number' ? Long.fromNumber(id) : id; - // If we have a firstBatch set it - if(Array.isArray(result.documents[0].cursor.firstBatch)) { - self.cursorState.documents = result.documents[0].cursor.firstBatch;//.reverse(); - } - - // Return after processing command cursor - return callback(null, null); - } - - if(Array.isArray(result.documents[0].result)) { - self.cursorState.documents = result.documents[0].result; - self.cursorState.cursorId = Long.ZERO; - return callback(null, null); - } - } - - // Otherwise fall back to regular find path - self.cursorState.cursorId = result.cursorId; - self.cursorState.documents = result.documents; - - // Transform the results with passed in transformation method if provided - if(self.cursorState.transforms && typeof self.cursorState.transforms.query == 'function') { - self.cursorState.documents = self.cursorState.transforms.query(result); - } - - // Return callback - callback(null, null); - } - // console.log("------------------------- 2") - - // If we have a raw query decorate the function - if(self.options.raw || self.cmd.raw) { - queryCallback.raw = self.options.raw || self.cmd.raw; - } - // console.log("------------------------- 3") - - // Do we have documentsReturnedIn set on the query - if(typeof self.query.documentsReturnedIn == 'string') { - queryCallback.documentsReturnedIn = self.query.documentsReturnedIn; - } - // console.log("------------------------- 4") - - // Set up callback - self.callbacks.register(self.query.requestId, queryCallback); - - // Write the initial command out - self.connection.write(self.query.toBin()); -// console.log("------------------------- 5") -} - -Cursor.prototype._getmore = function(callback) { - if(this.logger.isDebug()) this.logger.debug(f("schedule getMore call for query [%s]", JSON.stringify(this.query))) - // Determine if it's a raw query - var raw = this.options.raw || this.cmd.raw; - // We have a wire protocol handler - this.server.wireProtocolHandler.getMore(this.bson, this.ns, this.cursorState, this.cursorState.batchSize, raw, this.connection, this.callbacks, this.options, callback); -} - -Cursor.prototype._killcursor = function(callback) { - // Set cursor to dead - this.cursorState.dead = true; - this.cursorState.killed = true; - // Remove documents - this.cursorState.documents = []; - - // If no cursor id just return - if(this.cursorState.cursorId == null || this.cursorState.cursorId.isZero() || this.cursorState.init == false) { - if(callback) callback(null, null); - return; - } - - // Execute command - this.server.wireProtocolHandler.killCursor(this.bson, this.ns, this.cursorState.cursorId, this.connection, this.callbacks, callback); -} - -/** - * Clone the cursor - * @method - * @return {Cursor} - */ -Cursor.prototype.clone = function() { - return this.topology.cursor(this.ns, this.cmd, this.options); -} - -/** - * Checks if the cursor is dead - * @method - * @return {boolean} A boolean signifying if the cursor is dead or not - */ -Cursor.prototype.isDead = function() { - return this.cursorState.dead == true; -} - -/** - * Checks if the cursor was killed by the application - * @method - * @return {boolean} A boolean signifying if the cursor was killed by the application - */ -Cursor.prototype.isKilled = function() { - return this.cursorState.killed == true; -} - -/** - * Checks if the cursor notified it's caller about it's death - * @method - * @return {boolean} A boolean signifying if the cursor notified the callback - */ -Cursor.prototype.isNotified = function() { - return this.cursorState.notified == true; -} - -/** - * Returns current buffered documents length - * @method - * @return {number} The number of items in the buffered documents - */ -Cursor.prototype.bufferedCount = function() { - return this.cursorState.documents.length - this.cursorState.cursorIndex; -} - -/** - * Returns current buffered documents - * @method - * @return {Array} An array of buffered documents - */ -Cursor.prototype.readBufferedDocuments = function(number) { - var unreadDocumentsLength = this.cursorState.documents.length - this.cursorState.cursorIndex; - var length = number < unreadDocumentsLength ? number : unreadDocumentsLength; - var elements = this.cursorState.documents.slice(this.cursorState.cursorIndex, this.cursorState.cursorIndex + length); - - // Transform the doc with passed in transformation method if provided - if(this.cursorState.transforms && typeof this.cursorState.transforms.doc == 'function') { - // Transform all the elements - for(var i = 0; i < elements.length; i++) { - elements[i] = this.cursorState.transforms.doc(elements[i]); - } - } - - // Ensure we do not return any more documents than the limit imposed - // Just return the number of elements up to the limit - if(this.cursorState.limit > 0 && (this.cursorState.currentLimit + elements.length) > this.cursorState.limit) { - elements = elements.slice(0, (this.cursorState.limit - this.cursorState.currentLimit)); - this.kill(); - } - - // Adjust current limit - this.cursorState.currentLimit = this.cursorState.currentLimit + elements.length; - this.cursorState.cursorIndex = this.cursorState.cursorIndex + elements.length; - - // Return elements - return elements; -} - -/** - * Kill the cursor - * @method - * @param {resultCallback} callback A callback function - */ -Cursor.prototype.kill = function(callback) { - this._killcursor(callback); -} - -/** - * Resets the cursor - * @method - * @return {null} - */ -Cursor.prototype.rewind = function() { - if(this.cursorState.init) { - if(!this.cursorState.dead) { - this.kill(); - } - - this.cursorState.currentLimit = 0; - this.cursorState.init = false; - this.cursorState.dead = false; - this.cursorState.killed = false; - this.cursorState.notified = false; - this.cursorState.documents = []; - this.cursorState.cursorId = null; - this.cursorState.cursorIndex = 0; - } -} - -/** - * Validate if the connection is dead and return error - */ -var isConnectionDead = function(self, callback) { - if(self.connection - && !self.connection.isConnected()) { - self.cursorState.notified = true; - self.cursorState.killed = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - callback(MongoError.create(f('connection to host %s:%s was destroyed', self.connection.host, self.connection.port))) - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead but was not explicitly killed by user - */ -var isCursorDeadButNotkilled = function(self, callback) { - // Cursor is dead but not marked killed, return null - if(self.cursorState.dead && !self.cursorState.killed) { - self.cursorState.notified = true; - self.cursorState.killed = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); - return true; - } - - return false; -} - -/** - * Validate if the cursor is dead and was killed by user - */ -var isCursorDeadAndKilled = function(self, callback) { - if(self.cursorState.dead && self.cursorState.killed) { - handleCallback(callback, MongoError.create("cursor is dead")); - return true; - } - - return false; -} - -/** - * Validate if the cursor was killed by the user - */ -var isCursorKilled = function(self, callback) { - if(self.cursorState.killed) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); - return true; - } - - return false; -} - -/** - * Mark cursor as being dead and notified - */ -var setCursorDeadAndNotified = function(self, callback) { - self.cursorState.dead = true; - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); -} - -/** - * Mark cursor as being notified - */ -var setCursorNotified = function(self, callback) { - self.cursorState.notified = true; - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - handleCallback(callback, null, null); -} - -var nextFunction = function(self, callback) { - // We have notified about it - if(self.cursorState.notified) { - return callback(new Error('cursor is exhausted')); - } - - // Cursor is killed return null - if(isCursorKilled(self, callback)) return; - - // Cursor is dead but not marked killed, return null - if(isCursorDeadButNotkilled(self, callback)) return; - - // We have a dead and killed cursor, attempting to call next should error - if(isCursorDeadAndKilled(self, callback)) return; - - // We have just started the cursor - if(!self.cursorState.init) { - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.topology.isConnected(self.options) && self.disconnectHandler != null) { - return self.disconnectHandler.addObjectAndMethod('cursor', self, 'next', [callback], callback); - } - - try { - // Get a server - self.server = self.topology.getServer(self.options); - // Get a connection - self.connection = self.server.getConnection(); - // Get the callbacks - self.callbacks = self.server.getCallbacks(); - } catch(err) { - return callback(err); - } - - // Set as init - self.cursorState.init = true; - - try { - // Get the right wire protocol command - self.query = self.server.wireProtocolHandler.command(self.bson, self.ns, self.cmd, self.cursorState, self.topology, self.options); - } catch(err) { - return callback(err); - } - } - - // Process exhaust messages - var processExhaustMessages = function(err, result) { - if(err) { - self.cursorState.dead = true; - self.callbacks.unregister(self.query.requestId); - return callback(err); - } - - // Concatenate all the documents - self.cursorState.documents = self.cursorState.documents.concat(result.documents); - - // If we have no documents left - if(Long.ZERO.equals(result.cursorId)) { - self.cursorState.cursorId = Long.ZERO; - self.callbacks.unregister(self.query.requestId); - return nextFunction(self, callback); - } - - // Set up next listener - self.callbacks.register(result.requestId, processExhaustMessages) - - // Initial result - if(self.cursorState.cursorId == null) { - self.cursorState.cursorId = result.cursorId; - nextFunction(self, callback); - } - } - - // If we have exhaust - if(self.cmd.exhaust && self.cursorState.cursorId == null) { - // Handle all the exhaust responses - self.callbacks.register(self.query.requestId, processExhaustMessages); - // Write the initial command out - return self.connection.write(self.query.toBin()); - } else if(self.cmd.exhaust && self.cursorState.cursorIndex < self.cursorState.documents.length) { - return handleCallback(callback, null, self.cursorState.documents[self.cursorState.cursorIndex++]); - } else if(self.cmd.exhaust && Long.ZERO.equals(self.cursorState.cursorId)) { - self.callbacks.unregister(self.query.requestId); - return setCursorNotified(self, callback); - } else if(self.cmd.exhaust) { - return setTimeout(function() { - if(Long.ZERO.equals(self.cursorState.cursorId)) return; - nextFunction(self, callback); - }, 1); - } - - // If we don't have a cursorId execute the first query - if(self.cursorState.cursorId == null) { - // Check if connection is dead and return if not possible to - // execute the query against the db - if(isConnectionDead(self, callback)) return; - - // Check if topology is destroyed - if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); - - // query, cmd, options, cursorState, callback - self._find(function(err, r) { - if(err) return handleCallback(callback, err, null); - if(self.cursorState.documents.length == 0 && !self.cmd.tailable && !self.cmd.awaitData) { - return setCursorNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } else if(self.cursorState.cursorIndex == self.cursorState.documents.length - && !Long.ZERO.equals(self.cursorState.cursorId)) { - // Ensure an empty cursor state - self.cursorState.documents = []; - self.cursorState.cursorIndex = 0; - - // Check if topology is destroyed - if(self.topology.isDestroyed()) return callback(new MongoError(f('connection destroyed, not possible to instantiate cursor'))); - - // Check if connection is dead and return if not possible to - // execute a getmore on this connection - if(isConnectionDead(self, callback)) return; - - // Execute the next get more - self._getmore(function(err, doc) { - if(err) return handleCallback(callback, err); - if(self.cursorState.documents.length == 0 - && Long.ZERO.equals(self.cursorState.cursorId)) { - self.cursorState.dead = true; - } - - // Tailable cursor getMore result, notify owner about it - // No attempt is made here to retry, this is left to the user of the - // core module to handle to keep core simple - if(self.cursorState.documents.length == 0 && self.cmd.tailable) { - return handleCallback(callback, MongoError.create({ - message: "No more documents in tailed cursor" - , tailable: self.cmd.tailable - , awaitData: self.cmd.awaitData - })); - } - - if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - return setCursorDeadAndNotified(self, callback); - } - - nextFunction(self, callback); - }); - } else if(self.cursorState.documents.length == self.cursorState.cursorIndex - && self.cmd.tailable) { - return handleCallback(callback, MongoError.create({ - message: "No more documents in tailed cursor" - , tailable: self.cmd.tailable - , awaitData: self.cmd.awaitData - })); - } else if(self.cursorState.documents.length == self.cursorState.cursorIndex - && Long.ZERO.equals(self.cursorState.cursorId)) { - setCursorDeadAndNotified(self, callback); - } else { - if(self.cursorState.limit > 0 && self.cursorState.currentLimit >= self.cursorState.limit) { - // Ensure we kill the cursor on the server - self.kill(); - // Set cursor in dead and notified state - return setCursorDeadAndNotified(self, callback); - } - - // Increment the current cursor limit - self.cursorState.currentLimit += 1; - - // Get the document - var doc = self.cursorState.documents[self.cursorState.cursorIndex++]; - - // Transform the doc with passed in transformation method if provided - if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function') { - doc = self.cursorState.transforms.doc(doc); - } - - // Return the document - handleCallback(callback, null, doc); - } -} - -/** - * Retrieve the next document from the cursor - * @method - * @param {resultCallback} callback A callback function - */ -Cursor.prototype.next = function(callback) { - nextFunction(this, callback); -} - -module.exports = Cursor; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js deleted file mode 100644 index 4e17ef3..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/error.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; - -/** - * Creates a new MongoError - * @class - * @augments Error - * @param {string} message The error message - * @return {MongoError} A MongoError instance - */ -function MongoError(message) { - this.name = 'MongoError'; - this.message = message; - Error.captureStackTrace(this, MongoError); -} - -/** - * Creates a new MongoError object - * @method - * @param {object} options The error options - * @return {MongoError} A MongoError instance - */ -MongoError.create = function(options) { - var err = null; - - if(options instanceof Error) { - err = new MongoError(options.message); - err.stack = options.stack; - } else if(typeof options == 'string') { - err = new MongoError(options); - } else { - err = new MongoError(options.message || options.errmsg || options.$err || "n/a"); - // Other options - for(var name in options) { - err[name] = options[name]; - } - } - - return err; -} - -// Extend JavaScript error -MongoError.prototype = new Error; - -module.exports = MongoError; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js deleted file mode 100644 index dcceda4..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/tools/smoke_plugin.js +++ /dev/null @@ -1,59 +0,0 @@ -var fs = require('fs'); - -/* Note: because this plugin uses process.on('uncaughtException'), only one - * of these can exist at any given time. This plugin and anything else that - * uses process.on('uncaughtException') will conflict. */ -exports.attachToRunner = function(runner, outputFile) { - var smokeOutput = { results : [] }; - var runningTests = {}; - - var integraPlugin = { - beforeTest: function(test, callback) { - test.startTime = Date.now(); - runningTests[test.name] = test; - callback(); - }, - afterTest: function(test, callback) { - smokeOutput.results.push({ - status: test.status, - start: test.startTime, - end: Date.now(), - test_file: test.name, - exit_code: 0, - url: "" - }); - delete runningTests[test.name]; - callback(); - }, - beforeExit: function(obj, callback) { - fs.writeFile(outputFile, JSON.stringify(smokeOutput), function() { - callback(); - }); - } - }; - - // In case of exception, make sure we write file - process.on('uncaughtException', function(err) { - // Mark all currently running tests as failed - for (var testName in runningTests) { - smokeOutput.results.push({ - status: "fail", - start: runningTests[testName].startTime, - end: Date.now(), - test_file: testName, - exit_code: 0, - url: "" - }); - } - - // write file - fs.writeFileSync(outputFile, JSON.stringify(smokeOutput)); - - // Standard NodeJS uncaught exception handler - console.error(err.stack); - process.exit(1); - }); - - runner.plugin(integraPlugin); - return integraPlugin; -}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js deleted file mode 100644 index ff7bf1b..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/command_result.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; - -var setProperty = require('../connection/utils').setProperty - , getProperty = require('../connection/utils').getProperty - , getSingleProperty = require('../connection/utils').getSingleProperty; - -/** - * Creates a new CommandResult instance - * @class - * @param {object} result CommandResult object - * @param {Connection} connection A connection instance associated with this result - * @return {CommandResult} A cursor instance - */ -var CommandResult = function(result, connection) { - this.result = result; - this.connection = connection; -} - -/** - * Convert CommandResult to JSON - * @method - * @return {object} - */ -CommandResult.prototype.toJSON = function() { - return this.result; -} - -/** - * Convert CommandResult to String representation - * @method - * @return {string} - */ -CommandResult.prototype.toString = function() { - return JSON.stringify(this.toJSON()); -} - -module.exports = CommandResult; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js deleted file mode 100644 index c54514a..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/mongos.js +++ /dev/null @@ -1,1000 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , b = require('bson') - , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain - , EventEmitter = require('events').EventEmitter - , BasicCursor = require('../cursor') - , BSON = require('bson').native().BSON - , BasicCursor = require('../cursor') - , Server = require('./server') - , Logger = require('../connection/logger') - , ReadPreference = require('./read_preference') - , Session = require('./session') - , MongoError = require('../error'); - -/** - * @fileOverview The **Mongos** class is a class that represents a Mongos Proxy topology and is - * used to construct connections. - * - * @example - * var Mongos = require('mongodb-core').Mongos - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new Mongos([{host: 'localhost', port: 30000}]); - * // Wait for the connection event - * server.on('connect', function(server) { - * server.destroy(); - * }); - * - * // Start connecting - * server.connect(); - */ - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -// All bson types -var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; -// BSON parser -var bsonInstance = null; - -// Instance id -var mongosId = 0; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for(var name in options) { - opts[name] = options[name]; - } - return opts; -} - -var State = function(readPreferenceStrategies) { - // Internal state - this.s = { - connectedServers: [] - , disconnectedServers: [] - , readPreferenceStrategies: readPreferenceStrategies - } -} - -// -// A Mongos connected -State.prototype.connected = function(server) { - // Locate in disconnected servers and remove - this.s.disconnectedServers = this.s.disconnectedServers.filter(function(s) { - return !s.equals(server); - }); - - var found = false; - // Check if the server exists - this.s.connectedServers.forEach(function(s) { - if(s.equals(server)) found = true; - }); - - // Add to disconnected list if it does not already exist - if(!found) this.s.connectedServers.push(server); -} - -// -// A Mongos disconnected -State.prototype.disconnected = function(server) { - // Locate in disconnected servers and remove - this.s.connectedServers = this.s.connectedServers.filter(function(s) { - return !s.equals(server); - }); - - var found = false; - // Check if the server exists - this.s.disconnectedServers.forEach(function(s) { - if(s.equals(server)) found = true; - }); - - // Add to disconnected list if it does not already exist - if(!found) this.s.disconnectedServers.push(server); -} - -// -// Return the list of disconnected servers -State.prototype.disconnectedServers = function() { - return this.s.disconnectedServers.slice(0); -} - -// -// Get connectedServers -State.prototype.connectedServers = function() { - return this.s.connectedServers.slice(0) -} - -// -// Get all servers -State.prototype.getAll = function() { - return this.s.connectedServers.slice(0).concat(this.s.disconnectedServers); -} - -// -// Get all connections -State.prototype.getAllConnections = function() { - var connections = []; - this.s.connectedServers.forEach(function(e) { - connections = connections.concat(e.connections()); - }); - return connections; -} - -// -// Destroy the state -State.prototype.destroy = function() { - // Destroy any connected servers - while(this.s.connectedServers.length > 0) { - var server = this.s.connectedServers.shift(); - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Server destroy - server.destroy(); - // Add to list of disconnected servers - this.s.disconnectedServers.push(server); - } -} - -// -// Are we connected -State.prototype.isConnected = function() { - return this.s.connectedServers.length > 0; -} - -// -// Pick a server -State.prototype.pickServer = function(readPreference) { - readPreference = readPreference || ReadPreference.primary; - - // Do we have a custom readPreference strategy, use it - if(this.s.readPreferenceStrategies != null && this.s.readPreferenceStrategies[readPreference] != null) { - return this.s.readPreferenceStrategies[readPreference].pickServer(connectedServers, readPreference); - } - - // No valid connections - if(this.s.connectedServers.length == 0) throw new MongoError("no mongos proxy available"); - // Pick first one - return this.s.connectedServers[0]; -} - -/** - * Creates a new Mongos instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {number} [options.reconnectTries=30] Reconnect retries for HA if no servers available - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=1000] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @return {Mongos} A cursor instance - * @fires Mongos#connect - * @fires Mongos#joined - * @fires Mongos#left - */ -var Mongos = function(seedlist, options) { - var self = this; - options = options || {}; - - // Add event listener - EventEmitter.call(this); - - // Validate seedlist - if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); - // Validate list - if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); - // Validate entries - seedlist.forEach(function(e) { - if(typeof e.host != 'string' || typeof e.port != 'number') - throw new MongoError("seedlist entry must contain a host and port"); - }); - - // BSON Parser, ensure we have a single instance - bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; - // Pick the right bson parser - var bson = options.bson ? options.bson : bsonInstance; - // Add bson parser to options - options.bson = bson; - - // The Mongos state - this.s = { - // Seed list for sharding passed in - seedlist: seedlist - // Passed in options - , options: options - // Logger - , logger: Logger('Mongos', options) - // Reconnect tries - , reconnectTries: options.reconnectTries || 30 - // Ha interval - , haInterval: options.haInterval || 5000 - // Have omitted fullsetup - , fullsetup: false - // Cursor factory - , Cursor: options.cursorFactory || BasicCursor - // Current credentials used for auth - , credentials: [] - // BSON Parser - , bsonInstance: bsonInstance - , bson: bson - // Default state - , state: DISCONNECTED - // Swallow or emit errors - , emitError: typeof options.emitError == 'boolean' ? options.emitError : false - // Contains any alternate strategies for picking - , readPreferenceStrategies: {} - // Auth providers - , authProviders: {} - // Unique instance id - , id: mongosId++ - // Authentication in progress - , authInProgress: false - // Servers added while auth in progress - , authInProgressServers: [] - // Current retries left - , retriesLeft: options.reconnectTries || 30 - // Do we have a not connected handler - , disconnectHandler: options.disconnectHandler - } - - // Set up the connection timeout for the options - options.connectionTimeout = options.connectionTimeout || 1000; - - // Create a new state for the mongos - this.s.mongosState = new State(this.s.readPreferenceStrategies); - - // BSON property (find a server and pass it along) - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - var servers = self.s.mongosState.getAll(); - return servers.length > 0 ? servers[0].bson : null; - } - }); - - Object.defineProperty(this, 'id', { - enumerable:true, get: function() { return self.s.id; } - }); - - Object.defineProperty(this, 'type', { - enumerable:true, get: function() { return 'mongos'; } - }); - - Object.defineProperty(this, 'haInterval', { - enumerable:true, get: function() { return self.s.haInterval; } - }); - - Object.defineProperty(this, 'state', { - enumerable:true, get: function() { return self.s.mongosState; } - }); -} - -inherits(Mongos, EventEmitter); - -/** - * Name of BSON parser currently used - * @method - * @return {string} - */ -Mongos.prototype.parserType = function() { - if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) - return 'c++'; - return 'js'; -} - -/** - * Execute a command - * @method - * @param {string} type Type of BSON parser to use (c++ or js) - */ -Mongos.prototype.setBSONParserType = function(type) { - var nBSON = null; - - if(type == 'c++') { - nBSON = require('bson').native().BSON; - } else if(type == 'js') { - nBSON = require('bson').pure().BSON; - } else { - throw new MongoError(f("% parser not supported", type)); - } - - this.s.options.bson = new nBSON(bsonTypes); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Mongos.prototype.lastIsMaster = function() { - var connectedServers = this.s.mongosState.connectedServers(); - if(connectedServers.length > 0) return connectedServers[0].lastIsMaster(); - return null; -} - -/** - * Initiate server connect - * @method - */ -Mongos.prototype.connect = function(_options) { - var self = this; - // Start replicaset inquiry process - setTimeout(mongosInquirer(self, self.s), self.s.haInterval); - // Additional options - if(_options) for(var name in _options) self.s.options[name] = _options[name]; - // For all entries in the seedlist build a server instance - self.s.seedlist.forEach(function(e) { - // Clone options - var opts = cloneOptions(self.s.options); - // Add host and port - opts.host = e.host; - opts.port = e.port; - opts.reconnect = false; - opts.readPreferenceStrategies = self.s.readPreferenceStrategies; - // Share the auth store - opts.authProviders = self.s.authProviders; - // Don't emit errors - opts.emitError = true; - // Create a new Server - self.s.mongosState.disconnected(new Server(opts)); - }); - - // Get the disconnected servers - var servers = self.s.mongosState.disconnectedServers(); - - // Attempt to connect to all the servers - while(servers.length > 0) { - // Get the server - var server = servers.shift(); - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { - server.removeAllListeners(e); - }); - - // Set up the event handlers - server.once('error', errorHandlerTemp(self, self.s, server)); - server.once('close', errorHandlerTemp(self, self.s, server)); - server.once('timeout', errorHandlerTemp(self, self.s, server)); - server.once('parseError', errorHandlerTemp(self, self.s, server)); - server.once('connect', connectHandler(self, self.s, 'connect')); - - if(self.s.logger.isInfo()) self.s.logger.info(f('connecting to server %s', server.name)); - // Attempt to connect - server.connect(); - } -} - -/** - * Destroy the server connection - * @method - */ -Mongos.prototype.destroy = function(emitClose) { - this.s.state = DESTROYED; - // Emit close - if(emitClose && self.listeners('close').length > 0) self.emit('close', self); - // Destroy the state - this.s.mongosState.destroy(); -} - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Mongos.prototype.isConnected = function() { - return this.s.mongosState.isConnected(); -} - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Mongos.prototype.isDestroyed = function() { - return this.s.state == DESTROYED; -} - -// -// Operations -// - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.insert = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - executeWriteOperation(this.s, 'insert', ns, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.update = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - executeWriteOperation(this.s, 'update', ns, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.remove = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - executeWriteOperation(this.s, 'remove', ns, ops, options, callback); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.command = function(ns, cmd, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - var self = this; - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - var server = null; - // Ensure we have no options - options = options || {}; - - // We need to execute the command on all servers - if(options.onAll) { - var servers = self.s.mongosState.getAll(); - var count = servers.length; - var cmdErr = null; - - for(var i = 0; i < servers.length; i++) { - servers[i].command(ns, cmd, options, function(err, r) { - count = count - 1; - // Finished executing command - if(count == 0) { - // Was it a logout command clear any credentials - if(cmd.logout) clearCredentials(state, ns); - // Return the error - callback(err, r); - } - }); - } - - return; - } - - - try { - // Get a primary - server = self.s.mongosState.pickServer(options.writeConcern ? ReadPreference.primary : options.readPreference); - } catch(err) { - return callback(err); - } - - // No server returned we had an error - if(server == null) return callback(new MongoError("no mongos found")); - server.command(ns, cmd, options, function(err, r) { - // Was it a logout command clear any credentials - if(cmd.logout) clearCredentials(self.s, ns); - callback(err, r); - }); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Mongos.prototype.cursor = function(ns, cmd, cursorOptions) { - cursorOptions = cursorOptions || {}; - var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; - return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -Mongos.prototype.auth = function(mechanism, db) { - var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - var callback = args.pop(); - - // If we don't have the mechanism fail - if(this.s.authProviders[mechanism] == null && mechanism != 'default') - throw new MongoError(f("auth provider %s does not exist", mechanism)); - - // Authenticate against all the servers - var servers = this.s.mongosState.connectedServers().slice(0); - var count = servers.length; - // Correct authentication - var authenticated = true; - var authErr = null; - // Set auth in progress - this.s.authInProgress = true; - - // Authenticate against all servers - while(servers.length > 0) { - var server = servers.shift(); - // Arguments without a callback - var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); - // Create arguments - var finalArguments = argsWithoutCallback.concat([function(err, r) { - count = count - 1; - if(err) authErr = err; - if(!r) authenticated = false; - - // We are done - if(count == 0) { - // We have more servers that are not authenticated, let's authenticate - if(self.s.authInProgressServers.length > 0) { - self.s.authInProgressServers = []; - return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); - } - - // Auth is done - self.s.authInProgress = false; - // Add successful credentials - if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); - // Return the auth error - if(authErr) return callback(authErr, false); - // Successfully authenticated session - callback(null, new Session({}, self)); - } - }]); - - // Execute the auth - server.auth.apply(server, finalArguments); - } -} - -// -// Plugin methods -// - -/** - * Add custom read preference strategy - * @method - * @param {string} name Name of the read preference strategy - * @param {object} strategy Strategy object instance - */ -Mongos.prototype.addReadPreferenceStrategy = function(name, strategy) { - if(this.s.readPreferenceStrategies == null) this.s.readPreferenceStrategies = {}; - this.s.readPreferenceStrategies[name] = strategy; -} - -/** - * Add custom authentication mechanism - * @method - * @param {string} name Name of the authentication mechanism - * @param {object} provider Authentication object instance - */ -Mongos.prototype.addAuthProvider = function(name, provider) { - this.s.authProviders[name] = provider; -} - -/** - * Get connection - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Connection} - */ -Mongos.prototype.getConnection = function(options) { - // Ensure we have no options - options = options || {}; - // Pick the right server based on readPreference - var server = this.s.mongosState.pickServer(options.readPreference); - if(server == null) return null; - // Return connection - return server.getConnection(); -} - -/** - * Get server - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Server} - */ -Mongos.prototype.getServer = function(options) { - // Ensure we have no options - options = options || {}; - // Pick the right server based on readPreference - return this.s.mongosState.pickServer(options.readPreference); -} - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Mongos.prototype.connections = function() { - return this.s.mongosState.getAllConnections(); -} - -// -// Inquires about state changes -// -var mongosInquirer = function(self, state) { - return function() { - if(state.state == DESTROYED) return - if(state.state == CONNECTED) state.retriesLeft = state.reconnectTries; - - // If we have a disconnected site - if(state.state == DISCONNECTED && state.retriesLeft == 0) { - self.destroy(); - return self.emit('error', new MongoError(f('failed to reconnect after %s', state.reconnectTries))); - } else if(state == DISCONNECTED) { - state.retriesLeft = state.retriesLeft - 1; - } - - // If we have a primary and a disconnect handler, execute - // buffered operations - if(state.mongosState.isConnected() && state.disconnectHandler) { - state.disconnectHandler.execute(); - } - - // Log the information - if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess running')); - - // Let's query any disconnected proxies - var disconnectedServers = state.mongosState.disconnectedServers(); - if(disconnectedServers.length == 0) return setTimeout(mongosInquirer(self, state), state.haInterval); - - // Count of connections waiting to be connected - var connectionCount = disconnectedServers.length; - if(state.logger.isDebug()) state.logger.debug(f('mongos ha proceess found %d disconnected proxies', connectionCount)); - - // Let's attempt to reconnect - while(disconnectedServers.length > 0) { - var server = disconnectedServers.shift(); - if(state.logger.isDebug()) state.logger.debug(f('attempting to connect to server %s', server.name)); - - // Remove any listeners - ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { - server.removeAllListeners(e); - }); - - // Set up the event handlers - server.once('error', errorHandlerTemp(self, state, server)); - server.once('close', errorHandlerTemp(self, state, server)); - server.once('timeout', errorHandlerTemp(self, state, server)); - server.once('connect', connectHandler(self, state, 'ha')); - // Start connect - server.connect(); - } - - // Let's keep monitoring but wait for possible timeout to happen - return setTimeout(mongosInquirer(self, state), state.options.connectionTimeout + state.haInterval); - } -} - -// -// Error handler for initial connect -var errorHandlerTemp = function(self, state, server) { - return function(err, server) { - // Log the information - if(state.logger.isInfo()) state.logger.info(f('server %s disconnected with error %s', server.name, JSON.stringify(err))); - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Signal disconnect of server - state.mongosState.disconnected(server); - } -} - -// -// Handlers -var errorHandler = function(self, state) { - return function(err, server) { - if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', server.name, JSON.stringify(err))); - state.mongosState.disconnected(server); - // No more servers left emit close - if(state.mongosState.connectedServers().length == 0) { - state.state = DISCONNECTED; - } - - // Signal server left - self.emit('left', 'mongos', server); - if(state.emitError) self.emit('error', err, server); - } -} - -var timeoutHandler = function(self, state) { - return function(err, server) { - if(state.logger.isInfo()) state.logger.info(f('server %s timed out', server.name)); - state.mongosState.disconnected(server); - - // No more servers emit close event if no entries left - if(state.mongosState.connectedServers().length == 0) { - state.state = DISCONNECTED; - } - - // Signal server left - self.emit('left', 'mongos', server); - } -} - -var closeHandler = function(self, state) { - return function(err, server) { - if(state.logger.isInfo()) state.logger.info(f('server %s closed', server.name)); - state.mongosState.disconnected(server); - - // No more servers left emit close - if(state.mongosState.connectedServers().length == 0) { - state.state = DISCONNECTED; - } - - // Signal server left - self.emit('left', 'mongos', server); - } -} - -// Connect handler -var connectHandler = function(self, state, e) { - return function(server) { - if(state.logger.isInfo()) state.logger.info(f('connected to %s', server.name)); - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect', 'message', 'parseError'].forEach(function(e) { - server.removeAllListeners(e); - }); - - // finish processing the server - var processNewServer = function(_server) { - // Add the server handling code - if(_server.isConnected()) { - _server.once('error', errorHandler(self, state)); - _server.once('close', closeHandler(self, state)); - _server.once('timeout', timeoutHandler(self, state)); - _server.once('parseError', timeoutHandler(self, state)); - } - - // Emit joined event - self.emit('joined', 'mongos', _server); - - // Add to list connected servers - state.mongosState.connected(_server); - - // Do we have a reconnect event - if('ha' == e && state.mongosState.connectedServers().length == 1) { - self.emit('reconnect', _server); - } - - // Full setup - if(state.mongosState.disconnectedServers().length == 0 && - state.mongosState.connectedServers().length > 0 && - !state.fullsetup) { - state.fullsetup = true; - self.emit('fullsetup'); - } - - // all connected - if(state.mongosState.disconnectedServers().length == 0 && - state.mongosState.connectedServers().length == state.seedlist.length && - !state.all) { - state.all = true; - self.emit('all'); - } - - // Set connected - if(state.state == DISCONNECTED) { - state.state = CONNECTED; - self.emit('connect', self); - } - } - - // Is there an authentication process ongoing - if(state.authInProgress) { - state.authInProgressServers.push(server); - } - - // No credentials just process server - if(state.credentials.length == 0) return processNewServer(server); - - // Do we have credentials, let's apply them all - var count = state.credentials.length; - // Apply the credentials - for(var i = 0; i < state.credentials.length; i++) { - server.auth.apply(server, state.credentials[i].concat([function(err, r) { - count = count - 1; - if(count == 0) processNewServer(server); - }])); - } - } -} - -// -// Add server to the list if it does not exist -var addToListIfNotExist = function(list, server) { - var found = false; - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Check if the server already exists - for(var i = 0; i < list.length; i++) { - if(list[i].equals(server)) found = true; - } - - if(!found) { - list.push(server); - } -} - -// Add the new credential for a db, removing the old -// credential from the cache -var addCredentials = function(state, db, argsWithoutCallback) { - // Remove any credentials for the db - clearCredentials(state, db + ".dummy"); - // Add new credentials to list - state.credentials.push(argsWithoutCallback); -} - -// Clear out credentials for a namespace -var clearCredentials = function(state, ns) { - var db = ns.split('.')[0]; - var filteredCredentials = []; - - // Filter out all credentials for the db the user is logging out off - for(var i = 0; i < state.credentials.length; i++) { - if(state.credentials[i][1] != db) filteredCredentials.push(state.credentials[i]); - } - - // Set new list of credentials - state.credentials = filteredCredentials; -} - -var processReadPreference = function(cmd, options) { - options = options || {} - // No read preference specified - if(options.readPreference == null) return cmd; -} - -// -// Execute write operation -var executeWriteOperation = function(state, op, ns, ops, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - var server = null; - // Ensure we have no options - options = options || {}; - try { - // Get a primary - server = state.mongosState.pickServer(); - } catch(err) { - return callback(err); - } - - // No server returned we had an error - if(server == null) return callback(new MongoError("no mongos found")); - // Execute the command - server[op](ns, ops, options, callback); -} - -/** - * A mongos connect event, used to verify that the connection is up and running - * - * @event Mongos#connect - * @type {Mongos} - */ - -/** - * A server member left the mongos list - * - * @event Mongos#left - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the mongos list - * - * @event Mongos#joined - * @type {Mongos} - * @param {string} type The type of member that left (mongos) - * @param {Server} server The server object that joined - */ - -module.exports = Mongos; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js deleted file mode 100644 index 913ca1b..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/read_preference.js +++ /dev/null @@ -1,106 +0,0 @@ -"use strict"; - -var needSlaveOk = ['primaryPreferred', 'secondary', 'secondaryPreferred', 'nearest']; - -/** - * @fileOverview The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is - * used to construct connections. - * - * @example - * var ReplSet = require('mongodb-core').ReplSet - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); - * // Wait for the connection event - * server.on('connect', function(server) { - * var cursor = server.cursor('db.test' - * , {find: 'db.test', query: {}} - * , {readPreference: new ReadPreference('secondary')}); - * cursor.next(function(err, doc) { - * server.destroy(); - * }); - * }); - * - * // Start connecting - * server.connect(); - */ - -/** - * Creates a new Pool instance - * @class - * @param {string} preference A string describing the preference (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @param {object} tags The tags object - * @param {object} [options] Additional read preference options - * @property {string} preference The preference string (primary|primaryPreferred|secondary|secondaryPreferred|nearest) - * @property {object} tags The tags object - * @property {object} options Additional read preference options - * @return {ReadPreference} - */ -var ReadPreference = function(preference, tags, options) { - this.preference = preference; - this.tags = tags; - this.options = options; -} - -/** - * This needs slaveOk bit set - * @method - * @return {boolean} - */ -ReadPreference.prototype.slaveOk = function() { - return needSlaveOk.indexOf(this.preference) != -1; -} - -/** - * Are the two read preference equal - * @method - * @return {boolean} - */ -ReadPreference.prototype.equals = function(readPreference) { - return readPreference.preference == this.preference; -} - -/** - * Return JSON representation - * @method - * @return {Object} - */ -ReadPreference.prototype.toJSON = function() { - var readPreference = {mode: this.preference}; - if(Array.isArray(this.tags)) readPreference.tags = this.tags; - return readPreference; -} - -/** - * Primary read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.primary = new ReadPreference('primary'); -/** - * Primary Preferred read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.primaryPreferred = new ReadPreference('primaryPreferred'); -/** - * Secondary read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.secondary = new ReadPreference('secondary'); -/** - * Secondary Preferred read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.secondaryPreferred = new ReadPreference('secondaryPreferred'); -/** - * Nearest read preference - * @method - * @return {ReadPreference} - */ -ReadPreference.nearest = new ReadPreference('nearest'); - -module.exports = ReadPreference; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js deleted file mode 100644 index 011c8fe..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset.js +++ /dev/null @@ -1,1333 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , b = require('bson') - , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain - , debugOptions = require('../connection/utils').debugOptions - , EventEmitter = require('events').EventEmitter - , Server = require('./server') - , ReadPreference = require('./read_preference') - , MongoError = require('../error') - , Ping = require('./strategies/ping') - , Session = require('./session') - , BasicCursor = require('../cursor') - , BSON = require('bson').native().BSON - , State = require('./replset_state') - , Logger = require('../connection/logger'); - -/** - * @fileOverview The **ReplSet** class is a class that represents a Replicaset topology and is - * used to construct connecctions. - * - * @example - * var ReplSet = require('mongodb-core').ReplSet - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new ReplSet([{host: 'localhost', port: 30000}], {setName: 'rs'}); - * // Wait for the connection event - * server.on('connect', function(server) { - * server.destroy(); - * }); - * - * // Start connecting - * server.connect(); - */ - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -// -// ReplSet instance id -var replSetId = 1; - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for(var name in options) { - opts[name] = options[name]; - } - return opts; -} - -// All bson types -var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; -// BSON parser -var bsonInstance = null; - -/** - * Creates a new Replset instance - * @class - * @param {array} seedlist A list of seeds for the replicaset - * @param {boolean} options.setName The Replicaset set name - * @param {boolean} [options.secondaryOnlyConnectionAllowed=false] Allow connection to a secondary only replicaset - * @param {number} [options.haInterval=5000] The High availability period for replicaset inquiry - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.singleBufferSerializtion=true] Serialize into single buffer, trade of peak memory for serialization speed - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) - * @return {ReplSet} A cursor instance - * @fires ReplSet#connect - * @fires ReplSet#ha - * @fires ReplSet#joined - * @fires ReplSet#left - */ -var ReplSet = function(seedlist, options) { - var self = this; - options = options || {}; - - // Validate seedlist - if(!Array.isArray(seedlist)) throw new MongoError("seedlist must be an array"); - // Validate list - if(seedlist.length == 0) throw new MongoError("seedlist must contain at least one entry"); - // Validate entries - seedlist.forEach(function(e) { - if(typeof e.host != 'string' || typeof e.port != 'number') - throw new MongoError("seedlist entry must contain a host and port"); - }); - - // Add event listener - EventEmitter.call(this); - - // Set the bson instance - bsonInstance = bsonInstance == null ? new BSON(bsonTypes) : bsonInstance; - - // Internal state hash for the object - this.s = { - options: options - // Logger instance - , logger: Logger('ReplSet', options) - // Uniquely identify the replicaset instance - , id: replSetId++ - // Index - , index: 0 - // Ha Index - , haId: 0 - // Current credentials used for auth - , credentials: [] - // Factory overrides - , Cursor: options.cursorFactory || BasicCursor - // BSON Parser, ensure we have a single instance - , bsonInstance: bsonInstance - // Pick the right bson parser - , bson: options.bson ? options.bson : bsonInstance - // Special replicaset options - , secondaryOnlyConnectionAllowed: typeof options.secondaryOnlyConnectionAllowed == 'boolean' - ? options.secondaryOnlyConnectionAllowed : false - , haInterval: options.haInterval || 10000 - // Are we running in debug mode - , debug: typeof options.debug == 'boolean' ? options.debug : false - // The replicaset name - , setName: options.setName - // Swallow or emit errors - , emitError: typeof options.emitError == 'boolean' ? options.emitError : false - // Grouping tag used for debugging purposes - , tag: options.tag - // Do we have a not connected handler - , disconnectHandler: options.disconnectHandler - // Currently connecting servers - , connectingServers: {} - // Contains any alternate strategies for picking - , readPreferenceStrategies: {} - // Auth providers - , authProviders: {} - // All the servers - , disconnectedServers: [] - // Initial connection servers - , initialConnectionServers: [] - // High availability process running - , highAvailabilityProcessRunning: false - // Full setup - , fullsetup: false - // All servers accounted for (used for testing) - , all: false - // Seedlist - , seedlist: seedlist - // Authentication in progress - , authInProgress: false - // Servers added while auth in progress - , authInProgressServers: [] - // Minimum heartbeat frequency used if we detect a server close - , minHeartbeatFrequencyMS: 500 - } - - // Add bson parser to options - options.bson = this.s.bson; - // Set up the connection timeout for the options - options.connectionTimeout = options.connectionTimeout || 10000; - - // Replicaset state - var replState = new State(this, { - id: this.s.id, setName: this.s.setName - , connectingServers: this.s.connectingServers - , secondaryOnlyConnectionAllowed: this.s.secondaryOnlyConnectionAllowed - }); - - // Add Replicaset state to our internal state - this.s.replState = replState; - - // BSON property (find a server and pass it along) - Object.defineProperty(this, 'bson', { - enumerable: true, get: function() { - var servers = self.s.replState.getAll(); - return servers.length > 0 ? servers[0].bson : null; - } - }); - - Object.defineProperty(this, 'id', { - enumerable:true, get: function() { return self.s.id; } - }); - - Object.defineProperty(this, 'haInterval', { - enumerable:true, get: function() { return self.s.haInterval; } - }); - - Object.defineProperty(this, 'state', { - enumerable:true, get: function() { return self.s.replState; } - }); - - // - // Debug options - if(self.s.debug) { - // Add access to the read Preference Strategies - Object.defineProperty(this, 'readPreferenceStrategies', { - enumerable: true, get: function() { return self.s.readPreferenceStrategies; } - }); - } - - Object.defineProperty(this, 'type', { - enumerable:true, get: function() { return 'replset'; } - }); - - // Add the ping strategy for nearest - this.addReadPreferenceStrategy('nearest', new Ping(options)); -} - -inherits(ReplSet, EventEmitter); - -// -// Plugin methods -// - -/** - * Add custom read preference strategy - * @method - * @param {string} name Name of the read preference strategy - * @param {object} strategy Strategy object instance - */ -ReplSet.prototype.addReadPreferenceStrategy = function(name, func) { - this.s.readPreferenceStrategies[name] = func; -} - -/** - * Add custom authentication mechanism - * @method - * @param {string} name Name of the authentication mechanism - * @param {object} provider Authentication object instance - */ -ReplSet.prototype.addAuthProvider = function(name, provider) { - if(this.s.authProviders == null) this.s.authProviders = {}; - this.s.authProviders[name] = provider; -} - -/** - * Name of BSON parser currently used - * @method - * @return {string} - */ -ReplSet.prototype.parserType = function() { - if(this.s.bson.serialize.toString().indexOf('[native code]') != -1) - return 'c++'; - return 'js'; -} - -/** - * Execute a command - * @method - * @param {string} type Type of BSON parser to use (c++ or js) - */ -ReplSet.prototype.setBSONParserType = function(type) { - var nBSON = null; - - if(type == 'c++') { - nBSON = require('bson').native().BSON; - } else if(type == 'js') { - nBSON = require('bson').pure().BSON; - } else { - throw new MongoError(f("% parser not supported", type)); - } - - this.s.options.bson = new nBSON(bsonTypes); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -ReplSet.prototype.lastIsMaster = function() { - return this.s.replState.lastIsMaster(); -} - -/** - * Get connection - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Connection} - */ -ReplSet.prototype.getConnection = function(options) { - // Ensure we have no options - options = options || {}; - // Pick the right server based on readPreference - var server = pickServer(this, this.s, options.readPreference); - if(server == null) return null; - // Return connection - return server.getConnection(); -} - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -ReplSet.prototype.connections = function() { - return this.s.replState.getAllConnections(); -} - -/** - * Get server - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Server} - */ -ReplSet.prototype.getServer = function(options) { - // Ensure we have no options - options = options || {}; - // Pick the right server based on readPreference - return pickServer(this, this.s, options.readPreference); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.cursor = function(ns, cmd, cursorOptions) { - cursorOptions = cursorOptions || {}; - var FinalCursor = cursorOptions.cursorFactory || this.s.Cursor; - return new FinalCursor(this.s.bson, ns, cmd, cursorOptions, this, this.s.options); -} - -// -// Execute write operation -var executeWriteOperation = function(self, op, ns, ops, options, callback) { - if(typeof options == 'function') { - callback = options; - options = {}; - } - - var server = null; - // Ensure we have no options - options = options || {}; - // Get a primary - try { - server = pickServer(self, self.s, ReadPreference.primary); - if(self.s.debug) self.emit('pickedServer', ReadPreference.primary, server); - } catch(err) { - return callback(err); - } - - // No server returned we had an error - if(server == null) return callback(new MongoError("no server found")); - - // Handler - var handler = function(err, r) { - // We have a no master error, immediately refresh the view of the replicaset - if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); - // Return the result - callback(err, r); - } - - // Add operationId if existing - if(callback.operationId) handler.operationId = callback.operationId; - // Execute the command - server[op](ns, ops, options, handler); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.command = function(ns, cmd, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - - var server = null; - var self = this; - // Ensure we have no options - options = options || {}; - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected(options) && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // We need to execute the command on all servers - if(options.onAll) { - var servers = this.s.replState.getAll(); - var count = servers.length; - var cmdErr = null; - - for(var i = 0; i < servers.length; i++) { - servers[i].command(ns, cmd, options, function(err, r) { - count = count - 1; - // Finished executing command - if(count == 0) { - // Was it a logout command clear any credentials - if(cmd.logout) clearCredentials(self.s, ns); - // We have a no master error, immediately refresh the view of the replicaset - if(notMasterError(r) || notMasterError(err)) replicasetInquirer(self, self.s, true)(); - // Return the error - callback(err, r); - } - }); - } - - return; - } - - // Pick the right server based on readPreference - try { - server = pickServer(self, self.s, options.writeConcern ? ReadPreference.primary : options.readPreference); - if(self.s.debug) self.emit('pickedServer', options.writeConcern ? ReadPreference.primary : options.readPreference, server); - } catch(err) { - return callback(err); - } - - // No server returned we had an error - if(server == null) return callback(new MongoError("no server found")); - // Execute the command - server.command(ns, cmd, options, function(err, r) { - // Was it a logout command clear any credentials - if(cmd.logout) clearCredentials(self.s, ns); - // We have a no master error, immediately refresh the view of the replicaset - if(notMasterError(r) || notMasterError(err)) { - replicasetInquirer(self, self.s, true)(); - } - // Return the error - callback(err, r); - }); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.remove = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - executeWriteOperation(this, 'remove', ns, ops, options, callback); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.insert = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - executeWriteOperation(this, 'insert', ns, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -ReplSet.prototype.update = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - if(this.s.replState.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!this.isConnected() && this.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return this.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - executeWriteOperation(this, 'update', ns, ops, options, callback); -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -ReplSet.prototype.auth = function(mechanism, db) { - var allArgs = Array.prototype.slice.call(arguments, 0).slice(0); - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - var callback = args.pop(); - - // If we don't have the mechanism fail - if(this.s.authProviders[mechanism] == null && mechanism != 'default') - throw new MongoError(f("auth provider %s does not exist", mechanism)); - - // Authenticate against all the servers - var servers = this.s.replState.getAll().slice(0); - var count = servers.length; - // Correct authentication - var authenticated = true; - var authErr = null; - // Set auth in progress - this.s.authInProgress = true; - - // Authenticate against all servers - while(servers.length > 0) { - var server = servers.shift(); - - // Arguments without a callback - var argsWithoutCallback = [mechanism, db].concat(args.slice(0)); - // Create arguments - var finalArguments = argsWithoutCallback.concat([function(err, r) { - count = count - 1; - if(err) authErr = err; - if(!r) authenticated = false; - - // We are done - if(count == 0) { - // We have more servers that are not authenticated, let's authenticate - if(self.s.authInProgressServers.length > 0) { - self.s.authInProgressServers = []; - return self.auth.apply(self, [mechanism, db].concat(args).concat([callback])); - } - - // Auth is done - self.s.authInProgress = false; - // Add successful credentials - if(authErr == null) addCredentials(self.s, db, argsWithoutCallback); - // Return the auth error - if(authErr) return callback(authErr, false); - // Successfully authenticated session - callback(null, new Session({}, self)); - } - }]); - - // Execute the auth - server.auth.apply(server, finalArguments); - } -} - -ReplSet.prototype.state = function() { - return this.s.replState.state; -} - -/** - * Ensure single socket connections to arbiters and hidden servers - * @method - */ -var handleIsmaster = function(self) { - return function(ismaster, _server) { - if(ismaster.arbiterOnly) { - _server.s.options.size = 1; - } else if(ismaster.hidden) { - _server.s.options.size = 1; - } - } -} - -/** - * Initiate server connect - * @method - */ -ReplSet.prototype.connect = function(_options) { - var self = this; - // Start replicaset inquiry process - setTimeout(replicasetInquirer(this, this.s, false), this.s.haInterval); - // Additional options - if(_options) for(var name in _options) this.s.options[name] = _options[name]; - - // Set the state as connecting - this.s.replState.state = CONNECTING; - - // No fullsetup reached - this.s.fullsetup = false; - - // For all entries in the seedlist build a server instance - this.s.seedlist.forEach(function(e) { - // Clone options - var opts = cloneOptions(self.s.options); - // Add host and port - opts.host = e.host; - opts.port = e.port; - opts.reconnect = false; - opts.readPreferenceStrategies = self.s.readPreferenceStrategies; - opts.emitError = true; - if(self.s.tag) opts.tag = self.s.tag; - // Share the auth store - opts.authProviders = self.s.authProviders; - // Create a new Server - var server = new Server(opts); - // Handle the ismaster - server.on('ismaster', handleIsmaster(self)); - // Add to list of disconnected servers - self.s.disconnectedServers.push(server); - // Add to list of inflight Connections - self.s.initialConnectionServers.push(server); - }); - - // Attempt to connect to all the servers - while(this.s.disconnectedServers.length > 0) { - // Get the server - var server = this.s.disconnectedServers.shift(); - - // Set up the event handlers - server.once('error', errorHandlerTemp(this, this.s, 'error')); - server.once('close', errorHandlerTemp(this, this.s, 'close')); - server.once('timeout', errorHandlerTemp(this, this.s, 'timeout')); - server.once('connect', connectHandler(this, this.s)); - - // Attempt to connect - server.connect(); - } -} - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -ReplSet.prototype.isConnected = function(options) { - options = options || {}; - // If we specified a read preference check if we are connected to something - // than can satisfy this - if(options.readPreference - && options.readPreference.equals(ReadPreference.secondary)) - return this.s.replState.isSecondaryConnected(); - - if(options.readPreference - && options.readPreference.equals(ReadPreference.primary)) - return this.s.replState.isSecondaryConnected() || this.s.replState.isPrimaryConnected(); - - if(this.s.secondaryOnlyConnectionAllowed - && this.s.replState.isSecondaryConnected()) return true; - return this.s.replState.isPrimaryConnected(); -} - -/** - * Figure out if the replicaset instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -ReplSet.prototype.isDestroyed = function() { - return this.s.replState.state == DESTROYED; -} - -/** - * Destroy the server connection - * @method - */ -ReplSet.prototype.destroy = function(emitClose) { - var self = this; - if(this.s.logger.isInfo()) this.s.logger.info(f('[%s] destroyed', this.s.id)); - this.s.replState.state = DESTROYED; - - // Emit close - if(emitClose && self.listeners('close').length > 0) self.emit('close', self); - - // Destroy state - this.s.replState.destroy(); - - // Clear out any listeners - var events = ['timeout', 'error', 'close', 'joined', 'left']; - events.forEach(function(e) { - self.removeAllListeners(e); - }); -} - -/** - * A replset connect event, used to verify that the connection is up and running - * - * @event ReplSet#connect - * @type {ReplSet} - */ - -/** - * The replset high availability event - * - * @event ReplSet#ha - * @type {function} - * @param {string} type The stage in the high availability event (start|end) - * @param {boolean} data.norepeat This is a repeating high availability process or a single execution only - * @param {number} data.id The id for this high availability request - * @param {object} data.state An object containing the information about the current replicaset - */ - -/** - * A server member left the replicaset - * - * @event ReplSet#left - * @type {function} - * @param {string} type The type of member that left (primary|secondary|arbiter) - * @param {Server} server The server object that left - */ - -/** - * A server member joined the replicaset - * - * @event ReplSet#joined - * @type {function} - * @param {string} type The type of member that joined (primary|secondary|arbiter) - * @param {Server} server The server object that joined - */ - -// -// Inquires about state changes -// - -// Add the new credential for a db, removing the old -// credential from the cache -var addCredentials = function(s, db, argsWithoutCallback) { - // Remove any credentials for the db - clearCredentials(s, db + ".dummy"); - // Add new credentials to list - s.credentials.push(argsWithoutCallback); -} - -// Clear out credentials for a namespace -var clearCredentials = function(s, ns) { - var db = ns.split('.')[0]; - var filteredCredentials = []; - - // Filter out all credentials for the db the user is logging out off - for(var i = 0; i < s.credentials.length; i++) { - if(s.credentials[i][1] != db) filteredCredentials.push(s.credentials[i]); - } - - // Set new list of credentials - s.credentials = filteredCredentials; -} - -// -// Filter serves by tags -var filterByTags = function(readPreference, servers) { - if(readPreference.tags == null) return servers; - var filteredServers = []; - var tags = readPreference.tags; - - // Iterate over all the servers - for(var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - // Did we find the a matching server - var found = true; - // Check if the server is valid - for(var name in tags) { - if(serverTag[name] != tags[name]) found = false; - } - - // Add to candidate list - if(found) filteredServers.push(servers[i]); - } - - // Returned filtered servers - return filteredServers; -} - -// -// Pick a server based on readPreference -var pickServer = function(self, s, readPreference) { - // If no read Preference set to primary by default - readPreference = readPreference || ReadPreference.primary; - - // Do we have a custom readPreference strategy, use it - if(s.readPreferenceStrategies != null && s.readPreferenceStrategies[readPreference.preference] != null) { - if(s.readPreferenceStrategies[readPreference.preference] == null) throw new MongoError(f("cannot locate read preference handler for %s", readPreference.preference)); - var server = s.readPreferenceStrategies[readPreference.preference].pickServer(s.replState, readPreference); - if(s.debug) self.emit('pickedServer', readPreference, server); - return server; - } - - // Filter out any hidden secondaries - var secondaries = s.replState.secondaries.filter(function(server) { - if(server.lastIsMaster().hidden) return false; - return true; - }); - - // Check if we can satisfy and of the basic read Preferences - if(readPreference.equals(ReadPreference.secondary) - && secondaries.length == 0) - throw new MongoError("no secondary server available"); - - if(readPreference.equals(ReadPreference.secondaryPreferred) - && secondaries.length == 0 - && s.replState.primary == null) - throw new MongoError("no secondary or primary server available"); - - if(readPreference.equals(ReadPreference.primary) - && s.replState.primary == null) - throw new MongoError("no primary server available"); - - // Secondary - if(readPreference.equals(ReadPreference.secondary)) { - s.index = (s.index + 1) % secondaries.length; - return secondaries[s.index]; - } - - // Secondary preferred - if(readPreference.equals(ReadPreference.secondaryPreferred)) { - if(secondaries.length > 0) { - // Apply tags if present - var servers = filterByTags(readPreference, secondaries); - // If have a matching server pick one otherwise fall through to primary - if(servers.length > 0) { - s.index = (s.index + 1) % servers.length; - return servers[s.index]; - } - } - - return s.replState.primary; - } - - // Primary preferred - if(readPreference.equals(ReadPreference.primaryPreferred)) { - if(s.replState.primary) return s.replState.primary; - - if(secondaries.length > 0) { - // Apply tags if present - var servers = filterByTags(readPreference, secondaries); - // If have a matching server pick one otherwise fall through to primary - if(servers.length > 0) { - s.index = (s.index + 1) % servers.length; - return servers[s.index]; - } - - // Throw error a we have not valid secondary or primary servers - throw new MongoError("no secondary or primary server available"); - } - } - - // Return the primary - return s.replState.primary; -} - -var replicasetInquirer = function(self, state, norepeat) { - return function() { - if(state.replState.state == DESTROYED) return - // Process already running don't rerun - if(state.highAvailabilityProcessRunning) return; - // Started processes - state.highAvailabilityProcessRunning = true; - if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring process running %s', state.id, JSON.stringify(state.replState))); - - // Unique HA id to identify the current look running - var localHaId = state.haId++; - - // Clean out any failed connection attempts - state.connectingServers = {}; - - // Controls if we are doing a single inquiry or repeating - norepeat = typeof norepeat == 'boolean' ? norepeat : false; - - // If we have a primary and a disconnect handler, execute - // buffered operations - if(state.replState.isPrimaryConnected() && state.replState.isSecondaryConnected() && state.disconnectHandler) { - state.disconnectHandler.execute(); - } - - // Emit replicasetInquirer - self.emit('ha', 'start', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - - // Let's process all the disconnected servers - while(state.disconnectedServers.length > 0) { - // Get the first disconnected server - var server = state.disconnectedServers.shift(); - if(state.logger.isInfo()) state.logger.info(f('[%s] monitoring attempting to connect to %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); - // Set up the event handlers - server.once('error', errorHandlerTemp(self, state, 'error')); - server.once('close', errorHandlerTemp(self, state, 'close')); - server.once('timeout', errorHandlerTemp(self, state, 'timeout')); - server.once('connect', connectHandler(self, state)); - // Attempt to connect - server.connect(); - } - - // Cleanup state (removed disconnected servers) - state.replState.clean(); - - // We need to query all servers - var servers = state.replState.getAll(); - var serversLeft = servers.length; - - // If no servers and we are not destroyed keep pinging - if(servers.length == 0 && state.replState.state == CONNECTED) { - // Emit ha process end - self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - // Ended highAvailabilityProcessRunning - state.highAvailabilityProcessRunning = false; - // Restart ha process - if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); - return; - } - - // - // ismaster for Master server - var primaryIsMaster = null; - - // Kill the server connection if it hangs - var timeoutServer = function(_server) { - return setTimeout(function() { - if(_server.isConnected()) { - _server.connections()[0].connection.destroy(); - } - }, self.s.options.connectionTimeout); - } - - // - // Inspect a specific servers ismaster - var inspectServer = function(server) { - if(state.replState.state == DESTROYED) return; - // Did we get a server - if(server && server.isConnected()) { - // Get the timeout id - var timeoutId = timeoutServer(server); - // Execute ismaster - server.command('system.$cmd', {ismaster:true}, function(err, r) { - // Clear out the timeoutServer - clearTimeout(timeoutId); - // If the state was destroyed - if(state.replState.state == DESTROYED) return; - // Count down the number of servers left - serversLeft = serversLeft - 1; - // If we have an error but still outstanding server request return - if(err && serversLeft > 0) return; - // We had an error and have no more servers to inspect, schedule a new check - if(err && serversLeft == 0) { - self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - // Ended highAvailabilityProcessRunnfing - state.highAvailabilityProcessRunning = false; - // Return the replicasetInquirer - if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); - return; - } - - // Let all the read Preferences do things to the servers - var rPreferencesCount = Object.keys(state.readPreferenceStrategies).length; - - // Handle the primary - var ismaster = r.result; - if(state.logger.isDebug()) state.logger.debug(f('[%s] monitoring process ismaster %s', state.id, JSON.stringify(ismaster))); - - // Update the replicaset state - state.replState.update(ismaster, server); - - // Add any new servers - if(err == null && ismaster.ismaster && Array.isArray(ismaster.hosts)) { - // Hosts to process - var hosts = ismaster.hosts; - // Add arbiters to list of hosts if we have any - if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); - if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); - // Process all the hsots - processHosts(self, state, hosts); - } - - // No read Preferences strategies - if(rPreferencesCount == 0) { - // Don't schedule a new inquiry - if(serversLeft > 0) return; - // Emit ha process end - self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - // Ended highAvailabilityProcessRunning - state.highAvailabilityProcessRunning = false; - // Let's keep monitoring - if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); - return; - } - - // No servers left to query, execute read preference strategies - if(serversLeft == 0) { - // Go over all the read preferences - for(var name in state.readPreferenceStrategies) { - state.readPreferenceStrategies[name].ha(self, state.replState, function() { - rPreferencesCount = rPreferencesCount - 1; - - if(rPreferencesCount == 0) { - // Add any new servers in primary ismaster - if(err == null - && ismaster.ismaster - && Array.isArray(ismaster.hosts)) { - processHosts(self, state, ismaster.hosts); - } - - // Emit ha process end - self.emit('ha', 'end', {norepeat: norepeat, id: localHaId, state: state.replState ? state.replState.toJSON() : {}}); - // Ended highAvailabilityProcessRunning - state.highAvailabilityProcessRunning = false; - // Let's keep monitoring - if(!norepeat) setTimeout(replicasetInquirer(self, state, false), state.haInterval); - return; - } - }); - } - } - }); - } - } - - // Call ismaster on all servers - for(var i = 0; i < servers.length; i++) { - inspectServer(servers[i]); - } - - // If no more initial servers and new scheduled servers to connect - if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { - state.fullsetup = true; - self.emit('fullsetup', self); - } - - // If all servers are accounted for and we have not sent the all event - if(state.replState.primary != null && self.lastIsMaster() - && Array.isArray(self.lastIsMaster().hosts) && !state.all) { - var length = 1 + state.replState.secondaries.length; - // If we have all secondaries + primary - if(length == self.lastIsMaster().hosts.length + 1) { - state.all = true; - self.emit('all', self); - } - } - } -} - -// Error handler for initial connect -var errorHandlerTemp = function(self, state, event) { - return function(err, server) { - // Log the information - if(state.logger.isInfo()) state.logger.info(f('[%s] server %s disconnected', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); - // Filter out any connection servers - state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { - return server.name != _server.name; - }); - - // Connection is destroyed, ignore - if(state.replState.state == DESTROYED) return; - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Push to list of disconnected servers - addToListIfNotExist(state.disconnectedServers, server); - - // End connection operation if we have no legal replicaset state - if(state.initialConnectionServers == 0 && state.replState.state == CONNECTING) { - if((state.secondaryOnlyConnectionAllowed && !state.replState.isSecondaryConnected() && !state.replState.isPrimaryConnected()) - || (!state.secondaryOnlyConnectionAllowed && !state.replState.isPrimaryConnected())) { - if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); - - if(self.listeners('error').length > 0) - return self.emit('error', new MongoError('no valid seed servers in list')); - } - } - - // If the number of disconnected servers is equal to - // the number of seed servers we cannot connect - if(state.disconnectedServers.length == state.seedlist.length && state.replState.state == CONNECTING) { - if(state.emitError && self.listeners('error').length > 0) { - if(state.logger.isInfo()) state.logger.info(f('[%s] no valid seed servers in list', state.id)); - - if(self.listeners('error').length > 0) - self.emit('error', new MongoError('no valid seed servers in list')); - } - } - } -} - -// Connect handler -var connectHandler = function(self, state) { - return function(server) { - if(state.logger.isInfo()) state.logger.info(f('[%s] connected to %s', state.id, server.name)); - // Destroyed connection - if(state.replState.state == DESTROYED) { - server.destroy(false, false); - return; - } - - // Filter out any connection servers - state.initialConnectionServers = state.initialConnectionServers.filter(function(_server) { - return server.name != _server.name; - }); - - // Process the new server - var processNewServer = function() { - // Discover any additional servers - var ismaster = server.lastIsMaster(); - - var events = ['error', 'close', 'timeout', 'connect', 'message']; - // Remove any non used handlers - events.forEach(function(e) { - server.removeAllListeners(e); - }) - - // Clean up - delete state.connectingServers[server.name]; - // Update the replicaset state, destroy if not added - if(!state.replState.update(ismaster, server)) { - return server.destroy(); - } - - // Add the server handling code - if(server.isConnected()) { - server.on('error', errorHandler(self, state)); - server.on('close', closeHandler(self, state)); - server.on('timeout', timeoutHandler(self, state)); - } - - // Hosts to process - var hosts = ismaster.hosts; - // Add arbiters to list of hosts if we have any - if(Array.isArray(ismaster.arbiters)) hosts = hosts.concat(ismaster.arbiters); - if(Array.isArray(ismaster.passives)) hosts = hosts.concat(ismaster.passives); - - // Add any new servers - processHosts(self, state, hosts); - - // If have the server instance already destroy it - if(state.initialConnectionServers.length == 0 && Object.keys(state.connectingServers).length == 0 - && !state.replState.isPrimaryConnected() && !state.secondaryOnlyConnectionAllowed && state.replState.state == CONNECTING) { - if(state.logger.isInfo()) state.logger.info(f('[%s] no primary found in replicaset', state.id)); - self.emit('error', new MongoError("no primary found in replicaset")); - return self.destroy(); - } - - // If no more initial servers and new scheduled servers to connect - if(state.replState.secondaries.length >= 1 && state.replState.primary != null && !state.fullsetup) { - state.fullsetup = true; - self.emit('fullsetup', self); - } - } - - // Save up new members to be authenticated against - if(self.s.authInProgress) { - self.s.authInProgressServers.push(server); - } - - // No credentials just process server - if(state.credentials.length == 0) return processNewServer(); - // Do we have credentials, let's apply them all - var count = state.credentials.length; - // Apply the credentials - for(var i = 0; i < state.credentials.length; i++) { - server.auth.apply(server, state.credentials[i].concat([function(err, r) { - count = count - 1; - if(count == 0) processNewServer(); - }])); - } - } -} - -// -// Detect if we need to add new servers -var processHosts = function(self, state, hosts) { - if(state.replState.state == DESTROYED) return; - if(Array.isArray(hosts)) { - // Check any hosts exposed by ismaster - for(var i = 0; i < hosts.length; i++) { - // If not found we need to create a new connection - if(!state.replState.contains(hosts[i])) { - if(state.connectingServers[hosts[i]] == null && !inInitialConnectingServers(self, state, hosts[i])) { - if(state.logger.isInfo()) state.logger.info(f('[%s] scheduled server %s for connection', state.id, hosts[i])); - // Make sure we know what is trying to connect - state.connectingServers[hosts[i]] = hosts[i]; - // Connect the server - connectToServer(self, state, hosts[i].split(':')[0], parseInt(hosts[i].split(':')[1], 10)); - } - } - } - } -} - -var inInitialConnectingServers = function(self, state, address) { - for(var i = 0; i < state.initialConnectionServers.length; i++) { - if(state.initialConnectionServers[i].name == address) return true; - } - return false; -} - -// Connect to a new server -var connectToServer = function(self, state, host, port) { - var opts = cloneOptions(state.options); - opts.host = host; - opts.port = port; - opts.reconnect = false; - opts.readPreferenceStrategies = state.readPreferenceStrategies; - if(state.tag) opts.tag = state.tag; - // Share the auth store - opts.authProviders = state.authProviders; - opts.emitError = true; - // Create a new server instance - var server = new Server(opts); - // Handle the ismaster - server.on('ismaster', handleIsmaster(self)); - // Set up the event handlers - server.once('error', errorHandlerTemp(self, state, 'error')); - server.once('close', errorHandlerTemp(self, state, 'close')); - server.once('timeout', errorHandlerTemp(self, state, 'timeout')); - server.once('connect', connectHandler(self, state)); - // Attempt to connect - server.connect(); -} - -// -// Add server to the list if it does not exist -var addToListIfNotExist = function(list, server) { - var found = false; - - // Remove any non used handlers - ['error', 'close', 'timeout', 'connect'].forEach(function(e) { - server.removeAllListeners(e); - }) - - // Check if the server already exists - for(var i = 0; i < list.length; i++) { - if(list[i].equals(server)) found = true; - } - - if(!found) { - list.push(server); - } - - return found; -} - -var errorHandler = function(self, state) { - return function(err, server) { - if(state.replState.state == DESTROYED) return; - if(state.logger.isInfo()) state.logger.info(f('[%s] server %s errored out with %s', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name, JSON.stringify(err))); - var found = addToListIfNotExist(state.disconnectedServers, server); - if(!found) self.emit('left', state.replState.remove(server), server); - if(found && state.emitError && self.listeners('error').length > 0) self.emit('error', err, server); - - // Fire off a detection of missing server using minHeartbeatFrequencyMS - setTimeout(function() { - replicasetInquirer(self, self.s, true)(); - }, self.s.minHeartbeatFrequencyMS); - } -} - -var timeoutHandler = function(self, state) { - return function(err, server) { - if(state.replState.state == DESTROYED) return; - if(state.logger.isInfo()) state.logger.info(f('[%s] server %s timed out', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); - var found = addToListIfNotExist(state.disconnectedServers, server); - if(!found) self.emit('left', state.replState.remove(server), server); - - // Fire off a detection of missing server using minHeartbeatFrequencyMS - setTimeout(function() { - replicasetInquirer(self, self.s, true)(); - }, self.s.minHeartbeatFrequencyMS); - } -} - -var closeHandler = function(self, state) { - return function(err, server) { - if(state.replState.state == DESTROYED) return; - if(state.logger.isInfo()) state.logger.info(f('[%s] server %s closed', state.id, server.lastIsMaster() ? server.lastIsMaster().me : server.name)); - var found = addToListIfNotExist(state.disconnectedServers, server); - if(!found) self.emit('left', state.replState.remove(server), server); - - // Fire off a detection of missing server using minHeartbeatFrequencyMS - setTimeout(function() { - replicasetInquirer(self, self.s, true)(); - }, self.s.minHeartbeatFrequencyMS); - } -} - -// -// Validate if a non-master or recovering error -var notMasterError = function(r) { - // Get result of any - var result = r && r.result ? r.result : r; - - // Explore if we have a not master error - if(result && (result.err == 'not master' - || result.errmsg == 'not master' || (result['$err'] && result['$err'].indexOf('not master or secondary') != -1) - || (result['$err'] && result['$err'].indexOf("not master and slaveOk=false") != -1) - || result.errmsg == 'node is recovering')) { - return true; - } - - return false; -} - -module.exports = ReplSet; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js deleted file mode 100644 index 951a043..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/replset_state.js +++ /dev/null @@ -1,483 +0,0 @@ -"use strict"; - -var Logger = require('../connection/logger') - , f = require('util').format - , ObjectId = require('bson').ObjectId - , MongoError = require('../error'); - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -/** - * Creates a new Replicaset State object - * @class - * @property {object} primary Primary property - * @property {array} secondaries List of secondaries - * @property {array} arbiters List of arbiters - * @return {State} A cursor instance - */ -var State = function(replSet, options) { - this.replSet = replSet; - this.options = options; - this.secondaries = []; - this.arbiters = []; - this.passives = []; - this.primary = null; - // Initial state is disconnected - this.state = DISCONNECTED; - // Current electionId - this.electionId = null; - // Get a logger instance - this.logger = Logger('ReplSet', options); - // Unpacked options - this.id = options.id; - this.setName = options.setName; - this.connectingServers = options.connectingServers; - this.secondaryOnlyConnectionAllowed = options.secondaryOnlyConnectionAllowed; -} - -/** - * Is there a secondary connected - * @method - * @return {boolean} - */ -State.prototype.isSecondaryConnected = function() { - for(var i = 0; i < this.secondaries.length; i++) { - if(this.secondaries[i].isConnected()) return true; - } - - return false; -} - -/** - * Is there a primary connection - * @method - * @return {boolean} - */ -State.prototype.isPrimaryConnected = function() { - return this.primary != null && this.primary.isConnected(); -} - -/** - * Is the given address the primary - * @method - * @param {string} address Server address - * @return {boolean} - */ -State.prototype.isPrimary = function(address) { - if(this.primary == null) return false; - return this.primary && this.primary.equals(address); -} - -/** - * Is the given address a secondary - * @method - * @param {string} address Server address - * @return {boolean} - */ -State.prototype.isSecondary = function(address) { - // Check if the server is a secondary at the moment - for(var i = 0; i < this.secondaries.length; i++) { - if(this.secondaries[i].equals(address)) { - return true; - } - } - - return false; -} - -/** - * Is the given address a secondary - * @method - * @param {string} address Server address - * @return {boolean} - */ -State.prototype.isPassive = function(address) { - // Check if the server is a secondary at the moment - for(var i = 0; i < this.passives.length; i++) { - if(this.passives[i].equals(address)) { - return true; - } - } - - return false; -} - -/** - * Does the replicaset contain this server - * @method - * @param {string} address Server address - * @return {boolean} - */ -State.prototype.contains = function(address) { - if(this.primary && this.primary.equals(address)) return true; - for(var i = 0; i < this.secondaries.length; i++) { - if(this.secondaries[i].equals(address)) return true; - } - - for(var i = 0; i < this.arbiters.length; i++) { - if(this.arbiters[i].equals(address)) return true; - } - - for(var i = 0; i < this.passives.length; i++) { - if(this.passives[i].equals(address)) return true; - } - - return false; -} - -/** - * Clean out all dead connections - * @method - */ -State.prototype.clean = function() { - if(this.primary != null && !this.primary.isConnected()) { - this.primary = null; - } - - // Filter out disconnected servers - this.secondaries = this.secondaries.filter(function(s) { - return s.isConnected(); - }); - - // Filter out disconnected servers - this.arbiters = this.arbiters.filter(function(s) { - return s.isConnected(); - }); -} - -/** - * Destroy state - * @method - */ -State.prototype.destroy = function() { - this.state = DESTROYED; - if(this.primary) this.primary.destroy(); - this.secondaries.forEach(function(s) { - s.destroy(); - }); -} - -/** - * Remove server from state - * @method - * @param {Server} Server to remove - * @return {string} Returns type of server removed (primary|secondary) - */ -State.prototype.remove = function(server) { - if(this.primary && this.primary.equals(server)) { - this.primary = null; - } - - var length = this.arbiters.length; - // Filter out the server from the arbiters - this.arbiters = this.arbiters.filter(function(s) { - return !s.equals(server); - }); - if(this.arbiters.length < length) return 'arbiter'; - - var length = this.passives.length; - // Filter out the server from the passives - this.passives = this.passives.filter(function(s) { - return !s.equals(server); - }); - - // We have removed a passive - if(this.passives.length < length) { - // Ensure we removed it from the list of secondaries as well if it exists - this.secondaries = this.secondaries.filter(function(s) { - return !s.equals(server); - }); - } - - // Filter out the server from the secondaries - this.secondaries = this.secondaries.filter(function(s) { - return !s.equals(server); - }); - - // Get the isMaster - var isMaster = server.lastIsMaster(); - // Return primary if the server was primary - if(isMaster.ismaster) return 'primary'; - if(isMaster.secondary) return 'secondary'; - if(isMaster.passive) return 'passive'; - return 'arbiter'; -} - -/** - * Get the server by name - * @method - * @param {string} address Server address - * @return {Server} - */ -State.prototype.get = function(server) { - var found = false; - // All servers to search - var servers = this.primary ? [this.primary] : []; - servers = servers.concat(this.secondaries); - // Locate the server - for(var i = 0; i < servers.length; i++) { - if(servers[i].equals(server)) { - return servers[i]; - } - } -} - -/** - * Get all the servers in the set - * @method - * @return {array} - */ -State.prototype.getAll = function() { - var servers = []; - if(this.primary) servers.push(this.primary); - return servers.concat(this.secondaries); -} - -/** - * All raw connections - * @method - * @return {array} - */ -State.prototype.getAllConnections = function() { - var connections = []; - if(this.primary) connections = connections.concat(this.primary.connections()); - this.secondaries.forEach(function(s) { - connections = connections.concat(s.connections()); - }) - - return connections; -} - -/** - * Return JSON object - * @method - * @return {object} - */ -State.prototype.toJSON = function() { - return { - primary: this.primary ? this.primary.lastIsMaster().me : null - , secondaries: this.secondaries.map(function(s) { - return s.lastIsMaster().me - }) - } -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -State.prototype.lastIsMaster = function() { - if(this.primary) return this.primary.lastIsMaster(); - if(this.secondaries.length > 0) return this.secondaries[0].lastIsMaster(); - return {}; -} - -/** - * Promote server to primary - * @method - * @param {Server} server Server we wish to promote - */ -State.prototype.promotePrimary = function(server) { - var currentServer = this.get(server); - // Server does not exist in the state, add it as new primary - if(currentServer == null) { - this.primary = server; - return; - } - - // We found a server, make it primary and remove it from the secondaries - // Remove the server first - this.remove(currentServer); - // Set as primary - this.primary = currentServer; -} - -var add = function(list, server) { - // Check if the server is a secondary at the moment - for(var i = 0; i < list.length; i++) { - if(list[i].equals(server)) return false; - } - - list.push(server); - return true; -} - -/** - * Add server to list of secondaries - * @method - * @param {Server} server Server we wish to add - */ -State.prototype.addSecondary = function(server) { - return add(this.secondaries, server); -} - -/** - * Add server to list of arbiters - * @method - * @param {Server} server Server we wish to add - */ -State.prototype.addArbiter = function(server) { - return add(this.arbiters, server); -} - -/** - * Add server to list of passives - * @method - * @param {Server} server Server we wish to add - */ -State.prototype.addPassive = function(server) { - return add(this.passives, server); -} - -var compareObjectIds = function(id1, id2) { - var a = new Buffer(id1.toHexString(), 'hex'); - var b = new Buffer(id2.toHexString(), 'hex'); - - if(a === b) { - return 0; - } - - if(typeof Buffer.compare === 'function') { - return Buffer.compare(a, b); - } - - var x = a.length; - var y = b.length; - var len = Math.min(x, y); - - for (var i = 0; i < len; i++) { - if (a[i] !== b[i]) { - break; - } - } - - if (i !== len) { - x = a[i]; - y = b[i]; - } - - return x < y ? -1 : y < x ? 1 : 0; -} - -/** - * Update the state given a specific ismaster result - * @method - * @param {object} ismaster IsMaster result - * @param {Server} server IsMaster Server source - */ -State.prototype.update = function(ismaster, server) { - var self = this; - // Not in a known connection valid state - if(!ismaster.ismaster && !ismaster.secondary && !ismaster.arbiterOnly) { - // Remove the state - var result = self.remove(server); - if(self.state == CONNECTED) { - if(self.logger.isInfo()) self.logger.info(f('[%s] removing %s from set', self.id, ismaster.me)); - self.replSet.emit('left', self.remove(server), server); - } - - return false; - } - - // Set the setName if it's not set from the first server - if(self.setName == null && ismaster.setName) { - if(self.logger.isInfo()) self.logger.info(f('[%s] setting setName to %s', self.id, ismaster.setName)); - self.setName = ismaster.setName; - } - - // Check if the replicaset name matches the provided one - if(ismaster.setName && self.setName != ismaster.setName) { - if(self.logger.isError()) self.logger.error(f('[%s] server in replset %s is not part of the specified setName %s', self.id, ismaster.setName, self.setName)); - self.remove(server); - self.replSet.emit('error', new MongoError("provided setName for Replicaset Connection does not match setName found in server seedlist")); - return false; - } - - // Log information - if(self.logger.isInfo()) self.logger.info(f('[%s] updating replicaset state %s', self.id, JSON.stringify(this))); - - // It's a master set it - if(ismaster.ismaster && self.setName == ismaster.setName && !self.isPrimary(ismaster.me)) { - // Check if the electionId is not null - if(ismaster.electionId instanceof ObjectId && self.electionId instanceof ObjectId) { - if(compareObjectIds(self.electionId, ismaster.electionId) == -1) { - self.electionId = ismaster.electionId; - } else if(compareObjectIds(self.electionId, ismaster.electionId) == 0) { - self.electionId = ismaster.electionId; - } else { - return false; - } - } - - // Initial electionId - if(ismaster.electionId instanceof ObjectId && self.electionId == null) { - self.electionId = ismaster.electionId; - } - - // Promote to primary - self.promotePrimary(server); - // Log change of primary - if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to primary', self.id, ismaster.me)); - // Emit primary - self.replSet.emit('joined', 'primary', this.primary); - - // We are connected - if(self.state == CONNECTING) { - self.state = CONNECTED; - self.replSet.emit('connect', self.replSet); - } else { - self.state = CONNECTED; - self.replSet.emit('reconnect', server); - } - } else if(!ismaster.ismaster && self.setName == ismaster.setName - && ismaster.arbiterOnly) { - if(self.addArbiter(server)) { - if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to arbiter', self.id, ismaster.me)); - self.replSet.emit('joined', 'arbiter', server); - return true; - }; - - return false; - } else if(!ismaster.ismaster && self.setName == ismaster.setName - && ismaster.secondary && ismaster.passive) { - if(self.addPassive(server) && self.addSecondary(server)) { - if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to passive', self.id, ismaster.me)); - self.replSet.emit('joined', 'passive', server); - - // If we have secondaryOnlyConnectionAllowed and just a passive it's - // still a valid connection - if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { - self.state = CONNECTED; - self.replSet.emit('connect', self.replSet); - } - - return true; - }; - - return false; - } else if(!ismaster.ismaster && self.setName == ismaster.setName - && ismaster.secondary) { - if(self.addSecondary(server)) { - if(self.logger.isInfo()) self.logger.info(f('[%s] promoting %s to secondary', self.id, ismaster.me)); - self.replSet.emit('joined', 'secondary', server); - - if(self.secondaryOnlyConnectionAllowed && self.state == CONNECTING) { - self.state = CONNECTED; - self.replSet.emit('connect', self.replSet); - } - - return true; - }; - - return false; - } - - // Return update applied - return true; -} - -module.exports = State; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js deleted file mode 100644 index 0fae9ea..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js +++ /dev/null @@ -1,1230 +0,0 @@ - "use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , bindToCurrentDomain = require('../connection/utils').bindToCurrentDomain - , EventEmitter = require('events').EventEmitter - , Pool = require('../connection/pool') - , b = require('bson') - , Query = require('../connection/commands').Query - , MongoError = require('../error') - , ReadPreference = require('./read_preference') - , BasicCursor = require('../cursor') - , CommandResult = require('./command_result') - , getSingleProperty = require('../connection/utils').getSingleProperty - , getProperty = require('../connection/utils').getProperty - , debugOptions = require('../connection/utils').debugOptions - , BSON = require('bson').native().BSON - , PreTwoSixWireProtocolSupport = require('../wireprotocol/2_4_support') - , TwoSixWireProtocolSupport = require('../wireprotocol/2_6_support') - , ThreeTwoWireProtocolSupport = require('../wireprotocol/3_2_support') - , Session = require('./session') - , Logger = require('../connection/logger') - , MongoCR = require('../auth/mongocr') - , X509 = require('../auth/x509') - , Plain = require('../auth/plain') - , GSSAPI = require('../auth/gssapi') - , SSPI = require('../auth/sspi') - , ScramSHA1 = require('../auth/scram'); - -/** - * @fileOverview The **Server** class is a class that represents a single server topology and is - * used to construct connections. - * - * @example - * var Server = require('mongodb-core').Server - * , ReadPreference = require('mongodb-core').ReadPreference - * , assert = require('assert'); - * - * var server = new Server({host: 'localhost', port: 27017}); - * // Wait for the connection event - * server.on('connect', function(server) { - * server.destroy(); - * }); - * - * // Start connecting - * server.connect(); - */ - -// All bson types -var bsonTypes = [b.Long, b.ObjectID, b.Binary, b.Code, b.DBRef, b.Symbol, b.Double, b.Timestamp, b.MaxKey, b.MinKey]; -// BSON parser -var bsonInstance = null; -// Server instance id -var serverId = 0; -// Callbacks instance id -var callbackId = 0; - -// Single store for all callbacks -var Callbacks = function() { - // EventEmitter.call(this); - var self = this; - // Callbacks - this.callbacks = {}; - // Set the callbacks id - this.id = callbackId++; - // Set the type to server - this.type = 'server'; -} - -// -// Clone the options -var cloneOptions = function(options) { - var opts = {}; - for(var name in options) { - opts[name] = options[name]; - } - return opts; -} - -// -// Flush all callbacks -Callbacks.prototype.flush = function(err) { - for(var id in this.callbacks) { - if(!isNaN(parseInt(id, 10))) { - var callback = this.callbacks[id]; - delete this.callbacks[id]; - callback(err, null); - } - } -} - -Callbacks.prototype.emit = function(id, err, value) { - var callback = this.callbacks[id]; - delete this.callbacks[id]; - callback(err, value); -} - -Callbacks.prototype.raw = function(id) { - if(this.callbacks[id] == null) return false; - return this.callbacks[id].raw == true ? true : false -} - -Callbacks.prototype.documentsReturnedIn = function(id) { - if(this.callbacks[id] == null) return false; - return typeof this.callbacks[id].documentsReturnedIn == 'string' ? this.callbacks[id].documentsReturnedIn : null; -} - -Callbacks.prototype.unregister = function(id) { - delete this.callbacks[id]; -} - -Callbacks.prototype.register = function(id, callback) { - this.callbacks[id] = bindToCurrentDomain(callback); -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) return callback; - return domain.bind(callback); -} - -var DISCONNECTED = 'disconnected'; -var CONNECTING = 'connecting'; -var CONNECTED = 'connected'; -var DESTROYED = 'destroyed'; - -// Supports server -var supportsServer = function(_s) { - return _s.ismaster && typeof _s.ismaster.minWireVersion == 'number'; -} - -// -// createWireProtocolHandler -var createWireProtocolHandler = function(result) { - // 3.2 wire protocol handler - if(result && result.maxWireVersion >= 4) { - return new ThreeTwoWireProtocolSupport(new TwoSixWireProtocolSupport()); - } - - // 2.6 wire protocol handler - if(result && result.maxWireVersion >= 2) { - return new TwoSixWireProtocolSupport(); - } - - // 2.4 or earlier wire protocol handler - return new PreTwoSixWireProtocolSupport(); -} - -// -// Reconnect server -var reconnectServer = function(self, state) { - // If the current reconnect retries is 0 stop attempting to reconnect - if(state.currentReconnectRetry == 0) { - return self.destroy(true, true); - } - - // Adjust the number of retries - state.currentReconnectRetry = state.currentReconnectRetry - 1; - - // Set status to connecting - state.state = CONNECTING; - // Create a new Pool - state.pool = new Pool(state.options); - // error handler - var reconnectErrorHandler = function(err) { - state.state = DISCONNECTED; - // Destroy the pool - state.pool.destroy(); - // Adjust the number of retries - state.currentReconnectRetry = state.currentReconnectRetry - 1; - // No more retries - if(state.currentReconnectRetry <= 0) { - self.state = DESTROYED; - self.emit('error', f('failed to connect to %s:%s after %s retries', state.options.host, state.options.port, state.reconnectTries)); - } else { - setTimeout(function() { - reconnectServer(self, state); - }, state.reconnectInterval); - } - } - - // - // Attempt to connect - state.pool.once('connect', function() { - // Reset retries - state.currentReconnectRetry = state.reconnectTries; - - // Remove any non used handlers - var events = ['error', 'close', 'timeout', 'parseError']; - events.forEach(function(e) { - state.pool.removeAllListeners(e); - }); - - // Set connected state - state.state = CONNECTED; - - // Add proper handlers - state.pool.once('error', reconnectErrorHandler); - state.pool.once('close', closeHandler(self, state)); - state.pool.once('timeout', timeoutHandler(self, state)); - state.pool.once('parseError', fatalErrorHandler(self, state)); - - // We need to ensure we have re-authenticated - var keys = Object.keys(state.authProviders); - if(keys.length == 0) return self.emit('reconnect', self); - - // Execute all providers - var count = keys.length; - // Iterate over keys - for(var i = 0; i < keys.length; i++) { - state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { - count = count - 1; - // We are done, emit reconnect event - if(count == 0) { - return self.emit('reconnect', self); - } - }); - } - }); - - // - // Handle connection failure - state.pool.once('error', errorHandler(self, state)); - state.pool.once('close', errorHandler(self, state)); - state.pool.once('timeout', errorHandler(self, state)); - state.pool.once('parseError', errorHandler(self, state)); - - // Connect pool - state.pool.connect(); -} - -// -// Handlers -var messageHandler = function(self, state) { - return function(response, connection) { - try { - // Parse the message - response.parse({raw: state.callbacks.raw(response.responseTo), documentsReturnedIn: state.callbacks.documentsReturnedIn(response.responseTo)}); - if(state.logger.isDebug()) state.logger.debug(f('message [%s] received from %s', response.raw.toString('hex'), self.name)); - state.callbacks.emit(response.responseTo, null, response); - } catch (err) { - state.callbacks.flush(new MongoError(err)); - self.destroy(); - } - } -} - -var errorHandler = function(self, state) { - return function(err, connection) { - if(state.state == DISCONNECTED || state.state == DESTROYED) return; - // Set disconnected state - state.state = DISCONNECTED; - if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); - if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); - // Flush out all the callbacks - if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); - // Destroy all connections - self.destroy(); - // Emit error event - if(state.emitError && self.listeners('error').length > 0) self.emit('error', err, self); - // If we specified the driver to reconnect perform it - if(state.reconnect) setTimeout(function() { - // state.currentReconnectRetry = state.reconnectTries, - reconnectServer(self, state) - }, state.reconnectInterval); - } -} - -var fatalErrorHandler = function(self, state) { - return function(err, connection) { - if(state.state == DISCONNECTED || state.state == DESTROYED) return; - // Set disconnected state - state.state = DISCONNECTED; - - if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'error', [self]); - if(state.logger.isInfo()) state.logger.info(f('server %s errored out with %s', self.name, JSON.stringify(err))); - // Flush out all the callbacks - if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s received an error %s", self.name, JSON.stringify(err)))); - // Emit error event - if(self.listeners('error').length > 0) self.emit('error', err, self); - // If we specified the driver to reconnect perform it - if(state.reconnect) setTimeout(function() { - // state.currentReconnectRetry = state.reconnectTries, - reconnectServer(self, state) - }, state.reconnectInterval); - // Destroy all connections - self.destroy(); - } -} - -var timeoutHandler = function(self, state) { - return function(err, connection) { - if(state.state == DISCONNECTED || state.state == DESTROYED) return; - // Set disconnected state - state.state = DISCONNECTED; - - if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'timeout', [self]); - if(state.logger.isInfo()) state.logger.info(f('server %s timed out', self.name)); - // Flush out all the callbacks - if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s timed out", self.name))); - // Emit error event - self.emit('timeout', err, self); - // If we specified the driver to reconnect perform it - if(state.reconnect) setTimeout(function() { - // state.currentReconnectRetry = state.reconnectTries, - reconnectServer(self, state) - }, state.reconnectInterval); - // Destroy all connections - self.destroy(); - } -} - -var closeHandler = function(self, state) { - return function(err, connection) { - if(state.state == DISCONNECTED || state.state == DESTROYED) return; - // Set disconnected state - state.state = DISCONNECTED; - - if(state.readPreferenceStrategies != null) notifyStrategies(self, self.s, 'close', [self]); - if(state.logger.isInfo()) state.logger.info(f('server %s closed', self.name)); - // Flush out all the callbacks - if(state.callbacks) state.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); - // Emit error event - self.emit('close', err, self); - // If we specified the driver to reconnect perform it - if(state.reconnect) setTimeout(function() { - // state.currentReconnectRetry = state.reconnectTries, - reconnectServer(self, state) - }, state.reconnectInterval); - // Destroy all connections - self.destroy(); - } -} - -var connectHandler = function(self, state) { - // Apply all stored authentications - var applyAuthentications = function(callback) { - // We need to ensure we have re-authenticated - var keys = Object.keys(state.authProviders); - if(keys.length == 0) return callback(null, null); - - // Execute all providers - var count = keys.length; - // Iterate over keys - for(var i = 0; i < keys.length; i++) { - state.authProviders[keys[i]].reauthenticate(self, state.pool, function(err, r) { - count = count - 1; - // We are done, emit reconnect event - if(count == 0) { - return callback(null, null); - } - }); - } - } - - return function(connection) { - // Apply any applyAuthentications - applyAuthentications(function() { - - // Execute an ismaster - self.command('system.$cmd', {ismaster:true}, function(err, r) { - if(err) { - state.state = DISCONNECTED; - return self.emit('close', err, self); - } - - // Set the current ismaster - if(!err) { - state.ismaster = r.result; - } - - // Emit the ismaster - self.emit('ismaster', r.result, self); - - // Determine the wire protocol handler - state.wireProtocolHandler = createWireProtocolHandler(state.ismaster); - - // Set the wireProtocolHandler - state.options.wireProtocolHandler = state.wireProtocolHandler; - - // Log the ismaster if available - if(state.logger.isInfo()) state.logger.info(f('server %s connected with ismaster [%s]', self.name, JSON.stringify(r.result))); - - // Validate if we it's a server we can connect to - if(!supportsServer(state) && state.wireProtocolHandler == null) { - state.state = DISCONNECTED - return self.emit('error', new MongoError("non supported server version"), self); - } - - // Set the details - if(state.ismaster && state.ismaster.me) state.serverDetails.name = state.ismaster.me; - - // No read preference strategies just emit connect - if(state.readPreferenceStrategies == null) { - state.state = CONNECTED; - return self.emit('connect', self); - } - - // Signal connect to all readPreferences - notifyStrategies(self, self.s, 'connect', [self], function(err, result) { - state.state = CONNECTED; - return self.emit('connect', self); - }); - }); - }); - } -} - -var slaveOk = function(r) { - if(r) return r.slaveOk() - return false; -} - -// -// Execute readPreference Strategies -var notifyStrategies = function(self, state, op, params, callback) { - if(typeof callback != 'function') { - // Notify query start to any read Preference strategies - for(var name in state.readPreferenceStrategies) { - if(state.readPreferenceStrategies[name][op]) { - var strat = state.readPreferenceStrategies[name]; - strat[op].apply(strat, params); - } - } - // Finish up - return; - } - - // Execute the async callbacks - var nPreferences = Object.keys(state.readPreferenceStrategies).length; - if(nPreferences == 0) return callback(null, null); - for(var name in state.readPreferenceStrategies) { - if(state.readPreferenceStrategies[name][op]) { - var strat = state.readPreferenceStrategies[name]; - // Add a callback to params - var cParams = params.slice(0); - cParams.push(function(err, r) { - nPreferences = nPreferences - 1; - if(nPreferences == 0) { - callback(null, null); - } - }) - // Execute the readPreference - strat[op].apply(strat, cParams); - } - } -} - -var debugFields = ['reconnect', 'reconnectTries', 'reconnectInterval', 'emitError', 'cursorFactory', 'host' - , 'port', 'size', 'keepAlive', 'keepAliveInitialDelay', 'noDelay', 'connectionTimeout' - , 'socketTimeout', 'singleBufferSerializtion', 'ssl', 'ca', 'cert', 'key', 'rejectUnauthorized', 'promoteLongs']; - -/** - * Creates a new Server instance - * @class - * @param {boolean} [options.reconnect=true] Server will attempt to reconnect on loss of connection - * @param {number} [options.reconnectTries=30] Server attempt to reconnect #times - * @param {number} [options.reconnectInterval=1000] Server will wait # milliseconds between retries - * @param {boolean} [options.emitError=false] Server will emit errors events - * @param {Cursor} [options.cursorFactory=Cursor] The cursor factory class used for all query cursors - * @param {string} options.host The server host - * @param {number} options.port The server port - * @param {number} [options.size=5] Server connection pool size - * @param {boolean} [options.keepAlive=true] TCP Connection keep alive enabled - * @param {number} [options.keepAliveInitialDelay=0] Initial delay before TCP keep alive enabled - * @param {boolean} [options.noDelay=true] TCP Connection no delay - * @param {number} [options.connectionTimeout=0] TCP Connection timeout setting - * @param {number} [options.socketTimeout=0] TCP Socket timeout setting - * @param {boolean} [options.ssl=false] Use SSL for connection - * @param {Buffer} [options.ca] SSL Certificate store binary buffer - * @param {Buffer} [options.cert] SSL Certificate binary buffer - * @param {Buffer} [options.key] SSL Key file binary buffer - * @param {string} [options.passphrase] SSL Certificate pass phrase - * @param {boolean} [options.rejectUnauthorized=true] Reject unauthorized server certificates - * @param {boolean} [options.promoteLongs=true] Convert Long values from the db into Numbers if they fit into 53 bits - * @return {Server} A cursor instance - * @fires Server#connect - * @fires Server#close - * @fires Server#error - * @fires Server#timeout - * @fires Server#parseError - * @fires Server#reconnect - */ -var Server = function(options) { - var self = this; - - // Add event listener - EventEmitter.call(this); - - // BSON Parser, ensure we have a single instance - if(bsonInstance == null) { - bsonInstance = new BSON(bsonTypes); - } - - // Reconnect retries - var reconnectTries = options.reconnectTries || 30; - - // Keeps all the internal state of the server - this.s = { - // Options - options: options - // Contains all the callbacks - , callbacks: new Callbacks() - // Logger - , logger: Logger('Server', options) - // Server state - , state: DISCONNECTED - // Reconnect option - , reconnect: typeof options.reconnect == 'boolean' ? options.reconnect : true - , reconnectTries: reconnectTries - , reconnectInterval: options.reconnectInterval || 1000 - // Swallow or emit errors - , emitError: typeof options.emitError == 'boolean' ? options.emitError : false - // Current state - , currentReconnectRetry: reconnectTries - // Contains the ismaster - , ismaster: null - // Contains any alternate strategies for picking - , readPreferenceStrategies: options.readPreferenceStrategies - // Auth providers - , authProviders: options.authProviders || {} - // Server instance id - , id: serverId++ - // Grouping tag used for debugging purposes - , tag: options.tag - // Do we have a not connected handler - , disconnectHandler: options.disconnectHandler - // wireProtocolHandler methods - , wireProtocolHandler: options.wireProtocolHandler || new PreTwoSixWireProtocolSupport() - // Factory overrides - , Cursor: options.cursorFactory || BasicCursor - // BSON Parser, ensure we have a single instance - , bsonInstance: bsonInstance - // Pick the right bson parser - , bson: options.bson ? options.bson : bsonInstance - // Internal connection pool - , pool: null - // Server details - , serverDetails: { - host: options.host - , port: options.port - , name: options.port ? f("%s:%s", options.host, options.port) : options.host - } - } - - // Reference state - var s = this.s; - - // Add bson parser to options - options.bson = s.bson; - - // Set error properties - getProperty(this, 'name', 'name', s.serverDetails, {}); - getProperty(this, 'bson', 'bson', s.options, {}); - getProperty(this, 'wireProtocolHandler', 'wireProtocolHandler', s.options, {}); - getSingleProperty(this, 'id', s.id); - - // Add auth providers - this.addAuthProvider('mongocr', new MongoCR()); - this.addAuthProvider('x509', new X509()); - this.addAuthProvider('plain', new Plain()); - this.addAuthProvider('gssapi', new GSSAPI()); - this.addAuthProvider('sspi', new SSPI()); - this.addAuthProvider('scram-sha-1', new ScramSHA1()); -} - -inherits(Server, EventEmitter); - -/** - * Execute a command - * @method - * @param {string} type Type of BSON parser to use (c++ or js) - */ -Server.prototype.setBSONParserType = function(type) { - var nBSON = null; - - if(type == 'c++') { - nBSON = require('bson').native().BSON; - } else if(type == 'js') { - nBSON = require('bson').pure().BSON; - } else { - throw new MongoError(f("% parser not supported", type)); - } - - this.s.options.bson = new nBSON(bsonTypes); -} - -/** - * Returns the last known ismaster document for this server - * @method - * @return {object} - */ -Server.prototype.lastIsMaster = function() { - return this.s.ismaster; -} - -/** - * Initiate server connect - * @method - */ -Server.prototype.connect = function(_options) { - var self = this; - // Set server specific settings - _options = _options || {} - // Set the promotion - if(typeof _options.promoteLongs == 'boolean') { - self.s.options.promoteLongs = _options.promoteLongs; - } - - // Destroy existing pool - if(self.s.pool) { - self.s.pool.destroy(); - self.s.pool = null; - } - - // Set the state to connection - self.s.state = CONNECTING; - // Create a new connection pool - if(!self.s.pool) { - self.s.options.messageHandler = messageHandler(self, self.s); - self.s.pool = new Pool(self.s.options); - } - - // Add all the event handlers - self.s.pool.once('timeout', timeoutHandler(self, self.s)); - self.s.pool.once('close', closeHandler(self, self.s)); - self.s.pool.once('error', errorHandler(self, self.s)); - self.s.pool.once('connect', connectHandler(self, self.s)); - self.s.pool.once('parseError', fatalErrorHandler(self, self.s)); - - // Connect the pool - self.s.pool.connect(); -} - -/** - * Destroy the server connection - * @method - */ -Server.prototype.destroy = function(emitClose, emitDestroy) { - var self = this; - if(self.s.logger.isDebug()) self.s.logger.debug(f('destroy called on server %s', self.name)); - // Emit close - if(emitClose && self.listeners('close').length > 0) self.emit('close', self); - - // Emit destroy event - if(emitDestroy) self.emit('destroy', self); - // Set state as destroyed - self.s.state = DESTROYED; - // Close the pool - self.s.pool.destroy(); - // Flush out all the callbacks - if(self.s.callbacks) self.s.callbacks.flush(new MongoError(f("server %s sockets closed", self.name))); -} - -/** - * Figure out if the server is connected - * @method - * @return {boolean} - */ -Server.prototype.isConnected = function() { - var self = this; - if(self.s.pool) return self.s.pool.isConnected(); - return false; -} - -/** - * Figure out if the server instance was destroyed by calling destroy - * @method - * @return {boolean} - */ -Server.prototype.isDestroyed = function() { - return this.s.state == DESTROYED; -} - -var executeSingleOperation = function(self, ns, cmd, queryOptions, options, onAll, callback) { - // Create a query instance - var query = new Query(self.s.bson, ns, cmd, queryOptions); - - // Set slave OK - query.slaveOk = slaveOk(options.readPreference); - - // Notify query start to any read Preference strategies - if(self.s.readPreferenceStrategies != null) - notifyStrategies(self, self.s, 'startOperation', [self, query, new Date()]); - - // Get a connection (either passed or from the pool) - var connection = options.connection || self.s.pool.get(); - - // Double check if we have a valid connection - if(!connection.isConnected()) { - return callback(new MongoError(f("no connection available to server %s", self.name))); - } - - // Print cmd and execution connection if in debug mode for logging - if(self.s.logger.isDebug()) { - var json = connection.toJSON(); - self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(cmd), json.id, json.host, json.port)); - } - - // Execute multiple queries - if(onAll) { - var connections = self.s.pool.getAll(); - var total = connections.length; - // We have an error - var error = null; - // Execute on all connections - for(var i = 0; i < connections.length; i++) { - try { - query.incRequestId(); - connections[i].write(query.toBin()); - } catch(err) { - total = total - 1; - if(total == 0) return callback(MongoError.create(err)); - } - - // Register the callback - self.s.callbacks.register(query.requestId, function(err, result) { - if(err) error = err; - total = total - 1; - - // Done - if(total == 0) { - // Notify end of command - notifyStrategies(self, self.s, 'endOperation', [self, error, result, new Date()]); - if(error) return callback(MongoError.create(error)); - // Execute callback, catch and rethrow if needed - try { callback(null, new CommandResult(result.documents[0], connections)); } - catch(err) { process.nextTick(function() { throw err}); } - } - }); - } - - return; - } - - // Execute a single command query - try { - connection.write(query.toBin()); - } catch(err) { - return callback(MongoError.create(err)); - } - - // Register the callback - self.s.callbacks.register(query.requestId, function(err, result) { - // Notify end of command - notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); - if(err) return callback(err); - if(result.documents[0]['$err'] - || result.documents[0]['errmsg'] - || result.documents[0]['err'] - || result.documents[0]['code']) return callback(MongoError.create(result.documents[0])); - // Execute callback, catch and rethrow if needed - try { callback(null, new CommandResult(result.documents[0], connection)); } - catch(err) { process.nextTick(function() { throw err}); } - }); -} - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Connection} [options.connection] Specify connection object to execute command against - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.command = function(ns, cmd, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Ensure we have no options - options = options || {}; - // Do we have a read Preference it need to be of type ReadPreference - if(options.readPreference && !(options.readPreference instanceof ReadPreference)) { - throw new Error("readPreference must be an instance of ReadPreference"); - } - - // Debug log - if(self.s.logger.isDebug()) self.s.logger.debug(f('executing command [%s] against %s', JSON.stringify({ - ns: ns, cmd: cmd, options: debugOptions(debugFields, options) - }), self.name)); - - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('command', ns, cmd, options, callback); - } - - // If we have no connection error - if(!self.s.pool.isConnected()) return callback(new MongoError(f("no connection available to server %s", self.name))); - - // Execute on all connections - var onAll = typeof options.onAll == 'boolean' ? options.onAll : false; - - // Check keys - var checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys: false; - - // Serialize function - var serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - - // Ignore undefined values - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - - // Query options - var queryOptions = { - numberToSkip: 0, numberToReturn: -1, checkKeys: checkKeys - }; - - // Set up the serialize functions and ignore undefined - if(serializeFunctions) queryOptions.serializeFunctions = serializeFunctions; - if(ignoreUndefined) queryOptions.ignoreUndefined = ignoreUndefined; - - // Single operation execution - if(!Array.isArray(cmd)) { - return executeSingleOperation(self, ns, cmd, queryOptions, options, onAll, callback); - } - - // Build commands for each of the instances - var queries = new Array(cmd.length); - for(var i = 0; i < cmd.length; i++) { - queries[i] = new Query(self.s.bson, ns, cmd[i], queryOptions); - queries[i].slaveOk = slaveOk(options.readPreference); - } - - // Notify query start to any read Preference strategies - if(self.s.readPreferenceStrategies != null) - notifyStrategies(self, self.s, 'startOperation', [self, queries, new Date()]); - - // Get a connection (either passed or from the pool) - var connection = options.connection || self.s.pool.get(); - - // Double check if we have a valid connection - if(!connection.isConnected()) { - return callback(new MongoError(f("no connection available to server %s", self.name))); - } - - // Print cmd and execution connection if in debug mode for logging - if(self.s.logger.isDebug()) { - var json = connection.toJSON(); - self.s.logger.debug(f('cmd [%s] about to be executed on connection with id %s at %s:%s', JSON.stringify(queries), json.id, json.host, json.port)); - } - - // Canceled operations - var canceled = false; - // Number of operations left - var operationsLeft = queries.length; - // Results - var results = []; - - // We need to nest the callbacks - for(var i = 0; i < queries.length; i++) { - // Get the query object - var query = queries[i]; - - // Execute a single command query - try { - connection.write(query.toBin()); - } catch(err) { - return callback(MongoError.create(err)); - } - - // Register the callback - self.s.callbacks.register(query.requestId, function(err, result) { - // If it's canceled ignore the operation - if(canceled) return; - // Update the current index - operationsLeft = operationsLeft - 1; - - // If we have an error cancel the operation - if(err) { - canceled = true; - return callback(err); - } - - // Return the result - if(result.documents[0]['$err'] - || result.documents[0]['errmsg'] - || result.documents[0]['err'] - || result.documents[0]['code']) { - - // Set to canceled - canceled = true; - // Return the error - return callback(MongoError.create(result.documents[0])); - } - - // Push results - results.push(result.documents[0]); - - // We are done, return the result - if(operationsLeft == 0) { - // Notify end of command - notifyStrategies(self, self.s, 'endOperation', [self, err, result, new Date()]); - - // Turn into command results - var commandResults = new Array(results.length); - for(var i = 0; i < results.length; i++) { - commandResults[i] = new CommandResult(results[i], connection); - } - - // Execute callback, catch and rethrow if needed - try { callback(null, commandResults); } - catch(err) { process.nextTick(function() { throw err}); } - } - }); - } -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.insert = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('insert', ns, ops, options, callback); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.s.wireProtocolHandler.insert(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.update = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('update', ns, ops, options, callback); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.s.wireProtocolHandler.update(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.remove = function(ns, ops, options, callback) { - if(typeof options == 'function') callback = options, options = {}; - var self = this; - if(this.s.state == DESTROYED) return callback(new MongoError(f('topology was destroyed'))); - // Topology is not connected, save the call in the provided store to be - // Executed at some point when the handler deems it's reconnected - if(!self.isConnected() && self.s.disconnectHandler != null) { - callback = bindToCurrentDomain(callback); - return self.s.disconnectHandler.add('remove', ns, ops, options, callback); - } - - // Setup the docs as an array - ops = Array.isArray(ops) ? ops : [ops]; - // Execute write - return self.s.wireProtocolHandler.remove(self, self.s.ismaster, ns, self.s.bson, self.s.pool, self.s.callbacks, ops, options, callback); -} - -/** - * Authenticate using a specified mechanism - * @method - * @param {string} mechanism The Auth mechanism we are invoking - * @param {string} db The db we are invoking the mechanism against - * @param {...object} param Parameters for the specific mechanism - * @param {authResultCallback} callback A callback function - */ -Server.prototype.auth = function(mechanism, db) { - var self = this; - var args = Array.prototype.slice.call(arguments, 2); - var callback = args.pop(); - - // If we don't have the mechanism fail - if(self.s.authProviders[mechanism] == null && mechanism != 'default') - throw new MongoError(f("auth provider %s does not exist", mechanism)); - - // If we have the default mechanism we pick mechanism based on the wire - // protocol max version. If it's >= 3 then scram-sha1 otherwise mongodb-cr - if(mechanism == 'default' && self.s.ismaster && self.s.ismaster.maxWireVersion >= 3) { - mechanism = 'scram-sha-1'; - } else if(mechanism == 'default') { - mechanism = 'mongocr'; - } - - // Actual arguments - var finalArguments = [self, self.s.pool, db].concat(args.slice(0)).concat([function(err, r) { - if(err) return callback(err); - if(!r) return callback(new MongoError('could not authenticate')); - callback(null, new Session({}, self)); - }]); - - // Let's invoke the auth mechanism - self.s.authProviders[mechanism].auth.apply(self.s.authProviders[mechanism], finalArguments); -} - -// -// Plugin methods -// - -/** - * Add custom read preference strategy - * @method - * @param {string} name Name of the read preference strategy - * @param {object} strategy Strategy object instance - */ -Server.prototype.addReadPreferenceStrategy = function(name, strategy) { - var self = this; - if(self.s.readPreferenceStrategies == null) self.s.readPreferenceStrategies = {}; - self.s.readPreferenceStrategies[name] = strategy; -} - -/** - * Add custom authentication mechanism - * @method - * @param {string} name Name of the authentication mechanism - * @param {object} provider Authentication object instance - */ -Server.prototype.addAuthProvider = function(name, provider) { - var self = this; - self.s.authProviders[name] = provider; -} - -/** - * Compare two server instances - * @method - * @param {Server} server Server to compare equality against - * @return {boolean} - */ -Server.prototype.equals = function(server) { - if(typeof server == 'string') return server == this.name; - return server.name == this.name; -} - -/** - * All raw connections - * @method - * @return {Connection[]} - */ -Server.prototype.connections = function() { - return this.s.pool.getAll(); -} - -/** - * Get server - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Server} - */ -Server.prototype.getServer = function(options) { - return this; -} - -/** - * Get connection - * @method - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @return {Connection} - */ -Server.prototype.getConnection = function(options) { - return this.s.pool.get(); -} - -/** - * Get callbacks object - * @method - * @return {Callbacks} - */ -Server.prototype.getCallbacks = function() { - return this.s.callbacks; -} - -/** - * Name of BSON parser currently used - * @method - * @return {string} - */ -Server.prototype.parserType = function() { - var s = this.s; - if(s.options.bson.serialize.toString().indexOf('[native code]') != -1) - return 'c++'; - return 'js'; -} - -// // Command -// { -// find: ns -// , query: -// , limit: -// , fields: -// , skip: -// , hint: -// , explain: -// , snapshot: -// , batchSize: -// , returnKey: -// , maxScan: -// , min: -// , max: -// , showDiskLoc: -// , comment: -// , maxTimeMS: -// , raw: -// , readPreference: -// , tailable: -// , oplogReplay: -// , noCursorTimeout: -// , awaitdata: -// , exhaust: -// , partial: -// } - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {ReadPreference} [options.readPreference] Specify read preference if command supports it - * @param {Boolean} [options.serializeFunctions=false] Specify if functions on an object should be serialized. - * @param {Boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. - * @param {opResultCallback} callback A callback function - */ -Server.prototype.cursor = function(ns, cmd, cursorOptions) { - var s = this.s; - cursorOptions = cursorOptions || {}; - // Set up final cursor type - var FinalCursor = cursorOptions.cursorFactory || s.Cursor; - // Return the cursor - return new FinalCursor(s.bson, ns, cmd, cursorOptions, this, s.options); -} - -/** - * A server connect event, used to verify that the connection is up and running - * - * @event Server#connect - * @type {Server} - */ - -/** - * The server connection closed, all pool connections closed - * - * @event Server#close - * @type {Server} - */ - -/** - * The server connection caused an error, all pool connections closed - * - * @event Server#error - * @type {Server} - */ - -/** - * The server connection timed out, all pool connections closed - * - * @event Server#timeout - * @type {Server} - */ - -/** - * The driver experienced an invalid message, all pool connections closed - * - * @event Server#parseError - * @type {Server} - */ - -/** - * The server reestablished the connection - * - * @event Server#reconnect - * @type {Server} - */ - -/** - * This is an insert result callback - * - * @callback opResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {CommandResult} command result - */ - -/** - * This is an authentication result callback - * - * @callback authResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {Session} an authenticated session - */ - -module.exports = Server; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js deleted file mode 100644 index 032c3c5..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/session.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; - -var inherits = require('util').inherits - , f = require('util').format - , EventEmitter = require('events').EventEmitter; - -/** - * Creates a new Authentication Session - * @class - * @param {object} [options] Options for the session - * @param {{Server}|{ReplSet}|{Mongos}} topology The topology instance underpinning the session - */ -var Session = function(options, topology) { - this.options = options; - this.topology = topology; - - // Add event listener - EventEmitter.call(this); -} - -inherits(Session, EventEmitter); - -/** - * Execute a command - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {object} cmd The command hash - * @param {object} [options.readPreference] Specify read preference if command supports it - * @param {object} [options.connection] Specify connection object to execute command against - * @param {opResultCallback} callback A callback function - */ -Session.prototype.command = function(ns, cmd, options, callback) { - this.topology.command(ns, cmd, options, callback); -} - -/** - * Insert one or more documents - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of documents to insert - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {opResultCallback} callback A callback function - */ -Session.prototype.insert = function(ns, ops, options, callback) { - this.topology.insert(ns, ops, options, callback); -} - -/** - * Perform one or more update operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of updates - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {opResultCallback} callback A callback function - */ -Session.prototype.update = function(ns, ops, options, callback) { - this.topology.update(ns, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {array} ops An array of removes - * @param {boolean} [options.ordered=true] Execute in order or out of order - * @param {object} [options.writeConcern={}] Write concern for the operation - * @param {opResultCallback} callback A callback function - */ -Session.prototype.remove = function(ns, ops, options, callback) { - this.topology.remove(ns, ops, options, callback); -} - -/** - * Perform one or more remove operations - * @method - * @param {string} ns The MongoDB fully qualified namespace (ex: db1.collection1) - * @param {{object}|{Long}} cmd Can be either a command returning a cursor or a cursorId - * @param {object} [options.batchSize=0] Batchsize for the operation - * @param {array} [options.documents=[]] Initial documents list for cursor - * @param {boolean} [options.tailable=false] Tailable flag set - * @param {boolean} [options.oplogReply=false] oplogReply flag set - * @param {boolean} [options.awaitdata=false] awaitdata flag set - * @param {boolean} [options.exhaust=false] exhaust flag set - * @param {boolean} [options.partial=false] partial flag set - * @param {opResultCallback} callback A callback function - */ -Session.prototype.cursor = function(ns, cmd, options) { - return this.topology.cursor(ns, cmd, options); -} - -module.exports = Session; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js deleted file mode 100644 index 3a7b460..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/strategies/ping.js +++ /dev/null @@ -1,276 +0,0 @@ -"use strict"; - -var Logger = require('../../connection/logger') - , EventEmitter = require('events').EventEmitter - , inherits = require('util').inherits - , f = require('util').format; - -/** - * Creates a new Ping read preference strategy instance - * @class - * @param {number} [options.pingInterval=5000] Ping interval to check the response time to the different servers - * @param {number} [options.acceptableLatency=250] Acceptable latency for selecting a server for reading (in milliseconds) - * @return {Ping} A cursor instance - */ -var Ping = function(options) { - // Add event listener - EventEmitter.call(this); - - // Contains the ping state - this.s = { - // Contains all the ping data - pings: {} - // Set no options if none provided - , options: options || {} - // Logger - , logger: Logger('Ping', options) - // Ping interval - , pingInterval: options.pingInterval || 10000 - , acceptableLatency: options.acceptableLatency || 15 - // Debug options - , debug: typeof options.debug == 'boolean' ? options.debug : false - // Index - , index: 0 - // Current ping time - , lastPing: null - - } - - // Log the options set - if(this.s.logger.isDebug()) this.s.logger.debug(f('ping strategy interval [%s], acceptableLatency [%s]', this.s.pingInterval, this.s.acceptableLatency)); - - // If we have enabled debug - if(this.s.debug) { - // Add access to the read Preference Strategies - Object.defineProperty(this, 'data', { - enumerable: true, get: function() { return this.s.pings; } - }); - } -} - -inherits(Ping, EventEmitter); - -/** - * @ignore - */ -var filterByTags = function(readPreference, servers) { - if(readPreference.tags == null) return servers; - var filteredServers = []; - var tags = readPreference.tags; - - // Iterate over all the servers - for(var i = 0; i < servers.length; i++) { - var serverTag = servers[i].lastIsMaster().tags || {}; - // Did we find the a matching server - var found = true; - // Check if the server is valid - for(var name in tags) { - if(serverTag[name] != tags[name]) found = false; - } - - // Add to candidate list - if(found) filteredServers.push(servers[i]); - } - - // Returned filtered servers - return filteredServers; -} - -/** - * Pick a server - * @method - * @param {State} set The current replicaset state object - * @param {ReadPreference} readPreference The current readPreference object - * @param {readPreferenceResultCallback} callback The callback to return the result from the function - * @return {object} - */ -Ping.prototype.pickServer = function(set, readPreference) { - var self = this; - // Only get primary and secondaries as seeds - var seeds = {}; - var servers = []; - if(set.primary) { - servers.push(set.primary); - } - - for(var i = 0; i < set.secondaries.length; i++) { - servers.push(set.secondaries[i]); - } - - // Filter by tags - servers = filterByTags(readPreference, servers); - - // Transform the list - var serverList = []; - // for(var name in seeds) { - for(var i = 0; i < servers.length; i++) { - serverList.push({name: servers[i].name, time: self.s.pings[servers[i].name] || 0}); - } - - // Sort by time - serverList.sort(function(a, b) { - return a.time > b.time; - }); - - // Locate lowest time (picked servers are lowest time + acceptable Latency margin) - var lowest = serverList.length > 0 ? serverList[0].time : 0; - - // Filter by latency - serverList = serverList.filter(function(s) { - return s.time <= lowest + self.s.acceptableLatency; - }); - - // No servers, default to primary - if(serverList.length == 0 && set.primary) { - if(self.s.logger.isInfo()) self.s.logger.info(f('picked primary server [%s]', set.primary.name)); - return set.primary; - } else if(serverList.length == 0) { - return null - } - - // We picked first server - if(self.s.logger.isInfo()) self.s.logger.info(f('picked server [%s] with ping latency [%s]', serverList[0].name, serverList[0].time)); - - // Add to the index - self.s.index = self.s.index + 1; - // Select the index - self.s.index = self.s.index % serverList.length; - // Return the first server of the sorted and filtered list - return set.get(serverList[self.s.index].name); -} - -/** - * Start of an operation - * @method - * @param {Server} server The server the operation is running against - * @param {object} query The operation running - * @param {Date} date The start time of the operation - * @return {object} - */ -Ping.prototype.startOperation = function(server, query, date) { -} - -/** - * End of an operation - * @method - * @param {Server} server The server the operation is running against - * @param {error} err An error from the operation - * @param {object} result The result from the operation - * @param {Date} date The start time of the operation - * @return {object} - */ -Ping.prototype.endOperation = function(server, err, result, date) { -} - -/** - * High availability process running - * @method - * @param {State} set The current replicaset state object - * @param {resultCallback} callback The callback to return the result from the function - * @return {object} - */ -Ping.prototype.ha = function(topology, state, callback) { - var self = this; - var servers = state.getAll(); - var count = servers.length; - - // No servers return - if(servers.length == 0) return callback(null, null); - - // Return if we have not yet reached the ping interval - if(self.s.lastPing != null) { - var diff = new Date().getTime() - self.s.lastPing.getTime(); - if(diff < self.s.pingInterval) return callback(null, null); - } - - // Execute operation - var operation = function(_server) { - var start = new Date(); - // Execute ping against server - _server.command('system.$cmd', {ismaster:1}, function(err, r) { - count = count - 1; - var time = new Date().getTime() - start.getTime(); - self.s.pings[_server.name] = time; - // Log info for debug - if(self.s.logger.isDebug()) self.s.logger.debug(f('ha latency for server [%s] is [%s] ms', _server.name, time)); - // We are done with all the servers - if(count == 0) { - // Emit ping event - topology.emit('ping', err, r ? r.result : null); - // Update the last ping time - self.s.lastPing = new Date(); - // Return - callback(null, null); - } - }); - } - - // Let's ping all servers - while(servers.length > 0) { - operation(servers.shift()); - } -} - -var removeServer = function(self, server) { - delete self.s.pings[server.name]; -} - -/** - * Server connection closed - * @method - * @param {Server} server The server that closed - */ -Ping.prototype.close = function(server) { - removeServer(this, server); -} - -/** - * Server connection errored out - * @method - * @param {Server} server The server that errored out - */ -Ping.prototype.error = function(server) { - removeServer(this, server); -} - -/** - * Server connection timeout - * @method - * @param {Server} server The server that timed out - */ -Ping.prototype.timeout = function(server) { - removeServer(this, server); -} - -/** - * Server connection happened - * @method - * @param {Server} server The server that connected - * @param {resultCallback} callback The callback to return the result from the function - */ -Ping.prototype.connect = function(server, callback) { - var self = this; - // Get the command start date - var start = new Date(); - // Execute ping against server - server.command('system.$cmd', {ismaster:1}, function(err, r) { - var time = new Date().getTime() - start.getTime(); - self.s.pings[server.name] = time; - // Log info for debug - if(self.s.logger.isDebug()) self.s.logger.debug(f('connect latency for server [%s] is [%s] ms', server.name, time)); - // Set last ping - self.s.lastPing = new Date(); - // Done, return - callback(null, null); - }); -} - -/** - * This is a result from a readPreference strategy - * - * @callback readPreferenceResultCallback - * @param {error} error An error object. Set to null if no error present - * @param {Server} server The server picked by the strategy - */ - -module.exports = Ping; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js deleted file mode 100644 index e2e6a67..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_4_support.js +++ /dev/null @@ -1,559 +0,0 @@ -"use strict"; - -var Insert = require('./commands').Insert - , Update = require('./commands').Update - , Remove = require('./commands').Remove - , Query = require('../connection/commands').Query - , copy = require('../connection/utils').copy - , KillCursor = require('../connection/commands').KillCursor - , GetMore = require('../connection/commands').GetMore - , Query = require('../connection/commands').Query - , ReadPreference = require('../topologies/read_preference') - , f = require('util').format - , CommandResult = require('../topologies/command_result') - , MongoError = require('../error') - , Long = require('bson').Long; - -// Write concern fields -var writeConcernFields = ['w', 'wtimeout', 'j', 'fsync']; - -var WireProtocol = function() {} - -// -// Needs to support legacy mass insert as well as ordered/unordered legacy -// emulation -// -WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - options = options || {}; - // Default is ordered execution - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - var legacy = typeof options.legacy == 'boolean' ? options.legacy : false; - ops = Array.isArray(ops) ? ops :[ops]; - - // If we have more than a 1000 ops fails - if(ops.length > 1000) return callback(new MongoError("exceeded maximum write batch size of 1000")); - - // Write concern - var writeConcern = options.writeConcern || {w:1}; - - // We are unordered - if(!ordered || writeConcern.w == 0) { - return executeUnordered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); - } - - return executeOrdered('insert', Insert, ismaster, ns, bson, pool, callbacks, ops, options, callback); -} - -WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - options = options || {}; - // Default is ordered execution - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - ops = Array.isArray(ops) ? ops :[ops]; - - // Write concern - var writeConcern = options.writeConcern || {w:1}; - - // We are unordered - if(!ordered || writeConcern.w == 0) { - return executeUnordered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); - } - - return executeOrdered('update', Update, ismaster, ns, bson, pool, callbacks, ops, options, callback); -} - -WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - options = options || {}; - // Default is ordered execution - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - ops = Array.isArray(ops) ? ops :[ops]; - - // Write concern - var writeConcern = options.writeConcern || {w:1}; - - // We are unordered - if(!ordered || writeConcern.w == 0) { - return executeUnordered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); - } - - return executeOrdered('remove', Remove, ismaster, ns, bson, pool, callbacks, ops, options, callback); -} - -WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { - // Create a kill cursor command - var killCursor = new KillCursor(bson, [cursorId]); - // Execute the kill cursor command - if(connection && connection.isConnected()) connection.write(killCursor.toBin()); - // Set cursor to 0 - cursorId = Long.ZERO; - // Return to caller - if(callback) callback(null, null); -} - -WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { - // Create getMore command - var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); - - // Query callback - var queryCallback = function(err, r) { - if(err) return callback(err); - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - return callback(new MongoError("cursor killed or timed out"), null); - } - - // Ensure we have a Long valie cursor id - var cursorId = typeof r.cursorId == 'number' - ? Long.fromNumber(r.cursorId) - : r.cursorId; - - // Set all the values - cursorState.documents = r.documents; - cursorState.cursorId = cursorId; - - // Return - callback(null); - } - - // If we have a raw query decorate the function - if(raw) { - queryCallback.raw = raw; - } - - // Register a callback - callbacks.register(getMore.requestId, queryCallback); - // Write out the getMore command - connection.write(getMore.toBin()); -} - -WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { - // Establish type of command - if(cmd.find) { - return setupClassicFind(bson, ns, cmd, cursorState, topology, options) - } else if(cursorState.cursorId != null) { - } else if(cmd) { - return setupCommand(bson, ns, cmd, cursorState, topology, options); - } else { - throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); - } -} - -// -// Execute a find command -var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Ensure we have at least some options - options = options || {}; - // Set the optional batchSize - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - var numberToReturn = 0; - - // Unpack the limit and batchSize values - if(cursorState.limit == 0) { - numberToReturn = cursorState.batchSize; - } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - var numberToSkip = cursorState.skip || 0; - // Build actual find command - var findCmd = {}; - // Using special modifier - var usesSpecialModifier = false; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - usesSpecialModifier = true; - } - - // Add special modifiers to the query - if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; - if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; - if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; - if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; - if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; - if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; - if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; - if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; - if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; - if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; - - // If we have explain, return a single document and close cursor - if(cmd.explain) { - numberToReturn = -1; - usesSpecialModifier = true; - findCmd['$explain'] = true; - } - - // If we have a special modifier - if(usesSpecialModifier) { - findCmd['$query'] = cmd.query; - } else { - findCmd = cmd.query; - } - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) { - cmd = copy(cmd); - delete cmd['readConcern']; - } - - // Set up the serialize and ignoreUndefined fields - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, numberToReturn: numberToReturn - , checkKeys: false, returnFieldSelector: cmd.fields - , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Set up the option bits for wire protocol - if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; - if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; - if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; - if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; - if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; - // Return the query - return query; -} - -// -// Set up a command cursor -var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Set empty options object - options = options || {} - - // Final query - var finalCmd = {}; - for(var name in cmd) { - finalCmd[name] = cmd[name]; - } - - // Build command namespace - var parts = ns.split(/\./); - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - finalCmd['$readPreference'] = readPreference.toJSON(); - } - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) delete cmd['readConcern']; - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - - // Set up the serialize and ignoreUndefined fields - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) { - return callback; - } else { - return domain.bind(callback); - } -} - -var hasWriteConcern = function(writeConcern) { - if(writeConcern.w - || writeConcern.wtimeout - || writeConcern.j == true - || writeConcern.fsync == true - || Object.keys(writeConcern).length == 0) { - return true; - } - return false; -} - -var cloneWriteConcern = function(writeConcern) { - var wc = {}; - if(writeConcern.w != null) wc.w = writeConcern.w; - if(writeConcern.wtimeout != null) wc.wtimeout = writeConcern.wtimeout; - if(writeConcern.j != null) wc.j = writeConcern.j; - if(writeConcern.fsync != null) wc.fsync = writeConcern.fsync; - return wc; -} - -// -// Aggregate up all the results -// -var aggregateWriteOperationResults = function(opType, ops, results, connection) { - var finalResult = { ok: 1, n: 0 } - - // Map all the results coming back - for(var i = 0; i < results.length; i++) { - var result = results[i]; - var op = ops[i]; - - if((result.upserted || (result.updatedExisting == false)) && finalResult.upserted == null) { - finalResult.upserted = []; - } - - // Push the upserted document to the list of upserted values - if(result.upserted) { - finalResult.upserted.push({index: i, _id: result.upserted}); - } - - // We have an upsert where we passed in a _id - if(result.updatedExisting == false && result.n == 1 && result.upserted == null) { - finalResult.upserted.push({index: i, _id: op.q._id}); - } - - // We have an insert command - if(result.ok == 1 && opType == 'insert' && result.err == null) { - finalResult.n = finalResult.n + 1; - } - - // We have a command error - if(result != null && result.ok == 0 || result.err || result.errmsg) { - if(result.ok == 0) finalResult.ok = 0; - finalResult.code = result.code; - finalResult.errmsg = result.errmsg || result.err || result.errMsg; - - // Check if we have a write error - if(result.code == 11000 - || result.code == 11001 - || result.code == 12582 - || result.code == 16544 - || result.code == 16538 - || result.code == 16542 - || result.code == 14 - || result.code == 13511) { - if(finalResult.writeErrors == null) finalResult.writeErrors = []; - finalResult.writeErrors.push({ - index: i - , code: result.code - , errmsg: result.errmsg || result.err || result.errMsg - }); - } else { - finalResult.writeConcernError = { - code: result.code - , errmsg: result.errmsg || result.err || result.errMsg - } - } - } else if(typeof result.n == 'number') { - finalResult.n += result.n; - } else { - finalResult.n += 1; - } - - // Result as expected - if(result != null && result.lastOp) finalResult.lastOp = result.lastOp; - } - - // Return finalResult aggregated results - return new CommandResult(finalResult, connection); -} - -// -// Execute all inserts in an ordered manner -// -var executeOrdered = function(opType ,command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - var _ops = ops.slice(0); - // Bind to current domain - callback = bindToCurrentDomain(callback); - // Collect all the getLastErrors - var getLastErrors = []; - - // Execute an operation - var executeOp = function(list, _callback) { - // Get a pool connection - var connection = pool.get(); - // No more items in the list - if(list.length == 0) return _callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - - // Get the first operation - var doc = list.shift(); - - // Create an insert command - var op = new command(Query.getRequestId(), ismaster, bson, ns, [doc], options); - // Write concern - var optionWriteConcern = options.writeConcern || {w:1}; - // Final write concern - var writeConcern = cloneWriteConcern(optionWriteConcern); - - // Get the db name - var db = ns.split('.').shift(); - - // Error out if no connection available - if(connection == null) - return _callback(new MongoError("no connection available")); - - try { - // Execute the insert - connection.write(op.toBin()); - - // If write concern 0 don't fire getLastError - if(hasWriteConcern(writeConcern)) { - var getLastErrorCmd = {getlasterror: 1}; - // Merge all the fields - for(var i = 0; i < writeConcernFields.length; i++) { - if(writeConcern[writeConcernFields[i]] != null) - getLastErrorCmd[writeConcernFields[i]] = writeConcern[writeConcernFields[i]]; - } - - // Create a getLastError command - var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); - // Write the lastError message - connection.write(getLastErrorOp.toBin()); - // Register the callback - callbacks.register(getLastErrorOp.requestId, function(err, result) { - if(err) return callback(err); - // Get the document - var doc = result.documents[0]; - // Save the getLastError document - getLastErrors.push(doc); - // If we have an error terminate - if(doc.ok == 0 || doc.err || doc.errmsg) return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - // Execute the next op in the list - executeOp(list, callback); - }); - } - } catch(err) { - if(typeof err == 'string') err = new MongoError(err); - // We have a serialization error, rewrite as a write error to have same behavior as modern - // write commands - getLastErrors.push({ ok: 1, errmsg: err.message, code: 14 }); - // Return due to an error - return callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - } - } - - // Execute the operations - executeOp(_ops, callback); -} - -var executeUnordered = function(opType, command, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - // Bind to current domain - callback = bindToCurrentDomain(callback); - // Total operations to write - var totalOps = ops.length; - // Collect all the getLastErrors - var getLastErrors = []; - // Write concern - var optionWriteConcern = options.writeConcern || {w:1}; - // Final write concern - var writeConcern = cloneWriteConcern(optionWriteConcern); - // Driver level error - var error; - - // Execute all the operations - for(var i = 0; i < ops.length; i++) { - // Create an insert command - var op = new command(Query.getRequestId(), ismaster, bson, ns, [ops[i]], options); - // Get db name - var db = ns.split('.').shift(); - - // Get a pool connection - var connection = pool.get(); - - // Error out if no connection available - if(connection == null) - return _callback(new MongoError("no connection available")); - - try { - // Execute the insert - connection.write(op.toBin()); - // If write concern 0 don't fire getLastError - if(hasWriteConcern(writeConcern)) { - var getLastErrorCmd = {getlasterror: 1}; - // Merge all the fields - for(var j = 0; j < writeConcernFields.length; j++) { - if(writeConcern[writeConcernFields[j]] != null) - getLastErrorCmd[writeConcernFields[j]] = writeConcern[writeConcernFields[j]]; - } - - // Create a getLastError command - var getLastErrorOp = new Query(bson, f("%s.$cmd", db), getLastErrorCmd, {numberToReturn: -1}); - // Write the lastError message - connection.write(getLastErrorOp.toBin()); - - // Give the result from getLastError the right index - var callbackOp = function(_index) { - return function(err, result) { - if(err) error = err; - // Update the number of operations executed - totalOps = totalOps - 1; - // Save the getLastError document - if(!err) getLastErrors[_index] = result.documents[0]; - // Check if we are done - if(totalOps == 0) { - if(error) return callback(error); - callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - } - } - } - - // Register the callback - callbacks.register(getLastErrorOp.requestId, callbackOp(i)); - } - } catch(err) { - if(typeof err == 'string') err = new MongoError(err); - // Update the number of operations executed - totalOps = totalOps - 1; - // We have a serialization error, rewrite as a write error to have same behavior as modern - // write commands - getLastErrors[i] = { ok: 1, errmsg: err.message, code: 14 }; - // Check if we are done - if(totalOps == 0) { - callback(null, aggregateWriteOperationResults(opType, ops, getLastErrors, connection)); - } - } - } - - // Empty w:0 return - if(writeConcern - && writeConcern.w == 0 && callback) { - callback(null, null); - } -} - -module.exports = WireProtocol; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js deleted file mode 100644 index b1d1d46..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/2_6_support.js +++ /dev/null @@ -1,291 +0,0 @@ -"use strict"; - -var Insert = require('./commands').Insert - , Update = require('./commands').Update - , Remove = require('./commands').Remove - , Query = require('../connection/commands').Query - , copy = require('../connection/utils').copy - , KillCursor = require('../connection/commands').KillCursor - , GetMore = require('../connection/commands').GetMore - , Query = require('../connection/commands').Query - , ReadPreference = require('../topologies/read_preference') - , f = require('util').format - , CommandResult = require('../topologies/command_result') - , MongoError = require('../error') - , Long = require('bson').Long; - -var WireProtocol = function() {} - -// -// Execute a write operation -var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { - if(ops.length == 0) throw new MongoError("insert must contain at least one document"); - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Split the ns up to get db and collection - var p = ns.split("."); - var d = p.shift(); - // Options - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - var writeConcern = options.writeConcern || {}; - // return skeleton - var writeCommand = {}; - writeCommand[type] = p.join('.'); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - writeCommand.writeConcern = writeConcern; - - // Options object - var opts = {}; - if(type == 'insert') opts.checkKeys = true; - // Ensure we support serialization of functions - if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; - if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; - // Execute command - topology.command(f("%s.$cmd", d), writeCommand, opts, callback); -} - -// -// Needs to support legacy mass insert as well as ordered/unordered legacy -// emulation -// -WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); -} - -WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'update', 'updates', ns, ops, options, callback); -} - -WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); -} - -WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { - // Create a kill cursor command - var killCursor = new KillCursor(bson, [cursorId]); - // Execute the kill cursor command - if(connection && connection.isConnected()) connection.write(killCursor.toBin()); - // Set cursor to 0 - cursorId = Long.ZERO; - // Return to caller - if(callback) callback(null, null); -} - -WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { - // Create getMore command - var getMore = new GetMore(bson, ns, cursorState.cursorId, {numberToReturn: batchSize}); - - // Query callback - var queryCallback = function(err, r) { - if(err) return callback(err); - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - return callback(new MongoError("cursor killed or timed out"), null); - } - - // Ensure we have a Long valie cursor id - var cursorId = typeof r.cursorId == 'number' - ? Long.fromNumber(r.cursorId) - : r.cursorId; - - // Set all the values - cursorState.documents = r.documents; - cursorState.cursorId = cursorId; - - // Return - callback(null); - } - - // If we have a raw query decorate the function - if(raw) { - queryCallback.raw = raw; - } - - // Register a callback - callbacks.register(getMore.requestId, queryCallback); - // Write out the getMore command - connection.write(getMore.toBin()); -} - -WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { - // Establish type of command - if(cmd.find) { - return setupClassicFind(bson, ns, cmd, cursorState, topology, options) - } else if(cursorState.cursorId != null) { - } else if(cmd) { - return setupCommand(bson, ns, cmd, cursorState, topology, options); - } else { - throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); - } -} - -// -// Execute a find command -var setupClassicFind = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Ensure we have at least some options - options = options || {}; - // Set the optional batchSize - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - var numberToReturn = 0; - - // Unpack the limit and batchSize values - if(cursorState.limit == 0) { - numberToReturn = cursorState.batchSize; - } else if(cursorState.limit < 0 || cursorState.limit < cursorState.batchSize || (cursorState.limit > 0 && cursorState.batchSize == 0)) { - numberToReturn = cursorState.limit; - } else { - numberToReturn = cursorState.batchSize; - } - - var numberToSkip = cursorState.skip || 0; - // Build actual find command - var findCmd = {}; - // Using special modifier - var usesSpecialModifier = false; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - usesSpecialModifier = true; - } - - // Add special modifiers to the query - if(cmd.sort) findCmd['orderby'] = cmd.sort, usesSpecialModifier = true; - if(cmd.hint) findCmd['$hint'] = cmd.hint, usesSpecialModifier = true; - if(cmd.snapshot) findCmd['$snapshot'] = cmd.snapshot, usesSpecialModifier = true; - if(cmd.returnKey) findCmd['$returnKey'] = cmd.returnKey, usesSpecialModifier = true; - if(cmd.maxScan) findCmd['$maxScan'] = cmd.maxScan, usesSpecialModifier = true; - if(cmd.min) findCmd['$min'] = cmd.min, usesSpecialModifier = true; - if(cmd.max) findCmd['$max'] = cmd.max, usesSpecialModifier = true; - if(cmd.showDiskLoc) findCmd['$showDiskLoc'] = cmd.showDiskLoc, usesSpecialModifier = true; - if(cmd.comment) findCmd['$comment'] = cmd.comment, usesSpecialModifier = true; - if(cmd.maxTimeMS) findCmd['$maxTimeMS'] = cmd.maxTimeMS, usesSpecialModifier = true; - - // If we have explain, return a single document and close cursor - if(cmd.explain) { - numberToReturn = -1; - usesSpecialModifier = true; - findCmd['$explain'] = true; - } - - // If we have a special modifier - if(usesSpecialModifier) { - findCmd['$query'] = cmd.query; - } else { - findCmd = cmd.query; - } - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server find command does not support a readConcern level of %s', cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) { - cmd = copy(cmd); - delete cmd['readConcern']; - } - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, ns, findCmd, { - numberToSkip: numberToSkip, numberToReturn: numberToReturn - , checkKeys: false, returnFieldSelector: cmd.fields - , serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Set up the option bits for wire protocol - if(typeof cmd.tailable == 'boolean') query.tailable = cmd.tailable; - if(typeof cmd.oplogReplay == 'boolean') query.oplogReplay = cmd.oplogReplay; - if(typeof cmd.noCursorTimeout == 'boolean') query.noCursorTimeout = cmd.noCursorTimeout; - if(typeof cmd.awaitData == 'boolean') query.awaitData = cmd.awaitData; - if(typeof cmd.exhaust == 'boolean') query.exhaust = cmd.exhaust; - if(typeof cmd.partial == 'boolean') query.partial = cmd.partial; - // Return the query - return query; -} - -// -// Set up a command cursor -var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Set empty options object - options = options || {} - - // Final query - var finalCmd = {}; - for(var name in cmd) { - finalCmd[name] = cmd[name]; - } - - // Build command namespace - var parts = ns.split(/\./); - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - finalCmd['$readPreference'] = readPreference.toJSON(); - } - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Throw on majority readConcern passed in - if(cmd.readConcern && cmd.readConcern.level != 'local') { - throw new MongoError(f('server %s command does not support a readConcern level of %s', JSON.stringify(cmd), cmd.readConcern.level)); - } - - // Remove readConcern, ensure no failing commands - if(cmd.readConcern) delete cmd['readConcern']; - - // Build Query object - var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) { - return callback; - } else { - return domain.bind(callback); - } -} - -module.exports = WireProtocol; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js deleted file mode 100644 index c5e61aa..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/3_2_support.js +++ /dev/null @@ -1,494 +0,0 @@ -"use strict"; - -var Insert = require('./commands').Insert - , Update = require('./commands').Update - , Remove = require('./commands').Remove - , Query = require('../connection/commands').Query - , copy = require('../connection/utils').copy - , KillCursor = require('../connection/commands').KillCursor - , GetMore = require('../connection/commands').GetMore - , Query = require('../connection/commands').Query - , ReadPreference = require('../topologies/read_preference') - , f = require('util').format - , CommandResult = require('../topologies/command_result') - , MongoError = require('../error') - , Long = require('bson').Long; - -var WireProtocol = function(legacyWireProtocol) { - this.legacyWireProtocol = legacyWireProtocol; -} - -// -// Execute a write operation -var executeWrite = function(topology, type, opsField, ns, ops, options, callback) { - if(ops.length == 0) throw new MongoError("insert must contain at least one document"); - if(typeof options == 'function') { - callback = options; - options = {}; - } - - // Split the ns up to get db and collection - var p = ns.split("."); - var d = p.shift(); - // Options - var ordered = typeof options.ordered == 'boolean' ? options.ordered : true; - var writeConcern = options.writeConcern || {}; - // return skeleton - var writeCommand = {}; - writeCommand[type] = p.join('.'); - writeCommand[opsField] = ops; - writeCommand.ordered = ordered; - writeCommand.writeConcern = writeConcern; - - // Do we have bypassDocumentValidation set, then enable it on the write command - if(typeof options.bypassDocumentValidation == 'boolean') { - writeCommand.bypassDocumentValidation = options.bypassDocumentValidation; - } - - // Options object - var opts = {}; - if(type == 'insert') opts.checkKeys = true; - // Ensure we support serialization of functions - if(options.serializeFunctions) opts.serializeFunctions = options.serializeFunctions; - if(options.ignoreUndefined) opts.ignoreUndefined = options.ignoreUndefined; - // Execute command - topology.command(f("%s.$cmd", d), writeCommand, opts, callback); -} - -// -// Needs to support legacy mass insert as well as ordered/unordered legacy -// emulation -// -WireProtocol.prototype.insert = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'insert', 'documents', ns, ops, options, callback); -} - -WireProtocol.prototype.update = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'update', 'updates', ns, ops, options, callback); -} - -WireProtocol.prototype.remove = function(topology, ismaster, ns, bson, pool, callbacks, ops, options, callback) { - executeWrite(topology, 'delete', 'deletes', ns, ops, options, callback); -} - -WireProtocol.prototype.killCursor = function(bson, ns, cursorId, connection, callbacks, callback) { - // Build command namespace - var parts = ns.split(/\./); - // Command namespace - var commandns = f('%s.$cmd', parts.shift()); - // Create getMore command - var killcursorCmd = { - killCursors: parts.join('.'), - cursors: [cursorId] - } - - // Build Query object - var query = new Query(bson, commandns, killcursorCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, returnFieldSelector: null - }); - - // Set query flags - query.slaveOk = true; - - // Execute the kill cursor command - if(connection && connection.isConnected()) { - connection.write(query.toBin()); - } - - // Kill cursor callback - var killCursorCallback = function(err, r) { - if(err) { - if(typeof callback != 'function') return; - return callback(err); - } - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - if(typeof callback != 'function') return; - return callback(new MongoError("cursor killed or timed out"), null); - } - - if(!Array.isArray(r.documents) || r.documents.length == 0) { - if(typeof callback != 'function') return; - return callback(new MongoError(f('invalid getMore result returned for cursor id %s', cursorState.cursorId))); - } - - // Return the result - if(typeof callback == 'function') { - callback(null, r.documents[0]); - } - } - - // Register a callback - callbacks.register(query.requestId, killCursorCallback); -} - -WireProtocol.prototype.getMore = function(bson, ns, cursorState, batchSize, raw, connection, callbacks, options, callback) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - // Build command namespace - var parts = ns.split(/\./); - // Command namespace - var commandns = f('%s.$cmd', parts.shift()); - - // Check if we have an maxTimeMS set - var maxTimeMS = typeof cursorState.cmd.maxTimeMS == 'number' ? cursorState.cmd.maxTimeMS : 3000; - - // Create getMore command - var getMoreCmd = { - getMore: cursorState.cursorId, - collection: parts.join('.'), - batchSize: batchSize, - maxTimeMS: maxTimeMS - } - - // Build Query object - var query = new Query(bson, commandns, getMoreCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, returnFieldSelector: null - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Query callback - var queryCallback = function(err, r) { - if(err) return callback(err); - - // If we have a timed out query or a cursor that was killed - if((r.responseFlags & (1 << 0)) != 0) { - return callback(new MongoError("cursor killed or timed out"), null); - } - - if(!Array.isArray(r.documents) || r.documents.length == 0) - return callback(new MongoError(f('invalid getMore result returned for cursor id %s', cursorState.cursorId))); - - // Raw, return all the extracted documents - if(raw) { - cursorState.documents = r.documents; - cursorState.cursorId = r.cursorId; - return callback(null, r.documents); - } - - // Ensure we have a Long valie cursor id - var cursorId = typeof r.documents[0].cursor.id == 'number' - ? Long.fromNumber(r.documents[0].cursor.id) - : r.documents[0].cursor.id; - - // Set all the values - cursorState.documents = r.documents[0].cursor.nextBatch; - cursorState.cursorId = cursorId; - - // Return the result - callback(null, r.documents[0]); - } - - // If we have a raw query decorate the function - if(raw) { - queryCallback.raw = raw; - } - - // Add the result field needed - queryCallback.documentsReturnedIn = 'nextBatch'; - - // Register a callback - callbacks.register(query.requestId, queryCallback); - // Write out the getMore command - connection.write(query.toBin()); -} - -WireProtocol.prototype.command = function(bson, ns, cmd, cursorState, topology, options) { - // Establish type of command - if(cmd.find) { - if(cmd.exhaust) { - return this.legacyWireProtocol.command(bson, ns, cmd, cursorState, topology, options); - } - - // Create the find command - var query = executeFindCommand(bson, ns, cmd, cursorState, topology, options) - // Mark the cmd as virtual - cmd.virtual = false; - // Signal the documents are in the firstBatch value - query.documentsReturnedIn = 'firstBatch'; - // Return the query - return query; - } else if(cursorState.cursorId != null) { - } else if(cmd) { - return setupCommand(bson, ns, cmd, cursorState, topology, options); - } else { - throw new MongoError(f("command %s does not return a cursor", JSON.stringify(cmd))); - } -} - -// // Command -// { -// find: ns -// , query: -// , limit: -// , fields: -// , skip: -// , hint: -// , explain: -// , snapshot: -// , batchSize: -// , returnKey: -// , maxScan: -// , min: -// , max: -// , showDiskLoc: -// , comment: -// , maxTimeMS: -// , raw: -// , readPreference: -// , tailable: -// , oplogReplay: -// , noCursorTimeout: -// , awaitdata: -// , exhaust: -// , partial: -// } - -// FIND/GETMORE SPEC -// { -// “find”: , -// “filter”: { ... }, -// “sort”: { ... }, -// “projection”: { ... }, -// “hint”: { ... }, -// “skip”: , -// “limit”: , -// “batchSize”: , -// “singleBatch”: , -// “comment”: , -// “maxScan”: , -// “maxTimeMS”: , -// “max”: { ... }, -// “min”: { ... }, -// “returnKey”: , -// “showRecordId”: , -// “snapshot”: , -// “tailable”: , -// “oplogReplay”: , -// “noCursorTimeout”: , -// “awaitData”: , -// “partial”: , -// “$readPreference”: { ... } -// } - -// -// Execute a find command -var executeFindCommand = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Ensure we have at least some options - options = options || {}; - // Set the optional batchSize - cursorState.batchSize = cmd.batchSize || cursorState.batchSize; - - // Build command namespace - var parts = ns.split(/\./); - // Command namespace - var commandns = f('%s.$cmd', parts.shift()); - - // Build actual find command - var findCmd = { - find: parts.join('.') - }; - - // I we provided a filter - if(cmd.query) findCmd.filter = cmd.query; - - // Sort value - var sortValue = cmd.sort; - - // Handle issue of sort being an Array - if(Array.isArray(sortValue)) { - var sortObject = {}; - - if(sortValue.length > 0 && !Array.isArray(sortValue[0])) { - var sortDirection = sortValue[1]; - // Translate the sort order text - if(sortDirection == 'asc') { - sortDirection = 1; - } else if(sortDirection == 'desc') { - sortDirection = -1; - } - - // Set the sort order - sortObject[sortValue[0]] = sortDirection; - } else { - for(var i = 0; i < sortValue.length; i++) { - var sortDirection = sortValue[i][1]; - // Translate the sort order text - if(sortDirection == 'asc') { - sortDirection = 1; - } else if(sortDirection == 'desc') { - sortDirection = -1; - } - - // Set the sort order - sortObject[sortValue[i][0]] = sortDirection; - } - } - - sortValue = sortObject; - }; - - // Add sort to command - if(cmd.sort) findCmd.sort = sortValue; - // Add a projection to the command - if(cmd.fields) findCmd.projection = cmd.fields; - // Add a hint to the command - if(cmd.hint) findCmd.hint = cmd.hint; - // Add a skip - if(cmd.skip) findCmd.skip = cmd.skip; - // Add a limit - if(cmd.limit) findCmd.limit = cmd.limit; - // Add a batchSize - if(cmd.batchSize) findCmd.batchSize = cmd.batchSize; - - // Check if we wish to have a singleBatch - if(cmd.limit < 0) { - findCmd.limit = Math.abs(cmd.limit); - findCmd.singleBatch = true; - } - - // If we have comment set - if(cmd.comment) findCmd.comment = cmd.comment; - - // If we have maxScan - if(cmd.maxScan) findCmd.maxScan = cmd.maxScan; - - // If we have maxTimeMS set - if(cmd.maxTimeMS) findCmd.maxTimeMS = cmd.maxTimeMS; - - // If we have min - if(cmd.min) findCmd.min = cmd.min; - - // If we have max - if(cmd.max) findCmd.max = cmd.max; - - // If we have returnKey set - if(cmd.returnKey) findCmd.returnKey = cmd.returnKey; - - // If we have showDiskLoc set - if(cmd.showDiskLoc) findCmd.showRecordId = cmd.showDiskLoc; - - // If we have snapshot set - if(cmd.snapshot) findCmd.snapshot = cmd.snapshot; - - // If we have tailable set - if(cmd.tailable) findCmd.tailable = cmd.tailable; - - // If we have oplogReplay set - if(cmd.oplogReplay) findCmd.oplogReplay = cmd.oplogReplay; - - // If we have noCursorTimeout set - if(cmd.noCursorTimeout) findCmd.noCursorTimeout = cmd.noCursorTimeout; - - // If we have awaitData set - if(cmd.awaitData) findCmd.awaitData = cmd.awaitData; - if(cmd.awaitdata) findCmd.awaitData = cmd.awaitdata; - - // If we have partial set - if(cmd.partial) findCmd.partial = cmd.partial; - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - findCmd['$readPreference'] = readPreference.toJSON(); - } - - // If we have explain, we need to rewrite the find command - // to wrap it in the explain command - if(cmd.explain) { - findCmd = { - explain: findCmd - } - } - - // Did we provide a readConcern - if(cmd.readConcern) findCmd.readConcern = cmd.readConcern; - - // Set up the serialize and ignoreUndefined fields - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, commandns, findCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, returnFieldSelector: null - , serializeFunctions: serializeFunctions, ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -// -// Set up a command cursor -var setupCommand = function(bson, ns, cmd, cursorState, topology, options) { - var readPreference = options.readPreference || new ReadPreference('primary'); - if(typeof readPreference == 'string') readPreference = new ReadPreference(readPreference); - if(!(readPreference instanceof ReadPreference)) throw new MongoError('readPreference must be a ReadPreference instance'); - - // Set empty options object - options = options || {} - - // Final query - var finalCmd = {}; - for(var name in cmd) { - finalCmd[name] = cmd[name]; - } - - // Build command namespace - var parts = ns.split(/\./); - - // We have a Mongos topology, check if we need to add a readPreference - if(topology.type == 'mongos' && readPreference) { - finalCmd['$readPreference'] = readPreference.toJSON(); - } - - // Serialize functions - var serializeFunctions = typeof options.serializeFunctions == 'boolean' - ? options.serializeFunctions : false; - - // Set up the serialize and ignoreUndefined fields - var ignoreUndefined = typeof options.ignoreUndefined == 'boolean' - ? options.ignoreUndefined : false; - - // Build Query object - var query = new Query(bson, f('%s.$cmd', parts.shift()), finalCmd, { - numberToSkip: 0, numberToReturn: -1 - , checkKeys: false, serializeFunctions: serializeFunctions - , ignoreUndefined: ignoreUndefined - }); - - // Set query flags - query.slaveOk = readPreference.slaveOk(); - - // Return the query - return query; -} - -/** - * @ignore - */ -var bindToCurrentDomain = function(callback) { - var domain = process.domain; - if(domain == null || callback == null) { - return callback; - } else { - return domain.bind(callback); - } -} - -module.exports = WireProtocol; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js deleted file mode 100644 index 9c665ee..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/lib/wireprotocol/commands.js +++ /dev/null @@ -1,357 +0,0 @@ -"use strict"; - -var MongoError = require('../error'); - -// Wire command operation ids -var OP_UPDATE = 2001; -var OP_INSERT = 2002; -var OP_DELETE = 2006; - -var Insert = function(requestId, ismaster, bson, ns, documents, options) { - // Basic options needed to be passed in - if(ns == null) throw new MongoError("ns must be specified for query"); - if(!Array.isArray(documents) || documents.length == 0) throw new MongoError("documents array must contain at least one document to insert"); - - // Validate that we are not passing 0x00 in the colletion name - if(!!~ns.indexOf("\x00")) { - throw new MongoError("namespace cannot contain a null character"); - } - - // Set internal - this.requestId = requestId; - this.bson = bson; - this.ns = ns; - this.documents = documents; - this.ismaster = ismaster; - - // Ensure empty options - options = options || {}; - - // Unpack options - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : true; - this.continueOnError = typeof options.continueOnError == 'boolean' ? options.continueOnError : false; - // Set flags - this.flags = this.continueOnError ? 1 : 0; -} - -// To Binary -Insert.prototype.toBin = function() { - // Contains all the buffers to be written - var buffers = []; - - // Header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // Flags - + Buffer.byteLength(this.ns) + 1 // namespace - ); - - // Add header to buffers - buffers.push(header); - - // Total length of the message - var totalLength = header.length; - - // Serialize all the documents - for(var i = 0; i < this.documents.length; i++) { - var buffer = this.bson.serialize(this.documents[i] - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - - // Document is larger than maxBsonObjectSize, terminate serialization - if(buffer.length > this.ismaster.maxBsonObjectSize) { - throw new MongoError("Document exceeds maximum allowed bson size of " + this.ismaster.maxBsonObjectSize + " bytes"); - } - - // Add to total length of wire protocol message - totalLength = totalLength + buffer.length; - // Add to buffer - buffers.push(buffer); - } - - // Command is larger than maxMessageSizeBytes terminate serialization - if(totalLength > this.ismaster.maxMessageSizeBytes) { - throw new MongoError("Command exceeds maximum message size of " + this.ismaster.maxMessageSizeBytes + " bytes"); - } - - // Add all the metadata - var index = 0; - - // Write header length - header[index + 3] = (totalLength >> 24) & 0xff; - header[index + 2] = (totalLength >> 16) & 0xff; - header[index + 1] = (totalLength >> 8) & 0xff; - header[index] = (totalLength) & 0xff; - index = index + 4; - - // Write header requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // No flags - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Operation - header[index + 3] = (OP_INSERT >> 24) & 0xff; - header[index + 2] = (OP_INSERT >> 16) & 0xff; - header[index + 1] = (OP_INSERT >> 8) & 0xff; - header[index] = (OP_INSERT) & 0xff; - index = index + 4; - - // Flags - header[index + 3] = (this.flags >> 24) & 0xff; - header[index + 2] = (this.flags >> 16) & 0xff; - header[index + 1] = (this.flags >> 8) & 0xff; - header[index] = (this.flags) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Return the buffers - return buffers; -} - -var Update = function(requestId, ismaster, bson, ns, update, options) { - // Basic options needed to be passed in - if(ns == null) throw new MongoError("ns must be specified for query"); - - // Ensure empty options - options = options || {}; - - // Set internal - this.requestId = requestId; - this.bson = bson; - this.ns = ns; - this.ismaster = ismaster; - - // Unpack options - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Unpack the update document - this.upsert = typeof update[0].upsert == 'boolean' ? update[0].upsert : false; - this.multi = typeof update[0].multi == 'boolean' ? update[0].multi : false; - this.q = update[0].q; - this.u = update[0].u; - - // Create flag value - this.flags = this.upsert ? 1 : 0; - this.flags = this.multi ? this.flags | 2 : this.flags; -} - -// To Binary -Update.prototype.toBin = function() { - // Contains all the buffers to be written - var buffers = []; - - // Header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // ZERO - + Buffer.byteLength(this.ns) + 1 // namespace - + 4 // Flags - ); - - // Add header to buffers - buffers.push(header); - - // Total length of the message - var totalLength = header.length; - - // Serialize the selector - var selector = this.bson.serialize(this.q - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - buffers.push(selector); - totalLength = totalLength + selector.length; - - // Serialize the update - var update = this.bson.serialize(this.u - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - buffers.push(update); - totalLength = totalLength + update.length; - - // Index in header buffer - var index = 0; - - // Write header length - header[index + 3] = (totalLength >> 24) & 0xff; - header[index + 2] = (totalLength >> 16) & 0xff; - header[index + 1] = (totalLength >> 8) & 0xff; - header[index] = (totalLength) & 0xff; - index = index + 4; - - // Write header requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // No flags - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Operation - header[index + 3] = (OP_UPDATE >> 24) & 0xff; - header[index + 2] = (OP_UPDATE >> 16) & 0xff; - header[index + 1] = (OP_UPDATE >> 8) & 0xff; - header[index] = (OP_UPDATE) & 0xff; - index = index + 4; - - // Write ZERO - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Flags - header[index + 3] = (this.flags >> 24) & 0xff; - header[index + 2] = (this.flags >> 16) & 0xff; - header[index + 1] = (this.flags >> 8) & 0xff; - header[index] = (this.flags) & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -} - -var Remove = function(requestId, ismaster, bson, ns, remove, options) { - // Basic options needed to be passed in - if(ns == null) throw new MongoError("ns must be specified for query"); - - // Ensure empty options - options = options || {}; - - // Set internal - this.requestId = requestId; - this.bson = bson; - this.ns = ns; - this.ismaster = ismaster; - - // Unpack options - this.serializeFunctions = typeof options.serializeFunctions == 'boolean' ? options.serializeFunctions : false; - this.ignoreUndefined = typeof options.ignoreUndefined == 'boolean' ? options.ignoreUndefined : false; - this.checkKeys = typeof options.checkKeys == 'boolean' ? options.checkKeys : false; - - // Unpack the update document - this.limit = typeof remove[0].limit == 'number' ? remove[0].limit : 1; - this.q = remove[0].q; - - // Create flag value - this.flags = this.limit == 1 ? 1 : 0; -} - -// To Binary -Remove.prototype.toBin = function() { - // Contains all the buffers to be written - var buffers = []; - - // Header buffer - var header = new Buffer( - 4 * 4 // Header - + 4 // ZERO - + Buffer.byteLength(this.ns) + 1 // namespace - + 4 // Flags - ); - - // Add header to buffers - buffers.push(header); - - // Total length of the message - var totalLength = header.length; - - // Serialize the selector - var selector = this.bson.serialize(this.q - , this.checkKeys - , true - , this.serializeFunctions - , 0, this.ignoreUndefined); - buffers.push(selector); - totalLength = totalLength + selector.length; - - // Index in header buffer - var index = 0; - - // Write header length - header[index + 3] = (totalLength >> 24) & 0xff; - header[index + 2] = (totalLength >> 16) & 0xff; - header[index + 1] = (totalLength >> 8) & 0xff; - header[index] = (totalLength) & 0xff; - index = index + 4; - - // Write header requestId - header[index + 3] = (this.requestId >> 24) & 0xff; - header[index + 2] = (this.requestId >> 16) & 0xff; - header[index + 1] = (this.requestId >> 8) & 0xff; - header[index] = (this.requestId) & 0xff; - index = index + 4; - - // No flags - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Operation - header[index + 3] = (OP_DELETE >> 24) & 0xff; - header[index + 2] = (OP_DELETE >> 16) & 0xff; - header[index + 1] = (OP_DELETE >> 8) & 0xff; - header[index] = (OP_DELETE) & 0xff; - index = index + 4; - - // Write ZERO - header[index + 3] = (0 >> 24) & 0xff; - header[index + 2] = (0 >> 16) & 0xff; - header[index + 1] = (0 >> 8) & 0xff; - header[index] = (0) & 0xff; - index = index + 4; - - // Write collection name - index = index + header.write(this.ns, index, 'utf8') + 1; - header[index - 1] = 0; - - // Write ZERO - header[index + 3] = (this.flags >> 24) & 0xff; - header[index + 2] = (this.flags >> 16) & 0xff; - header[index + 1] = (this.flags >> 8) & 0xff; - header[index] = (this.flags) & 0xff; - index = index + 4; - - // Return the buffers - return buffers; -} - -module.exports = { - Insert: Insert - , Update: Update - , Remove: Remove -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY deleted file mode 100644 index ecf5994..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/HISTORY +++ /dev/null @@ -1,113 +0,0 @@ -0.4.16 2015-10-07 ------------------ -- Fixed issue with return statement in Map.js. - -0.4.15 2015-10-06 ------------------ -- Exposed Map correctly via index.js file. - -0.4.14 2015-10-06 ------------------ -- Exposed Map correctly via bson.js file. - -0.4.13 2015-10-06 ------------------ -- Added ES6 Map type serialization as well as a polyfill for ES5. - -0.4.12 2015-09-18 ------------------ -- Made ignore undefined an optional parameter. - -0.4.11 2015-08-06 ------------------ -- Minor fix for invalid key checking. - -0.4.10 2015-08-06 ------------------ -- NODE-38 Added new BSONRegExp type to allow direct serialization to MongoDB type. -- Some performance improvements by in lining code. - -0.4.9 2015-08-06 ----------------- -- Undefined fields are omitted from serialization in objects. - -0.4.8 2015-07-14 ----------------- -- Fixed size validation to ensure we can deserialize from dumped files. - -0.4.7 2015-06-26 ----------------- -- Added ability to instruct deserializer to return raw BSON buffers for named array fields. -- Minor deserialization optimization by moving inlined function out. - -0.4.6 2015-06-17 ----------------- -- Fixed serializeWithBufferAndIndex bug. - -0.4.5 2015-06-17 ----------------- -- Removed any references to the shared buffer to avoid non GC collectible bson instances. - -0.4.4 2015-06-17 ----------------- -- Fixed rethrowing of error when not RangeError. - -0.4.3 2015-06-17 ----------------- -- Start buffer at 64K and double as needed, meaning we keep a low memory profile until needed. - -0.4.2 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.1 2015-06-16 ----------------- -- More fixes for corrupt Bson - -0.4.0 2015-06-16 ----------------- -- New JS serializer serializing into a single buffer then copying out the new buffer. Performance is similar to current C++ parser. -- Removed bson-ext extension dependency for now. - -0.3.2 2015-03-27 ----------------- -- Removed node-gyp from install script in package.json. - -0.3.1 2015-03-27 ----------------- -- Return pure js version on native() call if failed to initialize. - -0.3.0 2015-03-26 ----------------- -- Pulled out all C++ code into bson-ext and made it an optional dependency. - -0.2.21 2015-03-21 ------------------ -- Updated Nan to 1.7.0 to support io.js and node 0.12.0 - -0.2.19 2015-02-16 ------------------ -- Updated Nan to 1.6.2 to support io.js and node 0.12.0 - -0.2.18 2015-01-20 ------------------ -- Updated Nan to 1.5.1 to support io.js - -0.2.16 2014-12-17 ------------------ -- Made pid cycle on 0xffff to avoid weird overflows on creation of ObjectID's - -0.2.12 2014-08-24 ------------------ -- Fixes for fortify review of c++ extension -- toBSON correctly allows returns of non objects - -0.2.3 2013-10-01 ----------------- -- Drying of ObjectId code for generation of id (Issue #54, https://github.com/moredip) -- Fixed issue where corrupt CString's could cause endless loop -- Support for Node 0.11.X > (Issue #49, https://github.com/kkoopa) - -0.1.4 2012-09-25 ----------------- -- Added precompiled c++ native extensions for win32 ia32 and x64 diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md deleted file mode 100644 index 56327c2..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/README.md +++ /dev/null @@ -1,69 +0,0 @@ -Javascript + C++ BSON parser -============================ - -This BSON parser is primarily meant to be used with the `mongodb` node.js driver. -However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser. -The current build is located in the `browser_build/bson.js` file. - -A simple example of how to use BSON in the browser: - -```html - - - - - - - - -``` - -A simple example of how to use BSON in `node.js`: - -```javascript -var bson = require("bson"); -var BSON = new bson.BSONPure.BSON(); -var Long = bson.BSONPure.Long; - -var doc = {long: Long.fromNumber(100)} - -// Serialize a document -var data = BSON.serialize(doc, false, true, false); -console.log("data:", data); - -// Deserialize the resulting Buffer -var doc_2 = BSON.deserialize(data); -console.log("doc_2:", doc_2); -``` - -The API consists of two simple methods to serialize/deserialize objects to/from BSON format: - - * BSON.serialize(object, checkKeys, asBuffer, serializeFunctions) - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)** - * @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports - - * BSON.deserialize(buffer, options, isArray) - * Options - * **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * @param {TypedArray/Array} a TypedArray/Array containing the BSON data - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js deleted file mode 100644 index 555aa79..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/bson.js +++ /dev/null @@ -1,1574 +0,0 @@ -var Long = require('../lib/bson/long').Long - , Double = require('../lib/bson/double').Double - , Timestamp = require('../lib/bson/timestamp').Timestamp - , ObjectID = require('../lib/bson/objectid').ObjectID - , Symbol = require('../lib/bson/symbol').Symbol - , Code = require('../lib/bson/code').Code - , MinKey = require('../lib/bson/min_key').MinKey - , MaxKey = require('../lib/bson/max_key').MaxKey - , DBRef = require('../lib/bson/db_ref').DBRef - , Binary = require('../lib/bson/binary').Binary - , BinaryParser = require('../lib/bson/binary_parser').BinaryParser - , writeIEEE754 = require('../lib/bson/float_parser').writeIEEE754 - , readIEEE754 = require('../lib/bson/float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_UNDEFINED - **/ -BSON.BSON_DATA_UNDEFINED = 6; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - if(object.toBSON) { - if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); - object = object.toBSON(); - if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); - } - - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - var startIndex = index; - - switch(typeof value) { - case 'string': - // console.log("+++++++++++ index string:: " + index) - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // console.log("====== key :: " + name + " size ::" + size) - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // console.log("+++++++++++ index OBJECTID:: " + index) - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long || value['_bsontype'] == 'Long' ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - // console.log("++++++++++++++++++++++++++++++++++++ OLDJS :: " + buffer.length) - // console.log(buffer.toString('hex')) - // console.log(buffer.toString('ascii')) - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_UNDEFINED: - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -module.exports = BSON; -module.exports.Code = Code; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js deleted file mode 100644 index f19e44f..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/alternate_parsers/faster_bson.js +++ /dev/null @@ -1,429 +0,0 @@ -/// reduced to ~ 410 LOCs (parser only 300 vs. 1400+) with (some, needed) BSON classes "inlined". -/// Compare ~ 4,300 (22KB vs. 157KB) in browser build at: https://github.com/mongodb/js-bson/blob/master/browser_build/bson.js - -module.exports.calculateObjectSize = calculateObjectSize; - -function calculateObjectSize(object) { - var totalLength = (4 + 1); /// handles the obj.length prefix + terminating '0' ?! - for(var key in object) { /// looks like it handles arrays under the same for...in loop!? - totalLength += calculateElement(key, object[key]) - } - return totalLength; -} - -function calculateElement(name, value) { - var len = 1; /// always starting with 1 for the data type byte! - if (name) len += Buffer.byteLength(name, 'utf8') + 1; /// cstring: name + '0' termination - - if (value === undefined || value === null) return len; /// just the type byte plus name cstring - switch( value.constructor ) { /// removed all checks 'isBuffer' if Node.js Buffer class is present!? - - case ObjectID: /// we want these sorted from most common case to least common/deprecated; - return len + 12; - case String: - return len + 4 + Buffer.byteLength(value, 'utf8') +1; /// - case Number: - if (Math.floor(value) === value) { /// case: integer; pos.# more common, '&&' stops if 1st fails! - if ( value <= 2147483647 && value >= -2147483647 ) // 32 bit - return len + 4; - else return len + 8; /// covers Long-ish JS integers as Longs! - } else return len + 8; /// 8+1 --- covers Double & std. float - case Boolean: - return len + 1; - - case Array: - case Object: - return len + calculateObjectSize(value); - - case Buffer: /// replaces the entire Binary class! - return len + 4 + value.length + 1; - - case Regex: /// these are handled as strings by serializeFast() later, hence 'gim' opts = 3 + 1 chars - return len + Buffer.byteLength(value.source, 'utf8') + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) +1; - case Date: - case Long: - case Timestamp: - case Double: - return len + 8; - - case MinKey: - case MaxKey: - return len; /// these two return the type byte and name cstring only! - } - return 0; -} - -module.exports.serializeFast = serializeFast; -module.exports.serialize = function(object, checkKeys, asBuffer, serializeFunctions, index) { - var buffer = new Buffer(calculateObjectSize(object)); - return serializeFast(object, checkKeys, buffer, 0); -} - -function serializeFast(object, checkKeys, buffer, i) { /// set checkKeys = false in query(..., options object to save performance IFF you're certain your keys are safe/system-set! - var size = buffer.length; - buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; /// these get overwritten later! - buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; - - if (object.constructor === Array) { /// any need to checkKeys here?!? since we're doing for rather than for...in, should be safe from extra (non-numeric) keys added to the array?! - for(var j = 0; j < object.length; j++) { - i = packElement(j.toString(), object[j], checkKeys, buffer, i); - } - } else { /// checkKeys is needed if any suspicion of end-user key tampering/"injection" (a la SQL) - for(var key in object) { /// mostly there should never be direct access to them!? - if (checkKeys && (key.indexOf('\x00') >= 0 || key === '$where') ) { /// = "no script"?!; could add back key.indexOf('$') or maybe check for 'eval'?! -/// took out: || key.indexOf('.') >= 0... Don't we allow dot notation queries?! - console.log('checkKeys error: '); - return new Error('Illegal object key!'); - } - i = packElement(key, object[key], checkKeys, buffer, i); /// checkKeys pass needed for recursion! - } - } - buffer[i++] = 0; /// write terminating zero; !we do NOT -1 the index increase here as original does! - return i; -} - -function packElement(name, value, checkKeys, buffer, i) { /// serializeFunctions removed! checkKeys needed for Array & Object cases pass through (calling serializeFast recursively!) - if (value === undefined || value === null){ - buffer[i++] = 10; /// = BSON.BSON_DATA_NULL; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; /// buffer.write(...) returns bytesWritten! - return i; - } - switch(value.constructor) { - - case ObjectID: - buffer[i++] = 7; /// = BSON.BSON_DATA_OID; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; -/// i += buffer.write(value.id, i, 'binary'); /// OLD: writes a String to a Buffer; 'binary' deprecated!! - value.id.copy(buffer, i); /// NEW ObjectID version has this.id = Buffer at the ready! - return i += 12; - - case String: - buffer[i++] = 2; /// = BSON.BSON_DATA_STRING; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - - var size = Buffer.byteLength(value) + 1; /// includes the terminating '0'!? - buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; - buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; - - i += buffer.write(value, i, 'utf8'); buffer[i++] = 0; - return i; - - case Number: - if ( ~~(value) === value) { /// double-Tilde is equiv. to Math.floor(value) - if ( value <= 2147483647 && value >= -2147483647){ /// = BSON.BSON_INT32_MAX / MIN asf. - buffer[i++] = 16; /// = BSON.BSON_DATA_INT; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - buffer[i++] = value & 0xff; buffer[i++] = (value >> 8) & 0xff; - buffer[i++] = (value >> 16) & 0xff; buffer[i++] = (value >> 24) & 0xff; - -// Else large-ish JS int!? to Long!? - } else { /// if (value <= BSON.JS_INT_MAX && value >= BSON.JS_INT_MIN){ /// 9007199254740992 asf. - buffer[i++] = 18; /// = BSON.BSON_DATA_LONG; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - var lowBits = ( value % 4294967296 ) | 0, highBits = ( value / 4294967296 ) | 0; - - buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; - buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; - buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; - buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; - } - } else { /// we have a float / Double - buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; -/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); - buffer.writeDoubleLE(value, i); i += 8; - } - return i; - - case Boolean: - buffer[i++] = 8; /// = BSON.BSON_DATA_BOOLEAN; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - buffer[i++] = value ? 1 : 0; - return i; - - case Array: - case Object: - buffer[i++] = value.constructor === Array ? 4 : 3; /// = BSON.BSON_DATA_ARRAY / _OBJECT; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - - var endIndex = serializeFast(value, checkKeys, buffer, i); /// + 4); no longer needed b/c serializeFast writes a temp 4 bytes for length - var size = endIndex - i; - buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; - buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; - return endIndex; - - /// case Binary: /// is basically identical unless special/deprecated options! - case Buffer: /// solves ALL of our Binary needs without the BSON.Binary class!? - buffer[i++] = 5; /// = BSON.BSON_DATA_BINARY; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - var size = value.length; - buffer[i++] = size & 0xff; buffer[i++] = (size >> 8) & 0xff; - buffer[i++] = (size >> 16) & 0xff; buffer[i++] = (size >> 24) & 0xff; - - buffer[i++] = 0; /// write BSON.BSON_BINARY_SUBTYPE_DEFAULT; - value.copy(buffer, i); ///, 0, size); << defaults to sourceStart=0, sourceEnd=sourceBuffer.length); - i += size; - return i; - - case RegExp: - buffer[i++] = 11; /// = BSON.BSON_DATA_REGEXP; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - i += buffer.write(value.source, i, 'utf8'); buffer[i++] = 0x00; - - if (value.global) buffer[i++] = 0x73; // s = 'g' for JS Regex! - if (value.ignoreCase) buffer[i++] = 0x69; // i - if (value.multiline) buffer[i++] = 0x6d; // m - buffer[i++] = 0x00; - return i; - - case Date: - buffer[i++] = 9; /// = BSON.BSON_DATA_DATE; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - var millis = value.getTime(); - var lowBits = ( millis % 4294967296 ) | 0, highBits = ( millis / 4294967296 ) | 0; - - buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; - buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; - buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; - buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; - return i; - - case Long: - case Timestamp: - buffer[i++] = value.constructor === Long ? 18 : 17; /// = BSON.BSON_DATA_LONG / _TIMESTAMP - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - var lowBits = value.getLowBits(), highBits = value.getHighBits(); - - buffer[i++] = lowBits & 0xff; buffer[i++] = (lowBits >> 8) & 0xff; - buffer[i++] = (lowBits >> 16) & 0xff; buffer[i++] = (lowBits >> 24) & 0xff; - buffer[i++] = highBits & 0xff; buffer[i++] = (highBits >> 8) & 0xff; - buffer[i++] = (highBits >> 16) & 0xff; buffer[i++] = (highBits >> 24) & 0xff; - return i; - - case Double: - buffer[i++] = 1; /// = BSON.BSON_DATA_NUMBER; - i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; -/// OLD: writeIEEE754(buffer, value, i, 'little', 52, 8); i += 8; - buffer.writeDoubleLE(value, i); i += 8; - return i - - case MinKey: /// = BSON.BSON_DATA_MINKEY; - buffer[i++] = 127; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - return i; - case MaxKey: /// = BSON.BSON_DATA_MAXKEY; - buffer[i++] = 255; i += buffer.write(name, i, 'utf8'); buffer[i++] = 0; - return i; - - } /// end of switch - return i; /// ?! If no value to serialize -} - - -module.exports.deserializeFast = deserializeFast; - -function deserializeFast(buffer, i, isArray){ //// , options, isArray) { //// no more options! - if (buffer.length < 5) return new Error('Corrupt bson message < 5 bytes long'); /// from 'throw' - var elementType, tempindex = 0, name; - var string, low, high; /// = lowBits / highBits - /// using 'i' as the index to keep the lines shorter: - i || ( i = 0 ); /// for parseResponse it's 0; set to running index in deserialize(object/array) recursion - var object = isArray ? [] : {}; /// needed for type ARRAY recursion later! - var size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - if(size < 5 || size > buffer.length) return new Error('Corrupt BSON message'); -/// 'size' var was not used by anything after this, so we can reuse it - - while(true) { // While we have more left data left keep parsing - elementType = buffer[i++]; // Read the type - if (elementType === 0) break; // If we get a zero it's the last byte, exit - - tempindex = i; /// inlined readCStyleString & removed extra i= buffer.length) return new Error('Corrupt BSON document: illegal CString') - name = buffer.toString('utf8', i, tempindex); - i = tempindex + 1; /// Update index position to after the string + '0' termination - - switch(elementType) { - - case 7: /// = BSON.BSON_DATA_OID: - var buf = new Buffer(12); - buffer.copy(buf, 0, i, i += 12 ); /// copy 12 bytes from the current 'i' offset into fresh Buffer - object[name] = new ObjectID(buf); ///... & attach to the new ObjectID instance - break; - - case 2: /// = BSON.BSON_DATA_STRING: - size = buffer[i++] | buffer[i++] <<8 | buffer[i++] <<16 | buffer[i++] <<24; - object[name] = buffer.toString('utf8', i, i += size -1 ); - i++; break; /// need to get the '0' index "tick-forward" back! - - case 16: /// = BSON.BSON_DATA_INT: // Decode the 32bit value - object[name] = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; break; - - case 1: /// = BSON.BSON_DATA_NUMBER: // Decode the double value - object[name] = buffer.readDoubleLE(i); /// slightly faster depending on dec.points; a LOT cleaner - /// OLD: object[name] = readIEEE754(buffer, i, 'little', 52, 8); - i += 8; break; - - case 8: /// = BSON.BSON_DATA_BOOLEAN: - object[name] = buffer[i++] == 1; break; - - case 6: /// = BSON.BSON_DATA_UNDEFINED: /// deprecated - case 10: /// = BSON.BSON_DATA_NULL: - object[name] = null; break; - - case 4: /// = BSON.BSON_DATA_ARRAY - size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; /// NO 'i' increment since the size bytes are reread during the recursion! - object[name] = deserializeFast(buffer, i, true ); /// pass current index & set isArray = true - i += size; break; - case 3: /// = BSON.BSON_DATA_OBJECT: - size = buffer[i] | buffer[i+1] <<8 | buffer[i+2] <<16 | buffer[i+3] <<24; - object[name] = deserializeFast(buffer, i, false ); /// isArray = false => Object - i += size; break; - - case 5: /// = BSON.BSON_DATA_BINARY: // Decode the size of the binary blob - size = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - buffer[i++]; /// Skip, as we assume always default subtype, i.e. 0! - object[name] = buffer.slice(i, i += size); /// creates a new Buffer "slice" view of the same memory! - break; - - case 9: /// = BSON.BSON_DATA_DATE: /// SEE notes below on the Date type vs. other options... - low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - object[name] = new Date( high * 4294967296 + (low < 0 ? low + 4294967296 : low) ); break; - - case 18: /// = BSON.BSON_DATA_LONG: /// usage should be somewhat rare beyond parseResponse() -> cursorId, where it is handled inline, NOT as part of deserializeFast(returnedObjects); get lowBits, highBits: - low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - - size = high * 4294967296 + (low < 0 ? low + 4294967296 : low); /// from long.toNumber() - if (size < JS_INT_MAX && size > JS_INT_MIN) object[name] = size; /// positive # more likely! - else object[name] = new Long(low, high); break; - - case 127: /// = BSON.BSON_DATA_MIN_KEY: /// do we EVER actually get these BACK from MongoDB server?! - object[name] = new MinKey(); break; - case 255: /// = BSON.BSON_DATA_MAX_KEY: - object[name] = new MaxKey(); break; - - case 17: /// = BSON.BSON_DATA_TIMESTAMP: /// somewhat obscure internal BSON type; MongoDB uses it for (pseudo) high-res time timestamp (past millisecs precision is just a counter!) in the Oplog ts: field, etc. - low = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - high = buffer[i++] | buffer[i++] << 8 | buffer[i++] << 16 | buffer[i++] << 24; - object[name] = new Timestamp(low, high); break; - -/// case 11: /// = RegExp is skipped; we should NEVER be getting any from the MongoDB server!? - } /// end of switch(elementType) - } /// end of while(1) - return object; // Return the finalized object -} - - -function MinKey() { this._bsontype = 'MinKey'; } /// these are merely placeholders/stubs to signify the type!? - -function MaxKey() { this._bsontype = 'MaxKey'; } - -function Long(low, high) { - this._bsontype = 'Long'; - this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. -} -Long.prototype.getLowBits = function(){ return this.low_; } -Long.prototype.getHighBits = function(){ return this.high_; } - -Long.prototype.toNumber = function(){ - return this.high_ * 4294967296 + (this.low_ < 0 ? this.low_ + 4294967296 : this.low_); -} -Long.fromNumber = function(num){ - return new Long(num % 4294967296, num / 4294967296); /// |0 is forced in the constructor! -} -function Double(value) { - this._bsontype = 'Double'; - this.value = value; -} -function Timestamp(low, high) { - this._bsontype = 'Timestamp'; - this.low_ = low | 0; this.high_ = high | 0; /// force into 32 signed bits. -} -Timestamp.prototype.getLowBits = function(){ return this.low_; } -Timestamp.prototype.getHighBits = function(){ return this.high_; } - -/////////////////////////////// ObjectID ///////////////////////////////// -/// machine & proc IDs stored as 1 string, b/c Buffer shouldn't be held for long periods (could use SlowBuffer?!) - -var MACHINE = parseInt(Math.random() * 0xFFFFFF, 10); -var PROCESS = process.pid % 0xFFFF; -var MACHINE_AND_PROC = encodeIntBE(MACHINE, 3) + encodeIntBE(PROCESS, 2); /// keep as ONE string, ready to go. - -function encodeIntBE(data, bytes){ /// encode the bytes to a string - var result = ''; - if (bytes >= 4){ result += String.fromCharCode(Math.floor(data / 0x1000000)); data %= 0x1000000; } - if (bytes >= 3){ result += String.fromCharCode(Math.floor(data / 0x10000)); data %= 0x10000; } - if (bytes >= 2){ result += String.fromCharCode(Math.floor(data / 0x100)); data %= 0x100; } - result += String.fromCharCode(Math.floor(data)); - return result; -} -var _counter = ~~(Math.random() * 0xFFFFFF); /// double-tilde is equivalent to Math.floor() -var checkForHex = new RegExp('^[0-9a-fA-F]{24}$'); - -function ObjectID(id) { - this._bsontype = 'ObjectID'; - if (!id){ this.id = createFromScratch(); /// base case, DONE. - } else { - if (id.constructor === Buffer){ - this.id = id; /// case of - } else if (id.constructor === String) { - if ( id.length === 24 && checkForHex.test(id) ) { - this.id = new Buffer(id, 'hex'); - } else { - this.id = new Error('Illegal/faulty Hexadecimal string supplied!'); /// changed from 'throw' - } - } else if (id.constructor === Number) { - this.id = createFromTime(id); /// this is what should be the only interface for this!? - } - } -} -function createFromScratch() { - var buf = new Buffer(12), i = 0; - var ts = ~~(Date.now()/1000); /// 4 bytes timestamp in seconds, BigEndian notation! - buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; - buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; - - buf.write(MACHINE_AND_PROC, i, 5, 'utf8'); i += 5; /// write 3 bytes + 2 bytes MACHINE_ID and PROCESS_ID - _counter = ++_counter % 0xFFFFFF; /// 3 bytes internal _counter for subsecond resolution; BigEndian - buf[i++] = (_counter >> 16) & 0xFF; - buf[i++] = (_counter >> 8) & 0xFF; - buf[i++] = (_counter) & 0xFF; - return buf; -} -function createFromTime(ts) { - ts || ( ts = ~~(Date.now()/1000) ); /// 4 bytes timestamp in seconds only - var buf = new Buffer(12), i = 0; - buf[i++] = (ts >> 24) & 0xFF; buf[i++] = (ts >> 16) & 0xFF; - buf[i++] = (ts >> 8) & 0xFF; buf[i++] = (ts) & 0xFF; - - for (;i < 12; ++i) buf[i] = 0x00; /// indeces 4 through 11 (8 bytes) get filled up with nulls - return buf; -} -ObjectID.prototype.toHexString = function toHexString() { - return this.id.toString('hex'); -} -ObjectID.prototype.getTimestamp = function getTimestamp() { - return this.id.readUIntBE(0, 4); -} -ObjectID.prototype.getTimestampDate = function getTimestampDate() { - var ts = new Date(); - ts.setTime(this.id.readUIntBE(0, 4) * 1000); - return ts; -} -ObjectID.createPk = function createPk () { ///?override if a PrivateKey factory w/ unique factors is warranted?! - return new ObjectID(); -} -ObjectID.prototype.toJSON = function toJSON() { - return "ObjectID('" +this.id.toString('hex')+ "')"; -} - -/// module.exports.BSON = BSON; /// not needed anymore!? exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.Long = Long; /// ?! we really don't want to do the complicated Long math anywhere for now!? - -//module.exports.Double = Double; -//module.exports.Timestamp = Timestamp; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js deleted file mode 100644 index 8e942dd..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/bson.js +++ /dev/null @@ -1,4843 +0,0 @@ -var bson = (function(){ - - var pkgmap = {}, - global = {}, - nativeRequire = typeof require != 'undefined' && require, - lib, ties, main, async; - - function exports(){ return main(); }; - - exports.main = exports; - exports.module = module; - exports.packages = pkgmap; - exports.pkg = pkg; - exports.require = function require(uri){ - return pkgmap.main.index.require(uri); - }; - - - ties = {}; - - aliases = {}; - - - return exports; - -function join() { - return normalize(Array.prototype.join.call(arguments, "/")); -}; - -function normalize(path) { - var ret = [], parts = path.split('/'), cur, prev; - - var i = 0, l = parts.length-1; - for (; i <= l; i++) { - cur = parts[i]; - - if (cur === "." && prev !== undefined) continue; - - if (cur === ".." && ret.length && prev !== ".." && prev !== "." && prev !== undefined) { - ret.pop(); - prev = ret.slice(-1)[0]; - } else { - if (prev === ".") ret.pop(); - ret.push(cur); - prev = cur; - } - } - - return ret.join("/"); -}; - -function dirname(path) { - return path && path.substr(0, path.lastIndexOf("/")) || "."; -}; - -function findModule(workingModule, uri){ - var moduleId = join(dirname(workingModule.id), /\.\/$/.test(uri) ? (uri + 'index') : uri ).replace(/\.js$/, ''), - moduleIndexId = join(moduleId, 'index'), - pkg = workingModule.pkg, - module; - - var i = pkg.modules.length, - id; - - while(i-->0){ - id = pkg.modules[i].id; - - if(id==moduleId || id == moduleIndexId){ - module = pkg.modules[i]; - break; - } - } - - return module; -} - -function newRequire(callingModule){ - function require(uri){ - var module, pkg; - - if(/^\./.test(uri)){ - module = findModule(callingModule, uri); - } else if ( ties && ties.hasOwnProperty( uri ) ) { - return ties[uri]; - } else if ( aliases && aliases.hasOwnProperty( uri ) ) { - return require(aliases[uri]); - } else { - pkg = pkgmap[uri]; - - if(!pkg && nativeRequire){ - try { - pkg = nativeRequire(uri); - } catch (nativeRequireError) {} - - if(pkg) return pkg; - } - - if(!pkg){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module = pkg.index; - } - - if(!module){ - throw new Error('Cannot find module "'+uri+'" @[module: '+callingModule.id+' package: '+callingModule.pkg.name+']'); - } - - module.parent = callingModule; - return module.call(); - }; - - - return require; -} - - -function module(parent, id, wrapper){ - var mod = { pkg: parent, id: id, wrapper: wrapper }, - cached = false; - - mod.exports = {}; - mod.require = newRequire(mod); - - mod.call = function(){ - if(cached) { - return mod.exports; - } - - cached = true; - - global.require = mod.require; - - mod.wrapper(mod, mod.exports, global, global.require); - return mod.exports; - }; - - if(parent.mainModuleId == mod.id){ - parent.index = mod; - parent.parents.length === 0 && ( main = mod.call ); - } - - parent.modules.push(mod); -} - -function pkg(/* [ parentId ...], wrapper */){ - var wrapper = arguments[ arguments.length - 1 ], - parents = Array.prototype.slice.call(arguments, 0, arguments.length - 1), - ctx = wrapper(parents); - - - pkgmap[ctx.name] = ctx; - - arguments.length == 1 && ( pkgmap.main = ctx ); - - return function(modules){ - var id; - for(id in modules){ - module(ctx, id, modules[id]); - } - }; -} - - -}(this)); - -bson.pkg(function(parents){ - - return { - 'name' : 'bson', - 'mainModuleId' : 'bson', - 'modules' : [], - 'parents' : parents - }; - -})({ 'binary': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -// Binary default subtype -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - * @api private - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - * @api private - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class Represents the Binary BSON type. - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Grid} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @param {Character} byte_value a single byte we wish to write. - * @api public - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @param {Buffer|String} string a string or buffer to be written to the Binary BSON object. - * @param {Number} offset specify the binary of where to write the content. - * @api public - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, 'binary', offset); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @param {Number} position read from the given position in the Binary. - * @param {Number} length the number of bytes to read. - * @return {Buffer} - * @api public - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @return {String} - * @api public - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @return {Number} the length of the binary. - * @api public - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - * @api private - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - * @api private - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -exports.Binary = Binary; - - -}, - - - -'binary_parser': function(module, exports, global, require, undefined){ - /** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; - -}, - - - -'bson': function(module, exports, global, require, undefined){ - var Long = require('./long').Long - , Double = require('./double').Double - , Timestamp = require('./timestamp').Timestamp - , ObjectID = require('./objectid').ObjectID - , Symbol = require('./symbol').Symbol - , Code = require('./code').Code - , MinKey = require('./min_key').MinKey - , MaxKey = require('./max_key').MaxKey - , DBRef = require('./db_ref').DBRef - , Binary = require('./binary').Binary - , BinaryParser = require('./binary_parser').BinaryParser - , writeIEEE754 = require('./float_parser').writeIEEE754 - , readIEEE754 = require('./float_parser').readIEEE754 - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -/** - * Create a new BSON instance - * - * @class Represents the BSON Parser - * @return {BSON} instance of BSON Parser. - */ -function BSON () {}; - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.calculateObjectSize = function calculateObjectSize(object, serializeFunctions) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions) { - var isBuffer = typeof Buffer !== 'undefined'; - - switch(typeof value) { - case 'string': - return 1 + (!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1 + 4 + (!isBuffer ? numberOfBytes(value) : Buffer.byteLength(value, 'utf8')) + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (4 + 1); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } - case 'undefined': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - case 'boolean': - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.code.toString()) : Buffer.byteLength(value.code.toString(), 'utf8')) + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + ((!isBuffer ? numberOfBytes(value.value) : Buffer.byteLength(value.value, 'utf8')) + 4 + 1 + 1); - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + BSON.calculateObjectSize(ordered_values, serializeFunctions); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + BSON.calculateObjectSize(value, serializeFunctions) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + (!isBuffer ? numberOfBytes(value.source) : Buffer.byteLength(value.source, 'utf8')) + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1 + BSON.calculateObjectSize(value.scope, serializeFunctions); - } else if(serializeFunctions) { - return (name != null ? ((!isBuffer ? numberOfBytes(name) : Buffer.byteLength(name, 'utf8')) + 1) : 0) + 1 + 4 + (!isBuffer ? numberOfBytes(value.toString()) : Buffer.byteLength(value.toString(), 'utf8')) + 1; - } - } - } - - return 0; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.serializeWithBufferAndIndex = function serializeWithBufferAndIndex(object, checkKeys, buffer, index, serializeFunctions) { - // Default setting false - serializeFunctions = serializeFunctions == null ? false : serializeFunctions; - // Write end information (length of the object) - var size = buffer.length; - // Write the size of the object - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return serializeObject(object, checkKeys, buffer, index, serializeFunctions) - 1; -} - -/** - * @ignore - * @api private - */ -var serializeObject = function(object, checkKeys, buffer, index, serializeFunctions) { - // Process the object - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - index = packElement(i.toString(), object[i], checkKeys, buffer, index, serializeFunctions); - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Serialize the object - for(var key in object) { - // Check the key and throw error if it's illegal - if (key != '$db' && key != '$ref' && key != '$id') { - // dollars and dots ok - BSON.checkKey(key, !checkKeys); - } - - // Pack the element - index = packElement(key, object[key], checkKeys, buffer, index, serializeFunctions); - } - } - - // Write zero - buffer[index++] = 0; - return index; -} - -var stringToBytes = function(str) { - var ch, st, re = []; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re.concat( st.reverse() ); - } - // return an array of bytes - return re; -} - -var numberOfBytes = function(str) { - var ch, st, re = 0; - for (var i = 0; i < str.length; i++ ) { - ch = str.charCodeAt(i); // get char - st = []; // set up "stack" - do { - st.push( ch & 0xFF ); // push byte to stack - ch = ch >> 8; // shift value down by 1 byte - } - while ( ch ); - // add stack contents to result - // done because chars have "wrong" endianness - re = re + st.length; - } - // return an array of bytes - return re; -} - -/** - * @ignore - * @api private - */ -var writeToTypedArray = function(buffer, string, index) { - var bytes = stringToBytes(string); - for(var i = 0; i < bytes.length; i++) { - buffer[index + i] = bytes[i]; - } - return bytes.length; -} - -/** - * @ignore - * @api private - */ -var supportsBuffer = typeof Buffer != 'undefined'; - -/** - * @ignore - * @api private - */ -var packElement = function(name, value, checkKeys, buffer, index, serializeFunctions) { - var startIndex = index; - - switch(typeof value) { - case 'string': - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value) + 1 : numberOfBytes(value) + 1; - // Write the size of the string to buffer - buffer[index + 3] = (size >> 24) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index] = size & 0xff; - // Ajust the index - index = index + 4; - // Write the string - supportsBuffer ? buffer.write(value, index, 'utf8') : writeToTypedArray(buffer, value, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - // Return index - return index; - case 'number': - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; - case 'undefined': - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - case 'boolean': - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; - case 'object': - if(value === null || value instanceof MinKey || value instanceof MaxKey - || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - return index; - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write objectid - supportsBuffer ? buffer.write(value.id, index, 'binary') : writeToTypedArray(buffer, value.id, index); - // Ajust index - index = index + 12; - return index; - } else if(value instanceof Date || isDate(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; - } else if(value instanceof Long || value instanceof Timestamp || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; - } else if(value instanceof Double || value['_bsontype'] == 'Double') { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.code.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize + 4; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = supportsBuffer ? new Buffer(scopeSize) : new Uint8Array(new ArrayBuffer(scopeSize)); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - supportsBuffer ? scopeObjectBuffer.copy(buffer, index, 0, scopeSize) : buffer.set(scopeObjectBuffer, index); - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.code.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - supportsBuffer ? data.copy(buffer, index, 0, value.position) : buffer.set(data, index); - // Ajust index - index = index + value.position; - return index; - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate size - var size = supportsBuffer ? Buffer.byteLength(value.value) + 1 : numberOfBytes(value.value) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - buffer.write(value.value, index, 'utf8'); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - // Message size - var size = BSON.calculateObjectSize(ordered_values, serializeFunctions); - // Serialize the object - var endIndex = BSON.serializeWithBufferAndIndex(ordered_values, checkKeys, buffer, index, serializeFunctions); - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write zero for object - buffer[endIndex++] = 0x00; - // Return the end index - return endIndex; - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - supportsBuffer ? buffer.write(value.source, index, 'utf8') : writeToTypedArray(buffer, value.source, index); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Adjust the index - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - var endIndex = serializeObject(value, checkKeys, buffer, index + 4, serializeFunctions); - // Write size - var size = endIndex - index; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - return endIndex; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - - // Write the regular expression string - buffer.write(value.source, index, 'utf8'); - // Adjust the index - index = index + (supportsBuffer ? Buffer.byteLength(value.source) : numberOfBytes(value.source)); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Calculate the scope size - var scopeSize = BSON.calculateObjectSize(value.scope, serializeFunctions); - // Function string - var functionString = value.toString(); - // Function Size - var codeSize = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - - // Calculate full size of the object - var totalSize = 4 + codeSize + scopeSize; - - // Write the total size of the object - buffer[index++] = totalSize & 0xff; - buffer[index++] = (totalSize >> 8) & 0xff; - buffer[index++] = (totalSize >> 16) & 0xff; - buffer[index++] = (totalSize >> 24) & 0xff; - - // Write the size of the string to buffer - buffer[index++] = codeSize & 0xff; - buffer[index++] = (codeSize >> 8) & 0xff; - buffer[index++] = (codeSize >> 16) & 0xff; - buffer[index++] = (codeSize >> 24) & 0xff; - - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + codeSize - 1; - // Write zero - buffer[index++] = 0; - // Serialize the scope object - var scopeObjectBuffer = new Buffer(scopeSize); - // Execute the serialization into a seperate buffer - serializeObject(value.scope, checkKeys, scopeObjectBuffer, 0, serializeFunctions); - - // Adjusted scope Size (removing the header) - var scopeDocSize = scopeSize - 4; - // Write scope object size - buffer[index++] = scopeDocSize & 0xff; - buffer[index++] = (scopeDocSize >> 8) & 0xff; - buffer[index++] = (scopeDocSize >> 16) & 0xff; - buffer[index++] = (scopeDocSize >> 24) & 0xff; - - // Write the scopeObject into the buffer - scopeObjectBuffer.copy(buffer, index, 0, scopeSize); - - // Adjust index, removing the empty size of the doc (5 bytes 0000000005) - index = index + scopeDocSize - 5; - // Write trailing zero - buffer[index++] = 0; - return index - } else if(serializeFunctions) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = supportsBuffer ? buffer.write(name, index, 'utf8') : writeToTypedArray(buffer, name, index); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Function string - var functionString = value.toString(); - // Function Size - var size = supportsBuffer ? Buffer.byteLength(functionString) + 1 : numberOfBytes(functionString) + 1; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the string - supportsBuffer ? buffer.write(functionString, index, 'utf8') : writeToTypedArray(buffer, functionString, index); - // Update index - index = index + size - 1; - // Write zero - buffer[index++] = 0; - return index; - } - } - } - - // If no value to serialize - return index; -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - // Throw error if we are trying serialize an illegal type - if(object == null || typeof object != 'object' || Array.isArray(object)) - throw new Error("Only javascript objects supported"); - - // Emoty target buffer - var buffer = null; - // Calculate the size of the object - var size = BSON.calculateObjectSize(object, serializeFunctions); - // Fetch the best available type for storing the binary data - if(buffer = typeof Buffer != 'undefined') { - buffer = new Buffer(size); - asBuffer = true; - } else if(typeof Uint8Array != 'undefined') { - buffer = new Uint8Array(new ArrayBuffer(size)); - } else { - buffer = new Array(size); - } - - // If asBuffer is false use typed arrays - BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, 0, serializeFunctions); - return buffer; -} - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Crc state variables shared by function - * - * @ignore - * @api private - */ -var table = [0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D]; - -/** - * CRC32 hash method, Fast and enough versitility for our usage - * - * @ignore - * @api private - */ -var crc32 = function(string, start, end) { - var crc = 0 - var x = 0; - var y = 0; - crc = crc ^ (-1); - - for(var i = start, iTop = end; i < iTop;i++) { - y = (crc ^ string[i]) & 0xFF; - x = table[y]; - crc = (crc >>> 8) ^ x; - } - - return crc ^ (-1); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = BSON.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -/** - * Convert Uint8Array to String - * - * @ignore - * @api private - */ -var convertUint8ArrayToUtf8String = function(byteArray, startIndex, endIndex) { - return BinaryParser.decode_utf8(convertArraytoUtf8BinaryString(byteArray, startIndex, endIndex)); -} - -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - - return result; -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.deserialize = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] || true; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - // Reads in a C style string - var readCStyleString = function() { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00) { i++ } - // Grab utf8 encoded string - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, i) : convertUint8ArrayToUtf8String(buffer, index, i); - // Update index position - index = i + 1; - // Return string - return string; - } - - // Create holding object - var object = isArray ? [] : {}; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var name = readCStyleString(); - // Switch on the type - switch(elementType) { - case BSON.BSON_DATA_OID: - var string = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('binary', index, index + 12) : convertArraytoUtf8BinaryString(buffer, index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - break; - case BSON.BSON_DATA_STRING: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_INT: - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - break; - case BSON.BSON_DATA_NUMBER: - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - break; - case BSON.BSON_DATA_DATE: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - break; - case BSON.BSON_DATA_BOOLEAN: - // Parse the boolean value - object[name] = buffer[index++] == 1; - break; - case BSON.BSON_DATA_NULL: - // Parse the boolean value - object[name] = null; - break; - case BSON.BSON_DATA_BINARY: - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - break; - case BSON.BSON_DATA_ARRAY: - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, true); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_OBJECT: - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Set the array to the object - object[name] = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - break; - case BSON.BSON_DATA_REGEXP: - // Create the regexp - var source = readCStyleString(); - var regExpOptions = readCStyleString(); - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - break; - case BSON.BSON_DATA_LONG: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - break; - case BSON.BSON_DATA_SYMBOL: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_TIMESTAMP: - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - break; - case BSON.BSON_DATA_MIN_KEY: - // Parse the object - object[name] = new MinKey(); - break; - case BSON.BSON_DATA_MAX_KEY: - // Parse the object - object[name] = new MaxKey(); - break; - case BSON.BSON_DATA_CODE: - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Function string - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - break; - case BSON.BSON_DATA_CODE_W_SCOPE: - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Javascript function - var functionString = supportsBuffer && Buffer.isBuffer(buffer) ? buffer.toString('utf8', index, index + stringSize - 1) : convertUint8ArrayToUtf8String(buffer, index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = BSON.deserialize(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - - // Add string to object - break; - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Check if key name is valid. - * - * @ignore - * @api private - */ -BSON.checkKey = function checkKey (key, dollarsAndDotsOk) { - if (!key.length) return; - // Check if we have a legal key for the object - if (!!~key.indexOf("\x00")) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - if (!dollarsAndDotsOk) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } -}; - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return BSON.deserialize(data, options); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - return BSON.deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options); -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function(object, checkKeys, asBuffer, serializeFunctions) { - return BSON.serialize(object, checkKeys, asBuffer, serializeFunctions); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions) { - return BSON.calculateObjectSize(object, serializeFunctions); -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, buffer, startIndex, serializeFunctions) { - return BSON.serializeWithBufferAndIndex(object, checkKeys, buffer, startIndex, serializeFunctions); -} - -/** - * @ignore - * @api private - */ -exports.Code = Code; -exports.Symbol = Symbol; -exports.BSON = BSON; -exports.DBRef = DBRef; -exports.Binary = Binary; -exports.ObjectID = ObjectID; -exports.Long = Long; -exports.Timestamp = Timestamp; -exports.Double = Double; -exports.MinKey = MinKey; -exports.MaxKey = MaxKey; - -}, - - - -'code': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Code type. - * - * @class Represents the BSON Code type. - * @param {String|Function} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - * @api private - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -exports.Code = Code; -}, - - - -'db_ref': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON DBRef type. - * - * @class Represents the BSON DBRef type. - * @param {String} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {String} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -exports.DBRef = DBRef; -}, - - - -'double': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Double type. - * - * @class Represents the BSON Double type. - * @param {Number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @return {Number} returns the wrapped double number. - * @api public - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Double.prototype.toJSON = function() { - return this.value; -} - -exports.Double = Double; -}, - - - -'float_parser': function(module, exports, global, require, undefined){ - // Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; -}, - - - -'index': function(module, exports, global, require, undefined){ - try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('../../ext'); -} catch(err) { - // do nothing -} - -[ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '../../ext' -].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -}, - - - -'long': function(module, exports, global, require, undefined){ - // 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Long type. - * @param {Number} low the low (signed) 32 bits of the Long. - * @param {Number} high the high (signed) 32 bits of the Long. - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Long. - * @api public - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long equals the other - * @api public - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long does not equal the other. - * @api public - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than the other. - * @api public - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is less than or equal to the other. - * @api public - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than the other. - * @api public - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @param {Long} other Long to compare against. - * @return {Boolean} whether this Long is greater than or equal to the other. - * @api public - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @param {Long} other Long to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Long} the negation of this value. - * @api public - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - * @api public - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - * @api public - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - * @api public - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - * @api public - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - * @api public - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Long} the bitwise-NOT of this value. - * @api public - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - * @api public - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - * @api public - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - * @api public - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - * @api public - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - * @api public - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Long. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - * @api public - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @api private - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @api private - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Long = Long; -}, - - - -'max_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MaxKey type. - * - * @class Represents the BSON MaxKey type. - * @return {MaxKey} - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -exports.MaxKey = MaxKey; -}, - - - -'min_key': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON MinKey type. - * - * @class Represents the BSON MinKey type. - * @return {MinKey} - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -exports.MinKey = MinKey; -}, - - - -'objectid': function(module, exports, global, require, undefined){ - /** - * Module dependencies. - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class Represents the BSON ObjectID type -* @param {String|Number} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @return {Object} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id, _hex) { - if(!(this instanceof ObjectID)) return new ObjectID(id, _hex); - - this._bsontype = 'ObjectID'; - var __id = null; - - // Throw an error if it's not a valid setup - if(id != null && 'number' != typeof id && (id.length != 12 && id.length != 24)) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - // Generate id based on the input - if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } else if(checkForHexRegExp.test(id)) { - return ObjectID.createFromHexString(id); - } else { - throw new Error("Value passed in is not a valid 24 character hex string"); - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId as well as ObjectID -var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @return {String} return the 24 byte hex string representation. -* @api public -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @return {Number} returns next index value. -* @api private -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @param {Number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {String} return the 12 byte id binary string. -* @api private -*/ -ObjectID.prototype.generate = function(time) { - if ('number' == typeof time) { - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } else { - var unixTime = parseInt(Date.now()/1000,10); - var time4Bytes = BinaryParser.encodeInt(unixTime, 32, true, true); - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - } - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @api private -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @param {Object} otherID ObjectID instance to compare against. -* @return {Bool} the result of comparing two ObjectID's -* @api public -*/ -ObjectID.prototype.equals = function equals (otherID) { - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @return {Date} the generation date -* @api public -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -* @api private -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @param {Number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @param {String} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -* @api public -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -exports.ObjectID = ObjectID; -exports.ObjectId = ObjectID; - -}, - - - -'symbol': function(module, exports, global, require, undefined){ - /** - * A class representation of the BSON Symbol type. - * - * @class Represents the BSON Symbol type. - * @param {String} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @return {String} returns the wrapped string. - * @api public - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - * @api private - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - * @api private - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -exports.Symbol = Symbol; -}, - - - -'timestamp': function(module, exports, global, require, undefined){ - // 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class Represents the BSON Timestamp type. - * @param {Number} low the low (signed) 32 bits of the Timestamp. - * @param {Number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @api private - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @api private - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {Number} the value, assuming it is a 32-bit integer. - * @api public - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @return {Number} the closest floating-point representation to this value. - * @api public - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @return {String} the JSON representation. - * @api public - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @param {Number} [opt_radix] the radix in which the text should be written. - * @return {String} the textual representation of this value. - * @api public - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @return {Number} the high 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @return {Number} the low 32-bits as a signed value. - * @api public - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @return {Number} the low 32-bits as an unsigned value. - * @api public - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @return {Number} Returns the number of bits needed to represent the absolute value of this Timestamp. - * @api public - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @return {Boolean} whether this value is zero. - * @api public - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @return {Boolean} whether this value is negative. - * @api public - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @return {Boolean} whether this value is odd. - * @api public - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp equals the other - * @api public - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp does not equal the other. - * @api public - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than the other. - * @api public - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is less than or equal to the other. - * @api public - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than the other. - * @api public - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} whether this Timestamp is greater than or equal to the other. - * @api public - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @param {Timestamp} other Timestamp to compare against. - * @return {Boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - * @api public - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @return {Timestamp} the negation of this value. - * @api public - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - * @api public - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - * @api public - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - * @api public - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - * @api public - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @return {Timestamp} the bitwise-NOT of this value. - * @api public - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - * @api public - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - * @api public - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - * @api public - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - * @api public - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - * @api public - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @param {Number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - * @api public - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @param {Number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @param {Number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @param {Number} lowBits the low 32-bits. - * @param {Number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @param {String} str the textual representation of the Timestamp. - * @param {Number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - * @api public - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @api private - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @api private - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @api private - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -exports.Timestamp = Timestamp; -}, - - }); - - -if(typeof module != 'undefined' && module.exports ){ - module.exports = bson; - - if( !module.parent ){ - bson(); - } -} - -if(typeof window != 'undefined' && typeof require == 'undefined'){ - window.require = bson.require; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json deleted file mode 100644 index 3ebb587..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/browser_build/package.json +++ /dev/null @@ -1,8 +0,0 @@ -{ "name" : "bson" -, "description" : "A bson parser for node.js and the browser" -, "main": "../lib/bson/bson" -, "directories" : { "lib" : "../lib/bson" } -, "engines" : { "node" : ">=0.6.0" } -, "licenses" : [ { "type" : "Apache License, Version 2.0" - , "url" : "http://www.apache.org/licenses/LICENSE-2.0" } ] -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js deleted file mode 100644 index ef74b16..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary.js +++ /dev/null @@ -1,344 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -if(typeof window === 'undefined') { - var Buffer = require('buffer').Buffer; // TODO just use global Buffer -} - -/** - * A class representation of the BSON Binary type. - * - * Sub types - * - **BSON.BSON_BINARY_SUBTYPE_DEFAULT**, default BSON type. - * - **BSON.BSON_BINARY_SUBTYPE_FUNCTION**, BSON function type. - * - **BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY**, BSON byte array type. - * - **BSON.BSON_BINARY_SUBTYPE_UUID**, BSON uuid type. - * - **BSON.BSON_BINARY_SUBTYPE_MD5**, BSON md5 type. - * - **BSON.BSON_BINARY_SUBTYPE_USER_DEFINED**, BSON user defined type. - * - * @class - * @param {Buffer} buffer a buffer object containing the binary data. - * @param {Number} [subType] the option binary type. - * @return {Binary} - */ -function Binary(buffer, subType) { - if(!(this instanceof Binary)) return new Binary(buffer, subType); - - this._bsontype = 'Binary'; - - if(buffer instanceof Number) { - this.sub_type = buffer; - this.position = 0; - } else { - this.sub_type = subType == null ? BSON_BINARY_SUBTYPE_DEFAULT : subType; - this.position = 0; - } - - if(buffer != null && !(buffer instanceof Number)) { - // Only accept Buffer, Uint8Array or Arrays - if(typeof buffer == 'string') { - // Different ways of writing the length of the string for the different types - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(buffer); - } else if(typeof Uint8Array != 'undefined' || (Object.prototype.toString.call(buffer) == '[object Array]')) { - this.buffer = writeStringToArray(buffer); - } else { - throw new Error("only String, Buffer, Uint8Array or Array accepted"); - } - } else { - this.buffer = buffer; - } - this.position = buffer.length; - } else { - if(typeof Buffer != 'undefined') { - this.buffer = new Buffer(Binary.BUFFER_SIZE); - } else if(typeof Uint8Array != 'undefined'){ - this.buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE)); - } else { - this.buffer = new Array(Binary.BUFFER_SIZE); - } - // Set position to start of buffer - this.position = 0; - } -}; - -/** - * Updates this binary with byte_value. - * - * @method - * @param {string} byte_value a single byte we wish to write. - */ -Binary.prototype.put = function put(byte_value) { - // If it's a string and a has more than one character throw an error - if(byte_value['length'] != null && typeof byte_value != 'number' && byte_value.length != 1) throw new Error("only accepts single character String, Uint8Array or Array"); - if(typeof byte_value != 'number' && byte_value < 0 || byte_value > 255) throw new Error("only accepts number in a valid unsigned byte range 0-255"); - - // Decode the byte value once - var decoded_byte = null; - if(typeof byte_value == 'string') { - decoded_byte = byte_value.charCodeAt(0); - } else if(byte_value['length'] != null) { - decoded_byte = byte_value[0]; - } else { - decoded_byte = byte_value; - } - - if(this.buffer.length > this.position) { - this.buffer[this.position++] = decoded_byte; - } else { - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - // Create additional overflow buffer - var buffer = new Buffer(Binary.BUFFER_SIZE + this.buffer.length); - // Combine the two buffers together - this.buffer.copy(buffer, 0, 0, this.buffer.length); - this.buffer = buffer; - this.buffer[this.position++] = decoded_byte; - } else { - var buffer = null; - // Create a new buffer (typed or normal array) - if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - buffer = new Uint8Array(new ArrayBuffer(Binary.BUFFER_SIZE + this.buffer.length)); - } else { - buffer = new Array(Binary.BUFFER_SIZE + this.buffer.length); - } - - // We need to copy all the content to the new array - for(var i = 0; i < this.buffer.length; i++) { - buffer[i] = this.buffer[i]; - } - - // Reassign the buffer - this.buffer = buffer; - // Write the byte - this.buffer[this.position++] = decoded_byte; - } - } -}; - -/** - * Writes a buffer or string to the binary. - * - * @method - * @param {(Buffer|string)} string a string or buffer to be written to the Binary BSON object. - * @param {number} offset specify the binary of where to write the content. - * @return {null} - */ -Binary.prototype.write = function write(string, offset) { - offset = typeof offset == 'number' ? offset : this.position; - - // If the buffer is to small let's extend the buffer - if(this.buffer.length < offset + string.length) { - var buffer = null; - // If we are in node.js - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - buffer = new Buffer(this.buffer.length + string.length); - this.buffer.copy(buffer, 0, 0, this.buffer.length); - } else if(Object.prototype.toString.call(this.buffer) == '[object Uint8Array]') { - // Create a new buffer - buffer = new Uint8Array(new ArrayBuffer(this.buffer.length + string.length)) - // Copy the content - for(var i = 0; i < this.position; i++) { - buffer[i] = this.buffer[i]; - } - } - - // Assign the new buffer - this.buffer = buffer; - } - - if(typeof Buffer != 'undefined' && Buffer.isBuffer(string) && Buffer.isBuffer(this.buffer)) { - string.copy(this.buffer, offset, 0, string.length); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length - } else if(typeof Buffer != 'undefined' && typeof string == 'string' && Buffer.isBuffer(this.buffer)) { - this.buffer.write(string, offset, 'binary'); - this.position = (offset + string.length) > this.position ? (offset + string.length) : this.position; - // offset = string.length; - } else if(Object.prototype.toString.call(string) == '[object Uint8Array]' - || Object.prototype.toString.call(string) == '[object Array]' && typeof string != 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string[i]; - } - - this.position = offset > this.position ? offset : this.position; - } else if(typeof string == 'string') { - for(var i = 0; i < string.length; i++) { - this.buffer[offset++] = string.charCodeAt(i); - } - - this.position = offset > this.position ? offset : this.position; - } -}; - -/** - * Reads **length** bytes starting at **position**. - * - * @method - * @param {number} position read from the given position in the Binary. - * @param {number} length the number of bytes to read. - * @return {Buffer} - */ -Binary.prototype.read = function read(position, length) { - length = length && length > 0 - ? length - : this.position; - - // Let's return the data based on the type we have - if(this.buffer['slice']) { - return this.buffer.slice(position, position + length); - } else { - // Create a buffer to keep the result - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(length)) : new Array(length); - for(var i = 0; i < length; i++) { - buffer[i] = this.buffer[position++]; - } - } - // Return the buffer - return buffer; -}; - -/** - * Returns the value of this binary as a string. - * - * @method - * @return {string} - */ -Binary.prototype.value = function value(asRaw) { - asRaw = asRaw == null ? false : asRaw; - - // Optimize to serialize for the situation where the data == size of buffer - if(asRaw && typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer) && this.buffer.length == this.position) - return this.buffer; - - // If it's a node.js buffer object - if(typeof Buffer != 'undefined' && Buffer.isBuffer(this.buffer)) { - return asRaw ? this.buffer.slice(0, this.position) : this.buffer.toString('binary', 0, this.position); - } else { - if(asRaw) { - // we support the slice command use it - if(this.buffer['slice'] != null) { - return this.buffer.slice(0, this.position); - } else { - // Create a new buffer to copy content to - var newBuffer = Object.prototype.toString.call(this.buffer) == '[object Uint8Array]' ? new Uint8Array(new ArrayBuffer(this.position)) : new Array(this.position); - // Copy content - for(var i = 0; i < this.position; i++) { - newBuffer[i] = this.buffer[i]; - } - // Return the buffer - return newBuffer; - } - } else { - return convertArraytoUtf8BinaryString(this.buffer, 0, this.position); - } - } -}; - -/** - * Length. - * - * @method - * @return {number} the length of the binary. - */ -Binary.prototype.length = function length() { - return this.position; -}; - -/** - * @ignore - */ -Binary.prototype.toJSON = function() { - return this.buffer != null ? this.buffer.toString('base64') : ''; -} - -/** - * @ignore - */ -Binary.prototype.toString = function(format) { - return this.buffer != null ? this.buffer.slice(0, this.position).toString(format) : ''; -} - -/** - * Binary default subtype - * @ignore - */ -var BSON_BINARY_SUBTYPE_DEFAULT = 0; - -/** - * @ignore - */ -var writeStringToArray = function(data) { - // Create a buffer - var buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(data.length)) : new Array(data.length); - // Write the content to the buffer - for(var i = 0; i < data.length; i++) { - buffer[i] = data.charCodeAt(i); - } - // Write the string to the buffer - return buffer; -} - -/** - * Convert Array ot Uint8Array to Binary String - * - * @ignore - */ -var convertArraytoUtf8BinaryString = function(byteArray, startIndex, endIndex) { - var result = ""; - for(var i = startIndex; i < endIndex; i++) { - result = result + String.fromCharCode(byteArray[i]); - } - return result; -}; - -Binary.BUFFER_SIZE = 256; - -/** - * Default BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_DEFAULT = 0; -/** - * Function BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_FUNCTION = 1; -/** - * Byte Array BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_BYTE_ARRAY = 2; -/** - * OLD UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID_OLD = 3; -/** - * UUID BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_UUID = 4; -/** - * MD5 BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_MD5 = 5; -/** - * User BSON type - * - * @classconstant SUBTYPE_DEFAULT - **/ -Binary.SUBTYPE_USER_DEFINED = 128; - -/** - * Expose. - */ -module.exports = Binary; -module.exports.Binary = Binary; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js deleted file mode 100644 index d2fc811..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/binary_parser.js +++ /dev/null @@ -1,385 +0,0 @@ -/** - * Binary Parser. - * Jonas Raoni Soares Silva - * http://jsfromhell.com/classes/binary-parser [v1.0] - */ -var chr = String.fromCharCode; - -var maxBits = []; -for (var i = 0; i < 64; i++) { - maxBits[i] = Math.pow(2, i); -} - -function BinaryParser (bigEndian, allowExceptions) { - if(!(this instanceof BinaryParser)) return new BinaryParser(bigEndian, allowExceptions); - - this.bigEndian = bigEndian; - this.allowExceptions = allowExceptions; -}; - -BinaryParser.warn = function warn (msg) { - if (this.allowExceptions) { - throw new Error(msg); - } - - return 1; -}; - -BinaryParser.decodeFloat = function decodeFloat (data, precisionBits, exponentBits) { - var b = new this.Buffer(this.bigEndian, data); - - b.checkBuffer(precisionBits + exponentBits + 1); - - var bias = maxBits[exponentBits - 1] - 1 - , signal = b.readBits(precisionBits + exponentBits, 1) - , exponent = b.readBits(precisionBits, exponentBits) - , significand = 0 - , divisor = 2 - , curByte = b.buffer.length + (-precisionBits >> 3) - 1; - - do { - for (var byteValue = b.buffer[ ++curByte ], startBit = precisionBits % 8 || 8, mask = 1 << startBit; mask >>= 1; ( byteValue & mask ) && ( significand += 1 / divisor ), divisor *= 2 ); - } while (precisionBits -= startBit); - - return exponent == ( bias << 1 ) + 1 ? significand ? NaN : signal ? -Infinity : +Infinity : ( 1 + signal * -2 ) * ( exponent || significand ? !exponent ? Math.pow( 2, -bias + 1 ) * significand : Math.pow( 2, exponent - bias ) * ( 1 + significand ) : 0 ); -}; - -BinaryParser.decodeInt = function decodeInt (data, bits, signed, forceBigEndian) { - var b = new this.Buffer(this.bigEndian || forceBigEndian, data) - , x = b.readBits(0, bits) - , max = maxBits[bits]; //max = Math.pow( 2, bits ); - - return signed && x >= max / 2 - ? x - max - : x; -}; - -BinaryParser.encodeFloat = function encodeFloat (data, precisionBits, exponentBits) { - var bias = maxBits[exponentBits - 1] - 1 - , minExp = -bias + 1 - , maxExp = bias - , minUnnormExp = minExp - precisionBits - , n = parseFloat(data) - , status = isNaN(n) || n == -Infinity || n == +Infinity ? n : 0 - , exp = 0 - , len = 2 * bias + 1 + precisionBits + 3 - , bin = new Array(len) - , signal = (n = status !== 0 ? 0 : n) < 0 - , intPart = Math.floor(n = Math.abs(n)) - , floatPart = n - intPart - , lastBit - , rounded - , result - , i - , j; - - for (i = len; i; bin[--i] = 0); - - for (i = bias + 2; intPart && i; bin[--i] = intPart % 2, intPart = Math.floor(intPart / 2)); - - for (i = bias + 1; floatPart > 0 && i; (bin[++i] = ((floatPart *= 2) >= 1) - 0 ) && --floatPart); - - for (i = -1; ++i < len && !bin[i];); - - if (bin[(lastBit = precisionBits - 1 + (i = (exp = bias + 1 - i) >= minExp && exp <= maxExp ? i + 1 : bias + 1 - (exp = minExp - 1))) + 1]) { - if (!(rounded = bin[lastBit])) { - for (j = lastBit + 2; !rounded && j < len; rounded = bin[j++]); - } - - for (j = lastBit + 1; rounded && --j >= 0; (bin[j] = !bin[j] - 0) && (rounded = 0)); - } - - for (i = i - 2 < 0 ? -1 : i - 3; ++i < len && !bin[i];); - - if ((exp = bias + 1 - i) >= minExp && exp <= maxExp) { - ++i; - } else if (exp < minExp) { - exp != bias + 1 - len && exp < minUnnormExp && this.warn("encodeFloat::float underflow"); - i = bias + 1 - (exp = minExp - 1); - } - - if (intPart || status !== 0) { - this.warn(intPart ? "encodeFloat::float overflow" : "encodeFloat::" + status); - exp = maxExp + 1; - i = bias + 2; - - if (status == -Infinity) { - signal = 1; - } else if (isNaN(status)) { - bin[i] = 1; - } - } - - for (n = Math.abs(exp + bias), j = exponentBits + 1, result = ""; --j; result = (n % 2) + result, n = n >>= 1); - - for (n = 0, j = 0, i = (result = (signal ? "1" : "0") + result + bin.slice(i, i + precisionBits).join("")).length, r = []; i; j = (j + 1) % 8) { - n += (1 << j) * result.charAt(--i); - if (j == 7) { - r[r.length] = String.fromCharCode(n); - n = 0; - } - } - - r[r.length] = n - ? String.fromCharCode(n) - : ""; - - return (this.bigEndian ? r.reverse() : r).join(""); -}; - -BinaryParser.encodeInt = function encodeInt (data, bits, signed, forceBigEndian) { - var max = maxBits[bits]; - - if (data >= max || data < -(max / 2)) { - this.warn("encodeInt::overflow"); - data = 0; - } - - if (data < 0) { - data += max; - } - - for (var r = []; data; r[r.length] = String.fromCharCode(data % 256), data = Math.floor(data / 256)); - - for (bits = -(-bits >> 3) - r.length; bits--; r[r.length] = "\0"); - - return ((this.bigEndian || forceBigEndian) ? r.reverse() : r).join(""); -}; - -BinaryParser.toSmall = function( data ){ return this.decodeInt( data, 8, true ); }; -BinaryParser.fromSmall = function( data ){ return this.encodeInt( data, 8, true ); }; -BinaryParser.toByte = function( data ){ return this.decodeInt( data, 8, false ); }; -BinaryParser.fromByte = function( data ){ return this.encodeInt( data, 8, false ); }; -BinaryParser.toShort = function( data ){ return this.decodeInt( data, 16, true ); }; -BinaryParser.fromShort = function( data ){ return this.encodeInt( data, 16, true ); }; -BinaryParser.toWord = function( data ){ return this.decodeInt( data, 16, false ); }; -BinaryParser.fromWord = function( data ){ return this.encodeInt( data, 16, false ); }; -BinaryParser.toInt = function( data ){ return this.decodeInt( data, 32, true ); }; -BinaryParser.fromInt = function( data ){ return this.encodeInt( data, 32, true ); }; -BinaryParser.toLong = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromLong = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toDWord = function( data ){ return this.decodeInt( data, 32, false ); }; -BinaryParser.fromDWord = function( data ){ return this.encodeInt( data, 32, false ); }; -BinaryParser.toQWord = function( data ){ return this.decodeInt( data, 64, true ); }; -BinaryParser.fromQWord = function( data ){ return this.encodeInt( data, 64, true ); }; -BinaryParser.toFloat = function( data ){ return this.decodeFloat( data, 23, 8 ); }; -BinaryParser.fromFloat = function( data ){ return this.encodeFloat( data, 23, 8 ); }; -BinaryParser.toDouble = function( data ){ return this.decodeFloat( data, 52, 11 ); }; -BinaryParser.fromDouble = function( data ){ return this.encodeFloat( data, 52, 11 ); }; - -// Factor out the encode so it can be shared by add_header and push_int32 -BinaryParser.encode_int32 = function encode_int32 (number, asArray) { - var a, b, c, d, unsigned; - unsigned = (number < 0) ? (number + 0x100000000) : number; - a = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - b = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - c = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - d = Math.floor(unsigned); - return asArray ? [chr(a), chr(b), chr(c), chr(d)] : chr(a) + chr(b) + chr(c) + chr(d); -}; - -BinaryParser.encode_int64 = function encode_int64 (number) { - var a, b, c, d, e, f, g, h, unsigned; - unsigned = (number < 0) ? (number + 0x10000000000000000) : number; - a = Math.floor(unsigned / 0xffffffffffffff); - unsigned &= 0xffffffffffffff; - b = Math.floor(unsigned / 0xffffffffffff); - unsigned &= 0xffffffffffff; - c = Math.floor(unsigned / 0xffffffffff); - unsigned &= 0xffffffffff; - d = Math.floor(unsigned / 0xffffffff); - unsigned &= 0xffffffff; - e = Math.floor(unsigned / 0xffffff); - unsigned &= 0xffffff; - f = Math.floor(unsigned / 0xffff); - unsigned &= 0xffff; - g = Math.floor(unsigned / 0xff); - unsigned &= 0xff; - h = Math.floor(unsigned); - return chr(a) + chr(b) + chr(c) + chr(d) + chr(e) + chr(f) + chr(g) + chr(h); -}; - -/** - * UTF8 methods - */ - -// Take a raw binary string and return a utf8 string -BinaryParser.decode_utf8 = function decode_utf8 (binaryStr) { - var len = binaryStr.length - , decoded = '' - , i = 0 - , c = 0 - , c1 = 0 - , c2 = 0 - , c3; - - while (i < len) { - c = binaryStr.charCodeAt(i); - if (c < 128) { - decoded += String.fromCharCode(c); - i++; - } else if ((c > 191) && (c < 224)) { - c2 = binaryStr.charCodeAt(i+1); - decoded += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); - i += 2; - } else { - c2 = binaryStr.charCodeAt(i+1); - c3 = binaryStr.charCodeAt(i+2); - decoded += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); - i += 3; - } - } - - return decoded; -}; - -// Encode a cstring -BinaryParser.encode_cstring = function encode_cstring (s) { - return unescape(encodeURIComponent(s)) + BinaryParser.fromByte(0); -}; - -// Take a utf8 string and return a binary string -BinaryParser.encode_utf8 = function encode_utf8 (s) { - var a = "" - , c; - - for (var n = 0, len = s.length; n < len; n++) { - c = s.charCodeAt(n); - - if (c < 128) { - a += String.fromCharCode(c); - } else if ((c > 127) && (c < 2048)) { - a += String.fromCharCode((c>>6) | 192) ; - a += String.fromCharCode((c&63) | 128); - } else { - a += String.fromCharCode((c>>12) | 224); - a += String.fromCharCode(((c>>6) & 63) | 128); - a += String.fromCharCode((c&63) | 128); - } - } - - return a; -}; - -BinaryParser.hprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - process.stdout.write(number + " ") - } - } - - process.stdout.write("\n\n"); -}; - -BinaryParser.ilprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(10) - : s.charCodeAt(i).toString(10); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -BinaryParser.hlprint = function hprint (s) { - var number; - - for (var i = 0, len = s.length; i < len; i++) { - if (s.charCodeAt(i) < 32) { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '); - } else { - number = s.charCodeAt(i) <= 15 - ? "0" + s.charCodeAt(i).toString(16) - : s.charCodeAt(i).toString(16); - require('util').debug(number+' : '+ s.charAt(i)); - } - } -}; - -/** - * BinaryParser buffer constructor. - */ -function BinaryParserBuffer (bigEndian, buffer) { - this.bigEndian = bigEndian || 0; - this.buffer = []; - this.setBuffer(buffer); -}; - -BinaryParserBuffer.prototype.setBuffer = function setBuffer (data) { - var l, i, b; - - if (data) { - i = l = data.length; - b = this.buffer = new Array(l); - for (; i; b[l - i] = data.charCodeAt(--i)); - this.bigEndian && b.reverse(); - } -}; - -BinaryParserBuffer.prototype.hasNeededBits = function hasNeededBits (neededBits) { - return this.buffer.length >= -(-neededBits >> 3); -}; - -BinaryParserBuffer.prototype.checkBuffer = function checkBuffer (neededBits) { - if (!this.hasNeededBits(neededBits)) { - throw new Error("checkBuffer::missing bytes"); - } -}; - -BinaryParserBuffer.prototype.readBits = function readBits (start, length) { - //shl fix: Henri Torgemane ~1996 (compressed by Jonas Raoni) - - function shl (a, b) { - for (; b--; a = ((a %= 0x7fffffff + 1) & 0x40000000) == 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1); - return a; - } - - if (start < 0 || length <= 0) { - return 0; - } - - this.checkBuffer(start + length); - - var offsetLeft - , offsetRight = start % 8 - , curByte = this.buffer.length - ( start >> 3 ) - 1 - , lastByte = this.buffer.length + ( -( start + length ) >> 3 ) - , diff = curByte - lastByte - , sum = ((this.buffer[ curByte ] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1)) + (diff && (offsetLeft = (start + length) % 8) ? (this.buffer[lastByte++] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight : 0); - - for(; diff; sum += shl(this.buffer[lastByte++], (diff-- << 3) - offsetRight)); - - return sum; -}; - -/** - * Expose. - */ -BinaryParser.Buffer = BinaryParserBuffer; - -exports.BinaryParser = BinaryParser; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js deleted file mode 100644 index 36f0057..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/bson.js +++ /dev/null @@ -1,323 +0,0 @@ -// "use strict" - -var writeIEEE754 = require('./float_parser').writeIEEE754, - readIEEE754 = require('./float_parser').readIEEE754, - Map = require('./map'), - Long = require('./long').Long, - Double = require('./double').Double, - Timestamp = require('./timestamp').Timestamp, - ObjectID = require('./objectid').ObjectID, - BSONRegExp = require('./regexp').BSONRegExp, - Symbol = require('./symbol').Symbol, - Code = require('./code').Code, - MinKey = require('./min_key').MinKey, - MaxKey = require('./max_key').MaxKey, - DBRef = require('./db_ref').DBRef, - Binary = require('./binary').Binary; - -// Parts of the parser -var deserialize = require('./parser/deserializer'), - serializer = require('./parser/serializer'), - calculateObjectSize = require('./parser/calculate_size'); - -/** - * @ignore - * @api private - */ -// Max Size -var MAXSIZE = (1024*1024*17); -// Max Document Buffer size -var buffer = new Buffer(MAXSIZE); - -var BSON = function() { -} - -/** - * Serialize a Javascript object. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Boolean} asBuffer return the serialized object as a Buffer object **(ignore)**. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Buffer} returns the Buffer object containing the serialized object. - * @api public - */ -BSON.prototype.serialize = function serialize(object, checkKeys, asBuffer, serializeFunctions, index, ignoreUndefined) { - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, index || 0, 0, serializeFunctions, ignoreUndefined); - // Create the final buffer - var finishedBuffer = new Buffer(serializationIndex); - // Copy into the finished buffer - buffer.copy(finishedBuffer, 0, 0, finishedBuffer.length); - // Return the buffer - return finishedBuffer; -} - -/** - * Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization. - * - * @param {Object} object the Javascript object to serialize. - * @param {Boolean} checkKeys the serializer will check if keys are valid. - * @param {Buffer} buffer the Buffer you pre-allocated to store the serialized BSON object. - * @param {Number} index the index in the buffer where we wish to start serializing into. - * @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**. - * @return {Number} returns the new write index in the Buffer. - * @api public - */ -BSON.prototype.serializeWithBufferAndIndex = function(object, checkKeys, finalBuffer, startIndex, serializeFunctions, ignoreUndefined) { - // Attempt to serialize - var serializationIndex = serializer(buffer, object, checkKeys, startIndex || 0, 0, serializeFunctions, ignoreUndefined); - buffer.copy(finalBuffer, startIndex, 0, serializationIndex); - // Return the index - return startIndex + serializationIndex - 1; -} - -/** - * Deserialize data as BSON. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} buffer the buffer containing the serialized set of BSON documents. - * @param {Object} [options] additional options used for the deserialization. - * @param {Boolean} [isArray] ignore used for recursive parsing. - * @return {Object} returns the deserialized Javascript Object. - * @api public - */ -BSON.prototype.deserialize = function(data, options) { - return deserialize(data, options); -} - -/** - * Calculate the bson size for a passed in Javascript object. - * - * @param {Object} object the Javascript object to calculate the BSON byte size for. - * @param {Boolean} [serializeFunctions] serialize all functions in the object **(default:false)**. - * @return {Number} returns the number of bytes the BSON object will take up. - * @api public - */ -BSON.prototype.calculateObjectSize = function(object, serializeFunctions, ignoreUndefined) { - return calculateObjectSize(object, serializeFunctions, ignoreUndefined); -} - -/** - * Deserialize stream data as BSON documents. - * - * Options - * - **evalFunctions** {Boolean, default:false}, evaluate functions in the BSON document scoped to the object deserialized. - * - **cacheFunctions** {Boolean, default:false}, cache evaluated functions for reuse. - * - **cacheFunctionsCrc32** {Boolean, default:false}, use a crc32 code for caching, otherwise use the string of the function. - * - **promoteLongs** {Boolean, default:true}, when deserializing a Long will fit it into a Number if it's smaller than 53 bits - * - * @param {Buffer} data the buffer containing the serialized set of BSON documents. - * @param {Number} startIndex the start index in the data Buffer where the deserialization is to start. - * @param {Number} numberOfDocuments number of documents to deserialize. - * @param {Array} documents an array where to store the deserialized documents. - * @param {Number} docStartIndex the index in the documents array from where to start inserting documents. - * @param {Object} [options] additional options used for the deserialization. - * @return {Number} returns the next index in the buffer after deserialization **x** numbers of documents. - * @api public - */ -BSON.prototype.deserializeStream = function(data, startIndex, numberOfDocuments, documents, docStartIndex, options) { - // if(numberOfDocuments !== documents.length) throw new Error("Number of expected results back is less than the number of documents"); - options = options != null ? options : {}; - var index = startIndex; - // Loop over all documents - for(var i = 0; i < numberOfDocuments; i++) { - // Find size of the document - var size = data[index] | data[index + 1] << 8 | data[index + 2] << 16 | data[index + 3] << 24; - // Update options with index - options['index'] = index; - // Parse the document at this point - documents[docStartIndex + i] = this.deserialize(data, options); - // Adjust index by the document size - index = index + size; - } - - // Return object containing end index of parsing and list of documents - return index; -} - -/** - * @ignore - * @api private - */ -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// Return BSON -module.exports = BSON; -module.exports.Code = Code; -module.exports.Map = Map; -module.exports.Symbol = Symbol; -module.exports.BSON = BSON; -module.exports.DBRef = DBRef; -module.exports.Binary = Binary; -module.exports.ObjectID = ObjectID; -module.exports.Long = Long; -module.exports.Timestamp = Timestamp; -module.exports.Double = Double; -module.exports.MinKey = MinKey; -module.exports.MaxKey = MaxKey; -module.exports.BSONRegExp = BSONRegExp; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js deleted file mode 100644 index 83a42c9..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/code.js +++ /dev/null @@ -1,24 +0,0 @@ -/** - * A class representation of the BSON Code type. - * - * @class - * @param {(string|function)} code a string or function. - * @param {Object} [scope] an optional scope for the function. - * @return {Code} - */ -var Code = function Code(code, scope) { - if(!(this instanceof Code)) return new Code(code, scope); - this._bsontype = 'Code'; - this.code = code; - this.scope = scope == null ? {} : scope; -}; - -/** - * @ignore - */ -Code.prototype.toJSON = function() { - return {scope:this.scope, code:this.code}; -} - -module.exports = Code; -module.exports.Code = Code; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js deleted file mode 100644 index 06789a6..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/db_ref.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * A class representation of the BSON DBRef type. - * - * @class - * @param {string} namespace the collection name. - * @param {ObjectID} oid the reference ObjectID. - * @param {string} [db] optional db name, if omitted the reference is local to the current db. - * @return {DBRef} - */ -function DBRef(namespace, oid, db) { - if(!(this instanceof DBRef)) return new DBRef(namespace, oid, db); - - this._bsontype = 'DBRef'; - this.namespace = namespace; - this.oid = oid; - this.db = db; -}; - -/** - * @ignore - * @api private - */ -DBRef.prototype.toJSON = function() { - return { - '$ref':this.namespace, - '$id':this.oid, - '$db':this.db == null ? '' : this.db - }; -} - -module.exports = DBRef; -module.exports.DBRef = DBRef; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js deleted file mode 100644 index 09ed222..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/double.js +++ /dev/null @@ -1,33 +0,0 @@ -/** - * A class representation of the BSON Double type. - * - * @class - * @param {number} value the number we want to represent as a double. - * @return {Double} - */ -function Double(value) { - if(!(this instanceof Double)) return new Double(value); - - this._bsontype = 'Double'; - this.value = value; -} - -/** - * Access the number value. - * - * @method - * @return {number} returns the wrapped double number. - */ -Double.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Double.prototype.toJSON = function() { - return this.value; -} - -module.exports = Double; -module.exports.Double = Double; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js deleted file mode 100644 index 6fca392..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/float_parser.js +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) 2008, Fair Oaks Labs, Inc. -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright notice, -// this list of conditions and the following disclaimer. -// -// * Redistributions in binary form must reproduce the above copyright notice, -// this list of conditions and the following disclaimer in the documentation -// and/or other materials provided with the distribution. -// -// * Neither the name of Fair Oaks Labs, Inc. nor the names of its contributors -// may be used to endorse or promote products derived from this software -// without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -// POSSIBILITY OF SUCH DAMAGE. -// -// -// Modifications to writeIEEE754 to support negative zeroes made by Brian White - -var readIEEE754 = function(buffer, offset, endian, mLen, nBytes) { - var e, m, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - nBits = -7, - i = bBE ? 0 : (nBytes - 1), - d = bBE ? 1 : -1, - s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8); - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8); - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity); - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; - -var writeIEEE754 = function(buffer, value, offset, endian, mLen, nBytes) { - var e, m, c, - bBE = (endian === 'big'), - eLen = nBytes * 8 - mLen - 1, - eMax = (1 << eLen) - 1, - eBias = eMax >> 1, - rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0), - i = bBE ? (nBytes-1) : 0, - d = bBE ? -1 : 1, - s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e+eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8); - - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8); - - buffer[offset + i - d] |= s * 128; -}; - -exports.readIEEE754 = readIEEE754; -exports.writeIEEE754 = writeIEEE754; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js deleted file mode 100644 index f4147b2..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/index.js +++ /dev/null @@ -1,86 +0,0 @@ -try { - exports.BSONPure = require('./bson'); - exports.BSONNative = require('bson-ext'); -} catch(err) { -} - -[ './binary_parser' - , './binary' - , './code' - , './map' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './regexp' - , './symbol' - , './timestamp' - , './long'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - exports[i] = module[i]; - } -}); - -// Exports all the classes for the PURE JS BSON Parser -exports.pure = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './map' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './regexp' - , './symbol' - , './timestamp' - , './long' - , '././bson'].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - // Return classes list - return classes; -} - -// Exports all the classes for the NATIVE JS BSON Parser -exports.native = function() { - var classes = {}; - // Map all the classes - [ './binary_parser' - , './binary' - , './code' - , './map' - , './db_ref' - , './double' - , './max_key' - , './min_key' - , './objectid' - , './regexp' - , './symbol' - , './timestamp' - , './long' - ].forEach(function (path) { - var module = require('./' + path); - for (var i in module) { - classes[i] = module[i]; - } - }); - - // Catch error and return no classes found - try { - classes['BSON'] = require('bson-ext') - } catch(err) { - return exports.pure(); - } - - // Return classes list - return classes; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js deleted file mode 100644 index 6f18885..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/long.js +++ /dev/null @@ -1,856 +0,0 @@ -// 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * Defines a Long class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Long". This - * implementation is derived from LongLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Longs. - * - * The internal representation of a Long is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Long. - * @param {number} high the high (signed) 32 bits of the Long. - * @return {Long} - */ -function Long(low, high) { - if(!(this instanceof Long)) return new Long(low, high); - - this._bsontype = 'Long'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @method - * @return {number} the value, assuming it is a 32-bit integer. - */ -Long.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Long.prototype.toNumber = function() { - return this.high_ * Long.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Long.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Long.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = Long.fromNumber(radix); - var div = this.div(radixLong); - var rem = div.multiply(radixLong).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Long.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Long.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Long.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Long.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Long. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Long. - */ -Long.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Long.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Long.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Long.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Long.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Long equals the other - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long equals the other - */ -Long.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Long does not equal the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long does not equal the other. - */ -Long.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Long is less than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than the other. - */ -Long.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Long is less than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is less than or equal to the other. - */ -Long.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Long is greater than the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than the other. - */ -Long.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Long is greater than or equal to the other. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} whether this Long is greater than or equal to the other. - */ -Long.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Long with the given one. - * - * @method - * @param {Long} other Long to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Long.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Long} the negation of this value. - */ -Long.prototype.negate = function() { - if (this.equals(Long.MIN_VALUE)) { - return Long.MIN_VALUE; - } else { - return this.not().add(Long.ONE); - } -}; - -/** - * Returns the sum of this and the given Long. - * - * @method - * @param {Long} other Long to add to this one. - * @return {Long} the sum of this and the given Long. - */ -Long.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Long. - * - * @method - * @param {Long} other Long to subtract from this. - * @return {Long} the difference of this and the given Long. - */ -Long.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Long. - * - * @method - * @param {Long} other Long to multiply with this. - * @return {Long} the product of this and the other. - */ -Long.prototype.multiply = function(other) { - if (this.isZero()) { - return Long.ZERO; - } else if (other.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - return other.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } else if (other.equals(Long.MIN_VALUE)) { - return this.isOdd() ? Long.MIN_VALUE : Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Longs are small, use float multiplication - if (this.lessThan(Long.TWO_PWR_24_) && - other.lessThan(Long.TWO_PWR_24_)) { - return Long.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Long divided by the given one. - * - * @method - * @param {Long} other Long by which to divide. - * @return {Long} this Long divided by the given one. - */ -Long.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Long.ZERO; - } - - if (this.equals(Long.MIN_VALUE)) { - if (other.equals(Long.ONE) || - other.equals(Long.NEG_ONE)) { - return Long.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Long.ZERO)) { - return other.isNegative() ? Long.ONE : Long.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Long.MIN_VALUE)) { - return Long.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Long.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Long.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Long.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Long.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Long modulo the given one. - * - * @method - * @param {Long} other Long by which to mod. - * @return {Long} this Long modulo the given one. - */ -Long.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Long} the bitwise-NOT of this value. - */ -Long.prototype.not = function() { - return Long.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to AND. - * @return {Long} the bitwise-AND of this and the other. - */ -Long.prototype.and = function(other) { - return Long.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to OR. - * @return {Long} the bitwise-OR of this and the other. - */ -Long.prototype.or = function(other) { - return Long.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Long and the given one. - * - * @method - * @param {Long} other the Long with which to XOR. - * @return {Long} the bitwise-XOR of this and the other. - */ -Long.prototype.xor = function(other) { - return Long.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Long with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the left by the given amount. - */ -Long.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Long.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Long.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount. - */ -Long.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Long.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Long with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Long} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Long.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Long.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Long.fromBits(high, 0); - } else { - return Long.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Long representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Long} the corresponding Long value. - */ -Long.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Long.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Long(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Long.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Long} the corresponding Long value. - */ -Long.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Long.ZERO; - } else if (value <= -Long.TWO_PWR_63_DBL_) { - return Long.MIN_VALUE; - } else if (value + 1 >= Long.TWO_PWR_63_DBL_) { - return Long.MAX_VALUE; - } else if (value < 0) { - return Long.fromNumber(-value).negate(); - } else { - return new Long( - (value % Long.TWO_PWR_32_DBL_) | 0, - (value / Long.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Long representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Long} the corresponding Long value. - */ -Long.fromBits = function(lowBits, highBits) { - return new Long(lowBits, highBits); -}; - -/** - * Returns a Long representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Long. - * @param {number} opt_radix the radix in which the text is written. - * @return {Long} the corresponding Long value. - */ -Long.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Long.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Long.fromNumber(Math.pow(radix, 8)); - - var result = Long.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Long.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Long.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Long.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Long representations of small integer values. - * @type {Object} - * @ignore - */ -Long.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Long.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_32_DBL_ = Long.TWO_PWR_16_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_31_DBL_ = Long.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_48_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_64_DBL_ = Long.TWO_PWR_32_DBL_ * Long.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Long.TWO_PWR_63_DBL_ = Long.TWO_PWR_64_DBL_ / 2; - -/** @type {Long} */ -Long.ZERO = Long.fromInt(0); - -/** @type {Long} */ -Long.ONE = Long.fromInt(1); - -/** @type {Long} */ -Long.NEG_ONE = Long.fromInt(-1); - -/** @type {Long} */ -Long.MAX_VALUE = - Long.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Long} */ -Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0); - -/** - * @type {Long} - * @ignore - */ -Long.TWO_PWR_24_ = Long.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Long; -module.exports.Long = Long; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js deleted file mode 100644 index f53c8c1..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/map.js +++ /dev/null @@ -1,126 +0,0 @@ -"use strict" - -// We have an ES6 Map available, return the native instance -if(typeof global.Map !== 'undefined') { - module.exports = global.Map; - module.exports.Map = global.Map; -} else { - // We will return a polyfill - var Map = function(array) { - this._keys = []; - this._values = {}; - - for(var i = 0; i < array.length; i++) { - if(array[i] == null) continue; // skip null and undefined - var entry = array[i]; - var key = entry[0]; - var value = entry[1]; - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = {v: value, i: this._keys.length - 1}; - } - } - - Map.prototype.clear = function() { - this._keys = []; - this._values = {}; - } - - Map.prototype.delete = function(key) { - var value = this._values[key]; - if(value == null) return false; - // Delete entry - delete this._values[key]; - // Remove the key from the ordered keys list - this._keys.splice(value.i, 1); - return true; - } - - Map.prototype.entries = function() { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? [key, self._values[key].v] : undefined, - done: key !== undefined ? false : true - } - } - }; - } - - Map.prototype.forEach = function(callback, self) { - self = self || this; - - for(var i = 0; i < this._keys.length; i++) { - var key = this._keys[i]; - // Call the forEach callback - callback.call(self, this._values[key].v, key, self); - } - } - - Map.prototype.get = function(key) { - return this._values[key] ? this._values[key].v : undefined; - } - - Map.prototype.has = function(key) { - return this._values[key] != null; - } - - Map.prototype.keys = function(key) { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? key : undefined, - done: key !== undefined ? false : true - } - } - }; - } - - Map.prototype.set = function(key, value) { - if(this._values[key]) { - this._values[key].v = value; - return this; - } - - // Add the key to the list of keys in order - this._keys.push(key); - // Add the key and value to the values dictionary with a point - // to the location in the ordered keys list - this._values[key] = {v: value, i: this._keys.length - 1}; - return this; - } - - Map.prototype.values = function(key, value) { - var self = this; - var index = 0; - - return { - next: function() { - var key = self._keys[index++]; - return { - value: key !== undefined ? self._values[key].v : undefined, - done: key !== undefined ? false : true - } - } - }; - } - - // Last ismaster - Object.defineProperty(Map.prototype, 'size', { - enumerable:true, - get: function() { return this._keys.length; } - }); - - module.exports = Map; - module.exports.Map = Map; -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js deleted file mode 100644 index 03ee9cd..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/max_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MaxKey type. - * - * @class - * @return {MaxKey} A MaxKey instance - */ -function MaxKey() { - if(!(this instanceof MaxKey)) return new MaxKey(); - - this._bsontype = 'MaxKey'; -} - -module.exports = MaxKey; -module.exports.MaxKey = MaxKey; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js deleted file mode 100644 index 5e120fb..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/min_key.js +++ /dev/null @@ -1,14 +0,0 @@ -/** - * A class representation of the BSON MinKey type. - * - * @class - * @return {MinKey} A MinKey instance - */ -function MinKey() { - if(!(this instanceof MinKey)) return new MinKey(); - - this._bsontype = 'MinKey'; -} - -module.exports = MinKey; -module.exports.MinKey = MinKey; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js deleted file mode 100644 index 3ddcb14..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/objectid.js +++ /dev/null @@ -1,273 +0,0 @@ -/** - * Module dependencies. - * @ignore - */ -var BinaryParser = require('./binary_parser').BinaryParser; - -/** - * Machine id. - * - * Create a random 3-byte value (i.e. unique for this - * process). Other drivers use a md5 of the machine id here, but - * that would mean an asyc call to gethostname, so we don't bother. - * @ignore - */ -var MACHINE_ID = parseInt(Math.random() * 0xFFFFFF, 10); - -// Regular expression that checks for hex value -var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$"); - -/** -* Create a new ObjectID instance -* -* @class -* @param {(string|number)} id Can be a 24 byte hex string, 12 byte binary string or a Number. -* @property {number} generationTime The generation time of this ObjectId instance -* @return {ObjectID} instance of ObjectID. -*/ -var ObjectID = function ObjectID(id) { - if(!(this instanceof ObjectID)) return new ObjectID(id); - if((id instanceof ObjectID)) return id; - - this._bsontype = 'ObjectID'; - var __id = null; - var valid = ObjectID.isValid(id); - - // Throw an error if it's not a valid setup - if(!valid && id != null){ - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - } else if(valid && typeof id == 'string' && id.length == 24) { - return ObjectID.createFromHexString(id); - } else if(id == null || typeof id == 'number') { - // convert to 12 byte binary string - this.id = this.generate(id); - } else if(id != null && id.length === 12) { - // assume 12 byte string - this.id = id; - } - - if(ObjectID.cacheHexString) this.__id = this.toHexString(); -}; - -// Allow usage of ObjectId as well as ObjectID -var ObjectId = ObjectID; - -// Precomputed hex table enables speedy hex string conversion -var hexTable = []; -for (var i = 0; i < 256; i++) { - hexTable[i] = (i <= 15 ? '0' : '') + i.toString(16); -} - -/** -* Return the ObjectID id as a 24 byte hex string representation -* -* @method -* @return {string} return the 24 byte hex string representation. -*/ -ObjectID.prototype.toHexString = function() { - if(ObjectID.cacheHexString && this.__id) return this.__id; - - var hexString = ''; - - for (var i = 0; i < this.id.length; i++) { - hexString += hexTable[this.id.charCodeAt(i)]; - } - - if(ObjectID.cacheHexString) this.__id = hexString; - return hexString; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.get_inc = function() { - return ObjectID.index = (ObjectID.index + 1) % 0xFFFFFF; -}; - -/** -* Update the ObjectID index used in generating new ObjectID's on the driver -* -* @method -* @return {number} returns next index value. -* @ignore -*/ -ObjectID.prototype.getInc = function() { - return this.get_inc(); -}; - -/** -* Generate a 12 byte id string used in ObjectID's -* -* @method -* @param {number} [time] optional parameter allowing to pass in a second based timestamp. -* @return {string} return the 12 byte id binary string. -*/ -ObjectID.prototype.generate = function(time) { - if ('number' != typeof time) { - time = parseInt(Date.now()/1000,10); - } - - var time4Bytes = BinaryParser.encodeInt(time, 32, true, true); - /* for time-based ObjectID the bytes following the time will be zeroed */ - var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false); - var pid2Bytes = BinaryParser.fromShort(typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid % 0xFFFF); - var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true); - - return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes; -}; - -/** -* Converts the id into a 24 byte hex string for printing -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toString = function() { - return this.toHexString(); -}; - -/** -* Converts to a string representation of this Id. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.inspect = ObjectID.prototype.toString; - -/** -* Converts to its JSON representation. -* -* @return {String} return the 24 byte hex string representation. -* @ignore -*/ -ObjectID.prototype.toJSON = function() { - return this.toHexString(); -}; - -/** -* Compares the equality of this ObjectID with `otherID`. -* -* @method -* @param {object} otherID ObjectID instance to compare against. -* @return {boolean} the result of comparing two ObjectID's -*/ -ObjectID.prototype.equals = function equals (otherID) { - if(otherID == null) return false; - var id = (otherID instanceof ObjectID || otherID.toHexString) - ? otherID.id - : ObjectID.createFromHexString(otherID).id; - - return this.id === id; -} - -/** -* Returns the generation date (accurate up to the second) that this ID was generated. -* -* @method -* @return {date} the generation date -*/ -ObjectID.prototype.getTimestamp = function() { - var timestamp = new Date(); - timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000); - return timestamp; -} - -/** -* @ignore -*/ -ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10); - -/** -* @ignore -*/ -ObjectID.createPk = function createPk () { - return new ObjectID(); -}; - -/** -* Creates an ObjectID from a second based number, with the rest of the ObjectID zeroed out. Used for comparisons or sorting the ObjectID. -* -* @method -* @param {number} time an integer number representing a number of seconds. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromTime = function createFromTime (time) { - var id = BinaryParser.encodeInt(time, 32, true, true) + - BinaryParser.encodeInt(0, 64, true, true); - return new ObjectID(id); -}; - -/** -* Creates an ObjectID from a hex string representation of an ObjectID. -* -* @method -* @param {string} hexString create a ObjectID from a passed in 24 byte hexstring. -* @return {ObjectID} return the created ObjectID -*/ -ObjectID.createFromHexString = function createFromHexString (hexString) { - // Throw an error if it's not a valid setup - if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24) - throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"); - - var len = hexString.length; - - if(len > 12*2) { - throw new Error('Id cannot be longer than 12 bytes'); - } - - var result = '' - , string - , number; - - for (var index = 0; index < len; index += 2) { - string = hexString.substr(index, 2); - number = parseInt(string, 16); - result += BinaryParser.fromByte(number); - } - - return new ObjectID(result, hexString); -}; - -/** -* Checks if a value is a valid bson ObjectId -* -* @method -* @return {boolean} return true if the value is a valid bson ObjectId, return false otherwise. -*/ -ObjectID.isValid = function isValid(id) { - if(id == null) return false; - - if(typeof id == 'number') - return true; - if(typeof id == 'string') { - return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id)); - } - return false; -}; - -/** -* @ignore -*/ -Object.defineProperty(ObjectID.prototype, "generationTime", { - enumerable: true - , get: function () { - return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)); - } - , set: function (value) { - var value = BinaryParser.encodeInt(value, 32, true, true); - this.id = value + this.id.substr(4); - // delete this.__id; - this.toHexString(); - } -}); - -/** - * Expose. - */ -module.exports = ObjectID; -module.exports.ObjectID = ObjectID; -module.exports.ObjectId = ObjectID; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js deleted file mode 100644 index 03513f3..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/calculate_size.js +++ /dev/null @@ -1,310 +0,0 @@ -"use strict" - -var writeIEEE754 = require('../float_parser').writeIEEE754 - , readIEEE754 = require('../float_parser').readIEEE754 - , Long = require('../long').Long - , Double = require('../double').Double - , Timestamp = require('../timestamp').Timestamp - , ObjectID = require('../objectid').ObjectID - , Symbol = require('../symbol').Symbol - , BSONRegExp = require('../regexp').BSONRegExp - , Code = require('../code').Code - , MinKey = require('../min_key').MinKey - , MaxKey = require('../max_key').MaxKey - , DBRef = require('../db_ref').DBRef - , Binary = require('../binary').Binary; - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -var calculateObjectSize = function calculateObjectSize(object, serializeFunctions, ignoreUndefined) { - var totalLength = (4 + 1); - - if(Array.isArray(object)) { - for(var i = 0; i < object.length; i++) { - totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined) - } - } else { - // If we have toBSON defined, override the current object - if(object.toBSON) { - object = object.toBSON(); - } - - // Calculate size - for(var key in object) { - totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined) - } - } - - return totalLength; -} - -/** - * @ignore - * @api private - */ -function calculateElement(name, value, serializeFunctions, isArray, ignoreUndefined) { - // If we have toBSON defined, override the current object - if(value && value.toBSON){ - value = value.toBSON(); - } - - switch(typeof value) { - case 'string': - return 1 + Buffer.byteLength(name, 'utf8') + 1 + 4 + Buffer.byteLength(value, 'utf8') + 1; - case 'number': - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { // 32 bit - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (4 + 1); - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } - } else { // 64 bit - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } - case 'undefined': - if(isArray || !ignoreUndefined) return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); - return 0; - case 'boolean': - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 1); - case 'object': - if(value == null || value instanceof MinKey || value instanceof MaxKey || value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1); - } else if(value instanceof ObjectID || value['_bsontype'] == 'ObjectID') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (12 + 1); - } else if(value instanceof Date || isDate(value)) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } else if(typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (1 + 4 + 1) + value.length; - } else if(value instanceof Long || value instanceof Double || value instanceof Timestamp - || value['_bsontype'] == 'Long' || value['_bsontype'] == 'Double' || value['_bsontype'] == 'Timestamp') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1); - } else if(value instanceof Code || value['_bsontype'] == 'Code') { - // Calculate size depending on the availability of a scope - if(value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.code.toString(), 'utf8') + 1; - } - } else if(value instanceof Binary || value['_bsontype'] == 'Binary') { - // Check what kind of subtype we have - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1 + 4); - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (value.position + 1 + 4 + 1); - } - } else if(value instanceof Symbol || value['_bsontype'] == 'Symbol') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + Buffer.byteLength(value.value, 'utf8') + 4 + 1 + 1; - } else if(value instanceof DBRef || value['_bsontype'] == 'DBRef') { - // Set up correct object for serialization - var ordered_values = { - '$ref': value.namespace - , '$id' : value.oid - }; - - // Add db reference if it exists - if(null != value.db) { - ordered_values['$db'] = value.db; - } - - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + calculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined); - } else if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else if(value instanceof BSONRegExp || value['_bsontype'] == 'BSONRegExp') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.pattern, 'utf8') + 1 - + Buffer.byteLength(value.options, 'utf8') + 1 - } else { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + calculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1; - } - case 'function': - // WTF for 0.4.X where typeof /someregexp/ === 'function' - if(value instanceof RegExp || Object.prototype.toString.call(value) === '[object RegExp]' || String.call(value) == '[object RegExp]') { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + Buffer.byteLength(value.source, 'utf8') + 1 - + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1 - } else { - if(serializeFunctions && value.scope != null && Object.keys(value.scope).length > 0) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1 + calculateObjectSize(value.scope, serializeFunctions, ignoreUndefined); - } else if(serializeFunctions) { - return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + 1 + 4 + Buffer.byteLength(value.toString(), 'utf8') + 1; - } - } - } - - return 0; -} - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = calculateObjectSize; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js deleted file mode 100644 index 5f1cc10..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/deserializer.js +++ /dev/null @@ -1,544 +0,0 @@ -"use strict" - -var writeIEEE754 = require('../float_parser').writeIEEE754, - readIEEE754 = require('../float_parser').readIEEE754, - f = require('util').format, - Long = require('../long').Long, - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - DBRef = require('../db_ref').DBRef, - BSONRegExp = require('../regexp').BSONRegExp, - Binary = require('../binary').Binary; - -var deserialize = function(buffer, options, isArray) { - var index = 0; - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || buffer.length < size) { - throw new Error("corrupt bson message"); - } - - // Illegal end value - if(buffer[size - 1] != 0) { - throw new Error("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00"); - } - - // Start deserializtion - return deserializeObject(buffer, options, isArray); -} - -// Reads in a C style string -var readCStyleStringSpecial = function(buffer, index) { - // Get the start search index - var i = index; - // Locate the end of the c string - while(buffer[i] !== 0x00 && i < buffer.length) { - i++ - } - // If are at the end of the buffer there is a problem with the document - if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString") - // Grab utf8 encoded string - var string = buffer.toString('utf8', index, i); - // Update index position - index = i + 1; - // Return string - return {s: string, i: index}; -} - -var deserializeObject = function(buffer, options, isArray) { - // Options - options = options == null ? {} : options; - var evalFunctions = options['evalFunctions'] == null ? false : options['evalFunctions']; - var cacheFunctions = options['cacheFunctions'] == null ? false : options['cacheFunctions']; - var cacheFunctionsCrc32 = options['cacheFunctionsCrc32'] == null ? false : options['cacheFunctionsCrc32']; - var promoteLongs = options['promoteLongs'] == null ? true : options['promoteLongs']; - var fieldsAsRaw = options['fieldsAsRaw'] == null ? {} : options['fieldsAsRaw']; - // Return BSONRegExp objects instead of native regular expressions - var bsonRegExp = typeof options['bsonRegExp'] == 'boolean' ? options['bsonRegExp'] : false; - - // Validate that we have at least 4 bytes of buffer - if(buffer.length < 5) throw new Error("corrupt bson message < 5 bytes long"); - - // Set up index - var index = typeof options['index'] == 'number' ? options['index'] : 0; - - // Read the document size - var size = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - - // Ensure buffer is valid size - if(size < 5 || size > buffer.length) throw new Error("corrupt bson message"); - - // Create holding object - var object = isArray ? [] : {}; - - // While we have more left data left keep parsing - while(true) { - // Read the type - var elementType = buffer[index++]; - // If we get a zero it's the last byte, exit - if(elementType == 0) break; - // Read the name of the field - var r = readCStyleStringSpecial(buffer, index); - var name = r.s; - index = r.i; - - // Switch on the type - if(elementType == BSON.BSON_DATA_OID) { - var string = buffer.toString('binary', index, index + 12); - // Decode the oid - object[name] = new ObjectID(string); - // Update index - index = index + 12; - } else if(elementType == BSON.BSON_DATA_STRING) { - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Validate if string Size is larger than the actual provided buffer - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Add string to object - object[name] = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - } else if(elementType == BSON.BSON_DATA_INT) { - // Decode the 32bit value - object[name] = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } else if(elementType == BSON.BSON_DATA_NUMBER) { - // Decode the double value - object[name] = readIEEE754(buffer, index, 'little', 52, 8); - // Update the index - index = index + 8; - } else if(elementType == BSON.BSON_DATA_DATE) { - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set date object - object[name] = new Date(new Long(lowBits, highBits).toNumber()); - } else if(elementType == BSON.BSON_DATA_BOOLEAN) { - // Parse the boolean value - object[name] = buffer[index++] == 1; - } else if(elementType == BSON.BSON_DATA_UNDEFINED || elementType == BSON.BSON_DATA_NULL) { - // Parse the boolean value - object[name] = null; - } else if(elementType == BSON.BSON_DATA_BINARY) { - // Decode the size of the binary blob - var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Decode the subtype - var subType = buffer[index++]; - // Decode as raw Buffer object if options specifies it - if(buffer['slice'] != null) { - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Slice the data - object[name] = new Binary(buffer.slice(index, index + binarySize), subType); - } else { - var _buffer = typeof Uint8Array != 'undefined' ? new Uint8Array(new ArrayBuffer(binarySize)) : new Array(binarySize); - // If we have subtype 2 skip the 4 bytes for the size - if(subType == Binary.SUBTYPE_BYTE_ARRAY) { - binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - } - // Copy the data - for(var i = 0; i < binarySize; i++) { - _buffer[i] = buffer[index + i]; - } - // Create the binary object - object[name] = new Binary(_buffer, subType); - } - // Update the index - index = index + binarySize; - } else if(elementType == BSON.BSON_DATA_ARRAY) { - options['index'] = index; - // Decode the size of the array document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - var arrayOptions = options; - - // All elements of array to be returned as raw bson - if(fieldsAsRaw[name]) { - arrayOptions = {}; - for(var n in options) arrayOptions[n] = options[n]; - arrayOptions['raw'] = true; - } - - // Set the array to the object - object[name] = deserializeObject(buffer, arrayOptions, true); - // Adjust the index - index = index + objectSize; - } else if(elementType == BSON.BSON_DATA_OBJECT) { - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Validate if string Size is larger than the actual provided buffer - if(objectSize <= 0 || objectSize > (buffer.length - index)) throw new Error("bad embedded document length in bson"); - - // We have a raw value - if(options['raw']) { - // Set the array to the object - object[name] = buffer.slice(index, index + objectSize); - } else { - // Set the array to the object - object[name] = deserializeObject(buffer, options, false); - } - - // Adjust the index - index = index + objectSize; - } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == false) { - // Create the regexp - var r = readCStyleStringSpecial(buffer, index); - var source = r.s; - index = r.i; - - var r = readCStyleStringSpecial(buffer, index); - var regExpOptions = r.s; - index = r.i; - - // For each option add the corresponding one for javascript - var optionsArray = new Array(regExpOptions.length); - - // Parse options - for(var i = 0; i < regExpOptions.length; i++) { - switch(regExpOptions[i]) { - case 'm': - optionsArray[i] = 'm'; - break; - case 's': - optionsArray[i] = 'g'; - break; - case 'i': - optionsArray[i] = 'i'; - break; - } - } - - object[name] = new RegExp(source, optionsArray.join('')); - } else if(elementType == BSON.BSON_DATA_REGEXP && bsonRegExp == true) { - // Create the regexp - var r = readCStyleStringSpecial(buffer, index); - var source = r.s; - index = r.i; - - var r = readCStyleStringSpecial(buffer, index); - var regExpOptions = r.s; - index = r.i; - - // Set the object - object[name] = new BSONRegExp(source, regExpOptions); - } else if(elementType == BSON.BSON_DATA_LONG) { - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Create long object - var long = new Long(lowBits, highBits); - // Promote the long if possible - if(promoteLongs) { - object[name] = long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG) ? long.toNumber() : long; - } else { - object[name] = long; - } - } else if(elementType == BSON.BSON_DATA_SYMBOL) { - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Validate if string Size is larger than the actual provided buffer - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Add string to object - object[name] = new Symbol(buffer.toString('utf8', index, index + stringSize - 1)); - // Update parse index position - index = index + stringSize; - } else if(elementType == BSON.BSON_DATA_TIMESTAMP) { - // Unpack the low and high bits - var lowBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var highBits = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Set the object - object[name] = new Timestamp(lowBits, highBits); - } else if(elementType == BSON.BSON_DATA_MIN_KEY) { - // Parse the object - object[name] = new MinKey(); - } else if(elementType == BSON.BSON_DATA_MAX_KEY) { - // Parse the object - object[name] = new MaxKey(); - } else if(elementType == BSON.BSON_DATA_CODE) { - // Read the content of the field - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Validate if string Size is larger than the actual provided buffer - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Function string - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - } else { - object[name] = new Code(functionString, {}); - } - - // Update parse index position - index = index + stringSize; - } else if(elementType == BSON.BSON_DATA_CODE_W_SCOPE) { - // Read the content of the field - var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24; - // Validate if string Size is larger than the actual provided buffer - if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson"); - // Javascript function - var functionString = buffer.toString('utf8', index, index + stringSize - 1); - // Update parse index position - index = index + stringSize; - // Parse the element - options['index'] = index; - // Decode the size of the object document - var objectSize = buffer[index] | buffer[index + 1] << 8 | buffer[index + 2] << 16 | buffer[index + 3] << 24; - // Decode the scope object - var scopeObject = deserializeObject(buffer, options, false); - // Adjust the index - index = index + objectSize; - - // If we are evaluating the functions - if(evalFunctions) { - // Contains the value we are going to set - var value = null; - // If we have cache enabled let's look for the md5 of the function in the cache - if(cacheFunctions) { - var hash = cacheFunctionsCrc32 ? crc32(functionString) : functionString; - // Got to do this to avoid V8 deoptimizing the call due to finding eval - object[name] = isolateEvalWithHash(functionCache, hash, functionString, object); - } else { - // Set directly - object[name] = isolateEval(functionString); - } - - // Set the scope on the object - object[name].scope = scopeObject; - } else { - object[name] = new Code(functionString, scopeObject); - } - } - } - - // Check if we have a db ref object - if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']); - - // Return the final objects - return object; -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEvalWithHash = function(functionCache, hash, functionString, object) { - // Contains the value we are going to set - var value = null; - - // Check for cache hit, eval if missing and return cached function - if(functionCache[hash] == null) { - eval("value = " + functionString); - functionCache[hash] = value; - } - // Set the object - return functionCache[hash].bind(object); -} - -/** - * Ensure eval is isolated. - * - * @ignore - * @api private - */ -var isolateEval = function(functionString) { - // Contains the value we are going to set - var value = null; - // Eval the function - eval("value = " + functionString); - return value; -} - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = deserialize diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js deleted file mode 100644 index 285e45b..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/parser/serializer.js +++ /dev/null @@ -1,909 +0,0 @@ -"use strict" - -var writeIEEE754 = require('../float_parser').writeIEEE754, - readIEEE754 = require('../float_parser').readIEEE754, - Long = require('../long').Long, - Map = require('../map'), - Double = require('../double').Double, - Timestamp = require('../timestamp').Timestamp, - ObjectID = require('../objectid').ObjectID, - Symbol = require('../symbol').Symbol, - Code = require('../code').Code, - BSONRegExp = require('../regexp').BSONRegExp, - MinKey = require('../min_key').MinKey, - MaxKey = require('../max_key').MaxKey, - DBRef = require('../db_ref').DBRef, - Binary = require('../binary').Binary; - -var regexp = /\x00/ - -// To ensure that 0.4 of node works correctly -var isDate = function isDate(d) { - return typeof d === 'object' && Object.prototype.toString.call(d) === '[object Date]'; -} - -var isRegExp = function isRegExp(d) { - return Object.prototype.toString.call(d) === '[object RegExp]'; -} - -var serializeString = function(buffer, key, value, index) { - // Encode String type - buffer[index++] = BSON.BSON_DATA_STRING; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes + 1; - buffer[index - 1] = 0; - // Write the string - var size = buffer.write(value, index + 4, 'utf8'); - // Write the size of the string to buffer - buffer[index + 3] = (size + 1 >> 24) & 0xff; - buffer[index + 2] = (size + 1 >> 16) & 0xff; - buffer[index + 1] = (size + 1 >> 8) & 0xff; - buffer[index] = size + 1 & 0xff; - // Update index - index = index + 4 + size; - // Write zero - buffer[index++] = 0; - return index; -} - -var serializeNumber = function(buffer, key, value, index) { - // We have an integer value - if(Math.floor(value) === value && value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // If the value fits in 32 bits encode as int, if it fits in a double - // encode it as a double, otherwise long - if(value >= BSON.BSON_INT32_MIN && value <= BSON.BSON_INT32_MAX) { - // Set int type 32 bits or less - buffer[index++] = BSON.BSON_DATA_INT; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the int value - buffer[index++] = value & 0xff; - buffer[index++] = (value >> 8) & 0xff; - buffer[index++] = (value >> 16) & 0xff; - buffer[index++] = (value >> 24) & 0xff; - } else if(value >= BSON.JS_INT_MIN && value <= BSON.JS_INT_MAX) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } else { - // Set long type - buffer[index++] = BSON.BSON_DATA_LONG; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var longVal = Long.fromNumber(value); - var lowBits = longVal.getLowBits(); - var highBits = longVal.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - } - } else { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - } - - return index; -} - -var serializeUndefined = function(buffer, key, value, index) { - // Set long type - buffer[index++] = BSON.BSON_DATA_NULL; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -var serializeBoolean = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BOOLEAN; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Encode the boolean value - buffer[index++] = value ? 1 : 0; - return index; -} - -var serializeDate = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_DATE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the date - var dateInMilis = Long.fromNumber(value.getTime()); - var lowBits = dateInMilis.getLowBits(); - var highBits = dateInMilis.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -var serializeRegExp = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Adjust the index - index = index + buffer.write(value.source, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the parameters - if(value.global) buffer[index++] = 0x73; // s - if(value.ignoreCase) buffer[index++] = 0x69; // i - if(value.multiline) buffer[index++] = 0x6d; // m - // Add ending zero - buffer[index++] = 0x00; - return index; -} - -var serializeBSONRegExp = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_REGEXP; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Adjust the index - index = index + buffer.write(value.pattern, index, 'utf8'); - // Write zero - buffer[index++] = 0x00; - // Write the options - index = index + buffer.write(value.options, index, 'utf8'); - // Add ending zero - buffer[index++] = 0x00; - return index; -} - -var serializeMinMax = function(buffer, key, value, index) { - // Write the type of either min or max key - if(value === null) { - buffer[index++] = BSON.BSON_DATA_NULL; - } else if(value instanceof MinKey) { - buffer[index++] = BSON.BSON_DATA_MIN_KEY; - } else { - buffer[index++] = BSON.BSON_DATA_MAX_KEY; - } - - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - return index; -} - -var serializeObjectId = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OID; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Write the objectId into the shared buffer - buffer.write(value.id, index, 'binary') - - // Ajust index - return index + 12; -} - -var serializeBuffer = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Get size of the buffer (current write point) - var size = value.length; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the default subtype - buffer[index++] = BSON.BSON_BINARY_SUBTYPE_DEFAULT; - // Copy the content form the binary field to the buffer - value.copy(buffer, index, 0, size); - // Adjust the index - index = index + size; - return index; -} - -var serializeObject = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { - // Write the type - buffer[index++] = Array.isArray(value) ? BSON.BSON_DATA_ARRAY : BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - var endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined); - // Write size - var size = endIndex - index; - return endIndex; -} - -var serializeLong = function(buffer, key, value, index) { - // Write the type - buffer[index++] = value instanceof Long ? BSON.BSON_DATA_LONG : BSON.BSON_DATA_TIMESTAMP; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the date - var lowBits = value.getLowBits(); - var highBits = value.getHighBits(); - // Encode low bits - buffer[index++] = lowBits & 0xff; - buffer[index++] = (lowBits >> 8) & 0xff; - buffer[index++] = (lowBits >> 16) & 0xff; - buffer[index++] = (lowBits >> 24) & 0xff; - // Encode high bits - buffer[index++] = highBits & 0xff; - buffer[index++] = (highBits >> 8) & 0xff; - buffer[index++] = (highBits >> 16) & 0xff; - buffer[index++] = (highBits >> 24) & 0xff; - return index; -} - -var serializeDouble = function(buffer, key, value, index) { - // Encode as double - buffer[index++] = BSON.BSON_DATA_NUMBER; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write float - writeIEEE754(buffer, value, index, 'little', 52, 8); - // Ajust index - index = index + 8; - return index; -} - -var serializeFunction = function(buffer, key, value, index, checkKeys, depth) { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - return index; -} - -var serializeCode = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) { - if(value.scope != null && Object.keys(value.scope).length > 0) { - // Write the type - buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - // Starting index - var startIndex = index; - - // Serialize the function - // Get the function string - var functionString = typeof value.code == 'string' ? value.code : value.code.toString(); - // Index adjustment - index = index + 4; - // Write string into buffer - var codeSize = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = codeSize & 0xff; - buffer[index + 1] = (codeSize >> 8) & 0xff; - buffer[index + 2] = (codeSize >> 16) & 0xff; - buffer[index + 3] = (codeSize >> 24) & 0xff; - // Write end 0 - buffer[index + 4 + codeSize - 1] = 0; - // Write the - index = index + codeSize + 4; - - // - // Serialize the scope value - var endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined) - index = endIndex - 1; - - // Writ the total - var totalSize = endIndex - startIndex; - - // Write the total size of the object - buffer[startIndex++] = totalSize & 0xff; - buffer[startIndex++] = (totalSize >> 8) & 0xff; - buffer[startIndex++] = (totalSize >> 16) & 0xff; - buffer[startIndex++] = (totalSize >> 24) & 0xff; - // Write trailing zero - buffer[index++] = 0; - } else { - buffer[index++] = BSON.BSON_DATA_CODE; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Function string - var functionString = value.code.toString(); - // Write the string - var size = buffer.write(functionString, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0; - } - - return index; -} - -var serializeBinary = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_BINARY; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Extract the buffer - var data = value.value(true); - // Calculate size - var size = value.position; - // Write the size of the string to buffer - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - // Write the subtype to the buffer - buffer[index++] = value.sub_type; - - // If we have binary type 2 the 4 first bytes are the size - if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) { - buffer[index++] = size & 0xff; - buffer[index++] = (size >> 8) & 0xff; - buffer[index++] = (size >> 16) & 0xff; - buffer[index++] = (size >> 24) & 0xff; - } - - // Write the data to the object - data.copy(buffer, index, 0, value.position); - // Adjust the index - index = index + value.position; - return index; -} - -var serializeSymbol = function(buffer, key, value, index) { - // Write the type - buffer[index++] = BSON.BSON_DATA_SYMBOL; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - // Write the string - var size = buffer.write(value.value, index + 4, 'utf8') + 1; - // Write the size of the string to buffer - buffer[index] = size & 0xff; - buffer[index + 1] = (size >> 8) & 0xff; - buffer[index + 2] = (size >> 16) & 0xff; - buffer[index + 3] = (size >> 24) & 0xff; - // Update index - index = index + 4 + size - 1; - // Write zero - buffer[index++] = 0x00; - return index; -} - -var serializeDBRef = function(buffer, key, value, index, depth, serializeFunctions) { - // Write the type - buffer[index++] = BSON.BSON_DATA_OBJECT; - // Number of written bytes - var numberOfWrittenBytes = buffer.write(key, index, 'utf8'); - - // Encode the name - index = index + numberOfWrittenBytes; - buffer[index++] = 0; - - var startIndex = index; - var endIndex; - - // Serialize object - if(null != value.db) { - endIndex = serializeInto(buffer, { - '$ref': value.namespace - , '$id' : value.oid - , '$db' : value.db - }, false, index, depth + 1, serializeFunctions); - } else { - endIndex = serializeInto(buffer, { - '$ref': value.namespace - , '$id' : value.oid - }, false, index, depth + 1, serializeFunctions); - } - - // Calculate object size - var size = endIndex - startIndex; - // Write the size - buffer[startIndex++] = size & 0xff; - buffer[startIndex++] = (size >> 8) & 0xff; - buffer[startIndex++] = (size >> 16) & 0xff; - buffer[startIndex++] = (size >> 24) & 0xff; - // Set index - return endIndex; -} - -var serializeInto = function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined) { - startingIndex = startingIndex || 0; - - // Start place to serialize into - var index = startingIndex + 4; - var self = this; - - // Special case isArray - if(Array.isArray(object)) { - // Get object keys - for(var i = 0; i < object.length; i++) { - var key = "" + i; - var value = object[i]; - - // Is there an override value - if(value && value.toBSON) { - if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); - value = value.toBSON(); - } - - var type = typeof value; - if(type == 'string') { - index = serializeString(buffer, key, value, index); - } else if(type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if(value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if(type == 'undefined' || value == null) { - index = serializeUndefined(buffer, key, value, index); - } else if(value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if(Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if(value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if(type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if(value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if(typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if(value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if(value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if(value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if(value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else if(object instanceof Map) { - var iterator = object.entries(); - var done = false; - - while(!done) { - // Unpack the next entry - var entry = iterator.next(); - done = entry.done; - // Are we done, then skip and terminate - if(done) continue; - - // Get the entry values - var key = entry.value[0]; - var value = entry.value[1]; - - // Check the type of the value - var type = typeof value; - - // Check the key and throw error if it's illegal - if(key != '$db' && key != '$ref' && key != '$id') { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - - if (checkKeys) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } - } - - // console.log("---------------------------------------------------") - // console.dir("key = " + key) - // console.dir("value = " + value) - - if(type == 'string') { - index = serializeString(buffer, key, value, index); - } else if(type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if(value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if(value === undefined && ignoreUndefined == true) { - } else if(value === null || value === undefined) { - index = serializeUndefined(buffer, key, value, index); - } else if(value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if(Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if(value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if(type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if(value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if(value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if(value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if(value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if(value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if(value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } else { - // Did we provide a custom serialization method - if(object.toBSON) { - if(typeof object.toBSON != 'function') throw new Error("toBSON is not a function"); - object = object.toBSON(); - if(object != null && typeof object != 'object') throw new Error("toBSON function did not return an object"); - } - - // Iterate over all the keys - for(var key in object) { - var value = object[key]; - // Is there an override value - if(value && value.toBSON) { - if(typeof value.toBSON != 'function') throw new Error("toBSON is not a function"); - value = value.toBSON(); - } - - // Check the type of the value - var type = typeof value; - - // Check the key and throw error if it's illegal - if(key != '$db' && key != '$ref' && key != '$id') { - if (key.match(regexp) != null) { - // The BSON spec doesn't allow keys with null bytes because keys are - // null-terminated. - throw Error("key " + key + " must not contain null bytes"); - } - - if (checkKeys) { - if('$' == key[0]) { - throw Error("key " + key + " must not start with '$'"); - } else if (!!~key.indexOf('.')) { - throw Error("key " + key + " must not contain '.'"); - } - } - } - - if(type == 'string') { - index = serializeString(buffer, key, value, index); - } else if(type == 'number') { - index = serializeNumber(buffer, key, value, index); - } else if(type == 'boolean') { - index = serializeBoolean(buffer, key, value, index); - } else if(value instanceof Date || isDate(value)) { - index = serializeDate(buffer, key, value, index); - } else if(value === undefined && ignoreUndefined == true) { - } else if(value === null || value === undefined) { - index = serializeUndefined(buffer, key, value, index); - } else if(value['_bsontype'] == 'ObjectID') { - index = serializeObjectId(buffer, key, value, index); - } else if(Buffer.isBuffer(value)) { - index = serializeBuffer(buffer, key, value, index); - } else if(value instanceof RegExp || isRegExp(value)) { - index = serializeRegExp(buffer, key, value, index); - } else if(type == 'object' && value['_bsontype'] == null) { - index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') { - index = serializeLong(buffer, key, value, index); - } else if(value['_bsontype'] == 'Double') { - index = serializeDouble(buffer, key, value, index); - } else if(value['_bsontype'] == 'Code') { - index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined); - } else if(typeof value == 'function' && serializeFunctions) { - index = serializeFunction(buffer, key, value, index, checkKeys, depth, serializeFunctions); - } else if(value['_bsontype'] == 'Binary') { - index = serializeBinary(buffer, key, value, index); - } else if(value['_bsontype'] == 'Symbol') { - index = serializeSymbol(buffer, key, value, index); - } else if(value['_bsontype'] == 'DBRef') { - index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions); - } else if(value['_bsontype'] == 'BSONRegExp') { - index = serializeBSONRegExp(buffer, key, value, index); - } else if(value['_bsontype'] == 'MinKey' || value['_bsontype'] == 'MaxKey') { - index = serializeMinMax(buffer, key, value, index); - } - } - } - - // Final padding byte for object - buffer[index++] = 0x00; - - // Final size - var size = index - startingIndex; - // Write the size of the object - buffer[startingIndex++] = size & 0xff; - buffer[startingIndex++] = (size >> 8) & 0xff; - buffer[startingIndex++] = (size >> 16) & 0xff; - buffer[startingIndex++] = (size >> 24) & 0xff; - return index; -} - -var BSON = {}; - -/** - * Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5 - * - * @ignore - * @api private - */ -var functionCache = BSON.functionCache = {}; - -/** - * Number BSON Type - * - * @classconstant BSON_DATA_NUMBER - **/ -BSON.BSON_DATA_NUMBER = 1; -/** - * String BSON Type - * - * @classconstant BSON_DATA_STRING - **/ -BSON.BSON_DATA_STRING = 2; -/** - * Object BSON Type - * - * @classconstant BSON_DATA_OBJECT - **/ -BSON.BSON_DATA_OBJECT = 3; -/** - * Array BSON Type - * - * @classconstant BSON_DATA_ARRAY - **/ -BSON.BSON_DATA_ARRAY = 4; -/** - * Binary BSON Type - * - * @classconstant BSON_DATA_BINARY - **/ -BSON.BSON_DATA_BINARY = 5; -/** - * ObjectID BSON Type - * - * @classconstant BSON_DATA_OID - **/ -BSON.BSON_DATA_OID = 7; -/** - * Boolean BSON Type - * - * @classconstant BSON_DATA_BOOLEAN - **/ -BSON.BSON_DATA_BOOLEAN = 8; -/** - * Date BSON Type - * - * @classconstant BSON_DATA_DATE - **/ -BSON.BSON_DATA_DATE = 9; -/** - * null BSON Type - * - * @classconstant BSON_DATA_NULL - **/ -BSON.BSON_DATA_NULL = 10; -/** - * RegExp BSON Type - * - * @classconstant BSON_DATA_REGEXP - **/ -BSON.BSON_DATA_REGEXP = 11; -/** - * Code BSON Type - * - * @classconstant BSON_DATA_CODE - **/ -BSON.BSON_DATA_CODE = 13; -/** - * Symbol BSON Type - * - * @classconstant BSON_DATA_SYMBOL - **/ -BSON.BSON_DATA_SYMBOL = 14; -/** - * Code with Scope BSON Type - * - * @classconstant BSON_DATA_CODE_W_SCOPE - **/ -BSON.BSON_DATA_CODE_W_SCOPE = 15; -/** - * 32 bit Integer BSON Type - * - * @classconstant BSON_DATA_INT - **/ -BSON.BSON_DATA_INT = 16; -/** - * Timestamp BSON Type - * - * @classconstant BSON_DATA_TIMESTAMP - **/ -BSON.BSON_DATA_TIMESTAMP = 17; -/** - * Long BSON Type - * - * @classconstant BSON_DATA_LONG - **/ -BSON.BSON_DATA_LONG = 18; -/** - * MinKey BSON Type - * - * @classconstant BSON_DATA_MIN_KEY - **/ -BSON.BSON_DATA_MIN_KEY = 0xff; -/** - * MaxKey BSON Type - * - * @classconstant BSON_DATA_MAX_KEY - **/ -BSON.BSON_DATA_MAX_KEY = 0x7f; - -/** - * Binary Default Type - * - * @classconstant BSON_BINARY_SUBTYPE_DEFAULT - **/ -BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0; -/** - * Binary Function Type - * - * @classconstant BSON_BINARY_SUBTYPE_FUNCTION - **/ -BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1; -/** - * Binary Byte Array Type - * - * @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY - **/ -BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -/** - * Binary UUID Type - * - * @classconstant BSON_BINARY_SUBTYPE_UUID - **/ -BSON.BSON_BINARY_SUBTYPE_UUID = 3; -/** - * Binary MD5 Type - * - * @classconstant BSON_BINARY_SUBTYPE_MD5 - **/ -BSON.BSON_BINARY_SUBTYPE_MD5 = 4; -/** - * Binary User Defined Type - * - * @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED - **/ -BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -// BSON MAX VALUES -BSON.BSON_INT32_MAX = 0x7FFFFFFF; -BSON.BSON_INT32_MIN = -0x80000000; - -BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1; -BSON.BSON_INT64_MIN = -Math.pow(2, 63); - -// JS MAX PRECISE VALUES -BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double. -BSON.JS_INT_MIN = -0x20000000000000; // Any integer down to -2^53 can be precisely represented by a double. - -// Internal long versions -var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double. -var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double. - -module.exports = serializeInto; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js deleted file mode 100644 index 6b148b2..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/regexp.js +++ /dev/null @@ -1,30 +0,0 @@ -/** - * A class representation of the BSON RegExp type. - * - * @class - * @return {BSONRegExp} A MinKey instance - */ -function BSONRegExp(pattern, options) { - if(!(this instanceof BSONRegExp)) return new BSONRegExp(); - - // Execute - this._bsontype = 'BSONRegExp'; - this.pattern = pattern; - this.options = options; - - // Validate options - for(var i = 0; i < options.length; i++) { - if(!(this.options[i] == 'i' - || this.options[i] == 'm' - || this.options[i] == 'x' - || this.options[i] == 'l' - || this.options[i] == 's' - || this.options[i] == 'u' - )) { - throw new Error('the regular expression options [' + this.options[i] + "] is not supported"); - } - } -} - -module.exports = BSONRegExp; -module.exports.BSONRegExp = BSONRegExp; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js deleted file mode 100644 index 7681a4d..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/symbol.js +++ /dev/null @@ -1,47 +0,0 @@ -/** - * A class representation of the BSON Symbol type. - * - * @class - * @deprecated - * @param {string} value the string representing the symbol. - * @return {Symbol} - */ -function Symbol(value) { - if(!(this instanceof Symbol)) return new Symbol(value); - this._bsontype = 'Symbol'; - this.value = value; -} - -/** - * Access the wrapped string value. - * - * @method - * @return {String} returns the wrapped string. - */ -Symbol.prototype.valueOf = function() { - return this.value; -}; - -/** - * @ignore - */ -Symbol.prototype.toString = function() { - return this.value; -} - -/** - * @ignore - */ -Symbol.prototype.inspect = function() { - return this.value; -} - -/** - * @ignore - */ -Symbol.prototype.toJSON = function() { - return this.value; -} - -module.exports = Symbol; -module.exports.Symbol = Symbol; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js deleted file mode 100644 index 7718caf..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/lib/bson/timestamp.js +++ /dev/null @@ -1,856 +0,0 @@ -// 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. -// -// Copyright 2009 Google Inc. All Rights Reserved - -/** - * This type is for INTERNAL use in MongoDB only and should not be used in applications. - * The appropriate corresponding type is the JavaScript Date type. - * - * Defines a Timestamp class for representing a 64-bit two's-complement - * integer value, which faithfully simulates the behavior of a Java "Timestamp". This - * implementation is derived from TimestampLib in GWT. - * - * Constructs a 64-bit two's-complement integer, given its low and high 32-bit - * values as *signed* integers. See the from* functions below for more - * convenient ways of constructing Timestamps. - * - * The internal representation of a Timestamp is the two given signed, 32-bit values. - * We use 32-bit pieces because these are the size of integers on which - * Javascript performs bit-operations. For operations like addition and - * multiplication, we split each number into 16-bit pieces, which can easily be - * multiplied within Javascript's floating-point representation without overflow - * or change in sign. - * - * In the algorithms below, we frequently reduce the negative case to the - * positive case by negating the input(s) and then post-processing the result. - * Note that we must ALWAYS check specially whether those values are MIN_VALUE - * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - * a positive number, it overflows back into a negative). Not handling this - * case would often result in infinite recursion. - * - * @class - * @param {number} low the low (signed) 32 bits of the Timestamp. - * @param {number} high the high (signed) 32 bits of the Timestamp. - */ -function Timestamp(low, high) { - if(!(this instanceof Timestamp)) return new Timestamp(low, high); - this._bsontype = 'Timestamp'; - /** - * @type {number} - * @ignore - */ - this.low_ = low | 0; // force into 32 signed bits. - - /** - * @type {number} - * @ignore - */ - this.high_ = high | 0; // force into 32 signed bits. -}; - -/** - * Return the int value. - * - * @return {number} the value, assuming it is a 32-bit integer. - */ -Timestamp.prototype.toInt = function() { - return this.low_; -}; - -/** - * Return the Number value. - * - * @method - * @return {number} the closest floating-point representation to this value. - */ -Timestamp.prototype.toNumber = function() { - return this.high_ * Timestamp.TWO_PWR_32_DBL_ + - this.getLowBitsUnsigned(); -}; - -/** - * Return the JSON value. - * - * @method - * @return {string} the JSON representation. - */ -Timestamp.prototype.toJSON = function() { - return this.toString(); -} - -/** - * Return the String value. - * - * @method - * @param {number} [opt_radix] the radix in which the text should be written. - * @return {string} the textual representation of this value. - */ -Timestamp.prototype.toString = function(opt_radix) { - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - // We need to change the Timestamp value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixTimestamp = Timestamp.fromNumber(radix); - var div = this.div(radixTimestamp); - var rem = div.multiply(radixTimestamp).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 6)); - - var rem = this; - var result = ''; - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt(); - var digits = intval.toString(radix); - - rem = remDiv; - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - result = '' + digits + result; - } - } -}; - -/** - * Return the high 32-bits value. - * - * @method - * @return {number} the high 32-bits as a signed value. - */ -Timestamp.prototype.getHighBits = function() { - return this.high_; -}; - -/** - * Return the low 32-bits value. - * - * @method - * @return {number} the low 32-bits as a signed value. - */ -Timestamp.prototype.getLowBits = function() { - return this.low_; -}; - -/** - * Return the low unsigned 32-bits value. - * - * @method - * @return {number} the low 32-bits as an unsigned value. - */ -Timestamp.prototype.getLowBitsUnsigned = function() { - return (this.low_ >= 0) ? - this.low_ : Timestamp.TWO_PWR_32_DBL_ + this.low_; -}; - -/** - * Returns the number of bits needed to represent the absolute value of this Timestamp. - * - * @method - * @return {number} Returns the number of bits needed to represent the absolute value of this Timestamp. - */ -Timestamp.prototype.getNumBitsAbs = function() { - if (this.isNegative()) { - if (this.equals(Timestamp.MIN_VALUE)) { - return 64; - } else { - return this.negate().getNumBitsAbs(); - } - } else { - var val = this.high_ != 0 ? this.high_ : this.low_; - for (var bit = 31; bit > 0; bit--) { - if ((val & (1 << bit)) != 0) { - break; - } - } - return this.high_ != 0 ? bit + 33 : bit + 1; - } -}; - -/** - * Return whether this value is zero. - * - * @method - * @return {boolean} whether this value is zero. - */ -Timestamp.prototype.isZero = function() { - return this.high_ == 0 && this.low_ == 0; -}; - -/** - * Return whether this value is negative. - * - * @method - * @return {boolean} whether this value is negative. - */ -Timestamp.prototype.isNegative = function() { - return this.high_ < 0; -}; - -/** - * Return whether this value is odd. - * - * @method - * @return {boolean} whether this value is odd. - */ -Timestamp.prototype.isOdd = function() { - return (this.low_ & 1) == 1; -}; - -/** - * Return whether this Timestamp equals the other - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp equals the other - */ -Timestamp.prototype.equals = function(other) { - return (this.high_ == other.high_) && (this.low_ == other.low_); -}; - -/** - * Return whether this Timestamp does not equal the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp does not equal the other. - */ -Timestamp.prototype.notEquals = function(other) { - return (this.high_ != other.high_) || (this.low_ != other.low_); -}; - -/** - * Return whether this Timestamp is less than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than the other. - */ -Timestamp.prototype.lessThan = function(other) { - return this.compare(other) < 0; -}; - -/** - * Return whether this Timestamp is less than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is less than or equal to the other. - */ -Timestamp.prototype.lessThanOrEqual = function(other) { - return this.compare(other) <= 0; -}; - -/** - * Return whether this Timestamp is greater than the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than the other. - */ -Timestamp.prototype.greaterThan = function(other) { - return this.compare(other) > 0; -}; - -/** - * Return whether this Timestamp is greater than or equal to the other. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} whether this Timestamp is greater than or equal to the other. - */ -Timestamp.prototype.greaterThanOrEqual = function(other) { - return this.compare(other) >= 0; -}; - -/** - * Compares this Timestamp with the given one. - * - * @method - * @param {Timestamp} other Timestamp to compare against. - * @return {boolean} 0 if they are the same, 1 if the this is greater, and -1 if the given one is greater. - */ -Timestamp.prototype.compare = function(other) { - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) { - return -1; - } - if (!thisNeg && otherNeg) { - return 1; - } - - // at this point, the signs are the same, so subtraction will not overflow - if (this.subtract(other).isNegative()) { - return -1; - } else { - return 1; - } -}; - -/** - * The negation of this value. - * - * @method - * @return {Timestamp} the negation of this value. - */ -Timestamp.prototype.negate = function() { - if (this.equals(Timestamp.MIN_VALUE)) { - return Timestamp.MIN_VALUE; - } else { - return this.not().add(Timestamp.ONE); - } -}; - -/** - * Returns the sum of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to add to this one. - * @return {Timestamp} the sum of this and the given Timestamp. - */ -Timestamp.prototype.add = function(other) { - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 + b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns the difference of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to subtract from this. - * @return {Timestamp} the difference of this and the given Timestamp. - */ -Timestamp.prototype.subtract = function(other) { - return this.add(other.negate()); -}; - -/** - * Returns the product of this and the given Timestamp. - * - * @method - * @param {Timestamp} other Timestamp to multiply with this. - * @return {Timestamp} the product of this and the other. - */ -Timestamp.prototype.multiply = function(other) { - if (this.isZero()) { - return Timestamp.ZERO; - } else if (other.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - return other.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } else if (other.equals(Timestamp.MIN_VALUE)) { - return this.isOdd() ? Timestamp.MIN_VALUE : Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().multiply(other.negate()); - } else { - return this.negate().multiply(other).negate(); - } - } else if (other.isNegative()) { - return this.multiply(other.negate()).negate(); - } - - // If both Timestamps are small, use float multiplication - if (this.lessThan(Timestamp.TWO_PWR_24_) && - other.lessThan(Timestamp.TWO_PWR_24_)) { - return Timestamp.fromNumber(this.toNumber() * other.toNumber()); - } - - // Divide each Timestamp into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high_ >>> 16; - var a32 = this.high_ & 0xFFFF; - var a16 = this.low_ >>> 16; - var a00 = this.low_ & 0xFFFF; - - var b48 = other.high_ >>> 16; - var b32 = other.high_ & 0xFFFF; - var b16 = other.low_ >>> 16; - var b00 = other.low_ & 0xFFFF; - - var c48 = 0, c32 = 0, c16 = 0, c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xFFFF; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xFFFF; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xFFFF; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xFFFF; - return Timestamp.fromBits((c16 << 16) | c00, (c48 << 16) | c32); -}; - -/** - * Returns this Timestamp divided by the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to divide. - * @return {Timestamp} this Timestamp divided by the given one. - */ -Timestamp.prototype.div = function(other) { - if (other.isZero()) { - throw Error('division by zero'); - } else if (this.isZero()) { - return Timestamp.ZERO; - } - - if (this.equals(Timestamp.MIN_VALUE)) { - if (other.equals(Timestamp.ONE) || - other.equals(Timestamp.NEG_ONE)) { - return Timestamp.MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - var approx = halfThis.div(other).shiftLeft(1); - if (approx.equals(Timestamp.ZERO)) { - return other.isNegative() ? Timestamp.ONE : Timestamp.NEG_ONE; - } else { - var rem = this.subtract(other.multiply(approx)); - var result = approx.add(rem.div(other)); - return result; - } - } - } else if (other.equals(Timestamp.MIN_VALUE)) { - return Timestamp.ZERO; - } - - if (this.isNegative()) { - if (other.isNegative()) { - return this.negate().div(other.negate()); - } else { - return this.negate().div(other).negate(); - } - } else if (other.isNegative()) { - return this.div(other.negate()).negate(); - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - var res = Timestamp.ZERO; - var rem = this; - while (rem.greaterThanOrEqual(other)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - var approx = Math.max(1, Math.floor(rem.toNumber() / other.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = (log2 <= 48) ? 1 : Math.pow(2, log2 - 48); - - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - var approxRes = Timestamp.fromNumber(approx); - var approxRem = approxRes.multiply(other); - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Timestamp.fromNumber(approx); - approxRem = approxRes.multiply(other); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) { - approxRes = Timestamp.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - return res; -}; - -/** - * Returns this Timestamp modulo the given one. - * - * @method - * @param {Timestamp} other Timestamp by which to mod. - * @return {Timestamp} this Timestamp modulo the given one. - */ -Timestamp.prototype.modulo = function(other) { - return this.subtract(this.div(other).multiply(other)); -}; - -/** - * The bitwise-NOT of this value. - * - * @method - * @return {Timestamp} the bitwise-NOT of this value. - */ -Timestamp.prototype.not = function() { - return Timestamp.fromBits(~this.low_, ~this.high_); -}; - -/** - * Returns the bitwise-AND of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to AND. - * @return {Timestamp} the bitwise-AND of this and the other. - */ -Timestamp.prototype.and = function(other) { - return Timestamp.fromBits(this.low_ & other.low_, this.high_ & other.high_); -}; - -/** - * Returns the bitwise-OR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to OR. - * @return {Timestamp} the bitwise-OR of this and the other. - */ -Timestamp.prototype.or = function(other) { - return Timestamp.fromBits(this.low_ | other.low_, this.high_ | other.high_); -}; - -/** - * Returns the bitwise-XOR of this Timestamp and the given one. - * - * @method - * @param {Timestamp} other the Timestamp with which to XOR. - * @return {Timestamp} the bitwise-XOR of this and the other. - */ -Timestamp.prototype.xor = function(other) { - return Timestamp.fromBits(this.low_ ^ other.low_, this.high_ ^ other.high_); -}; - -/** - * Returns this Timestamp with bits shifted to the left by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the left by the given amount. - */ -Timestamp.prototype.shiftLeft = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var low = this.low_; - if (numBits < 32) { - var high = this.high_; - return Timestamp.fromBits( - low << numBits, - (high << numBits) | (low >>> (32 - numBits))); - } else { - return Timestamp.fromBits(0, low << (numBits - 32)); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount. - */ -Timestamp.prototype.shiftRight = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >> numBits); - } else { - return Timestamp.fromBits( - high >> (numBits - 32), - high >= 0 ? 0 : -1); - } - } -}; - -/** - * Returns this Timestamp with bits shifted to the right by the given amount, with the new top bits matching the current sign bit. - * - * @method - * @param {number} numBits the number of bits by which to shift. - * @return {Timestamp} this shifted to the right by the given amount, with zeros placed into the new leading bits. - */ -Timestamp.prototype.shiftRightUnsigned = function(numBits) { - numBits &= 63; - if (numBits == 0) { - return this; - } else { - var high = this.high_; - if (numBits < 32) { - var low = this.low_; - return Timestamp.fromBits( - (low >>> numBits) | (high << (32 - numBits)), - high >>> numBits); - } else if (numBits == 32) { - return Timestamp.fromBits(high, 0); - } else { - return Timestamp.fromBits(high >>> (numBits - 32), 0); - } - } -}; - -/** - * Returns a Timestamp representing the given (32-bit) integer value. - * - * @method - * @param {number} value the 32-bit integer in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromInt = function(value) { - if (-128 <= value && value < 128) { - var cachedObj = Timestamp.INT_CACHE_[value]; - if (cachedObj) { - return cachedObj; - } - } - - var obj = new Timestamp(value | 0, value < 0 ? -1 : 0); - if (-128 <= value && value < 128) { - Timestamp.INT_CACHE_[value] = obj; - } - return obj; -}; - -/** - * Returns a Timestamp representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * - * @method - * @param {number} value the number in question. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromNumber = function(value) { - if (isNaN(value) || !isFinite(value)) { - return Timestamp.ZERO; - } else if (value <= -Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MIN_VALUE; - } else if (value + 1 >= Timestamp.TWO_PWR_63_DBL_) { - return Timestamp.MAX_VALUE; - } else if (value < 0) { - return Timestamp.fromNumber(-value).negate(); - } else { - return new Timestamp( - (value % Timestamp.TWO_PWR_32_DBL_) | 0, - (value / Timestamp.TWO_PWR_32_DBL_) | 0); - } -}; - -/** - * Returns a Timestamp representing the 64-bit integer that comes by concatenating the given high and low bits. Each is assumed to use 32 bits. - * - * @method - * @param {number} lowBits the low 32-bits. - * @param {number} highBits the high 32-bits. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromBits = function(lowBits, highBits) { - return new Timestamp(lowBits, highBits); -}; - -/** - * Returns a Timestamp representation of the given string, written using the given radix. - * - * @method - * @param {string} str the textual representation of the Timestamp. - * @param {number} opt_radix the radix in which the text is written. - * @return {Timestamp} the corresponding Timestamp value. - */ -Timestamp.fromString = function(str, opt_radix) { - if (str.length == 0) { - throw Error('number format error: empty string'); - } - - var radix = opt_radix || 10; - if (radix < 2 || 36 < radix) { - throw Error('radix out of range: ' + radix); - } - - if (str.charAt(0) == '-') { - return Timestamp.fromString(str.substring(1), radix).negate(); - } else if (str.indexOf('-') >= 0) { - throw Error('number format error: interior "-" character: ' + str); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = Timestamp.fromNumber(Math.pow(radix, 8)); - - var result = Timestamp.ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = Timestamp.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Timestamp.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Timestamp.fromNumber(value)); - } - } - return result; -}; - -// NOTE: Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the -// from* methods on which they depend. - - -/** - * A cache of the Timestamp representations of small integer values. - * @type {Object} - * @ignore - */ -Timestamp.INT_CACHE_ = {}; - -// NOTE: the compiler should inline these constant values below and then remove -// these variables, so there should be no runtime penalty for these. - -/** - * Number used repeated below in calculations. This must appear before the - * first call to any from* function below. - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_16_DBL_ = 1 << 16; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_24_DBL_ = 1 << 24; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_32_DBL_ = Timestamp.TWO_PWR_16_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_31_DBL_ = Timestamp.TWO_PWR_32_DBL_ / 2; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_48_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_16_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_64_DBL_ = Timestamp.TWO_PWR_32_DBL_ * Timestamp.TWO_PWR_32_DBL_; - -/** - * @type {number} - * @ignore - */ -Timestamp.TWO_PWR_63_DBL_ = Timestamp.TWO_PWR_64_DBL_ / 2; - -/** @type {Timestamp} */ -Timestamp.ZERO = Timestamp.fromInt(0); - -/** @type {Timestamp} */ -Timestamp.ONE = Timestamp.fromInt(1); - -/** @type {Timestamp} */ -Timestamp.NEG_ONE = Timestamp.fromInt(-1); - -/** @type {Timestamp} */ -Timestamp.MAX_VALUE = - Timestamp.fromBits(0xFFFFFFFF | 0, 0x7FFFFFFF | 0); - -/** @type {Timestamp} */ -Timestamp.MIN_VALUE = Timestamp.fromBits(0, 0x80000000 | 0); - -/** - * @type {Timestamp} - * @ignore - */ -Timestamp.TWO_PWR_24_ = Timestamp.fromInt(1 << 24); - -/** - * Expose. - */ -module.exports = Timestamp; -module.exports.Timestamp = Timestamp; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json deleted file mode 100644 index 1eb5b0a..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/package.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "name": "bson", - "description": "A bson parser for node.js and the browser", - "keywords": [ - "mongodb", - "bson", - "parser" - ], - "version": "0.4.16", - "author": { - "name": "Christian Amor Kvalheim", - "email": "christkv@gmail.com" - }, - "contributors": [], - "repository": { - "type": "git", - "url": "git://github.com/mongodb/js-bson.git" - }, - "bugs": { - "url": "https://github.com/mongodb/js-bson/issues" - }, - "devDependencies": { - "nodeunit": "0.9.0", - "gleak": "0.2.3", - "one": "2.X.X", - "benchmark": "1.0.0", - "colors": "1.1.0" - }, - "config": { - "native": false - }, - "main": "./lib/bson/index", - "directories": { - "lib": "./lib/bson" - }, - "engines": { - "node": ">=0.6.19" - }, - "scripts": { - "test": "nodeunit ./test/node" - }, - "browser": "lib/bson/bson.js", - "license": "Apache-2.0", - "gitHead": "4166146d0539a050946c1cae9188f274dd751ed9", - "homepage": "https://github.com/mongodb/js-bson", - "_id": "bson@0.4.16", - "_shasum": "e78fb993535123851f857fb83c7f68b1cd7e6caa", - "_from": "bson@>=0.4.0 <0.5.0", - "_npmVersion": "2.14.4", - "_nodeVersion": "4.1.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "octave", - "email": "chinsay@gmail.com" - }, - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "e78fb993535123851f857fb83c7f68b1cd7e6caa", - "tarball": "http://registry.npmjs.org/bson/-/bson-0.4.16.tgz" - }, - "_resolved": "https://registry.npmjs.org/bson/-/bson-0.4.16.tgz" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js deleted file mode 100644 index c707cfc..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/bson/tools/gleak.js +++ /dev/null @@ -1,21 +0,0 @@ - -var gleak = require('gleak')(); -gleak.ignore('AssertionError'); -gleak.ignore('testFullSpec_param_found'); -gleak.ignore('events'); -gleak.ignore('Uint8Array'); -gleak.ignore('Uint8ClampedArray'); -gleak.ignore('TAP_Global_Harness'); -gleak.ignore('setImmediate'); -gleak.ignore('clearImmediate'); - -gleak.ignore('DTRACE_NET_SERVER_CONNECTION'); -gleak.ignore('DTRACE_NET_STREAM_END'); -gleak.ignore('DTRACE_NET_SOCKET_READ'); -gleak.ignore('DTRACE_NET_SOCKET_WRITE'); -gleak.ignore('DTRACE_HTTP_SERVER_REQUEST'); -gleak.ignore('DTRACE_HTTP_SERVER_RESPONSE'); -gleak.ignore('DTRACE_HTTP_CLIENT_REQUEST'); -gleak.ignore('DTRACE_HTTP_CLIENT_RESPONSE'); - -module.exports = gleak; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml deleted file mode 100644 index b0fb9f4..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -language: node_js -node_js: - - "0.8" - - "0.10" - - "0.12" - - "iojs-v1.8.4" - - "iojs-v2.5.0" - - "iojs-v3.3.0" - - "4" -addons: - apt: - sources: - - ubuntu-toolchain-r-test - packages: - - g++-4.8 -before_install: - - '[ "${TRAVIS_NODE_VERSION}" != "0.8" ] || npm install -g npm@1.4.28' - - if [[ $TRAVIS_OS_NAME == "linux" ]]; then export CXX=g++-4.8; fi - - $CXX --version - - npm explore npm -g -- npm install node-gyp@latest \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE deleted file mode 100644 index 261eeb9..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md deleted file mode 100644 index 7428b0d..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/README.md +++ /dev/null @@ -1,4 +0,0 @@ -kerberos -======== - -Kerberos library for node.js \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp deleted file mode 100644 index 6655299..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/binding.gyp +++ /dev/null @@ -1,46 +0,0 @@ -{ - 'targets': [ - { - 'target_name': 'kerberos', - 'cflags!': [ '-fno-exceptions' ], - 'cflags_cc!': [ '-fno-exceptions' ], - 'include_dirs': [ '> $(depfile) -# Add extra rules as in (2). -# We remove slashes and replace spaces with new lines; -# remove blank lines; -# delete the first line and append a colon to the remaining lines. -sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ - grep -v '^$$' |\ - sed -e 1d -e 's|$$|:|' \ - >> $(depfile) -rm $(depfile).raw -endef - -# Command definitions: -# - cmd_foo is the actual command to run; -# - quiet_cmd_foo is the brief-output summary of the command. - -quiet_cmd_cc = CC($(TOOLSET)) $@ -cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_cxx = CXX($(TOOLSET)) $@ -cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< - -quiet_cmd_touch = TOUCH $@ -cmd_touch = touch $@ - -quiet_cmd_copy = COPY $@ -# send stderr to /dev/null to ignore messages when linking directories. -cmd_copy = rm -rf "$@" && cp -af "$<" "$@" - -quiet_cmd_alink = AR($(TOOLSET)) $@ -cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^) - -quiet_cmd_alink_thin = AR($(TOOLSET)) $@ -cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^) - -# Due to circular dependencies between libraries :(, we wrap the -# special "figure out circular dependencies" flags around the entire -# input list during linking. -quiet_cmd_link = LINK($(TOOLSET)) $@ -cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS) - -# We support two kinds of shared objects (.so): -# 1) shared_library, which is just bundling together many dependent libraries -# into a link line. -# 2) loadable_module, which is generating a module intended for dlopen(). -# -# They differ only slightly: -# In the former case, we want to package all dependent code into the .so. -# In the latter case, we want to package just the API exposed by the -# outermost module. -# This means shared_library uses --whole-archive, while loadable_module doesn't. -# (Note that --whole-archive is incompatible with the --start-group used in -# normal linking.) - -# Other shared-object link notes: -# - Set SONAME to the library filename so our binaries don't reference -# the local, absolute paths used on the link command-line. -quiet_cmd_solink = SOLINK($(TOOLSET)) $@ -cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS) - -quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ -cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS) - - -# Define an escape_quotes function to escape single quotes. -# This allows us to handle quotes properly as long as we always use -# use single quotes and escape_quotes. -escape_quotes = $(subst ','\'',$(1)) -# This comment is here just to include a ' to unconfuse syntax highlighting. -# Define an escape_vars function to escape '$' variable syntax. -# This allows us to read/write command lines with shell variables (e.g. -# $LD_LIBRARY_PATH), without triggering make substitution. -escape_vars = $(subst $$,$$$$,$(1)) -# Helper that expands to a shell command to echo a string exactly as it is in -# make. This uses printf instead of echo because printf's behaviour with respect -# to escape sequences is more portable than echo's across different shells -# (e.g., dash, bash). -exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' - -# Helper to compare the command we're about to run against the command -# we logged the last time we ran the command. Produces an empty -# string (false) when the commands match. -# Tricky point: Make has no string-equality test function. -# The kernel uses the following, but it seems like it would have false -# positives, where one string reordered its arguments. -# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ -# $(filter-out $(cmd_$@), $(cmd_$(1)))) -# We instead substitute each for the empty string into the other, and -# say they're equal if both substitutions produce the empty string. -# .d files contain ? instead of spaces, take that into account. -command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ - $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) - -# Helper that is non-empty when a prerequisite changes. -# Normally make does this implicitly, but we force rules to always run -# so we can check their command lines. -# $? -- new prerequisites -# $| -- order-only dependencies -prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) - -# Helper that executes all postbuilds until one fails. -define do_postbuilds - @E=0;\ - for p in $(POSTBUILDS); do\ - eval $$p;\ - E=$$?;\ - if [ $$E -ne 0 ]; then\ - break;\ - fi;\ - done;\ - if [ $$E -ne 0 ]; then\ - rm -rf "$@";\ - exit $$E;\ - fi -endef - -# do_cmd: run a command via the above cmd_foo names, if necessary. -# Should always run for a given target to handle command-line changes. -# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. -# Third argument, if non-zero, makes it do POSTBUILDS processing. -# Note: We intentionally do NOT call dirx for depfile, since it contains ? for -# spaces already and dirx strips the ? characters. -define do_cmd -$(if $(or $(command_changed),$(prereq_changed)), - @$(call exact_echo, $($(quiet)cmd_$(1))) - @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" - $(if $(findstring flock,$(word 1,$(cmd_$1))), - @$(cmd_$(1)) - @echo " $(quiet_cmd_$(1)): Finished", - @$(cmd_$(1)) - ) - @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) - @$(if $(2),$(fixup_dep)) - $(if $(and $(3), $(POSTBUILDS)), - $(call do_postbuilds) - ) -) -endef - -# Declare the "all" target first so it is the default, -# even though we don't have the deps yet. -.PHONY: all -all: - -# make looks for ways to re-generate included makefiles, but in our case, we -# don't have a direct way. Explicitly telling make that it has nothing to do -# for them makes it go faster. -%.d: ; - -# Use FORCE_DO_CMD to force a target to run. Should be coupled with -# do_cmd. -.PHONY: FORCE_DO_CMD -FORCE_DO_CMD: - -TOOLSET := target -# Suffix rules, putting all outputs into $(obj). -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD - @$(call do_cmd,cxx,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD - @$(call do_cmd,cc,1) -$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD - @$(call do_cmd,cc,1) - - -ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ - $(findstring $(join ^,$(prefix)),\ - $(join ^,kerberos.target.mk)))),) - include kerberos.target.mk -endif - -quiet_cmd_regen_makefile = ACTION Regenerating $@ -cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/home/fmason/hub/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/home/fmason/.node-gyp/0.12.7/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/fmason/.node-gyp/0.12.7" "-Dmodule_root_dir=/home/fmason/hub/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos" binding.gyp -Makefile: $(srcdir)/../../../../../../../../../.node-gyp/0.12.7/common.gypi $(srcdir)/../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp - $(call do_cmd,regen_makefile) - -# "all" is a concatenation of the "all" targets from all the included -# sub-makefiles. This is just here to clarify. -all: - -# Add in dependency-tracking rules. $(all_deps) is the list of every single -# target in our tree. Only consider the ones with .d (dependency) info: -d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) -ifneq ($(d_files),) - include $(d_files) -endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d deleted file mode 100644 index 0bc3206..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/kerberos.node := rm -rf "Release/kerberos.node" && cp -af "Release/obj.target/kerberos.node" "Release/kerberos.node" diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d deleted file mode 100644 index 2ec56f5..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos.node.d +++ /dev/null @@ -1 +0,0 @@ -cmd_Release/obj.target/kerberos.node := g++ -shared -pthread -rdynamic -m64 -Wl,-soname=kerberos.node -o Release/obj.target/kerberos.node -Wl,--start-group Release/obj.target/kerberos/lib/kerberos.o Release/obj.target/kerberos/lib/worker.o Release/obj.target/kerberos/lib/kerberosgss.o Release/obj.target/kerberos/lib/base64.o Release/obj.target/kerberos/lib/kerberos_context.o -Wl,--end-group -lkrb5 -lgssapi_krb5 diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d deleted file mode 100644 index cfee5be..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/base64.o.d +++ /dev/null @@ -1,4 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/base64.o := cc '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/base64.o.d.raw -c -o Release/obj.target/kerberos/lib/base64.o ../lib/base64.c -Release/obj.target/kerberos/lib/base64.o: ../lib/base64.c ../lib/base64.h -../lib/base64.c: -../lib/base64.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d deleted file mode 100644 index a313cb5..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d +++ /dev/null @@ -1,71 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberos.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos.o ../lib/kerberos.cc -Release/obj.target/kerberos/lib/kerberos.o: ../lib/kerberos.cc \ - ../lib/kerberos.h /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /usr/include/mit-krb5/gssapi/gssapi.h \ - /usr/include/mit-krb5/gssapi/gssapi_generic.h \ - /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ - /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ - /usr/include/mit-krb5/krb5/krb5.h ../node_modules/nan/nan.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ - /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ - /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ - ../node_modules/nan/nan_callbacks.h \ - ../node_modules/nan/nan_callbacks_12_inl.h \ - ../node_modules/nan/nan_maybe_pre_43_inl.h \ - ../node_modules/nan/nan_converters.h \ - ../node_modules/nan/nan_converters_pre_43_inl.h \ - ../node_modules/nan/nan_new.h \ - ../node_modules/nan/nan_implementation_12_inl.h \ - ../node_modules/nan/nan_persistent_12_inl.h \ - ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h \ - ../lib/kerberosgss.h ../lib/worker.h ../lib/kerberos_context.h -../lib/kerberos.cc: -../lib/kerberos.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/usr/include/mit-krb5/gssapi/gssapi.h: -/usr/include/mit-krb5/gssapi/gssapi_generic.h: -/usr/include/mit-krb5/gssapi/gssapi_krb5.h: -/usr/include/mit-krb5/gssapi/gssapi_ext.h: -/usr/include/mit-krb5/krb5.h: -/usr/include/mit-krb5/krb5/krb5.h: -../node_modules/nan/nan.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: -/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/src/smalloc.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: -../node_modules/nan/nan_callbacks.h: -../node_modules/nan/nan_callbacks_12_inl.h: -../node_modules/nan/nan_maybe_pre_43_inl.h: -../node_modules/nan/nan_converters.h: -../node_modules/nan/nan_converters_pre_43_inl.h: -../node_modules/nan/nan_new.h: -../node_modules/nan/nan_implementation_12_inl.h: -../node_modules/nan/nan_persistent_12_inl.h: -../node_modules/nan/nan_weak.h: -../node_modules/nan/nan_object_wrap.h: -../lib/kerberosgss.h: -../lib/worker.h: -../lib/kerberos_context.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d deleted file mode 100644 index fcffab4..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d +++ /dev/null @@ -1,70 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberos_context.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberos_context.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberos_context.o ../lib/kerberos_context.cc -Release/obj.target/kerberos/lib/kerberos_context.o: \ - ../lib/kerberos_context.cc ../lib/kerberos_context.h \ - /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /usr/include/mit-krb5/gssapi/gssapi.h \ - /usr/include/mit-krb5/gssapi/gssapi_generic.h \ - /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ - /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ - /usr/include/mit-krb5/krb5/krb5.h ../node_modules/nan/nan.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ - /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ - /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ - ../node_modules/nan/nan_callbacks.h \ - ../node_modules/nan/nan_callbacks_12_inl.h \ - ../node_modules/nan/nan_maybe_pre_43_inl.h \ - ../node_modules/nan/nan_converters.h \ - ../node_modules/nan/nan_converters_pre_43_inl.h \ - ../node_modules/nan/nan_new.h \ - ../node_modules/nan/nan_implementation_12_inl.h \ - ../node_modules/nan/nan_persistent_12_inl.h \ - ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h \ - ../lib/kerberosgss.h -../lib/kerberos_context.cc: -../lib/kerberos_context.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/usr/include/mit-krb5/gssapi/gssapi.h: -/usr/include/mit-krb5/gssapi/gssapi_generic.h: -/usr/include/mit-krb5/gssapi/gssapi_krb5.h: -/usr/include/mit-krb5/gssapi/gssapi_ext.h: -/usr/include/mit-krb5/krb5.h: -/usr/include/mit-krb5/krb5/krb5.h: -../node_modules/nan/nan.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: -/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/src/smalloc.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: -../node_modules/nan/nan_callbacks.h: -../node_modules/nan/nan_callbacks_12_inl.h: -../node_modules/nan/nan_maybe_pre_43_inl.h: -../node_modules/nan/nan_converters.h: -../node_modules/nan/nan_converters_pre_43_inl.h: -../node_modules/nan/nan_new.h: -../node_modules/nan/nan_implementation_12_inl.h: -../node_modules/nan/nan_persistent_12_inl.h: -../node_modules/nan/nan_weak.h: -../node_modules/nan/nan_object_wrap.h: -../lib/kerberosgss.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d deleted file mode 100644 index d4cefbf..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d +++ /dev/null @@ -1,16 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/kerberosgss.o := cc '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/kerberosgss.o.d.raw -c -o Release/obj.target/kerberos/lib/kerberosgss.o ../lib/kerberosgss.c -Release/obj.target/kerberos/lib/kerberosgss.o: ../lib/kerberosgss.c \ - ../lib/kerberosgss.h /usr/include/mit-krb5/gssapi/gssapi.h \ - /usr/include/mit-krb5/gssapi/gssapi_generic.h \ - /usr/include/mit-krb5/gssapi/gssapi_krb5.h \ - /usr/include/mit-krb5/gssapi/gssapi_ext.h /usr/include/mit-krb5/krb5.h \ - /usr/include/mit-krb5/krb5/krb5.h ../lib/base64.h -../lib/kerberosgss.c: -../lib/kerberosgss.h: -/usr/include/mit-krb5/gssapi/gssapi.h: -/usr/include/mit-krb5/gssapi/gssapi_generic.h: -/usr/include/mit-krb5/gssapi/gssapi_krb5.h: -/usr/include/mit-krb5/gssapi/gssapi_ext.h: -/usr/include/mit-krb5/krb5.h: -/usr/include/mit-krb5/krb5/krb5.h: -../lib/base64.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d deleted file mode 100644 index 02da394..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/.deps/Release/obj.target/kerberos/lib/worker.o.d +++ /dev/null @@ -1,57 +0,0 @@ -cmd_Release/obj.target/kerberos/lib/worker.o := g++ '-DNODE_GYP_MODULE_NAME=kerberos' '-D_LARGEFILE_SOURCE' '-D_FILE_OFFSET_BITS=64' '-DBUILDING_NODE_EXTENSION' -I/home/fmason/.node-gyp/0.12.7/src -I/home/fmason/.node-gyp/0.12.7/deps/uv/include -I/home/fmason/.node-gyp/0.12.7/deps/v8/include -I../node_modules/nan -I/usr/include/mit-krb5 -fPIC -pthread -Wall -Wextra -Wno-unused-parameter -m64 -O3 -ffunction-sections -fdata-sections -fno-tree-vrp -fno-tree-sink -fno-omit-frame-pointer -fno-rtti -MMD -MF ./Release/.deps/Release/obj.target/kerberos/lib/worker.o.d.raw -c -o Release/obj.target/kerberos/lib/worker.o ../lib/worker.cc -Release/obj.target/kerberos/lib/worker.o: ../lib/worker.cc \ - ../lib/worker.h /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h \ - /home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - /home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h \ - ../node_modules/nan/nan.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h \ - /home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h \ - /home/fmason/.node-gyp/0.12.7/src/node_buffer.h \ - /home/fmason/.node-gyp/0.12.7/src/node.h \ - /home/fmason/.node-gyp/0.12.7/src/smalloc.h \ - /home/fmason/.node-gyp/0.12.7/src/node_version.h \ - ../node_modules/nan/nan_callbacks.h \ - ../node_modules/nan/nan_callbacks_12_inl.h \ - ../node_modules/nan/nan_maybe_pre_43_inl.h \ - ../node_modules/nan/nan_converters.h \ - ../node_modules/nan/nan_converters_pre_43_inl.h \ - ../node_modules/nan/nan_new.h \ - ../node_modules/nan/nan_implementation_12_inl.h \ - ../node_modules/nan/nan_persistent_12_inl.h \ - ../node_modules/nan/nan_weak.h ../node_modules/nan/nan_object_wrap.h -../lib/worker.cc: -../lib/worker.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8stdint.h: -/home/fmason/.node-gyp/0.12.7/deps/v8/include/v8config.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -/home/fmason/.node-gyp/0.12.7/src/node_object_wrap.h: -../node_modules/nan/nan.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-errno.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-version.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-unix.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-threadpool.h: -/home/fmason/.node-gyp/0.12.7/deps/uv/include/uv-linux.h: -/home/fmason/.node-gyp/0.12.7/src/node_buffer.h: -/home/fmason/.node-gyp/0.12.7/src/node.h: -/home/fmason/.node-gyp/0.12.7/src/smalloc.h: -/home/fmason/.node-gyp/0.12.7/src/node_version.h: -../node_modules/nan/nan_callbacks.h: -../node_modules/nan/nan_callbacks_12_inl.h: -../node_modules/nan/nan_maybe_pre_43_inl.h: -../node_modules/nan/nan_converters.h: -../node_modules/nan/nan_converters_pre_43_inl.h: -../node_modules/nan/nan_new.h: -../node_modules/nan/nan_implementation_12_inl.h: -../node_modules/nan/nan_persistent_12_inl.h: -../node_modules/nan/nan_weak.h: -../node_modules/nan/nan_object_wrap.h: diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/kerberos.node deleted file mode 100755 index 2bcec8ec0121131fd8bf4a7bd02d25f4198f6fc3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 85259 zcmeFad3=;b@;^R-fC0org$3~%6&3Ix0fGTU6T-km14IIX2ZoSLAQF<8OgKa|Y!YM~ zN8^33(bW}iyb(o%AVJpyT~}Ez@T7;hinwXJZiK~9=Me(vhjN{eyJC#w&!8p zTuG^}qg?}BgQmJy)+VK<4oFE{ol<)=N9xwiHPDqn+Mbv9Oz6`kA@%H(9&0lby5zXe zopV&r{rTATj-%APL=Q4eX`M1_U%gwdHTvwRu<+ujS=PPi%3cro`y#~M6 z;rDv{-iY6u@XMc@@p}t?Z^iE&_`MUqP5AvQe(%9Af9};6*L}FI!tebCegM~p%;!gN zebjvBWi@^u!|&txeGjk&JH^*Q{m!|%c8ZrPK0U)^UXZSvf7$LkrB zZt;$7$v$T8irc=vcIm#u-+JPK0T)iWzW<80w+?#Z9N(QKE0zyG;NzYD_~wAWFSu>^ zd0(#W+q3&gr@l7(vVXh!5Bu}7e{A*MKIxf%HXJ{9MR@*236-zBx#!u?w+Fm3_n|&1 zeLkPp`onF*XWh7R_YI4mS=m-GKPzYR!5=rCwPnwbzD2uQcJ=*uVgDgRavr&q za!%G>_dV&ot8N>9$Ii8V8^&~R+jzp<6}OzS^|;4g$GE3YT6)sn+lDuGJMyVzecyWG z$;T5*-uk@c&TP*=zj|x>mOXcLfBC}KXMA?=+Rv`Nr0}(mj%(A zto-S+eYXww{i*LWFCOyN6Cbwpo$;@WW*&CTZ6%ILjix$Yy21lzj*rD(d4S91tOdIz z1I~SrjWC~|KDcxISU7iQmdYIF5by#*y=9=&dumyp3en8GcTjal)`8RMg?;9u9$=o#~-V9RFl}+8O-=apqeRN6$yZ zi6^JW(evmy{=Y7c9+Kk3&((3}^=X_qd~FlB;6K9-5YsuAJD0yG&ieW*{Gqct;T;Iy8GaY^(3yT#K%Ymudbt{>YZskqJT)xy?d7U`K_mR| z8~!AL{vgoTZq)Gm`r`Tm>x<*eepw@qG5BSOKg7GHX~cMgFE-GL*d{6HgTmFOS%b2R<|$jzUR%=nE)&ese+!;F(+#u={3 zT_ePQdbyhZsu5orJau`HYk$}IuNs8841-@$o|GnyfP2f2!oSo*$`lP_S;@~bqlaBa z500MCmG$1s)oeD7>&?9OA>VO)*9E%2*NjtO_|_I{#5ab)56JJN-?BpE+su5=bnI*R zI{NfTJ>Sc<{Si&y!|;6=bsfj4yjJ6n(HGY|(ND*H*%avcK-VFz?TJSTCCKFGEa>?t zoIEs{bC^_v_sM$i<=WNG?#Fc1^saXFFDQvjUNt}KQ9=0nv8xNKddwJN^KG{ zmt(J!jQ(9_d`EfQT))v$!2MF zxrQSCQ~z78(}?%s2mEO@{#?0A!{x?L#>CNc1<1s&CTn^pNB9ii_Hp%2*q3(9Y`5;_ znfbQY=iE5)(^XI~cR@vYLAAfI%3o06Dkv!}FLf2TsR#jN)ug=LIR^ah?#t-u>B;)_%GI+b1w81 z`G=+EmsKp9==0~4Lu*jOgi>Ewu?PA*ck-Da%kV7L`1G?2%W8a)?rCY>!t&xWUw%eAM<2L_lV^Nu}u)Jf}YG2htUlm07wN{ZVVi!HB8IUAx*bHCc z{OrQAvN?rC^F33~)b_WL;|u+TIrjAPQ(rKQ5ZvumoV;9QZ$-|fK8DD9jV+#_MZS*}q;994}^75>F#d9u8t z^cpW-V=t`iG+9g$5sbT>!o@n*S0%HhpF{{E>sBl3lxY=pc0X+f-%v*q+nqxxkf}y&niJcXdeJE^vHaFRcZO$v^1DtLRH0r z>Hd<8Sn2c5ESe0jPovnHc-oRmpN=&cV3cQZk*|{RGTl>ERZ)d#Suj$E6fB$qGrqAr zW0Rg^#n1nUV5pX>Y~C*24gFt#ZmmQPKig#2)<>Sc$CHc zc#!~=M^AIOKu4*TqVd`2(}R}b1<-wJL57pcp#D;LoIywQNk)<`oY{=>7FK5$*36w} zR-Be%!~{gavWT7G9=04@_h97=;l!&5!UUk<#ic&D5?s|+RaIV5P*#Bi0u;xrk!aoL;EkPFQgHaZ{JKuRdnVZpV2A)`bz zV8m!}&yHNG036m%3V671R;JRgP0|G?lz#EB&K08*NjQ4ODl*-iWujt28 zWrnE;v&u^6mivnHDqvq<6+?QA{5oz&RW&MRZ6K?lF8ZU&ijEe$(pY2t&&SG$k&LBJ z`Tu+{N3eXU7yl839F_*jVkFUvT|y^TT3Wk-rDlq(QYVu~wq70i>S;ySY}&~73_Yd4zSuj4 zicYwgQaoO6vyzk@TJlF=V>3BFiG z(eSc8pIo@0eN>Ar6QQE01RZA>tD}ybq}s_(cWT9s1Ziogvtsiu?b~sFJUQ@J_)+h6 zm|%v3>7-zd&W5><3LU|XB;>-!G!BZQ$G;@YkJ@`q4Ne%0h9mXbDNxmKYALcHe?7gJ zb(b-rqN>P;ac!eRoJhV!br@f|5v;0Wm!4H{Qv41{@As}+7PG zr~rikcf2u7B6L)82ddKYi)u=%d@(&8iKXWp2s&~EilZWE(q$l2WP~7Sc~RvOVP}qC zI6XOPfhPPo_h7-T&m~YI7i1Sqo>nkD-!rvfa@Hh|^eZef0#x~m3otdk%fx&vxuX=W z$SB?^`P0T_<$J~#V7Rk$vOA6zqlF?2@0wpVC%r(_;3!Hkm4#I>hVWZ3AICWhDo2jc zv_(a*6%Gs*`XVs9>tvx(bA5j9IZ$~mz#(AaTyB@4m*SdA-Oe+sb_Bu{Ll^r%Sh2*S zqw5rvRu-07I7d`!wy=o1;TR*8 zi^@5(=&;(HW1fx;W+8NFNE0?+ zVAM{v?^JLds3o;VZ0jV%SliMibUCXJ?^x|d@>C}!5VzGFS2od+V#t%XP?Fzp#E(-Z z6mlQ5BxhQIC!@-TDx@0pew$=4m~EM%=LtgGtkUpZdF2_&t^!{$yI|PKBO;%MTc3xWobJk= zIWucqPC*)^6yljP(QyPrwj*xAu!2cB({vylE+6$RC07@Dnp^{k_{>{{`ZjAfJcHkz zk8lZ2Kao#5ebbixy5o00)5;d7jTGkAu6!b${X-s6oGn3=u8T|GB-FP|yJ7_PqHO$6 z_l}MsP134w*^zq>^yucotwH%=FPAIf|B?T+Oq6Dn+?#W`+(6|Ww*+?zd%7+Mjz0;I zd4_4v1l*^z6nFTNTvr>M|BzBV$+Dm876aD|Al%(`Z=`=0*AUajd-nf$bUvQ2=;3fgh(qr2^S)5IQT&p{wZtxd2#TYwFRD_&Z5?Q_eOtMz92r2pAt z;s0#mU2SfGNYC$~I6p}i9=F~jKPeVIIf8Y$`dj!LExg;pn@1<4b&!R>$)ZoS@NNsA zVc{RJ@R=6=Nel0_@cf>M^OI-cA9Ikn&b08yTlm=)-aJwvt@AAW9Tt71g|D;li!HqK ztPh)OE&Np${Yndeg@tdl@aY!*W(#i~g^<=J3*ThXud?uWS@_i!{#gsZ#=@_*@XZ$f zdJDhV!Urt;77K44<&f5`7CvOrZ@2J^EWEPti!J=kCeARP)LQsv3twsB`{U^j{zP-K zZggAtTQo}k9c1C7nbqY=weUL2>P{IJ9*H9IlWF0jdEJHQqN4KXysNw9S$HR=vt_1* zN1}@S%(n1OzGmY*3y(w+`Kh$~skjvI{@KESZk4MuYKdUXg^Gp>R*I4+z5o(vK*}~(|tH{r03y(*6B0pO!eE$g6 z<=SfDO-h#5?G}E3MXxOUp%#9Zg}>9n@3HWQS$J1MRR4!t_#_Lz&cdfy_#-TQe+z%4 zg?C$c%}F;7vhYV+^r;s97z>|a;RjmyObdUkh4)(c<1Bohg&$<$XIl8d7JjycA7bI> zS@;tye5Hjy(ZVmb@F!XLS_^-&gAPaxGg-^BcnHE07!e?3dObb8G!h0=z zwuR5L@Z&A~Obc(H!Y{V)UJGAq;d3nfN(+C6g>SU*XIl81 zE&S~kzRAMpTKH8K-fU5%b+v_`Y|*c=@KY>&vxU#I@S83CSr&eag`aBSw_5mo3%}jM zKWyQZg>SU*yDa=P3%|$0Pq*-{u2KI#+rlSV_!$;H#lp|D@ck|PITqe+;m@`3gDm`c z7CzO&KV#uDEd2QvKGVX_vhZFDe}RS1v+ye{{7eh~Hw!=8!WUThc@}=Qg|D>mg%*CX zg`Z>LYc2eh7Jj9LFS78B7QWcR-)!N17QV^Cmst2!7JjaUUv1&%S@<;;zSP1uTlfnt z{ALS3-@O_!NEgpY0Me}2yGYCEwTvd@$kF0)I-FTZeFy!0!|0mLc3I@Y{s{M7UPqR|#{A5Uv#X zCBobqgl7x9mN2&j;XHvKCp>^~roaynK9q2(z;_d7i63?gd@JF@38x5rEn$}KVVA&H z5N639-t`OT|7XH(!rKMDm@tz>c#FVQgjuqOn+3j*@G*o}3p|JLK*CJ|pG%mfdAL#F zsf3RsTr2PygpVg&DeySLg9y(Scr@X`g!2R*Mwq2|I8)#ugij!xD)7;SPbBOXcmUy( z2&V{q5Mh?uVVA%?2@fT_>u0e);Z(xg1>XBC;55Qp1pbaNOYCs7z&i;KC%jtVPYJW6 z4mSz>K4F&9;YNYqCOndGt-!AmW+@!56!;~=8H8sGyp}La-*BG5j}snEI8)#U2#+D0 zD)8NeS+a)R0^drQrD`}u;A;u96b-uszJf4I(D1IG#Quac32ztpV!~O3w+LKCn5Aa8 zS>Ou^XA@p6@EpS92{#FRE@76A;YNX{5}rV~R^T%TPb6F^@HoO=!m|Y)O*n^ep1{Kh zpFucN;30%r3Wie!KALbYVYk2o2u~uMBJe?kS=xnN0{0}$k}kY!uh^e3OS$lNf%mQf z%n~lVMd0rUvvdnL3%rwXKH=2@e@d98SGY;w_X)G)3O5S;Her@p;aY)TCCm~lTq*EN zgl7_-E$~{x=Mc^l_;JGL63!I(0mA1IP8IlW!Yq-(Zh>zl%+e^FBJj0@SrUa^0$)Lx zrA>I(f5rZUXA|Bo@Wq4+32za&iZDxR|-6iFcVOCw!otamlDnsco^Xe31N5gtrTPG2!Kew+LKC_|Jr!1-_7Q z9pTji&mmk-xJlr12{#aK1U%gv>b(lB-cb4>VCoHxy$`aj?T>bE;0qOkNF@0J3_$WD zI1*7q@z1;-u)5Y*ll)-bMF;rB68v=it*c}&wU*YuwPwCNv+ zr4M!6OuEq6wYW_84&FoBx;+Oh>N0Bs3b+yMjRNkwS#8@XuQ$}~8clzNMZbPeS8w1Y z@A{pmdlR;J-`Z0no%{Ba&Tpf$H?XPgQ}(YNdk*@!YL55TjZH=~SO&iE?~i%C{gm6K zPQsE<^WX-vHg!t{VZ!$tO865|3c95}jBftpAl#JITDSq!;sBsAR@;_Y;Taep`N&!q ze!^$sbF_QobZ_uiLIMWM4Sb^x!vws67BvvDjbu52P2S+dw%Wy@8k6=TN&X81 z8hxZ;T3;e59z) zk`6WZosAI18|>;0Rs&kx9~K*h<>_ts(VIMemwNC&ZEZP$mxHdlJ#GH9tU&$1Cxw1# zlDDA^b@~`A5^rFe8qO=~bx16d%?cj{Od~t2Mu(iBCn;-F{lF%CPRIdr6+X1Cfqp~X zUPW}E+M-H}iUpapAR^)7{%Q;q^=tAx_@kERue`>{a}6-ROPtQ5J=pf-YKSccS*Y$Q!iL>a%-=MgBZ{R2Hp>l(d(wDLHINMwT{;q|F{U4-{BvD zFSx8BNI^<4JE@_$W{zXp(aBFw>{YitxlVOGHDS?-s*+2h;RA0=b_x{f@*hlp32gHQ zGn2^qJcP(b{b2)A$T)<1q>v{#m(bW_7a@fp9k|qx?=VWJ_c6NpdfoiPLNu>nb1yVU zS2)%a<pBe0Q8?SV~ge~XT< zM@&(F!x(khNeR)}jL_nKfoWhiS5e&aDDL^++Txb9lUK$|u3rgCBju@G{1=FtFU_b^ z2@TDG>?D6L!$$H;uQUW1NH-s%n_oh0w3hXpYDBZFKZ*4!i`0P)Il=mYH>24b$absO zW#uDi1X|LX5jFhqn_;R2O2Dc^-jMn0T%i&=^zW}io%X*xwtv(f-D>WKE`HtKd%vfe zbTI0zUgI)oXYVBVZRhsx*7vu@AFOVT8NaOE`0)SpW`#$7gS34Y=GM;s-JV+Y8}biU zqhrS3zti#G{TkzEIpdpL9GbNS3pZ7bqQheu1~#e5P^2e#kEAqp6!7B%UosmngnYa{ zLYE?`XS2GNoPwUs@TycXUQS>m+SJ9s=LUADIp}WN)9dhig&j4&k742nzsG<#{JI-{ zr&;`tj>E5~;rAV`o$@<}9W}pln_m|2hTo0Q59jv==I_k!anWnX`O%)7-=E|03$vr< zw-57(%@jZ8LSv{Ll38*_B5$=`Bz&R zVnRav4Sn@)>M(d{?Q>0Na3$BjjS@09_*dp;RRXeS(YY<{?Og4_eaIaae(fu{!dKNb z5FX{__~3I)@oE?-#s~J1=yFY@UKENJ)sLM+>BnFfX+|a0dKfP^uotrA26n3=f$psY zQ?-MiL-(fQv$XC|FJnZt1!yqL4K1!z8}WHkLtAqFPhD7@EUe^+FA84_w?mDW;dX#r z1t3Lk$k&(~cxo|5Wb3A#7&%zSyxb9ss~E@QT-4m!BZS6H`KsMJ_|B1eQm1f?)>g_TDyl>?Rka3kaTc>Ne0_6reE^nIPe`Lgn>83N%ojhQKF308 zyRI3msEMmd15FsER$^$i6gcqqhBBc-t%`X-dF$43Qt*o_Fi=i#ktp~AN0=SzGio&e z1-Ga{BG0-!(5n;CcT&TT$@Nc2w~?H}AoKz$hM!529MMIL@_)o&M)@ZQix%~S=uRvD zJ+a_ZmFR6$@f4=0n%OH>`Mtr_DF1QV7-{lHwOEnPQ9i}Am47b8;Vh~!nt0T+)K*ZG zUoK;a^1qi!?p9;4G^za0&{W^-Pf?>OoL(fSV<@)m2idWd=w6c=KKCDy6FhYwYxUmh zVf4;vNgRk4l+8QTGK$vlfxm|?<=XPN-%*R`c*{3(#Y!=qbwO5v*_WmL7`_z8){%N0 zaBm#r+VEsdFbcPY_qL;dEQY=*u(a5S}k zhEJ^@;~&oDKv=HzEjTEf`>;7|T6RNMtP<8ST`0E>f!nGC zFnba9bg8*JBKsJGkxx)+c?0iDQ(CjS5RI+x+4TjZUrykc7YCs)!k@Ys6e!{lvy$t1 zFq9L#gL|6Xz^B3Cs9ciNA_&V5TqDoXBH;c6u32@bwfPU96u6i5mskRGz!o`tBO0~* zIl&3ohc+~UAOT9qYH46FgazPJ4H8Q)1a0d}j(jLyPlWuc7%aopv{dA1A)*gQ{ydCC z`L})T7<$WWK~zCgbj8GOwU9;xE5F zpIbrR`l2%l!-6lXq?k0K`+Grht6>K3PT^%tR}S*_>~kP!=8B|}weCt)ND zXvsLk|}A#rWG364}rGs)2`mSy$SwF!nIz; z6Rx*lLds7#l>RX0VsSk}s9My!UudqA0UNH_;M%$p<7c)dKb_gDZqH?x{monVO_J&f z%OWt`k`qiEh-r37zIu;j1n!@)PivX2=3$zQ+cZC^f_W)O99LZ=WQ&v3RtO}~@MZPz zXKihv#R+n}<1K1a>liy5nz61B_CfDSYfgJ*Eyh8IkGWD`gIF)5z)AGV32AybMRI)> z=#5Yb$yf1(Us@u_{3l36?e4=ovjW{ol@quiNsE8KP=c7-%;woBepbGi1P*F7qhkv` zVcfvWDh*(6XqnC~ZE74Wr4A7zq!&s3MkmEYg-G*8QP&1I~ zNRA)uz3O&1wA1$!TyjE-k~m)G2KFMh+ct#m|xBkl_1r$sR@SaG>vLq2j6OC zfTx3ulA(5}qoP9`XHW+KWe40$eSX;?KJ^QZO9^@R)%`bNVTpu`=@`J6@$6?Y>vodF1}TaAb$hxb*B4-g*6rzk<-G&Cn) zbwpP#(uv?)fTGa!G(*NHmu)&s+24FgUs4bV1DQ=dD}XAN~?Zq=zLA^rZbe zOQHgUZ*u({jBQ1VA}#|aNkoeKOplzv5t9PtN#n;XPD#G#$A*FHF~Ls5KoDId47|<0(J=5CbgW)rqZ0;}Lusb=ds?*Zgn`XQ z_ij+rd-~(5!@$=ZQ-^^fx>Ts!iCCAvCkzy$&UL~-e~usQeb>!y@bCLRE>0M@0OPAe zgvmB0xP99I_WwZM* zob@|!KImDQJ9ybjd3Zwb=ORFDQ}19j?5rFLuBQTry(?-GQ%gA-otd?E6T@BK0h($h0-sH<#Vq@!WK2l z@cAcT!{^lx!RImDx|en14R(pdwReH!-1dmQH>f5K66|}{O>S2jJ{-jJvIC5VT#tca zc_x~FLETKpKOoLg!B`&1kJ;kx%-G0}^e2+MEhK#gB0Pli!L6hb@p2lFcD!5x9Yo+r zitQ>wVSl+vZT%oNsVll3m)^_C^`&4NP3pOUuUT=*OH$RhocI|s@k|7OZ7Rjga}9Ki zd6wST$vhu|Rm?oU#gsXT8Z%D>W7I>*SG`3S2zoKoFiNE!-oP7mU!qjnmyq0W21vcZ z98@?tz3TpZS@PARfT-JxnnvHWK|fQ|TyK=vUk2A28jX}{=a;8A8hv0t3am@M!#;)& z?3T5cuI9w}+FisV&YgpK)7RbtYQ~bNW7h9NTUNengVAZBXN2hnHI!5V><4lG@n2-xrXC_mynHto5nJ-zCVXHj zJI={>>2zDOWxL$uy8|%~5?unA>ol710>I=3XZOpgy9Dn&Pp*G2k%m6lllEiX#Y}aJ zVpH8>n$@hg^Ff*$aOVap;V)ffNua|;z+wrHhj?5e_em^}!V1CDDSsd1)SSGxQ4Ir_ z8>-Re?{1ZiMXrt@3AFJgIP#3)0Kjq>5Gj9e$3&e20h~VQ@;5iIPhBTn5(ldH@qsph zEvV2|=vr-JW3Uen6;S?iA7G-|3(z|FneumwvB4mYfO8`^t~&4ih)g}QBo zcV}%{(F9jU`MVJ1@85L!`-m=oSFAw;=yF-W2Uau#Qf_h!_P+lbH~9Dc6qlUPLMeYs zFupoU*n-a{)g6?I_JiZ*hUU#y-S8RpY;yhcP;E}oKTy}dTPc=IvmScEbV09PfhJ)a zoTNzk`-tQ{%so!tgDlaFiX3L}zD{m%4vtoKs1Gq1^WHm{fOz^+&4^MqQp)-CyiodA zvtm5GFR?J->+kWpL3sogPapj*g2#csn0(~$@f$wOd&1{n^uUD3XAt>x zW3iEs&+z$3VBz!jKf&jI#HJ2;?+roLV@CAl9cmB8r{bE}8TqfVle}=fFla$MRsVw4 znHT=OkK|o-`r~`EBf0At3`mN<3&p|AejeeO=|cXS1Z*VVVZU%GbP<7By-Eu0iZR6H zURGP*X_x=#f~NH3S*D%;@@<5FRl0o6gq1!^QV<3f0Rj>{CE_`f$*1|1L0}^a0yz~ zY^pred%^{f9``>nGteY~uTFw*U|d)TsdE~X4j&Acf{A3+Nid(Jxi)pPxWYD7D+0-e zuEC%dL{U`+b#4^(qB!j~HPJ!sR;Pj^Q|1VuWO;2+qtKDzE={gG)FFoCK;26pT4GZs zjQ2NO{(~#^E%#sJ5~>L!t3gGwfq z&X0+2i@fSel60CMk%k_Hlho}=Os+owzRJ|cx3bHAurJ-)tKi(Q&#CL@f9S7m({ShVpr)nD&MTq?ufy%O6y*w4#Ecj*7-6L z{~!$G?1z|wj(?b_6aTRORaZ_tlztfe%hK4xVqwHTsE0oLk-$3sZGjWM0wB`t`CLdog$^Hkf1xYH=zil35HTLD z#C#ZUQ#lCEfv)Hz9u1TUNjxfrSd2$spt}{dVMIJPbFKvc$8iX>R)f76+Uv7z~YM&-hhvc1w-yX&Yy-5c|8;#&0F%I zohJ?V2iaG0DpqkamfZ{eu^{x>?6;VMQ-<=-q~rz`r?e|Y(dh!TKyILRLxf|N)I|CP|6#W34)Q!Rxd^V}2pj6C%SOHRsUX0HuMg6`= z8M>H*=_&rA!!%dRIIf6j8F~b!DkXSlWoV|ckxAw=#P@0;DC(uw`AzER7yCD`CMxdOlfl1KwIeR4d ze4P>KL^BO4Gm7#U)JYBs_ve9Pv>PB}ZBqy7rq)(j`5V+hXm5SjaOr0H|68t78B7(6 zY*X($sNL$#SG6oHK$&v}yIwHQ6q@^6UCjNh0eWcq-q6=E^`3-7=?`MER8Cum=y0?*8=y7m?%c(P)2x z<+YBoK`v%fwp5^r65(81?{auw&A7j{vENF|JJIxIbq+v8J-xASQx{^Uit&s>^_J@f zm5yudf%XPWq0qG0%|UZiMZ-$ zdbpO00sdM#YpB}^h_AorK>IUP$IgNFM2;Wqy=A!@+UeWl&y1$}zE%jFlo$VCNz%Pe z0;S3TjKC%LwNAumIncfi7H|%=a0cN}x)?gCB;{ z_ruq;5C_-bqT}GD7)O0YK8&TGK~OMaG@Op%7~IC9&7khakVFlMqJ|o(eo@q629?M` z^%m&AFN;*_TQuphcw_E+ScksVD%Wq+KMd91L4}TH7Zr1!7#sf*o%kmm#9M}L#&miT z4yAv9Nm|N$5^N;?Va8PE=fYNQo&9U0mamW`9pfKDN+WU2?-HKy^zF#lgT(e4;m++ms;6G+Sf$d z>yH!6whS@ujo%;%E zz$6lVj*LesLJ%Ep#c(s{rP#8nN_U4ZC)bytd$g>=7M*3)a!ep5TQp1NF^a8*%Ve#b zkYu<@eLh17B85||iR;fntB|b{GE9|2;du}xOG|`Yw?0Cn$ZXX%PJh0Is0?IaFe<&IJ%!&080&PKBg9)0 zg}S|sg!Ow8+XJXtoWxcRZ6UGkzSs@z^i5qFO>9qsld8Z!Cb3Ner78gIB({8fmc+JK zR+4^TV=~7JNMiekc-l64T7O0pE3t8BALmXj>bHm=gr`VJO`|DYj8Bk-QLER5SwHtl zGBd`-BPIM2H0%DL6FY7JfsP$l<5Nz{1eW}+@TX3{D8CG#Z2mk)j+FFw$^oPy#`7Cz z>;A}}2fzg*`4agv6H-QC`)=V?6EQ}(3;v0oKOnuG=s`X#hK|AkkzLO(G`0`%xx^2n zAfd5ci5NpfH<1)6@LBNEIZ8baH(;jA3>bKni5utB{QMZIfKF8~#t8{_nE?+1FKk8!divD(#MjD^5@+k}{W zcn`5~_VXb>1M54&Q3C5L>+~$oB1y-5I8*im|AA*l_5(M`VB1*FJk$)9mlF=94~k`( zCR8md{DNj#2-qaUv%xaDAGjG}b3c&D4#B?PF6v}IFhcY$`++53`5XIzvoYeY?FWt{ z$9DUHE|}qO?FZbh_s|)C`-a;HtxBZ!H(Y=AU6! zgv}rV>F)`f-%HJSc{5^%I)&p0dpFle*!(Xp&VFDSIH?T$V?6qBP^v+Iov?WrK6ls; z^b>g{Y~C)uw2fi&6S}$;Hviw*56sX)a{ZKXf)fdc(rZ!ISS9SY@N@dW{m*gw8`V*u zGVAA0$lHO2olcSVwmSZ;(ej-|lDP2?c8bP7 z8BAC{1mmd735U|3KP`r3nouGBVP<4m2-t~#U}?oah%NDt9T5MjI*Wgh8}g${Q%k_o zj(<|7;lMvlif~EmC>gEiZv0cF0{=vOLZtqYc7ID2aC+6a7^#;ERf`&Kq<&D$E{bY; z20q3|mZUz2+&;MME~!HAZdZlAZNz*DcvIB!Ooo3bokfAV8|_XEeuGF@=Tc~bG5Ag) zvd&~42O>8(4^Lz)V+`i~B95s~T{a76Q%ARIMe+Q%`RUl=cMJ7wqJAHYAQd`JkI{q5 z{a9_o1g%FHn>0O!O0MUrkpz>#$*EPj#_KK~cv$C2$- zxaDUGE%kDW99|CRVG1<9>Wt_(x&Be+l*Re(=snJ&gKz6r_s4BG-PxaU112jB?SVAy;Z_ zJi1G-40Vo?>n*@Wu1!xsu04Cr^KYY&Px_!S`~d`Vo_`CC-AMe;P!(6M^~&!!fD640ZPTSz!2)MhRl!Nc!I+=1^csUB2!BFDg2bP%lc z_aLqVsq@8YerfC=n3{LWf>_j|X?zhq*!LvJE<67n>Szq(d_6s}7GF=-?`X)w`oLGV z_wMnhdV^E37s%^xz7T`=sf2oebt;XYen$o`V<(;h9~cSYRG-H=T3$-)8z5@YM2j`i zVEEBm5W3Vik43D$5g$3j=OJEH!{+<0czy!km2AXv(64q_{uN)C=MAh|43z4DE|?j; z{|Kt$zqD}Z-qr9j;Kar|)H{?1E_5Y``7}J!4U5F{SF`gs>Phg&yJn7^??%fuwmc3~ z;1r8T`q2G1Y8>?wN`DScViLzr4md{0aQ||La%;Ejs$E;qDpHRcC2BXl;=M*yAn3LnRj+s3C;=s*LHfmK)O z@$eQsYgm{ve{8gRBO0Aqqr*yem;-6N!FBTaX=nkn-&X3Tn>iG##Uq5mQG_~`Yb6+x zljqi}bD3pHth!{O>6&;I{GG5qv`b8#!hrIE9cuo|Kb1|sZ7vvFIw=1fr??I{F0NT>i zH=L@`(-YD|zVZz@jX!bz9D4%BZm*|<9**j%M0A#3FgM1ZW=l+n)zeorO?!Wu0e3Ze z`cPb4{As-?NA%QP++l~>_mI|8cL)nTtr#Aor`4ik(bEt3XzS^pG7-_!xtu8UG!-Oj z9eIS-rD*RU`tP7rf0OQ!b=ShF8a)N2$HS?TARIk${?rrWQF}e@d@!n~(?nS8DrzfdL?N7Ieazsxb14}vH1yB0Z$Fx8wy=qvDo>mg8*WK&* zXzS@=nTY6V7$*va3;~I{0slZxsZl-s6_n~y=^oM3oiLB1ry}X`a9)g_IDg9bBO2T5 z>7@tI*{r)iaiCy&fiFf+DV(#Wh{UJc#q-+fX+OBD(bJXGqt??!5*$TOPm4S3P>+Bo z_4G6?fQRzaV)Qgyd{O-AUVOCm)F2ZPJ@w>7p{Fh&Q48=7^pqFX(^62Xv!#1PPmAah z#-GMWkB2K`^u+m7Pj8^Hy`FBpKcWTowdgE;VsVU~l;|YZpZwx^?ew$_CN_F1W*@Dm z9C0Gi(^bGyjuqfZJzYf$gwiLb#^@=7SnW^C@X^-OESZSt=~EfDO})%l;Pfq8Dct>NX|JT3Rp@D)=@n5}`qZKrC2bIe#42fu zxLrFXt%ZG!l1^tIt)zkCL87EmU@1o-cv4BFbh%La2)q;3%J>HptCchpA8jRNz#UAo zTPMS|si&ZL(Rea)D7wxvJIv8JSj$)LSlnbbEdt5!W)xPlOR5;>b`7SzL90A^>uNn zJ$I`;qJeE{JBV6a1=*%P1G4oK)JJ4E5<0{?3_dq)Eo^()v<--DdysASo3?#WLbM<6 z7pNfH1E&3BwtvyOU5_j6^U)qIL3A-B&ynQQ){itvqdJrA6Qb?6#SGD?PGI|S(e|b7 z+Iz9Rd$j#L(+*>U1;z&){t_;XEi6tYxgT=g52dcA({a}$FJUUgNVuQXZG8dvSDkLC z^!^~y|4sCW_P^*}-GBM-?tdp1NA!IWZ$a_;nV(ZIQe+>T{@4)i9wP6H7>&ku?~90h z|Mx#~nnd|zAiUmbW?=g5fk`*FcvfRu;ZkFv4LOqXG$z+i!d62z3op77(RP$>gBK^) z>u(Qw8goP4K0&a}3H%G@dzNHtxj%Vk zryKf2j$X^r17CWJwlI(-yo-_5R~RN(b8}>Pz17;L20Fw056AF)tz67|6|CoRBD~uW zFu|K!JI&tao!ANQO7ixs#s;}z0Hkfb5j)c4!O-M=AP(Qnuo)V=Zx9eS67dia`gs$1 zU*Phu_CS;M&ECLM8R+c|+>j}kkXL5jkSCYWOkDiOB@b?xjStC#LzQxwUYk64R%7yD zUsLkn1*?+>*EA;&Ube*>@}%U3Lj6IK6WD{(keGS=gfEfmH{^Ij4XL1Mk+;(%L5h}! zM8MEJ9IYV*AH6|o1H{2NEDqjUu{2oQ|YiZzs5q~IQE*WDoHt*MRvN{9j5LX54p z5GKo9{#PV}6mZk-z6yFoKmVb*f!Rqd?8ewe?MQ6nn`5}yfAV+{Zx7U{Jd#rz__-A? zV$5Xw^=MZoqM`NA(H*^#JwGxhh^2 z<;4Nrb_9q2oaY9wGn2fbn(bb^d=xJtRo-BV>f`uZ%}LhG-uRoISx$?K%LZPkUzHY> zFE|NSOAjLQV+K>;fq|FQARc!$G;2-xS4Vo8c|LR;i1`M#OolJ4oz}ae<5}@-khku1 z7rrnYTDD!1wQ8a?bxV_6{@&gYUc7<^wLfverTz6G&ZV?qOSaYq-oC1_^EB2?U09R* z7J-On>l2yWpz~;}TGC-QiCWIB>So$E=-JvCo!DnaPM}S{Bo?9Td++kER&j*jWo~ba zrwJcnArDc!t~S>-a+Q}7ZN7`CcA{Hj@G_#>F*w8G>YWsvf@7sAn5w4vX*J3O zu8i>m>FyYD{J=r{kQ*o-2!7-71x$hVdIRGJ!c)c%Odb09nf!uQPJO!e{ z<2l9Lz%DDH^ZD2sNc``H=B(uFU&cENqdFUdWGV0 zUCFex+>w_xeTOMPe~oNbKR^(PzR3-I9t8Sn2B${W86;{Z5%xG(=8Lf!)kt`NkOy8$ zuK$K@b;~xp{Dn;%>rTY2F9q|01smWH%R}#fgQ9J6bL$dhbb*I_Vg1W z%IN=E>I%Px6|McerWyU!hfN&bv&vfp2?L&{@L(Z;cPv|@lA%CoHYYIAP1@}M<*9VU z3(HS)sC0A3{2Iva37j0hN=6y)a%mf;YIz=oDY5=m?Xe}|6PdV+(d-RfjCa4v+*J3! zm?0e5Tz%C~^qdz>JGcYRJl-R|kP8WHp7Z^}o16_qbloPG7TaSh& zD&bh+3#iY~*cKuRfFSFf;AQ<=?~c?jSj%C9>K#$}@~>uMooTH%G<|~?&Ecom z8%#VFGjKto&3L_OOT#MDf{&}6j}1_N!x{tOm1;fjunqEW8ezoJa<;cYx zXA}9Y#myiW0*U@V-Cd;S4;v%MFYeNS#i*Ror1V+?#Z< z9&w)-dYw#?u}_?0oZ|)vB$&yh&Bfl~`-{5Z56KPdiCw;tYPFoBF&LsWaE*1$Cirp) zlDu{ezAriI8jX>>^AzV!5%1!}@DeljFA`mtDTeReM_;G~N2-)!s*NDFT;>KCB|Hi) zW5tmKxKWJ1oPu_Ubl8#bmnWgr*0A~o{i4Y@_Wq0GJ%2|TlIP_!gkay2Wx{k8CN8ik zMY7xmrbCe~)m$@p&0Kj=CU9Pj^K3EKt-PwOunh#o!?)UnlIy<)nkL8E=Js4YO^SeL zi#OQq(0n)aT7yF7TUqJ8tt@9eFqQ;-|7pQVsPfap10h6c>`AZ!BIJtiE#1r7z7iZz zsN_Z0HcNp_=(iegP|tQVj3JnGlAy2`&U%*0ki!ZZZr)9in5?@N9ztLA9D?MWRkyv1y8RZXcRjyUsFl0( z7%&cv-2xp$xr4v6lpFqw_$u-gt#F*S!hM?11wtq%vIr>Msn7-u(olhZl1=r#SNFeG zGn%XWH-Bq0N=F9>G5Iif(3hBF_#GhZ_YrrfC-b<#+SQZK-zK;eU1O$5jk!wW`fD8A z0d?m+y02T~U{v55i3=_rq^r*F-~~uj+Wmt|Q#JNOjn#`GxHLm!H)*Ua4UFK`iDxyi zmLFtMj9;l&ryVNh->Q_z@oV*}E>?2_|1rtnX1Y`GvWyP(X{RZ;zb$RuQa)gEZx?1> zd3!9}tr-rL!o#PXJhFQBX5%vcIYHU}!4a-Iimn24UBWtHHzHWX3(`J7GHyl!8H_Qb zS@^Fvnk;-VoQrO4668hJlwF4B8W=+Xpr%ndX~&1P>Pdr)ow#bb-gW7G&{4;r^A zF%_#vUe5IzM#B=o6!`vKAUPX(KAKM$ws>m6#-;vtz1&A`xRktu)q@~bBPxtqwctA4 z&>Iae9!rsezFNq@u1x@4>Na$h)r(V!Hxto)&4ip>&*-841z9Z~_e}g`ZSoAn2?bv8 zzov5N{Hi(WMMZ#;ylV=|D~f&deN})`yldw8sw%1rX3hlEA4##B`W7=plw5fTM#b#L zK@`Z;Bo)SP^}UE((+@fT3ikzft0p~*`Wx8+w}^JDOQF=Lhw&Mf4`D1P*z5;7o)hjt zKL#BJgB}9Fp@lCOx#6Ypfjy`ckJ^IAuNtO8 zMfG@LI#>C-7|~OYw+G9EOu?F34uN;DE^Aa{;9S^L@K1s)L$&mydY|6LmgU!C!~Ow- z!}S}qi`0Mgi*qi96wvI&fjC4|H$$%QOK3v=LSlc8!7^-~+eY_Dx!4GNboS~KGBR;? zEPU@pRB@3%iMW{vqcj&X-2!Af zSx@Q~C<|d-*NP#;(O`amL~A4wNk{#`1Nqh2IPtp^WdoDEk$n@65j}{#NMSIYTRn&Q znDC!TkH>mp6Ls&N`ba$vT;bq|y(Wv9FrLV_mexomLRxiX z2^!%reIR-s7EwfG=Nm$4ZnS}N(4<}zf;%E>^ghf{R|~Tv5$Yr45yYnt50{)az150P z;d6e9)L)vOp)9>SNW+7riFO>ju`k@`d^lD3aS^^&42AU)iHvt*$r@XHx))jx`VhM= z8JM6-8fgp(Ua45T3|`ksJj+f+@N&DtIl^YV=q_+W8NL3`=o6HW;TyyV!cYAK9>EN? zk!~CsyM(g}Y=Zju{$Rvhd94c?`cc?Nxo}J#?M}pBh~VQ#p!lH=5FsLzFt6uyL`7`y zv%!Z3UE(Z*6Mv^(yvot*6um!6)=FK33kn6-PFtxzpfh8`6_^L22ZCr5e9((1;@Alr zDlF&lGr~m&hY++9buM)Tmx{QgKgB7N;96n6%>`2!MoC{qmsb2OA}zml-jt-?gp#7? z*$E)j2Yhoe52xP7`;QN%4kPE;7ostGo*ml%DXL}q+OwxmpB_N=`66rD?w#xZdt{bQ zwu4_q^_)`oQa5kWUUeC|LfqtfzD6Re?&mJv!20B?mTR@%4JDN{CO>^}R^3;49o+gv zZ{3Ej%{#l)eR_KG(|!7_JnQG=r}KXqpZs+8zV)9bW;LtCx=&L*$xkl?$cA-)9eFH8%Cu7x>ws}D?JULU%C{`;n#;ikO<#DtvnD|Fbup` zw<8r@5-vRz{S%sZCid8?Mf=mrvl55`M{vW4Ky>kj&Pv>r)pac1G={pBf9y!t*BAs8 zr=iQ*v6y%3JC2?MuiB(AUd=&NyGN-&h+gJV;aB09&iSaWWT0C8XR*}vP;DqNGqkuX z^qaG1eOs5hmIS`Rw-y%hvm z$xn|sFtc_aG8QXvZ}JQI2}0Hz(D>vR68mMh_NH_Y;a%pmK}e9#?y6 zKM;JR36^%PYa>A$IK3(a?`7AXdLRg%2jmI7wEoL3Fn40s`n`#{p>q<(_josRWm;Ap z3V)7#an}0ni5NXMbXJ!an3WeD;4S(tEBS>HY3uiO8Q)_QwpR(78f?x7r8jg@*Q_w zbztoBx$rQHSUW?JPo@Az18xo)11`hp(a;?|ANm7-Z|fnN6XEemE~U=@-WL7k_x-)C z3WOf}?`;(j?&R-n;ruEm@T0us+-!>LzQTFg01A*B!m)GY?}G86!#1^_cr4lizGi4( zbL20AWuaB>Dyz@0)bsd?q@n4}dehj3zi_hAd47;JF3wXI^;0cZL#{_eUx1HS&j5xJ zTGyNN9!R%O|Me{_3;B~}M`+QkKUp?e|1q*M@}=0$A0!K!KUQ`cVzJy@Q#nSovqUuR zw0DbKT*S^_EJGauxrS1%$lohFQXOgJvQ%itTW_%24ddMKlVAONMgz3+Rn0CKLZq?WTo^b zRi&Si=!2<8ANBU1Z+-vKX3F=WysSOpXspUGZ;Igo)b9N-X?*{sH!ovX9pF5vTz)yE zIht0*JLouv@G0zo=T=$#hKB$^O+itv$7n1c4}-YTCGPmA<(%>K|5ps~`}L0PBd9HakNL1FYiMfYQkd;JxERR4Fwj*k9U zp!kCR7ws?l9|SY#_Yr*E0BP=)1@RmD?*snS|LqXz59$91WHj-A3_$(M-I5sp=l2ZY z`|yA4cVrE`&07cO;vU=w{weAK7%tWZGl8+!z?*T`K&Fcesuva%4pBa+c>?#3LRb$o zFo0PPr>=koCUQVyk1_ZhV~^3GF!p#6b1>^65!(H|>j4X(8!AN@;K!a~fcttm23SxJ z_D4addd++d+lT+d9OyKk{_+`wE}Y%}pZY zp@#E)g%7A$#$frr!m=@L`+x0=8u10;dvHqq4a<6CyKwRI}|V9S14Z2(aiT1 zZqh`XHPMnJ5XtuyP6v_62Yv8S{2%kM^{wl7+}Ga1O2w_pAim6dlUmMspAQ({yXeh% z=r@StPqz+Z-kSu zy8kG`crZW~nTXMk#$i2x7U!Wwe!=g~OWAX`+I<wlccB=*| zHq-9#)5b(n0@mtTXW$Uv5cdoYjYz=U@yqLP&6ai7Vf( zf{Dq?Djr%!G4XvLOqu7K`;#u1K31lV?~98QIbT|7QzB3BsU(gb>ia0BAGs%Db~QLZ z!ee06$PQINS)k8}n7DeJ77e9)VnsinSo3$i8u1yT=S4;T3;kz_khG|y+KK+{C0g_x zXp*9zMY>@6&QoYLocFd9{cVheyO~Dx|9lU~IRfiM^m`}^M8A@YY&Q*vLwS@Nme%hQ zvudsX6Q3b^WmNRfpiuRKkhG{0jAmNi9W zQx=H+7M=f8jvPw=3>n%I{Y%k}7JUH8qwfVjfpTN(3#;JoLE>u5ed$sT-KO4!{FM7+ zjuT9OFI}trP0ATrC3rsx#)_(Z`FDVRMdfJ}1acojx$E&yZt&Rjk$miSQ}nUh{h^wU zkKOK8iJ*5LyUl=E|k6&+0dH%PAWGjp(66w?YlCsZ`5DdwtOR_iP?E@Qz^j< z@7ocpY*VEemT&2kzav%#Bp4Zr5oqY1pveG$2adSyzJh`aI<$Ttb0s-$n6)dPIt|{|X4=pb&=Wl^lX8{E~ zc^*io`Yx&|t@2f4^3{-`w8-bK_E(jb&vn;Sm7a*(Ab#ImUzNM0tZ*)9%8Nl)1WnE< zESm2wsVOg_KFQG<$5P^n?utrM6qdP*=AoOfd~RfX4%TrfE#FC}<$!S&`b{YHl@(`K z)X-(zw66KFn7B);-Q^W9rM^SshtSpj!tx^DugT?~=fe%2>Y6g%2Exr9!ZC)P>Z`7- zD6a;#1d_zIX#-o6tAXy^<%J7C-RZ32=_f9^tfGv8G)=&V@h2tJ=|ZvPLwe{uiF^FD-IU8{(c^SU!666p5A$Hls&t zFCDZnWAx};M82|9`AHL;HrRdMqEi1n_cZrdw-e~Hb>N$25ARx7QCi$_XflX1a7=HP z%g7gJ7=-R@6HNw*Te~SEBf5hgkDIfW;3u}1<+S4lx8oQKE-bC`*C70KF2MA1qzxpG z_&>kif9h}acDbDX9jtR{)Kn1Q*y=&YRu6U|VVyjr+BLVjx}bDHWkr?0fXi6J$PES6 zzM=vrKM7H}MDG|}acOmBS>cjs&l;VMNYAh@qZJmJj#XF%F(WyM!lEKyWh}=9^O3t3 zR3Z@T1j_U(o%zrMWT;$HP*hY{G>?IoW74j-rgiSzlXq^yJGb7QJM_+d zcfT=FwZEduSHRJWAZfMaPo(8iWOj|#YqtQBRMy} z-}H~m-?TgY+kXGgX&^m)MEb~6GDeLabLv>r(Us7pYht(V`z7`0*=zsa2PCH)c+kOp z`u?e3|3fsvfI|;E{D>pnM;(34z+;a)e$e0{C!BcF$wO1qh7FhYtZ~`nJrgE+bIv$3 zchcl3d1p<{pEmvM88gp0w{T8Tv9DzAywVHjmn|r-sJy7E+F!G9(c&c+v$K}tgrSi# z$wUv-VLETRoFwG(BkuY9;>adl`HHh)JesAjtUB9x46V`er}K6DhvU!xT73Nfo7V*l()~mEy zM7?d%Yw>|vXpy3}mR6-$AB``dwrZ>vt*^QN+I#IYXU?1h;_bcn`|ij2zL~Ypzt>)S z@3q%n`!RFQE+2}=H-jDl-3Qu?Rn#cxKG4a?uNkYvTF|#ZH`6^h$f1C;C&wgYMgjc+j^%CzIapLp?z=A4Iw69&`k>7F1y2-2qw%x)!to^dRUWx_=ly zxPiX)E9eFE$giP4(9MrPF7_Js{T6aT%O6Glper7a$G6e_LC6QKeFA#Kc1rUI$_cs+ zv>9~rbI>E`k>^of(6uk19YLqR2)StYeV}VWryqj;Kx;ww6Mh)-XeaMaC@1K_myj=L z$6vq)O6Sh+C;Vm93wA>1yazy!fHs2Ch2I6_l{PeAq~V~#f6B?o+<+fMrUJ$PBt&3o zJl+G{im~}MV<(@Jm%Ti5mH6UEKKJR;si#vy;;F`G#Xvkhj)2Os`NQcox&BHB!Y#$O z;Y0Cga*nSuYZ(_3y-dc@aU;aTrp=c`@qPhT_!vTC4cT*Q9|J_o`79Rg&2 z;ICfqS%<%r_|h-5a4Y^7z*devli)wc!rzp_KLPdM4E~!;`BwfY@z<-;C_Pn!e=_>w zQj;I$2~&AcoC;!}lRXu2UEo`E96qYwzk+WY_!8wkcK!B%KNEfa>ZJTvd(x{Z@2cz? zB9*Gd)E;kuf8WLN_$N&MujIBGpzZNUK&+Fb-oeusmI}?cAzV5sIgx5yo~SprWcBT(*2M0LOLFS zoNiF>SK*+vt*g4KY`I;DKY~voe7oc~j?cda{EIYy)$#eM-)+(SXB?mZ1@Mn({_NxP zQ@<<3SR~8;DjfDP>RSfc)bAF7{}wOw^QeWt<~yD%yz71Etn;tV@a*+a>#+Nf_V@<) z4`QsUg$y$fv?JY;9w+b^b{he@4Atb1=C1R>AI&F$a})lk8vL6v#_e|Dm;IqZ@t+Nz zcTw(gjDZ`e+{2b~*Q#=_^VhDg)7N1vk)^%rcezlu)lz0ECsx2m?M zUZ$^B*~|2oAbst+c>FYssa_fwbsg(;{>XlSlSh)0%k=kB|GO$4{}j5Kx7yOKPU(00 zNKlxwm+9X{`pMtJbernG(URV={x8Y`u)0HmwzOaDu0e|4Nc_4|I5d*5yBe`{&HoS*BjMIjMK_IDcD zC*tX;81JA(zQqRbrb?mjQ$MID{@dg6KY-QSY~`o+Y+CP={owm!I0;gyars@8W7Ylf zIG&eE=m7m-0YpXA^UQis`Y$8C0`e!A@fb(Ao)mux z$Ghc!?QzoI%ki}&U$>#9A3ufo9_0TM=+TTf+qe$Cp)iefLbgSE&p}rh{TY4*u=3Zd zaojUivg&Rm`OgM_V0S!z$eKU<=5H&(ONo&2PX$jG$p`<(Z%-d!=Hz({L&V~>wML4h%c#Hrr$zTd0MLPmyxa! zbLK2-xv0KRCf9cj_{x8Uxh(9_EKgGTA2J1#-P{3wdEgVmCcmZKA47aC=HNY)ue3|p z?HoBj@Qjre3um{JMD!ohH@N^hb8ok`oT?o?EzI9X{AftxF9ZMd10Q_8+6Mm3;J*%O z&GJ@L-wdz!LE+@>+ekk2E!!XbnZJ+6H(B{-U*VafC&Y3y319&rC(yn?-HbIev;GO`@z!5`eRMD{VDVt zWUK57e!Cg~#Or@Y@tNEc~#&y4BwFHMw&Y{TH(b9h3yY#py_zZZq)kHj$+X~enPOx5WQ6ZZ z5518oUP#6l;7w zgxC3ez&H7j{`)@PZ!*PGzR%zd2L2!hrl0$7N6I@%_CuNYpViwGTA!t|`bOF`F%8>@hr=aT^AWHQAwG=ZIfsUnsmvU7x zzRAV7e5{C#pcqf2PgpZnyqw+~&lL}NijWBkfbcsWAMne(NVP#0<6$bs+ujnC|8^f{ z>s$Px8*;^AD#qH3(0e)J`Ha_4jK{J=8*;@RIpt6aWqBQa-9}%s7;jVP-^St#+P|F3 zf_;nF-%*w$>7jqm6F>1le` zmHAK)O0!(q!lo>7(PxFYF)cKjDV|UJ8!~;)GvVzlan#fNw=D69x9B%n;$5!~VORw4 zE65hE@%iq}5|5EBto8?2XNi0Kw;<&U8KIlA#7&tKkQW)lm1GPz($}3?$aR!$qfcf1 zYOXdzG{b9YZ$iKkPY5P(o$o5tU}wez*vD@&n&A^}$}GA&S3I8SLm0*k{4mM?YbF`b zkFrpVr?P@DldH!34k<6qEfV7QqLezCAs3Fk9U1 zxfJEz<)qY#I(k>c;!(ERn(J8q}12k7fyj(&t+LN4o?*KWexoS-(!jpeq~I--ihM!Y#+i`W)shkvS;j>2y-90 z6W=*S2yeRC$63^qgGj5zH){hDO@5_n{RR+TJPgu#KX{o$nBamA3~3(sf-uMmYsyrqrT;5S>iv_)}$ePXZq0X zS>g`Q7ZCodXXu73@v4`?Kk^O1HQeI=9KtX9hc3?&&t=pgd~4=szL}*4ly6XXK6#zg zz)209)WAs%oYcTc4V=`#Ne!ITz)209)WAs%xN2Z~gNj-;Pth$*_cQI`cvk`c&myqu zl~>lOit77`w);=p?q}KV=h*Jg=X-4Z%4;RxV~by2&DDxx%UNDuen?Sf6T99ilmOn* zCa*%KA7MJe@w9JE7wwVL^|$xqF`}bf5xq(dOe9nY{G=+cMcBip3tQUqdXY0$yW#l# zhjIFeOkGnX!A_C9HgH9-+a@pUhRbUb(|y==piARxaU=>|x||hUF#3ssE}h@|aaI1! zI2wd5{E95=qsu+Y_Y(su{_lLRs)-YYjw4Lc7(_yBYm~LgdgXvzT2bdmWdX%ZZhVy4SjcJH!4bz28+nEkB z9cH?T=~kvYnC@kIfaxKoN16KPaQ;lEF%2=TVY-lMJJUg?!%R0Z-O6+a)4fa&Fg?Wd zC{uqe=g)K+(-6}drVE+2GaY0)%ybjetxR_?-OKa<(?d*;GWFMS{!FJa4Kb}@x{zr* z(?O=gOgAyz%5(?Qy-W`3K;)IXQ=XF82(h-nSeg-qL-4l*5Px{2vlraPGKWqN?=A*M%}`s+D=rqh^)nAR{| z$h4j5Ak$%{o0x88x`XLnrU#fFVybdY{a)l%<4kIdLiBj5)g2{_c#)h~+W z6C1_y(a_>{+#oJSPpydJXou0>i|2HVjy9y#cM#gzYD8DG(ql9zXjfFpFj{(hTUH7w zLx(SFMM4rrIYX{2Wy`Y8RtSk9Z+sQYLZ}QE_w|Y5*4VOTc!a{P$Pal>^O_8N^n79; z&sQ{^YLn}=-52BjD8_!BUe9+l?cxYMf626^FUNg0K03Xg4{5qz{@EJ8^D~c5ujeTh zz)7}Fujf~q>iHB{BAYulY1xfb=w1()W74r0FQHKwiUH@*Rv8LDaJx%rekkXIA$DV!#FsdSzjV?VO)>O}P zRjkTOhl%##V@*$IyVIqq{7=1t3_tx~=4k!jq>Dd?SWzT;LBCY8IPbh9p zr`jB?Za*#a7F+trVHKn4Eb82ri}JEw_u_`K(DtR*JG#gBTq^Fz$8epo^f69gvFI}3Fd)Il( z2>yDF^B<=f8Moa^Ikqk)IoHw~K5*mrezP<+A5* ziAo82P&z%1S|dI1HhO$a#yvuhd&#(0=2UrfgHh4y#J_&9U_CK(?u zw4X}GPZ8SxB;(j!(SF4e;SmKw`wI&Udzy&;UucD7*du6HW{Lwo8SU3q?lUKYJxAIY#_O;S6!zw&i#mHyR5d3GxcQO7Q6)k8yCjQ1o1!#N=<0FjUq@u+x z#y6a&fTfH-%ea`IjMFJnB)^AoE&p`jX(;WM{ffVhmX zoALR;Nk5CYU3mLYT+94=|9Twr|3van7OU8vD;VF&{Cb~T>+=BcW7+M7dz1iew=c1r zz)po<$MP@qse0{aT>hsVaoVm{J+2trnE&U@AF|nlwyRY;j$&T}m10-GFd zSB0Ff-L3@7(R$E&9(ha&)_R`d=X$Yx&EE{%NpG#d(?qHt>tQ*ffeX&$GR6Zod^6+r z-ywc1J_bpAT;Oyo^1#qoHu976Q z4jm8viXSReK68ZNdWl;(RrqEX{27+h!vh^XTS(WLm`FP1Tjzp*#Rb321>XsLyvi!+ z`w4NtFr*eurRerUKhyjW7jfLP@49TC*_F2ktKX8%1$A$lC z#(P*l+7BFMeEaoEu-4n8Jm-4N0Z#V6=mEw52`V+m;;{eS zihB+Bqw~>-PVz66c(&Lzr1V!9pyPIg;iv)iX!L~{%Qf^J&fyiX$S69 z{_ncrBT`Os8R_n*3;&c;RC)HZ{lHVmD*)Un--zUACJSkI;ok||Y5aQBMb2S~!=GQE zgx|vU;77pRvwE zj$kctr}8gy!Jl@)GqGRlRL}Y9Q|&aD!6?2 z0)iPIb1r9*3ts1fe?{WZ{}v@*`|U2^WG8Rg)`=H0|CSpR{~<-h6^s}DhXUj~91y%! z;>=_rk4X6zfP?S2@aLo9ob2th5{I+?XC*+-d#iyv>HlIEe5VWks0%)}&{_U@F8D^^ z)E`G|{c(p2{{i4m^?lm~pEyPJqtOLIUWOu~7`T%j=DOf3fji~9UgGeFJU^#r|LJM>)>sS5KOFi+9*zo+h4JCu+B>{VUU3Yt|uAwPt%vjjcH4qJl z!w^^>EH{$g+fA=WZw#Fu>&5%fDZV6-9IxJrY~`>^pmHR|&q|gc-^uRG&?H|RoyuUA zQ8C!csI(FcB;E)dEU~@=nKcp&S;1=jTS#gnq>_c30tQqPoMjk|^TUzI1xC$+hN?*2 zxebP)6>rU=x+FYU+|$zAUmPq!d};yQBnS5q~Fy_>sJG-*pF!}}-8+9g+^{fT`;_VdY z7Ho?4L$KYo*-O|Yk6J*tZD=Ynl6@PzAY5HZps_awr`W$zi;`Y&Q2IWLGY!r;vHXrH z-R@&k`mV)y1e|=!hwO(5cjT;jtF~Kv`|&#J_V!|oD#kfg^NsqtrU*P;ThwgS{$)mM zSFAhQhj&tQJ0~E+Xp0$3x?+o4x{NlwQygzAA6S8-LzeY)Mf;;|#i3aMz**36j*-9j_+!^5PPhwpz$0e%?;Z^3S1HI5Z+S?oJ6*0W8yqCie zhB4AGif7J{r7`bj!DX9qp}bw!l=HWp>kebm6H{bl@X4iAXugbxd>iA--S25mr(yo zJt8FBdF=PG%lFh{%l-Zky?5>4VkD!CPL}T_3#y(RcSpa zM!8QKx@pSeHk+Yg&N7>6mRX&c`svTFc}Lou@BaQ8A~!Zg!PXQe09zLn_Js zvVRx7q>SsO4bkN%qz;);dv7$V`+ZV-@mw+(XfzKMs*|RYq7Bp!j&x>2th)+F6wn{B z6GM!6_OSwskcQa{D$n z8>Pi%BD$ipKe@#XgSa7tj(o61T^L!IGBjXLZuH>%p#FBFwPR@_0ZCVVnN7I7Cf3^; zMK>n%3)SM-l&&a7z=S%QN)6lwXKKY&_G7SIJkTFS7V`i1Nu6(IQs<)yMMCwuCnOD_ zaws;tp0qXTt@(HjyRDVcX-dJ8c`Zw$T1>c+WawUnYM|ZCdLYd6avI!AX>bo1<+>y= zjLt?APO^X$aY7ndhI3hBt%(Mt?hlPCJ(Sg8 z_0g5^Ajz7b$ptE_?UwB${NB#~C^@%qV{2z)XD1uRtftN-I38r6H!58P^kZ0* zYtgL{Ozq>OP%IQgTW7RH40LyOc3X^(%budzs>BF0lSUJqbd{R5EM96->YS)oN(4KR zGBPHzkAz8BEJD}V)ZmOT4gR*SknkeJFIUdg-Xyg=yaLlpoR1Z5#9R=XqBZr*nwC~f zWmeWjjBt5x6q@Wd`ooccA(YQL#=B{4JP;76ZT|~1^Xxog!@`s zdT6jyE~yE}^F%SCB=ss`)J5i@D0+U3Ng7RDAf$McDDmWj%+5%O(hVPXqajyHN~QJOkqOAJ%gGiVN1Mw^o`Au=<^`I}nQ zrHtZ1>bY`$+JMI?k2xAbhe2!CO?7S7_6e47^XO(!>t47%c~~f_pE8aI%NAhXOQ%-- zgRREwC&2(YcQqW#1w_I>SZ9yqDyg=q+Cu&N%-J7wok*|yvFgQ0&HcY5(9{)Mjtbe_ zp_(8piT10F2V+?jOWh^OgBGhS+O1WV5E~4k-E1P=$^-8qH#(9{oUB$KTt`Q04fMI# zEi#?So-i~=Zr`XL2i)vadbCRP!tzK=EvmsR2WGjfl;v=&tCK-Usn&9mZMc_GJO6Ul zc=CW$gEL2M3QHOiQMeEj{bx;Y$im*t4FwsGVWCC2KB!bz$`4N&T3ER!fY8^fL~f31=SV*D6ok zRY&n9ReNS62IZ9|X78z;BXu6H2R^s07|YVr>Uo;Vur<)oR4E->Vu?a4IPRGkc4yI8 z)q9L_*J5=vVQlT}X~AmRG6grN=XJ+0A4K)BDU;kiP|9UYptrq~tyI-d2%<}e+=Z04#u5?QVOk%zUzJvmsO)M4eB#LD;R z`5Q0PE#0%O&+MM$IphX|-Im(g zToBTIY9yP2jFg&BoVw~%2p9{Lm+EbTAw3T3c@iuGZPVS_gVwQ6&*&6PoK|`qLohBZ z#b!q1T=}y(a@7M$>IBSmq1b0~>e0tq)&v8!(Uu;zQrpr-RW`{t@H&tz$Z>@klFQDh z%j$y*N5)sKtPVR7_}v%_P#o9ow%&3omEI$#4KNx@)ov2z9EoMx+*aC!3XkzGLj^VLk$T0P&QAewGxdf9SQUps?DQLpn8|$KJjnjHeFWb-zTxfGA zmiGb3?rfDzof6Pl>S`Nt0d@}!{H_;v>KAZoK_Q1iIkt4u8PmOkovr#eIrOd6U)l5! P%l;=Z#GwXJZiK~9=Me(vhjN{eyJC#w&!8p zTuG^}qg?}BgQmJy)+VK<4oFE{ol<)=N9xwiHPDqn+Mbv9Oz6`kA@%H(9&0lby5zXe zopV&r{rTATj-%APL=Q4eX`M1_U%gwdHTvwRu<+ujS=PPi%3cro`y#~M6 z;rDv{-iY6u@XMc@@p}t?Z^iE&_`MUqP5AvQe(%9Af9};6*L}FI!tebCegM~p%;!gN zebjvBWi@^u!|&txeGjk&JH^*Q{m!|%c8ZrPK0U)^UXZSvf7$LkrB zZt;$7$v$T8irc=vcIm#u-+JPK0T)iWzW<80w+?#Z9N(QKE0zyG;NzYD_~wAWFSu>^ zd0(#W+q3&gr@l7(vVXh!5Bu}7e{A*MKIxf%HXJ{9MR@*236-zBx#!u?w+Fm3_n|&1 zeLkPp`onF*XWh7R_YI4mS=m-GKPzYR!5=rCwPnwbzD2uQcJ=*uVgDgRavr&q za!%G>_dV&ot8N>9$Ii8V8^&~R+jzp<6}OzS^|;4g$GE3YT6)sn+lDuGJMyVzecyWG z$;T5*-uk@c&TP*=zj|x>mOXcLfBC}KXMA?=+Rv`Nr0}(mj%(A zto-S+eYXww{i*LWFCOyN6Cbwpo$;@WW*&CTZ6%ILjix$Yy21lzj*rD(d4S91tOdIz z1I~SrjWC~|KDcxISU7iQmdYIF5by#*y=9=&dumyp3en8GcTjal)`8RMg?;9u9$=o#~-V9RFl}+8O-=apqeRN6$yZ zi6^JW(evmy{=Y7c9+Kk3&((3}^=X_qd~FlB;6K9-5YsuAJD0yG&ieW*{Gqct;T;Iy8GaY^(3yT#K%Ymudbt{>YZskqJT)xy?d7U`K_mR| z8~!AL{vgoTZq)Gm`r`Tm>x<*eepw@qG5BSOKg7GHX~cMgFE-GL*d{6HgTmFOS%b2R<|$jzUR%=nE)&ese+!;F(+#u={3 zT_ePQdbyhZsu5orJau`HYk$}IuNs8841-@$o|GnyfP2f2!oSo*$`lP_S;@~bqlaBa z500MCmG$1s)oeD7>&?9OA>VO)*9E%2*NjtO_|_I{#5ab)56JJN-?BpE+su5=bnI*R zI{NfTJ>Sc<{Si&y!|;6=bsfj4yjJ6n(HGY|(ND*H*%avcK-VFz?TJSTCCKFGEa>?t zoIEs{bC^_v_sM$i<=WNG?#Fc1^saXFFDQvjUNt}KQ9=0nv8xNKddwJN^KG{ zmt(J!jQ(9_d`EfQT))v$!2MF zxrQSCQ~z78(}?%s2mEO@{#?0A!{x?L#>CNc1<1s&CTn^pNB9ii_Hp%2*q3(9Y`5;_ znfbQY=iE5)(^XI~cR@vYLAAfI%3o06Dkv!}FLf2TsR#jN)ug=LIR^ah?#t-u>B;)_%GI+b1w81 z`G=+EmsKp9==0~4Lu*jOgi>Ewu?PA*ck-Da%kV7L`1G?2%W8a)?rCY>!t&xWUw%eAM<2L_lV^Nu}u)Jf}YG2htUlm07wN{ZVVi!HB8IUAx*bHCc z{OrQAvN?rC^F33~)b_WL;|u+TIrjAPQ(rKQ5ZvumoV;9QZ$-|fK8DD9jV+#_MZS*}q;994}^75>F#d9u8t z^cpW-V=t`iG+9g$5sbT>!o@n*S0%HhpF{{E>sBl3lxY=pc0X+f-%v*q+nqxxkf}y&niJcXdeJE^vHaFRcZO$v^1DtLRH0r z>Hd<8Sn2c5ESe0jPovnHc-oRmpN=&cV3cQZk*|{RGTl>ERZ)d#Suj$E6fB$qGrqAr zW0Rg^#n1nUV5pX>Y~C*24gFt#ZmmQPKig#2)<>Sc$CHc zc#!~=M^AIOKu4*TqVd`2(}R}b1<-wJL57pcp#D;LoIywQNk)<`oY{=>7FK5$*36w} zR-Be%!~{gavWT7G9=04@_h97=;l!&5!UUk<#ic&D5?s|+RaIV5P*#Bi0u;xrk!aoL;EkPFQgHaZ{JKuRdnVZpV2A)`bz zV8m!}&yHNG036m%3V671R;JRgP0|G?lz#EB&K08*NjQ4ODl*-iWujt28 zWrnE;v&u^6mivnHDqvq<6+?QA{5oz&RW&MRZ6K?lF8ZU&ijEe$(pY2t&&SG$k&LBJ z`Tu+{N3eXU7yl839F_*jVkFUvT|y^TT3Wk-rDlq(QYVu~wq70i>S;ySY}&~73_Yd4zSuj4 zicYwgQaoO6vyzk@TJlF=V>3BFiG z(eSc8pIo@0eN>Ar6QQE01RZA>tD}ybq}s_(cWT9s1Ziogvtsiu?b~sFJUQ@J_)+h6 zm|%v3>7-zd&W5><3LU|XB;>-!G!BZQ$G;@YkJ@`q4Ne%0h9mXbDNxmKYALcHe?7gJ zb(b-rqN>P;ac!eRoJhV!br@f|5v;0Wm!4H{Qv41{@As}+7PG zr~rikcf2u7B6L)82ddKYi)u=%d@(&8iKXWp2s&~EilZWE(q$l2WP~7Sc~RvOVP}qC zI6XOPfhPPo_h7-T&m~YI7i1Sqo>nkD-!rvfa@Hh|^eZef0#x~m3otdk%fx&vxuX=W z$SB?^`P0T_<$J~#V7Rk$vOA6zqlF?2@0wpVC%r(_;3!Hkm4#I>hVWZ3AICWhDo2jc zv_(a*6%Gs*`XVs9>tvx(bA5j9IZ$~mz#(AaTyB@4m*SdA-Oe+sb_Bu{Ll^r%Sh2*S zqw5rvRu-07I7d`!wy=o1;TR*8 zi^@5(=&;(HW1fx;W+8NFNE0?+ zVAM{v?^JLds3o;VZ0jV%SliMibUCXJ?^x|d@>C}!5VzGFS2od+V#t%XP?Fzp#E(-Z z6mlQ5BxhQIC!@-TDx@0pew$=4m~EM%=LtgGtkUpZdF2_&t^!{$yI|PKBO;%MTc3xWobJk= zIWucqPC*)^6yljP(QyPrwj*xAu!2cB({vylE+6$RC07@Dnp^{k_{>{{`ZjAfJcHkz zk8lZ2Kao#5ebbixy5o00)5;d7jTGkAu6!b${X-s6oGn3=u8T|GB-FP|yJ7_PqHO$6 z_l}MsP134w*^zq>^yucotwH%=FPAIf|B?T+Oq6Dn+?#W`+(6|Ww*+?zd%7+Mjz0;I zd4_4v1l*^z6nFTNTvr>M|BzBV$+Dm876aD|Al%(`Z=`=0*AUajd-nf$bUvQ2=;3fgh(qr2^S)5IQT&p{wZtxd2#TYwFRD_&Z5?Q_eOtMz92r2pAt z;s0#mU2SfGNYC$~I6p}i9=F~jKPeVIIf8Y$`dj!LExg;pn@1<4b&!R>$)ZoS@NNsA zVc{RJ@R=6=Nel0_@cf>M^OI-cA9Ikn&b08yTlm=)-aJwvt@AAW9Tt71g|D;li!HqK ztPh)OE&Np${Yndeg@tdl@aY!*W(#i~g^<=J3*ThXud?uWS@_i!{#gsZ#=@_*@XZ$f zdJDhV!Urt;77K44<&f5`7CvOrZ@2J^EWEPti!J=kCeARP)LQsv3twsB`{U^j{zP-K zZggAtTQo}k9c1C7nbqY=weUL2>P{IJ9*H9IlWF0jdEJHQqN4KXysNw9S$HR=vt_1* zN1}@S%(n1OzGmY*3y(w+`Kh$~skjvI{@KESZk4MuYKdUXg^Gp>R*I4+z5o(vK*}~(|tH{r03y(*6B0pO!eE$g6 z<=SfDO-h#5?G}E3MXxOUp%#9Zg}>9n@3HWQS$J1MRR4!t_#_Lz&cdfy_#-TQe+z%4 zg?C$c%}F;7vhYV+^r;s97z>|a;RjmyObdUkh4)(c<1Bohg&$<$XIl8d7JjycA7bI> zS@;tye5Hjy(ZVmb@F!XLS_^-&gAPaxGg-^BcnHE07!e?3dObb8G!h0=z zwuR5L@Z&A~Obc(H!Y{V)UJGAq;d3nfN(+C6g>SU*XIl81 zE&S~kzRAMpTKH8K-fU5%b+v_`Y|*c=@KY>&vxU#I@S83CSr&eag`aBSw_5mo3%}jM zKWyQZg>SU*yDa=P3%|$0Pq*-{u2KI#+rlSV_!$;H#lp|D@ck|PITqe+;m@`3gDm`c z7CzO&KV#uDEd2QvKGVX_vhZFDe}RS1v+ye{{7eh~Hw!=8!WUThc@}=Qg|D>mg%*CX zg`Z>LYc2eh7Jj9LFS78B7QWcR-)!N17QV^Cmst2!7JjaUUv1&%S@<;;zSP1uTlfnt z{ALS3-@O_!NEgpY0Me}2yGYCEwTvd@$kF0)I-FTZeFy!0!|0mLc3I@Y{s{M7UPqR|#{A5Uv#X zCBobqgl7x9mN2&j;XHvKCp>^~roaynK9q2(z;_d7i63?gd@JF@38x5rEn$}KVVA&H z5N639-t`OT|7XH(!rKMDm@tz>c#FVQgjuqOn+3j*@G*o}3p|JLK*CJ|pG%mfdAL#F zsf3RsTr2PygpVg&DeySLg9y(Scr@X`g!2R*Mwq2|I8)#ugij!xD)7;SPbBOXcmUy( z2&V{q5Mh?uVVA%?2@fT_>u0e);Z(xg1>XBC;55Qp1pbaNOYCs7z&i;KC%jtVPYJW6 z4mSz>K4F&9;YNYqCOndGt-!AmW+@!56!;~=8H8sGyp}La-*BG5j}snEI8)#U2#+D0 zD)8NeS+a)R0^drQrD`}u;A;u96b-uszJf4I(D1IG#Quac32ztpV!~O3w+LKCn5Aa8 zS>Ou^XA@p6@EpS92{#FRE@76A;YNX{5}rV~R^T%TPb6F^@HoO=!m|Y)O*n^ep1{Kh zpFucN;30%r3Wie!KALbYVYk2o2u~uMBJe?kS=xnN0{0}$k}kY!uh^e3OS$lNf%mQf z%n~lVMd0rUvvdnL3%rwXKH=2@e@d98SGY;w_X)G)3O5S;Her@p;aY)TCCm~lTq*EN zgl7_-E$~{x=Mc^l_;JGL63!I(0mA1IP8IlW!Yq-(Zh>zl%+e^FBJj0@SrUa^0$)Lx zrA>I(f5rZUXA|Bo@Wq4+32za&iZDxR|-6iFcVOCw!otamlDnsco^Xe31N5gtrTPG2!Kew+LKC_|Jr!1-_7Q z9pTji&mmk-xJlr12{#aK1U%gv>b(lB-cb4>VCoHxy$`aj?T>bE;0qOkNF@0J3_$WD zI1*7q@z1;-u)5Y*ll)-bMF;rB68v=it*c}&wU*YuwPwCNv+ zr4M!6OuEq6wYW_84&FoBx;+Oh>N0Bs3b+yMjRNkwS#8@XuQ$}~8clzNMZbPeS8w1Y z@A{pmdlR;J-`Z0no%{Ba&Tpf$H?XPgQ}(YNdk*@!YL55TjZH=~SO&iE?~i%C{gm6K zPQsE<^WX-vHg!t{VZ!$tO865|3c95}jBftpAl#JITDSq!;sBsAR@;_Y;Taep`N&!q ze!^$sbF_QobZ_uiLIMWM4Sb^x!vws67BvvDjbu52P2S+dw%Wy@8k6=TN&X81 z8hxZ;T3;e59z) zk`6WZosAI18|>;0Rs&kx9~K*h<>_ts(VIMemwNC&ZEZP$mxHdlJ#GH9tU&$1Cxw1# zlDDA^b@~`A5^rFe8qO=~bx16d%?cj{Od~t2Mu(iBCn;-F{lF%CPRIdr6+X1Cfqp~X zUPW}E+M-H}iUpapAR^)7{%Q;q^=tAx_@kERue`>{a}6-ROPtQ5J=pf-YKSccS*Y$Q!iL>a%-=MgBZ{R2Hp>l(d(wDLHINMwT{;q|F{U4-{BvD zFSx8BNI^<4JE@_$W{zXp(aBFw>{YitxlVOGHDS?-s*+2h;RA0=b_x{f@*hlp32gHQ zGn2^qJcP(b{b2)A$T)<1q>v{#m(bW_7a@fp9k|qx?=VWJ_c6NpdfoiPLNu>nb1yVU zS2)%a<pBe0Q8?SV~ge~XT< zM@&(F!x(khNeR)}jL_nKfoWhiS5e&aDDL^++Txb9lUK$|u3rgCBju@G{1=FtFU_b^ z2@TDG>?D6L!$$H;uQUW1NH-s%n_oh0w3hXpYDBZFKZ*4!i`0P)Il=mYH>24b$absO zW#uDi1X|LX5jFhqn_;R2O2Dc^-jMn0T%i&=^zW}io%X*xwtv(f-D>WKE`HtKd%vfe zbTI0zUgI)oXYVBVZRhsx*7vu@AFOVT8NaOE`0)SpW`#$7gS34Y=GM;s-JV+Y8}biU zqhrS3zti#G{TkzEIpdpL9GbNS3pZ7bqQheu1~#e5P^2e#kEAqp6!7B%UosmngnYa{ zLYE?`XS2GNoPwUs@TycXUQS>m+SJ9s=LUADIp}WN)9dhig&j4&k742nzsG<#{JI-{ zr&;`tj>E5~;rAV`o$@<}9W}pln_m|2hTo0Q59jv==I_k!anWnX`O%)7-=E|03$vr< zw-57(%@jZ8LSv{Ll38*_B5$=`Bz&R zVnRav4Sn@)>M(d{?Q>0Na3$BjjS@09_*dp;RRXeS(YY<{?Og4_eaIaae(fu{!dKNb z5FX{__~3I)@oE?-#s~J1=yFY@UKENJ)sLM+>BnFfX+|a0dKfP^uotrA26n3=f$psY zQ?-MiL-(fQv$XC|FJnZt1!yqL4K1!z8}WHkLtAqFPhD7@EUe^+FA84_w?mDW;dX#r z1t3Lk$k&(~cxo|5Wb3A#7&%zSyxb9ss~E@QT-4m!BZS6H`KsMJ_|B1eQm1f?)>g_TDyl>?Rka3kaTc>Ne0_6reE^nIPe`Lgn>83N%ojhQKF308 zyRI3msEMmd15FsER$^$i6gcqqhBBc-t%`X-dF$43Qt*o_Fi=i#ktp~AN0=SzGio&e z1-Ga{BG0-!(5n;CcT&TT$@Nc2w~?H}AoKz$hM!529MMIL@_)o&M)@ZQix%~S=uRvD zJ+a_ZmFR6$@f4=0n%OH>`Mtr_DF1QV7-{lHwOEnPQ9i}Am47b8;Vh~!nt0T+)K*ZG zUoK;a^1qi!?p9;4G^za0&{W^-Pf?>OoL(fSV<@)m2idWd=w6c=KKCDy6FhYwYxUmh zVf4;vNgRk4l+8QTGK$vlfxm|?<=XPN-%*R`c*{3(#Y!=qbwO5v*_WmL7`_z8){%N0 zaBm#r+VEsdFbcPY_qL;dEQY=*u(a5S}k zhEJ^@;~&oDKv=HzEjTEf`>;7|T6RNMtP<8ST`0E>f!nGC zFnba9bg8*JBKsJGkxx)+c?0iDQ(CjS5RI+x+4TjZUrykc7YCs)!k@Ys6e!{lvy$t1 zFq9L#gL|6Xz^B3Cs9ciNA_&V5TqDoXBH;c6u32@bwfPU96u6i5mskRGz!o`tBO0~* zIl&3ohc+~UAOT9qYH46FgazPJ4H8Q)1a0d}j(jLyPlWuc7%aopv{dA1A)*gQ{ydCC z`L})T7<$WWK~zCgbj8GOwU9;xE5F zpIbrR`l2%l!-6lXq?k0K`+Grht6>K3PT^%tR}S*_>~kP!=8B|}weCt)ND zXvsLk|}A#rWG364}rGs)2`mSy$SwF!nIz; z6Rx*lLds7#l>RX0VsSk}s9My!UudqA0UNH_;M%$p<7c)dKb_gDZqH?x{monVO_J&f z%OWt`k`qiEh-r37zIu;j1n!@)PivX2=3$zQ+cZC^f_W)O99LZ=WQ&v3RtO}~@MZPz zXKihv#R+n}<1K1a>liy5nz61B_CfDSYfgJ*Eyh8IkGWD`gIF)5z)AGV32AybMRI)> z=#5Yb$yf1(Us@u_{3l36?e4=ovjW{ol@quiNsE8KP=c7-%;woBepbGi1P*F7qhkv` zVcfvWDh*(6XqnC~ZE74Wr4A7zq!&s3MkmEYg-G*8QP&1I~ zNRA)uz3O&1wA1$!TyjE-k~m)G2KFMh+ct#m|xBkl_1r$sR@SaG>vLq2j6OC zfTx3ulA(5}qoP9`XHW+KWe40$eSX;?KJ^QZO9^@R)%`bNVTpu`=@`J6@$6?Y>vodF1}TaAb$hxb*B4-g*6rzk<-G&Cn) zbwpP#(uv?)fTGa!G(*NHmu)&s+24FgUs4bV1DQ=dD}XAN~?Zq=zLA^rZbe zOQHgUZ*u({jBQ1VA}#|aNkoeKOplzv5t9PtN#n;XPD#G#$A*FHF~Ls5KoDId47|<0(J=5CbgW)rqZ0;}Lusb=ds?*Zgn`XQ z_ij+rd-~(5!@$=ZQ-^^fx>Ts!iCCAvCkzy$&UL~-e~usQeb>!y@bCLRE>0M@0OPAe zgvmB0xP99I_WwZM* zob@|!KImDQJ9ybjd3Zwb=ORFDQ}19j?5rFLuBQTry(?-GQ%gA-otd?E6T@BK0h($h0-sH<#Vq@!WK2l z@cAcT!{^lx!RImDx|en14R(pdwReH!-1dmQH>f5K66|}{O>S2jJ{-jJvIC5VT#tca zc_x~FLETKpKOoLg!B`&1kJ;kx%-G0}^e2+MEhK#gB0Pli!L6hb@p2lFcD!5x9Yo+r zitQ>wVSl+vZT%oNsVll3m)^_C^`&4NP3pOUuUT=*OH$RhocI|s@k|7OZ7Rjga}9Ki zd6wST$vhu|Rm?oU#gsXT8Z%D>W7I>*SG`3S2zoKoFiNE!-oP7mU!qjnmyq0W21vcZ z98@?tz3TpZS@PARfT-JxnnvHWK|fQ|TyK=vUk2A28jX}{=a;8A8hv0t3am@M!#;)& z?3T5cuI9w}+FisV&YgpK)7RbtYQ~bNW7h9NTUNengVAZBXN2hnHI!5V><4lG@n2-xrXC_mynHto5nJ-zCVXHj zJI={>>2zDOWxL$uy8|%~5?unA>ol710>I=3XZOpgy9Dn&Pp*G2k%m6lllEiX#Y}aJ zVpH8>n$@hg^Ff*$aOVap;V)ffNua|;z+wrHhj?5e_em^}!V1CDDSsd1)SSGxQ4Ir_ z8>-Re?{1ZiMXrt@3AFJgIP#3)0Kjq>5Gj9e$3&e20h~VQ@;5iIPhBTn5(ldH@qsph zEvV2|=vr-JW3Uen6;S?iA7G-|3(z|FneumwvB4mYfO8`^t~&4ih)g}QBo zcV}%{(F9jU`MVJ1@85L!`-m=oSFAw;=yF-W2Uau#Qf_h!_P+lbH~9Dc6qlUPLMeYs zFupoU*n-a{)g6?I_JiZ*hUU#y-S8RpY;yhcP;E}oKTy}dTPc=IvmScEbV09PfhJ)a zoTNzk`-tQ{%so!tgDlaFiX3L}zD{m%4vtoKs1Gq1^WHm{fOz^+&4^MqQp)-CyiodA zvtm5GFR?J->+kWpL3sogPapj*g2#csn0(~$@f$wOd&1{n^uUD3XAt>x zW3iEs&+z$3VBz!jKf&jI#HJ2;?+roLV@CAl9cmB8r{bE}8TqfVle}=fFla$MRsVw4 znHT=OkK|o-`r~`EBf0At3`mN<3&p|AejeeO=|cXS1Z*VVVZU%GbP<7By-Eu0iZR6H zURGP*X_x=#f~NH3S*D%;@@<5FRl0o6gq1!^QV<3f0Rj>{CE_`f$*1|1L0}^a0yz~ zY^pred%^{f9``>nGteY~uTFw*U|d)TsdE~X4j&Acf{A3+Nid(Jxi)pPxWYD7D+0-e zuEC%dL{U`+b#4^(qB!j~HPJ!sR;Pj^Q|1VuWO;2+qtKDzE={gG)FFoCK;26pT4GZs zjQ2NO{(~#^E%#sJ5~>L!t3gGwfq z&X0+2i@fSel60CMk%k_Hlho}=Os+owzRJ|cx3bHAurJ-)tKi(Q&#CL@f9S7m({ShVpr)nD&MTq?ufy%O6y*w4#Ecj*7-6L z{~!$G?1z|wj(?b_6aTRORaZ_tlztfe%hK4xVqwHTsE0oLk-$3sZGjWM0wB`t`CLdog$^Hkf1xYH=zil35HTLD z#C#ZUQ#lCEfv)Hz9u1TUNjxfrSd2$spt}{dVMIJPbFKvc$8iX>R)f76+Uv7z~YM&-hhvc1w-yX&Yy-5c|8;#&0F%I zohJ?V2iaG0DpqkamfZ{eu^{x>?6;VMQ-<=-q~rz`r?e|Y(dh!TKyILRLxf|N)I|CP|6#W34)Q!Rxd^V}2pj6C%SOHRsUX0HuMg6`= z8M>H*=_&rA!!%dRIIf6j8F~b!DkXSlWoV|ckxAw=#P@0;DC(uw`AzER7yCD`CMxdOlfl1KwIeR4d ze4P>KL^BO4Gm7#U)JYBs_ve9Pv>PB}ZBqy7rq)(j`5V+hXm5SjaOr0H|68t78B7(6 zY*X($sNL$#SG6oHK$&v}yIwHQ6q@^6UCjNh0eWcq-q6=E^`3-7=?`MER8Cum=y0?*8=y7m?%c(P)2x z<+YBoK`v%fwp5^r65(81?{auw&A7j{vENF|JJIxIbq+v8J-xASQx{^Uit&s>^_J@f zm5yudf%XPWq0qG0%|UZiMZ-$ zdbpO00sdM#YpB}^h_AorK>IUP$IgNFM2;Wqy=A!@+UeWl&y1$}zE%jFlo$VCNz%Pe z0;S3TjKC%LwNAumIncfi7H|%=a0cN}x)?gCB;{ z_ruq;5C_-bqT}GD7)O0YK8&TGK~OMaG@Op%7~IC9&7khakVFlMqJ|o(eo@q629?M` z^%m&AFN;*_TQuphcw_E+ScksVD%Wq+KMd91L4}TH7Zr1!7#sf*o%kmm#9M}L#&miT z4yAv9Nm|N$5^N;?Va8PE=fYNQo&9U0mamW`9pfKDN+WU2?-HKy^zF#lgT(e4;m++ms;6G+Sf$d z>yH!6whS@ujo%;%E zz$6lVj*LesLJ%Ep#c(s{rP#8nN_U4ZC)bytd$g>=7M*3)a!ep5TQp1NF^a8*%Ve#b zkYu<@eLh17B85||iR;fntB|b{GE9|2;du}xOG|`Yw?0Cn$ZXX%PJh0Is0?IaFe<&IJ%!&080&PKBg9)0 zg}S|sg!Ow8+XJXtoWxcRZ6UGkzSs@z^i5qFO>9qsld8Z!Cb3Ner78gIB({8fmc+JK zR+4^TV=~7JNMiekc-l64T7O0pE3t8BALmXj>bHm=gr`VJO`|DYj8Bk-QLER5SwHtl zGBd`-BPIM2H0%DL6FY7JfsP$l<5Nz{1eW}+@TX3{D8CG#Z2mk)j+FFw$^oPy#`7Cz z>;A}}2fzg*`4agv6H-QC`)=V?6EQ}(3;v0oKOnuG=s`X#hK|AkkzLO(G`0`%xx^2n zAfd5ci5NpfH<1)6@LBNEIZ8baH(;jA3>bKni5utB{QMZIfKF8~#t8{_nE?+1FKk8!divD(#MjD^5@+k}{W zcn`5~_VXb>1M54&Q3C5L>+~$oB1y-5I8*im|AA*l_5(M`VB1*FJk$)9mlF=94~k`( zCR8md{DNj#2-qaUv%xaDAGjG}b3c&D4#B?PF6v}IFhcY$`++53`5XIzvoYeY?FWt{ z$9DUHE|}qO?FZbh_s|)C`-a;HtxBZ!H(Y=AU6! zgv}rV>F)`f-%HJSc{5^%I)&p0dpFle*!(Xp&VFDSIH?T$V?6qBP^v+Iov?WrK6ls; z^b>g{Y~C)uw2fi&6S}$;Hviw*56sX)a{ZKXf)fdc(rZ!ISS9SY@N@dW{m*gw8`V*u zGVAA0$lHO2olcSVwmSZ;(ej-|lDP2?c8bP7 z8BAC{1mmd735U|3KP`r3nouGBVP<4m2-t~#U}?oah%NDt9T5MjI*Wgh8}g${Q%k_o zj(<|7;lMvlif~EmC>gEiZv0cF0{=vOLZtqYc7ID2aC+6a7^#;ERf`&Kq<&D$E{bY; z20q3|mZUz2+&;MME~!HAZdZlAZNz*DcvIB!Ooo3bokfAV8|_XEeuGF@=Tc~bG5Ag) zvd&~42O>8(4^Lz)V+`i~B95s~T{a76Q%ARIMe+Q%`RUl=cMJ7wqJAHYAQd`JkI{q5 z{a9_o1g%FHn>0O!O0MUrkpz>#$*EPj#_KK~cv$C2$- zxaDUGE%kDW99|CRVG1<9>Wt_(x&Be+l*Re(=snJ&gKz6r_s4BG-PxaU112jB?SVAy;Z_ zJi1G-40Vo?>n*@Wu1!xsu04Cr^KYY&Px_!S`~d`Vo_`CC-AMe;P!(6M^~&!!fD640ZPTSz!2)MhRl!Nc!I+=1^csUB2!BFDg2bP%lc z_aLqVsq@8YerfC=n3{LWf>_j|X?zhq*!LvJE<67n>Szq(d_6s}7GF=-?`X)w`oLGV z_wMnhdV^E37s%^xz7T`=sf2oebt;XYen$o`V<(;h9~cSYRG-H=T3$-)8z5@YM2j`i zVEEBm5W3Vik43D$5g$3j=OJEH!{+<0czy!km2AXv(64q_{uN)C=MAh|43z4DE|?j; z{|Kt$zqD}Z-qr9j;Kar|)H{?1E_5Y``7}J!4U5F{SF`gs>Phg&yJn7^??%fuwmc3~ z;1r8T`q2G1Y8>?wN`DScViLzr4md{0aQ||La%;Ejs$E;qDpHRcC2BXl;=M*yAn3LnRj+s3C;=s*LHfmK)O z@$eQsYgm{ve{8gRBO0Aqqr*yem;-6N!FBTaX=nkn-&X3Tn>iG##Uq5mQG_~`Yb6+x zljqi}bD3pHth!{O>6&;I{GG5qv`b8#!hrIE9cuo|Kb1|sZ7vvFIw=1fr??I{F0NT>i zH=L@`(-YD|zVZz@jX!bz9D4%BZm*|<9**j%M0A#3FgM1ZW=l+n)zeorO?!Wu0e3Ze z`cPb4{As-?NA%QP++l~>_mI|8cL)nTtr#Aor`4ik(bEt3XzS^pG7-_!xtu8UG!-Oj z9eIS-rD*RU`tP7rf0OQ!b=ShF8a)N2$HS?TARIk${?rrWQF}e@d@!n~(?nS8DrzfdL?N7Ieazsxb14}vH1yB0Z$Fx8wy=qvDo>mg8*WK&* zXzS@=nTY6V7$*va3;~I{0slZxsZl-s6_n~y=^oM3oiLB1ry}X`a9)g_IDg9bBO2T5 z>7@tI*{r)iaiCy&fiFf+DV(#Wh{UJc#q-+fX+OBD(bJXGqt??!5*$TOPm4S3P>+Bo z_4G6?fQRzaV)Qgyd{O-AUVOCm)F2ZPJ@w>7p{Fh&Q48=7^pqFX(^62Xv!#1PPmAah z#-GMWkB2K`^u+m7Pj8^Hy`FBpKcWTowdgE;VsVU~l;|YZpZwx^?ew$_CN_F1W*@Dm z9C0Gi(^bGyjuqfZJzYf$gwiLb#^@=7SnW^C@X^-OESZSt=~EfDO})%l;Pfq8Dct>NX|JT3Rp@D)=@n5}`qZKrC2bIe#42fu zxLrFXt%ZG!l1^tIt)zkCL87EmU@1o-cv4BFbh%La2)q;3%J>HptCchpA8jRNz#UAo zTPMS|si&ZL(Rea)D7wxvJIv8JSj$)LSlnbbEdt5!W)xPlOR5;>b`7SzL90A^>uNn zJ$I`;qJeE{JBV6a1=*%P1G4oK)JJ4E5<0{?3_dq)Eo^()v<--DdysASo3?#WLbM<6 z7pNfH1E&3BwtvyOU5_j6^U)qIL3A-B&ynQQ){itvqdJrA6Qb?6#SGD?PGI|S(e|b7 z+Iz9Rd$j#L(+*>U1;z&){t_;XEi6tYxgT=g52dcA({a}$FJUUgNVuQXZG8dvSDkLC z^!^~y|4sCW_P^*}-GBM-?tdp1NA!IWZ$a_;nV(ZIQe+>T{@4)i9wP6H7>&ku?~90h z|Mx#~nnd|zAiUmbW?=g5fk`*FcvfRu;ZkFv4LOqXG$z+i!d62z3op77(RP$>gBK^) z>u(Qw8goP4K0&a}3H%G@dzNHtxj%Vk zryKf2j$X^r17CWJwlI(-yo-_5R~RN(b8}>Pz17;L20Fw056AF)tz67|6|CoRBD~uW zFu|K!JI&tao!ANQO7ixs#s;}z0Hkfb5j)c4!O-M=AP(Qnuo)V=Zx9eS67dia`gs$1 zU*Phu_CS;M&ECLM8R+c|+>j}kkXL5jkSCYWOkDiOB@b?xjStC#LzQxwUYk64R%7yD zUsLkn1*?+>*EA;&Ube*>@}%U3Lj6IK6WD{(keGS=gfEfmH{^Ij4XL1Mk+;(%L5h}! zM8MEJ9IYV*AH6|o1H{2NEDqjUu{2oQ|YiZzs5q~IQE*WDoHt*MRvN{9j5LX54p z5GKo9{#PV}6mZk-z6yFoKmVb*f!Rqd?8ewe?MQ6nn`5}yfAV+{Zx7U{Jd#rz__-A? zV$5Xw^=MZoqM`NA(H*^#JwGxhh^2 z<;4Nrb_9q2oaY9wGn2fbn(bb^d=xJtRo-BV>f`uZ%}LhG-uRoISx$?K%LZPkUzHY> zFE|NSOAjLQV+K>;fq|FQARc!$G;2-xS4Vo8c|LR;i1`M#OolJ4oz}ae<5}@-khku1 z7rrnYTDD!1wQ8a?bxV_6{@&gYUc7<^wLfverTz6G&ZV?qOSaYq-oC1_^EB2?U09R* z7J-On>l2yWpz~;}TGC-QiCWIB>So$E=-JvCo!DnaPM}S{Bo?9Td++kER&j*jWo~ba zrwJcnArDc!t~S>-a+Q}7ZN7`CcA{Hj@G_#>F*w8G>YWsvf@7sAn5w4vX*J3O zu8i>m>FyYD{J=r{kQ*o-2!7-71x$hVdIRGJ!c)c%Odb09nf!uQPJO!e{ z<2l9Lz%DDH^ZD2sNc``H=B(uFU&cENqdFUdWGV0 zUCFex+>w_xeTOMPe~oNbKR^(PzR3-I9t8Sn2B${W86;{Z5%xG(=8Lf!)kt`NkOy8$ zuK$K@b;~xp{Dn;%>rTY2F9q|01smWH%R}#fgQ9J6bL$dhbb*I_Vg1W z%IN=E>I%Px6|McerWyU!hfN&bv&vfp2?L&{@L(Z;cPv|@lA%CoHYYIAP1@}M<*9VU z3(HS)sC0A3{2Iva37j0hN=6y)a%mf;YIz=oDY5=m?Xe}|6PdV+(d-RfjCa4v+*J3! zm?0e5Tz%C~^qdz>JGcYRJl-R|kP8WHp7Z^}o16_qbloPG7TaSh& zD&bh+3#iY~*cKuRfFSFf;AQ<=?~c?jSj%C9>K#$}@~>uMooTH%G<|~?&Ecom z8%#VFGjKto&3L_OOT#MDf{&}6j}1_N!x{tOm1;fjunqEW8ezoJa<;cYx zXA}9Y#myiW0*U@V-Cd;S4;v%MFYeNS#i*Ror1V+?#Z< z9&w)-dYw#?u}_?0oZ|)vB$&yh&Bfl~`-{5Z56KPdiCw;tYPFoBF&LsWaE*1$Cirp) zlDu{ezAriI8jX>>^AzV!5%1!}@DeljFA`mtDTeReM_;G~N2-)!s*NDFT;>KCB|Hi) zW5tmKxKWJ1oPu_Ubl8#bmnWgr*0A~o{i4Y@_Wq0GJ%2|TlIP_!gkay2Wx{k8CN8ik zMY7xmrbCe~)m$@p&0Kj=CU9Pj^K3EKt-PwOunh#o!?)UnlIy<)nkL8E=Js4YO^SeL zi#OQq(0n)aT7yF7TUqJ8tt@9eFqQ;-|7pQVsPfap10h6c>`AZ!BIJtiE#1r7z7iZz zsN_Z0HcNp_=(iegP|tQVj3JnGlAy2`&U%*0ki!ZZZr)9in5?@N9ztLA9D?MWRkyv1y8RZXcRjyUsFl0( z7%&cv-2xp$xr4v6lpFqw_$u-gt#F*S!hM?11wtq%vIr>Msn7-u(olhZl1=r#SNFeG zGn%XWH-Bq0N=F9>G5Iif(3hBF_#GhZ_YrrfC-b<#+SQZK-zK;eU1O$5jk!wW`fD8A z0d?m+y02T~U{v55i3=_rq^r*F-~~uj+Wmt|Q#JNOjn#`GxHLm!H)*Ua4UFK`iDxyi zmLFtMj9;l&ryVNh->Q_z@oV*}E>?2_|1rtnX1Y`GvWyP(X{RZ;zb$RuQa)gEZx?1> zd3!9}tr-rL!o#PXJhFQBX5%vcIYHU}!4a-Iimn24UBWtHHzHWX3(`J7GHyl!8H_Qb zS@^Fvnk;-VoQrO4668hJlwF4B8W=+Xpr%ndX~&1P>Pdr)ow#bb-gW7G&{4;r^A zF%_#vUe5IzM#B=o6!`vKAUPX(KAKM$ws>m6#-;vtz1&A`xRktu)q@~bBPxtqwctA4 z&>Iae9!rsezFNq@u1x@4>Na$h)r(V!Hxto)&4ip>&*-841z9Z~_e}g`ZSoAn2?bv8 zzov5N{Hi(WMMZ#;ylV=|D~f&deN})`yldw8sw%1rX3hlEA4##B`W7=plw5fTM#b#L zK@`Z;Bo)SP^}UE((+@fT3ikzft0p~*`Wx8+w}^JDOQF=Lhw&Mf4`D1P*z5;7o)hjt zKL#BJgB}9Fp@lCOx#6Ypfjy`ckJ^IAuNtO8 zMfG@LI#>C-7|~OYw+G9EOu?F34uN;DE^Aa{;9S^L@K1s)L$&mydY|6LmgU!C!~Ow- z!}S}qi`0Mgi*qi96wvI&fjC4|H$$%QOK3v=LSlc8!7^-~+eY_Dx!4GNboS~KGBR;? zEPU@pRB@3%iMW{vqcj&X-2!Af zSx@Q~C<|d-*NP#;(O`amL~A4wNk{#`1Nqh2IPtp^WdoDEk$n@65j}{#NMSIYTRn&Q znDC!TkH>mp6Ls&N`ba$vT;bq|y(Wv9FrLV_mexomLRxiX z2^!%reIR-s7EwfG=Nm$4ZnS}N(4<}zf;%E>^ghf{R|~Tv5$Yr45yYnt50{)az150P z;d6e9)L)vOp)9>SNW+7riFO>ju`k@`d^lD3aS^^&42AU)iHvt*$r@XHx))jx`VhM= z8JM6-8fgp(Ua45T3|`ksJj+f+@N&DtIl^YV=q_+W8NL3`=o6HW;TyyV!cYAK9>EN? zk!~CsyM(g}Y=Zju{$Rvhd94c?`cc?Nxo}J#?M}pBh~VQ#p!lH=5FsLzFt6uyL`7`y zv%!Z3UE(Z*6Mv^(yvot*6um!6)=FK33kn6-PFtxzpfh8`6_^L22ZCr5e9((1;@Alr zDlF&lGr~m&hY++9buM)Tmx{QgKgB7N;96n6%>`2!MoC{qmsb2OA}zml-jt-?gp#7? z*$E)j2Yhoe52xP7`;QN%4kPE;7ostGo*ml%DXL}q+OwxmpB_N=`66rD?w#xZdt{bQ zwu4_q^_)`oQa5kWUUeC|LfqtfzD6Re?&mJv!20B?mTR@%4JDN{CO>^}R^3;49o+gv zZ{3Ej%{#l)eR_KG(|!7_JnQG=r}KXqpZs+8zV)9bW;LtCx=&L*$xkl?$cA-)9eFH8%Cu7x>ws}D?JULU%C{`;n#;ikO<#DtvnD|Fbup` zw<8r@5-vRz{S%sZCid8?Mf=mrvl55`M{vW4Ky>kj&Pv>r)pac1G={pBf9y!t*BAs8 zr=iQ*v6y%3JC2?MuiB(AUd=&NyGN-&h+gJV;aB09&iSaWWT0C8XR*}vP;DqNGqkuX z^qaG1eOs5hmIS`Rw-y%hvm z$xn|sFtc_aG8QXvZ}JQI2}0Hz(D>vR68mMh_NH_Y;a%pmK}e9#?y6 zKM;JR36^%PYa>A$IK3(a?`7AXdLRg%2jmI7wEoL3Fn40s`n`#{p>q<(_josRWm;Ap z3V)7#an}0ni5NXMbXJ!an3WeD;4S(tEBS>HY3uiO8Q)_QwpR(78f?x7r8jg@*Q_w zbztoBx$rQHSUW?JPo@Az18xo)11`hp(a;?|ANm7-Z|fnN6XEemE~U=@-WL7k_x-)C z3WOf}?`;(j?&R-n;ruEm@T0us+-!>LzQTFg01A*B!m)GY?}G86!#1^_cr4lizGi4( zbL20AWuaB>Dyz@0)bsd?q@n4}dehj3zi_hAd47;JF3wXI^;0cZL#{_eUx1HS&j5xJ zTGyNN9!R%O|Me{_3;B~}M`+QkKUp?e|1q*M@}=0$A0!K!KUQ`cVzJy@Q#nSovqUuR zw0DbKT*S^_EJGauxrS1%$lohFQXOgJvQ%itTW_%24ddMKlVAONMgz3+Rn0CKLZq?WTo^b zRi&Si=!2<8ANBU1Z+-vKX3F=WysSOpXspUGZ;Igo)b9N-X?*{sH!ovX9pF5vTz)yE zIht0*JLouv@G0zo=T=$#hKB$^O+itv$7n1c4}-YTCGPmA<(%>K|5ps~`}L0PBd9HakNL1FYiMfYQkd;JxERR4Fwj*k9U zp!kCR7ws?l9|SY#_Yr*E0BP=)1@RmD?*snS|LqXz59$91WHj-A3_$(M-I5sp=l2ZY z`|yA4cVrE`&07cO;vU=w{weAK7%tWZGl8+!z?*T`K&Fcesuva%4pBa+c>?#3LRb$o zFo0PPr>=koCUQVyk1_ZhV~^3GF!p#6b1>^65!(H|>j4X(8!AN@;K!a~fcttm23SxJ z_D4addd++d+lT+d9OyKk{_+`wE}Y%}pZY zp@#E)g%7A$#$frr!m=@L`+x0=8u10;dvHqq4a<6CyKwRI}|V9S14Z2(aiT1 zZqh`XHPMnJ5XtuyP6v_62Yv8S{2%kM^{wl7+}Ga1O2w_pAim6dlUmMspAQ({yXeh% z=r@StPqz+Z-kSu zy8kG`crZW~nTXMk#$i2x7U!Wwe!=g~OWAX`+I<wlccB=*| zHq-9#)5b(n0@mtTXW$Uv5cdoYjYz=U@yqLP&6ai7Vf( zf{Dq?Djr%!G4XvLOqu7K`;#u1K31lV?~98QIbT|7QzB3BsU(gb>ia0BAGs%Db~QLZ z!ee06$PQINS)k8}n7DeJ77e9)VnsinSo3$i8u1yT=S4;T3;kz_khG|y+KK+{C0g_x zXp*9zMY>@6&QoYLocFd9{cVheyO~Dx|9lU~IRfiM^m`}^M8A@YY&Q*vLwS@Nme%hQ zvudsX6Q3b^WmNRfpiuRKkhG{0jAmNi9W zQx=H+7M=f8jvPw=3>n%I{Y%k}7JUH8qwfVjfpTN(3#;JoLE>u5ed$sT-KO4!{FM7+ zjuT9OFI}trP0ATrC3rsx#)_(Z`FDVRMdfJ}1acojx$E&yZt&Rjk$miSQ}nUh{h^wU zkKOK8iJ*5LyUl=E|k6&+0dH%PAWGjp(66w?YlCsZ`5DdwtOR_iP?E@Qz^j< z@7ocpY*VEemT&2kzav%#Bp4Zr5oqY1pveG$2adSyzJh`aI<$Ttb0s-$n6)dPIt|{|X4=pb&=Wl^lX8{E~ zc^*io`Yx&|t@2f4^3{-`w8-bK_E(jb&vn;Sm7a*(Ab#ImUzNM0tZ*)9%8Nl)1WnE< zESm2wsVOg_KFQG<$5P^n?utrM6qdP*=AoOfd~RfX4%TrfE#FC}<$!S&`b{YHl@(`K z)X-(zw66KFn7B);-Q^W9rM^SshtSpj!tx^DugT?~=fe%2>Y6g%2Exr9!ZC)P>Z`7- zD6a;#1d_zIX#-o6tAXy^<%J7C-RZ32=_f9^tfGv8G)=&V@h2tJ=|ZvPLwe{uiF^FD-IU8{(c^SU!666p5A$Hls&t zFCDZnWAx};M82|9`AHL;HrRdMqEi1n_cZrdw-e~Hb>N$25ARx7QCi$_XflX1a7=HP z%g7gJ7=-R@6HNw*Te~SEBf5hgkDIfW;3u}1<+S4lx8oQKE-bC`*C70KF2MA1qzxpG z_&>kif9h}acDbDX9jtR{)Kn1Q*y=&YRu6U|VVyjr+BLVjx}bDHWkr?0fXi6J$PES6 zzM=vrKM7H}MDG|}acOmBS>cjs&l;VMNYAh@qZJmJj#XF%F(WyM!lEKyWh}=9^O3t3 zR3Z@T1j_U(o%zrMWT;$HP*hY{G>?IoW74j-rgiSzlXq^yJGb7QJM_+d zcfT=FwZEduSHRJWAZfMaPo(8iWOj|#YqtQBRMy} z-}H~m-?TgY+kXGgX&^m)MEb~6GDeLabLv>r(Us7pYht(V`z7`0*=zsa2PCH)c+kOp z`u?e3|3fsvfI|;E{D>pnM;(34z+;a)e$e0{C!BcF$wO1qh7FhYtZ~`nJrgE+bIv$3 zchcl3d1p<{pEmvM88gp0w{T8Tv9DzAywVHjmn|r-sJy7E+F!G9(c&c+v$K}tgrSi# z$wUv-VLETRoFwG(BkuY9;>adl`HHh)JesAjtUB9x46V`er}K6DhvU!xT73Nfo7V*l()~mEy zM7?d%Yw>|vXpy3}mR6-$AB``dwrZ>vt*^QN+I#IYXU?1h;_bcn`|ij2zL~Ypzt>)S z@3q%n`!RFQE+2}=H-jDl-3Qu?Rn#cxKG4a?uNkYvTF|#ZH`6^h$f1C;C&wgYMgjc+j^%CzIapLp?z=A4Iw69&`k>7F1y2-2qw%x)!to^dRUWx_=ly zxPiX)E9eFE$giP4(9MrPF7_Js{T6aT%O6Glper7a$G6e_LC6QKeFA#Kc1rUI$_cs+ zv>9~rbI>E`k>^of(6uk19YLqR2)StYeV}VWryqj;Kx;ww6Mh)-XeaMaC@1K_myj=L z$6vq)O6Sh+C;Vm93wA>1yazy!fHs2Ch2I6_l{PeAq~V~#f6B?o+<+fMrUJ$PBt&3o zJl+G{im~}MV<(@Jm%Ti5mH6UEKKJR;si#vy;;F`G#Xvkhj)2Os`NQcox&BHB!Y#$O z;Y0Cga*nSuYZ(_3y-dc@aU;aTrp=c`@qPhT_!vTC4cT*Q9|J_o`79Rg&2 z;ICfqS%<%r_|h-5a4Y^7z*devli)wc!rzp_KLPdM4E~!;`BwfY@z<-;C_Pn!e=_>w zQj;I$2~&AcoC;!}lRXu2UEo`E96qYwzk+WY_!8wkcK!B%KNEfa>ZJTvd(x{Z@2cz? zB9*Gd)E;kuf8WLN_$N&MujIBGpzZNUK&+Fb-oeusmI}?cAzV5sIgx5yo~SprWcBT(*2M0LOLFS zoNiF>SK*+vt*g4KY`I;DKY~voe7oc~j?cda{EIYy)$#eM-)+(SXB?mZ1@Mn({_NxP zQ@<<3SR~8;DjfDP>RSfc)bAF7{}wOw^QeWt<~yD%yz71Etn;tV@a*+a>#+Nf_V@<) z4`QsUg$y$fv?JY;9w+b^b{he@4Atb1=C1R>AI&F$a})lk8vL6v#_e|Dm;IqZ@t+Nz zcTw(gjDZ`e+{2b~*Q#=_^VhDg)7N1vk)^%rcezlu)lz0ECsx2m?M zUZ$^B*~|2oAbst+c>FYssa_fwbsg(;{>XlSlSh)0%k=kB|GO$4{}j5Kx7yOKPU(00 zNKlxwm+9X{`pMtJbernG(URV={x8Y`u)0HmwzOaDu0e|4Nc_4|I5d*5yBe`{&HoS*BjMIjMK_IDcD zC*tX;81JA(zQqRbrb?mjQ$MID{@dg6KY-QSY~`o+Y+CP={owm!I0;gyars@8W7Ylf zIG&eE=m7m-0YpXA^UQis`Y$8C0`e!A@fb(Ao)mux z$Ghc!?QzoI%ki}&U$>#9A3ufo9_0TM=+TTf+qe$Cp)iefLbgSE&p}rh{TY4*u=3Zd zaojUivg&Rm`OgM_V0S!z$eKU<=5H&(ONo&2PX$jG$p`<(Z%-d!=Hz({L&V~>wML4h%c#Hrr$zTd0MLPmyxa! zbLK2-xv0KRCf9cj_{x8Uxh(9_EKgGTA2J1#-P{3wdEgVmCcmZKA47aC=HNY)ue3|p z?HoBj@Qjre3um{JMD!ohH@N^hb8ok`oT?o?EzI9X{AftxF9ZMd10Q_8+6Mm3;J*%O z&GJ@L-wdz!LE+@>+ekk2E!!XbnZJ+6H(B{-U*VafC&Y3y319&rC(yn?-HbIev;GO`@z!5`eRMD{VDVt zWUK57e!Cg~#Or@Y@tNEc~#&y4BwFHMw&Y{TH(b9h3yY#py_zZZq)kHj$+X~enPOx5WQ6ZZ z5518oUP#6l;7w zgxC3ez&H7j{`)@PZ!*PGzR%zd2L2!hrl0$7N6I@%_CuNYpViwGTA!t|`bOF`F%8>@hr=aT^AWHQAwG=ZIfsUnsmvU7x zzRAV7e5{C#pcqf2PgpZnyqw+~&lL}NijWBkfbcsWAMne(NVP#0<6$bs+ujnC|8^f{ z>s$Px8*;^AD#qH3(0e)J`Ha_4jK{J=8*;@RIpt6aWqBQa-9}%s7;jVP-^St#+P|F3 zf_;nF-%*w$>7jqm6F>1le` zmHAK)O0!(q!lo>7(PxFYF)cKjDV|UJ8!~;)GvVzlan#fNw=D69x9B%n;$5!~VORw4 zE65hE@%iq}5|5EBto8?2XNi0Kw;<&U8KIlA#7&tKkQW)lm1GPz($}3?$aR!$qfcf1 zYOXdzG{b9YZ$iKkPY5P(o$o5tU}wez*vD@&n&A^}$}GA&S3I8SLm0*k{4mM?YbF`b zkFrpVr?P@DldH!34k<6qEfV7QqLezCAs3Fk9U1 zxfJEz<)qY#I(k>c;!(ERn(J8q}12k7fyj(&t+LN4o?*KWexoS-(!jpeq~I--ihM!Y#+i`W)shkvS;j>2y-90 z6W=*S2yeRC$63^qgGj5zH){hDO@5_n{RR+TJPgu#KX{o$nBamA3~3(sf-uMmYsyrqrT;5S>iv_)}$ePXZq0X zS>g`Q7ZCodXXu73@v4`?Kk^O1HQeI=9KtX9hc3?&&t=pgd~4=szL}*4ly6XXK6#zg zz)209)WAs%oYcTc4V=`#Ne!ITz)209)WAs%xN2Z~gNj-;Pth$*_cQI`cvk`c&myqu zl~>lOit77`w);=p?q}KV=h*Jg=X-4Z%4;RxV~by2&DDxx%UNDuen?Sf6T99ilmOn* zCa*%KA7MJe@w9JE7wwVL^|$xqF`}bf5xq(dOe9nY{G=+cMcBip3tQUqdXY0$yW#l# zhjIFeOkGnX!A_C9HgH9-+a@pUhRbUb(|y==piARxaU=>|x||hUF#3ssE}h@|aaI1! zI2wd5{E95=qsu+Y_Y(su{_lLRs)-YYjw4Lc7(_yBYm~LgdgXvzT2bdmWdX%ZZhVy4SjcJH!4bz28+nEkB z9cH?T=~kvYnC@kIfaxKoN16KPaQ;lEF%2=TVY-lMJJUg?!%R0Z-O6+a)4fa&Fg?Wd zC{uqe=g)K+(-6}drVE+2GaY0)%ybjetxR_?-OKa<(?d*;GWFMS{!FJa4Kb}@x{zr* z(?O=gOgAyz%5(?Qy-W`3K;)IXQ=XF82(h-nSeg-qL-4l*5Px{2vlraPGKWqN?=A*M%}`s+D=rqh^)nAR{| z$h4j5Ak$%{o0x88x`XLnrU#fFVybdY{a)l%<4kIdLiBj5)g2{_c#)h~+W z6C1_y(a_>{+#oJSPpydJXou0>i|2HVjy9y#cM#gzYD8DG(ql9zXjfFpFj{(hTUH7w zLx(SFMM4rrIYX{2Wy`Y8RtSk9Z+sQYLZ}QE_w|Y5*4VOTc!a{P$Pal>^O_8N^n79; z&sQ{^YLn}=-52BjD8_!BUe9+l?cxYMf626^FUNg0K03Xg4{5qz{@EJ8^D~c5ujeTh zz)7}Fujf~q>iHB{BAYulY1xfb=w1()W74r0FQHKwiUH@*Rv8LDaJx%rekkXIA$DV!#FsdSzjV?VO)>O}P zRjkTOhl%##V@*$IyVIqq{7=1t3_tx~=4k!jq>Dd?SWzT;LBCY8IPbh9p zr`jB?Za*#a7F+trVHKn4Eb82ri}JEw_u_`K(DtR*JG#gBTq^Fz$8epo^f69gvFI}3Fd)Il( z2>yDF^B<=f8Moa^Ikqk)IoHw~K5*mrezP<+A5* ziAo82P&z%1S|dI1HhO$a#yvuhd&#(0=2UrfgHh4y#J_&9U_CK(?u zw4X}GPZ8SxB;(j!(SF4e;SmKw`wI&Udzy&;UucD7*du6HW{Lwo8SU3q?lUKYJxAIY#_O;S6!zw&i#mHyR5d3GxcQO7Q6)k8yCjQ1o1!#N=<0FjUq@u+x z#y6a&fTfH-%ea`IjMFJnB)^AoE&p`jX(;WM{ffVhmX zoALR;Nk5CYU3mLYT+94=|9Twr|3van7OU8vD;VF&{Cb~T>+=BcW7+M7dz1iew=c1r zz)po<$MP@qse0{aT>hsVaoVm{J+2trnE&U@AF|nlwyRY;j$&T}m10-GFd zSB0Ff-L3@7(R$E&9(ha&)_R`d=X$Yx&EE{%NpG#d(?qHt>tQ*ffeX&$GR6Zod^6+r z-ywc1J_bpAT;Oyo^1#qoHu976Q z4jm8viXSReK68ZNdWl;(RrqEX{27+h!vh^XTS(WLm`FP1Tjzp*#Rb321>XsLyvi!+ z`w4NtFr*eurRerUKhyjW7jfLP@49TC*_F2ktKX8%1$A$lC z#(P*l+7BFMeEaoEu-4n8Jm-4N0Z#V6=mEw52`V+m;;{eS zihB+Bqw~>-PVz66c(&Lzr1V!9pyPIg;iv)iX!L~{%Qf^J&fyiX$S69 z{_ncrBT`Os8R_n*3;&c;RC)HZ{lHVmD*)Un--zUACJSkI;ok||Y5aQBMb2S~!=GQE zgx|vU;77pRvwE zj$kctr}8gy!Jl@)GqGRlRL}Y9Q|&aD!6?2 z0)iPIb1r9*3ts1fe?{WZ{}v@*`|U2^WG8Rg)`=H0|CSpR{~<-h6^s}DhXUj~91y%! z;>=_rk4X6zfP?S2@aLo9ob2th5{I+?XC*+-d#iyv>HlIEe5VWks0%)}&{_U@F8D^^ z)E`G|{c(p2{{i4m^?lm~pEyPJqtOLIUWOu~7`T%j=DOf3fji~9UgGeFJU^#r|LJM>)>sS5KOFi+9*zo+h4JCu+B>{VUU3Yt|uAwPt%vjjcH4qJl z!w^^>EH{$g+fA=WZw#Fu>&5%fDZV6-9IxJrY~`>^pmHR|&q|gc-^uRG&?H|RoyuUA zQ8C!csI(FcB;E)dEU~@=nKcp&S;1=jTS#gnq>_c30tQqPoMjk|^TUzI1xC$+hN?*2 zxebP)6>rU=x+FYU+|$zAUmPq!d};yQBnS5q~Fy_>sJG-*pF!}}-8+9g+^{fT`;_VdY z7Ho?4L$KYo*-O|Yk6J*tZD=Ynl6@PzAY5HZps_awr`W$zi;`Y&Q2IWLGY!r;vHXrH z-R@&k`mV)y1e|=!hwO(5cjT;jtF~Kv`|&#J_V!|oD#kfg^NsqtrU*P;ThwgS{$)mM zSFAhQhj&tQJ0~E+Xp0$3x?+o4x{NlwQygzAA6S8-LzeY)Mf;;|#i3aMz**36j*-9j_+!^5PPhwpz$0e%?;Z^3S1HI5Z+S?oJ6*0W8yqCie zhB4AGif7J{r7`bj!DX9qp}bw!l=HWp>kebm6H{bl@X4iAXugbxd>iA--S25mr(yo zJt8FBdF=PG%lFh{%l-Zky?5>4VkD!CPL}T_3#y(RcSpa zM!8QKx@pSeHk+Yg&N7>6mRX&c`svTFc}Lou@BaQ8A~!Zg!PXQe09zLn_Js zvVRx7q>SsO4bkN%qz;);dv7$V`+ZV-@mw+(XfzKMs*|RYq7Bp!j&x>2th)+F6wn{B z6GM!6_OSwskcQa{D$n z8>Pi%BD$ipKe@#XgSa7tj(o61T^L!IGBjXLZuH>%p#FBFwPR@_0ZCVVnN7I7Cf3^; zMK>n%3)SM-l&&a7z=S%QN)6lwXKKY&_G7SIJkTFS7V`i1Nu6(IQs<)yMMCwuCnOD_ zaws;tp0qXTt@(HjyRDVcX-dJ8c`Zw$T1>c+WawUnYM|ZCdLYd6avI!AX>bo1<+>y= zjLt?APO^X$aY7ndhI3hBt%(Mt?hlPCJ(Sg8 z_0g5^Ajz7b$ptE_?UwB${NB#~C^@%qV{2z)XD1uRtftN-I38r6H!58P^kZ0* zYtgL{Ozq>OP%IQgTW7RH40LyOc3X^(%budzs>BF0lSUJqbd{R5EM96->YS)oN(4KR zGBPHzkAz8BEJD}V)ZmOT4gR*SknkeJFIUdg-Xyg=yaLlpoR1Z5#9R=XqBZr*nwC~f zWmeWjjBt5x6q@Wd`ooccA(YQL#=B{4JP;76ZT|~1^Xxog!@`s zdT6jyE~yE}^F%SCB=ss`)J5i@D0+U3Ng7RDAf$McDDmWj%+5%O(hVPXqajyHN~QJOkqOAJ%gGiVN1Mw^o`Au=<^`I}nQ zrHtZ1>bY`$+JMI?k2xAbhe2!CO?7S7_6e47^XO(!>t47%c~~f_pE8aI%NAhXOQ%-- zgRREwC&2(YcQqW#1w_I>SZ9yqDyg=q+Cu&N%-J7wok*|yvFgQ0&HcY5(9{)Mjtbe_ zp_(8piT10F2V+?jOWh^OgBGhS+O1WV5E~4k-E1P=$^-8qH#(9{oUB$KTt`Q04fMI# zEi#?So-i~=Zr`XL2i)vadbCRP!tzK=EvmsR2WGjfl;v=&tCK-Usn&9mZMc_GJO6Ul zc=CW$gEL2M3QHOiQMeEj{bx;Y$im*t4FwsGVWCC2KB!bz$`4N&T3ER!fY8^fL~f31=SV*D6ok zRY&n9ReNS62IZ9|X78z;BXu6H2R^s07|YVr>Uo;Vur<)oR4E->Vu?a4IPRGkc4yI8 z)q9L_*J5=vVQlT}X~AmRG6grN=XJ+0A4K)BDU;kiP|9UYptrq~tyI-d2%<}e+=Z04#u5?QVOk%zUzJvmsO)M4eB#LD;R z`5Q0PE#0%O&+MM$IphX|-Im(g zToBTIY9yP2jFg&BoVw~%2p9{Lm+EbTAw3T3c@iuGZPVS_gVwQ6&*&6PoK|`qLohBZ z#b!q1T=}y(a@7M$>IBSmq1b0~>e0tq)&v8!(Uu;zQrpr-RW`{t@H&tz$Z>@klFQDh z%j$y*N5)sKtPVR7_}v%_P#o9ow%&3omEI$#4KNx@)ov2z9EoMx+*aC!3XkzGLj^VLk$T0P&QAewGxdf9SQUps?DQLpn8|$KJjnjHeFWb-zTxfGA zmiGb3?rfDzof6Pl>S`Nt0d@}!{H_;v>KAZoK_Q1iIkt4u8PmOkovr#eIrOd6U)l5! P%l;=Z#GuazH0^uT%U1ZAQC?N;)rgRTgJ*1435^qaOQ_Bv=idZ4pul7ZvryPOa z-bgSI4@JU`u0W_)?VJh(tzAj}(yAo?R%Ll~fI;>AED1%$K$Mc16pGigwMOzGu_Mc1t5=<-^U7rIFSr z_0mY)WM)j1(|1H|tja5mr0WZ=D#2Si=Lv8ok(14g*?^O$ja8dDlfcPBR-Awyl|4V~ z9s2p)87R)yo2$EUxD-$*n7pn1Rs|u#xoU_P()YxI34Lk{hnoe2pdwU*i~!h_RI_+p zw%1&@5k>pF{QQ>LC<}uB5X6ZeRTfdEora>KyBi@ z^p+bG=pw5tOC#=5Phv7F4OXB-8f_IQtq81oX;dti6OX_-iOIle(%P8KV{-(_jk?aEBr>I<%WhK~z68_FC7rjj~tmoKN0THuBG zmO_R+D1U`U&#q5il?%(Z!#>d{CHYYA$It_4@wEN&CBM7-C4f@pAj}k&mi+2&+F)OY zgM33=j;?8OmK%5$0+DGDoX@|MUBKJz-m>+DZQFP3tgc~EM6lV#S$VVb3kv7VEh?5u zO6SclTd=Tv(PEwOOvRF=&sI8?J@@?b6)RV*UbA-H`VG#FRjy5&sb8+GtM@iEDtq?s z^X)&-bg;RlwXOZoi!U8M66gqas$H*jhmQ61_Jt$;$D^_MiPujKoH~uc`aITcB&4yf zZii!ad&h}z{Di~p+~#y|*mQzgu5&K8v&y|jNA*RQv9$}QTZk}FB2>(soqq`q)gr)` zFrR{>TwL;|t*$6f*6i!S+{S$Uz$FU$_7>$ezHP79M0>GN2wA*yx^R%^kSd^bGkym7 zJXfvG4={dA57U{>*r~pFpo2JL@u)s_b1kk8#EG*r5DyS%M=VC1(FhvIbU9sMs=Wax zlAN6(b(7KV2*lK_Zoe81MmkjsN2kghdcsh+QyuVcb>}KTd?-eNV5F~44Z}3Tk+|w? zJkY)&77qk_SWdOu-xUq?scg~zW2k^wY?_Jz zaOA`FU*qwtV9rf&8O6g4`lK2hygnb1hq`(F{Vax_O{U{eV$f0D372TX&>Sw-!2#x* z2jeWbaIGkK{!tFXWmP|oP7r$jb(P-D_4fg4Ri8+Dkg@)3fXwwnfLYbAvgz^kdD2yS zH`nh3)T;gftAB~b;`$5VGS@!~7}jUyKx4v^Cb-Q;hsnMOwpDzB#mgqXIsQEsUuEKD zSo~TOj|A586YfK6{?;nRRgJM-GpKX-Fh}eJJ5+2Xb zUnyYbXAeV$@vws2(1+ZeubTsCo9B+cgL8Do`^-5XOq_$cKAs7y`VZ)b3nB05X>xaS z{hY(3AWtL@%|E}CWzX&2^dP(CN^pKwGeq2~^N6$NO-~OvK7rGv5KMv0&4F@G!#voX z>4JR}2x~6r34_~izzs0unaV#MXD=xu2)doWJPf%0TmAHUmr;&rS=mn5CK~dr1bv>N zKm2^I1Kj*>!7%KH72Yxfes~7_)fw;}z~>qEg}-l4&A?Ak{?xwk_anZCtmaAdPXcEU z75%q;>Q~=aS4Et@Iv1he5&lMBQ?2atH#Ic0dfWVMa;?wnCw{*gjfNwB{wI(0gB^(y zbs!W6XMZ#lj(7Qk-94-l|M=*m{|hBC{B$UpkK^`QU& diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/kerberos.o deleted file mode 100644 index bd32e748e877f91bad7aebd4e0e4efff1e686b1b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 86232 zcmeHw34B!5_5VvI2?-Dq5ftk-AX*f~On?ZeNK66~4HyY1)#@aK2}D9BCKEPA(FA2W z1W{|%{@RLF>sI%=i$-LTE*7m?+(8zJQNg9wJ^yp=^5#2t-U|Uy+kd^EyuACq@7#0F zJ@?%8y?5v0qLQ)6NlBItN!Dm9cBN6vnlV2XA0wh;tYubR{s>_m8}$u!p3FC&iGh5be@6b~{7J=; zugd&Q?`8X=hx(%zcuQJldi~KeI~LCG@kIFaCt2T;$d2ut(jQqX&qP)nS>un6>sUCK zsE+r2s!2*B!S((~(FT9Zg7x_wFZ-KTWuKk@^Zax2&pqdvtV0WlM|94if=T;*`g(tP zy~>(XUr~3===xw)L%@6DiQXIq%&4fHRuc>iDQ=h$tf(&xR)l8^I?}2O);Cl)goCx= zK}Q<5`WyF(X4Qq~QIh_lspkbN!$fT(2IZN-ikUHg>q%h*Mt9)GlfuIBdhx1fL?)FPdvB0|Ht{eEbD%Ba4vPA`yg);sD{ z1&#n6LFG1(j>}i9bLry$620N70=$6r&_y2fAwky`hNVC zYF90_ErD5~X^l0(hGT0hYWWDrCMv+Sd&ms3)5PHUjn(zR25L|mr~+442E7g8`s&*0 z-p2asqrKJCzDy6+d#h?HrV~x=G@`4d)@f=*JR|tEq~pAB z7+P=8In)uRmiF|sD2ZEA|&1GX!F49 zgh~anyYxqCP!U<{Yo$>|nEWnRP*ShV4zcp~|ESN8_WA$Af6n9; zi;|YRvO79D@+XPr=#uv~kk6~iu|wB2fAqkGk1yxSkk$MGEn$>IZ@NvBJxYl?d@qzZ z)xfn>*90$G-YASd&Qln1Ss3}otggkn+RCn2an)2MkuOM>lE}Z6X1COlP#JHzC5PhT zuB^;jU`fl|IuRegs3WWS%VeH?&92iNApx}lq@UszTvif!a4vDwZG%7Bw3zhvM;4`P znZ(0ZSF0UaWa--_Ef1Dzm88Ogw?Ep#9Q@IJs6)wWzJnB^P9>(#THmLN?m=c%(z1v% z`6!W*@RcPInO`kfWa{tlI?F9LnZ`MG_BxFkzf3R7!^n7xEgq^61{?LBjV#1eVWz$fJm07vp`lS_ER*; z9vPp_2HqlM8OF~fsk<;ftJ$gXA7yJryJq~b9E(9E(e6c6X)!Sxzi3PNkmBeG19>e% zcE81IQwGu}B6HoWt2+@1E-)HhE*g!<;9lG`$@UnU*7Bi&k+v_HjPOY*&)Ze5k!kK&Ic z=Y5iHeUMy#NrtuAb2!DXPC1zHds9wan{IuaGK}I6rsgfpu-a4W|1ZPZnAV@-&D~BU zd{sBS{KqYh{&trmakPLYX7G&KK&Ep2WoAL zBVRu?h_0!*6%;h+r8Y9F`9i{qqrY87r;^Cq(V;ZANtXl^(RETw&u<#t5k7c)Xi6h7EW$ zH@)rgH+_*59>4dbwl60BV>+@P8q=fcvx_hOgTHBqbf)Ik@b$&fl!27Z`XXPe zZ{1_WhZ^EHb<6N1)nY4FbA;=!$!g9gdZkoS*3x#-GP6cXXKmg5NE%ZWN6t-`>fbIX zNqwHyx0cgjfALf4Bte$cT8a^0rE5vcf@Pvhkg7@&yX%&%RB?0xb%R9~#?T)5>W zUtX|KPgjd0MM?~L3h~v&Ecg~jCtIS2pOVnY_@k2->t5b&CZ$SGJxijrUb>T4YpD5a zE?>@yjE`KLK0b2KViA3q+lu0dcs!-(=&F@K$t5aRCgeQ3xMfbdHlz|lvm@|qGE_-R zUAed?`sFBdk2aE7WycM0-ywPgxe)_3Bl{j#lzIv(o37LYe#e{~P`S8?sv-IPG{mrFV#Uu{)@3#Z?a-Ihj} zpFF*-h`nA+4ND@M1-%|}Y5&!wEU6TU>YKT1Q`JBfEY*ef75tAIc%4-De-04$bN#7? z`10OMx6Y%5s9TfrI?}BVlXj3Bz3b`oPP+AtXA1RrFQ*LtRl3!jno98{si}njDwR5~ z8&gyNo^HLKdaPwd(|k{)TPxG;o;eQ)#RvlrJgj`-pEAL z`I?`Pm5PU}S&L2*z?A*{O&9bde~hHacBRPoe!ggRxN*;Fo=Uu3TB2K3isHy2<0G}{ zg~!j$&RTMZsKq4dKed^;gp3wHmi;ekX8uIh-Mwa}l*&&uv5CzL&ts^Vil2Um)_aQ< zmmIlZaa*ZqR0uzd8o;+irKLV@(O;^%=}J3zE7g>#II$+j{f*WiP`+)VeEo_x~ab#rod@;qK7?GRX^qq|ZQV9@@%C zTGcXYk0)XK>+5K{jBH@H&r-Qq7p{kY4ub~jOR}1)No;J;P!jooN3>6oXUpEK?G%ym zG1LIaGTeiFHmZD5V^8C)tfkMh3q<|YEw#~5EW;mpu4x+$#lA_(T67AL`lH1(f-3IO z^!deESBxZ}=?fY&$%pKe&KNWG6U?QBMt#YtZJM?RncLp;fxEuw=vWrl-}y559|K!6dsddr+AsjD|LW(N;k5{C(pD!K$4_4Ij*($*QMjon{^GM zQZzeP0ZFOto8!1_Zr>Jn?b`D?P*LZ4Y0?qYyXNIRlxc-FkheXb+~=}PYish9>octt zp22^}wAwwX6#v+hO8D0v>P!}=q^`@fo=KrD^`jKu>zUT=sUgd{E-mllp4MAwl>LR> z@;3Ig{?Y9|YLl9KSS$UX2ssXz5c_bu{$+BBcL-Z?H^FV+8_6KP4rTN0@w z|MiF}N(s&gvsWEpP?#t!Il9om}+{fiNWeq*H7K<&$a9=LC(9)V5 z?w3Tq5$<0cNf{_2TqaZ&+Mx1gv=1%X(1IS%dyG~#Hr&@qs96)KjN!fKCa$9#5#<|5AT^QG99Cy7;{q8omLOblJDZMy?R3SpUH)G1aCvHL&h@=78D z50_;$?C^BKNH;i(t`S`~OjWNJUF#SW))poqd(oH95&b#z+nu>hgRdiS6 z*ZJLp{*)ncn@UJ^<>Z5H)g(krbH`KhK_3g_DcwZv0VLZrolrD3au}+cJMAu-gfx(g z!t~fSVdhMo_2sIwj`XrZ8_7XlN$%6!%X&X~N=K%(+B2BCV(O+T{-r0C@I@)q@hlUa z^%|^<%QCG$^&CNyW$u`N z$N%o*f167#k|XHY^>aj|9exkm|E-i9+Q*YcIXJeD zj|)m@AMYSQw2udiMC233G$kTZi1zVu?jG#+@muKo+jxCnr80M!RyCOVPSyIZ5Q*%m zi!mKL-b{CtNaxAA;wq6YF`pSCg~;dYqQCM(`}&Z$soK{~bV2I|d(lTuB!O}BvsgbW zUhFUOsrEa{eLU6TEUI=-(iFj58>eA$5#1_@%*{52#+2w>xa64d&A;GD66i+Vjf4p;Nnc-dkd-L>G^E?tvo)aaT|N2 zT0YTF$~t@ILi3rd=4**X%*|-tqNmkuH;ECkezj4J4C2Q>C6N;jr>QaNCdWZ3S&MF= zR7%x;V#)rGf(`3$SJJja$kFZbm0U>4Zp-KKg`o(* zFT1DyD%*Of2aRvG_88KXZC&4UHMIfPWzoGm`QMZL?-l;{4gb3`o0}9JaQvd)*;mgy zlfS3uol{`_wXt;Xt%tQo#rvdtzAkt^`DASUb0*nT`LBLvn$^s&N-&9fB6_Hzk;8EH zc;YJtVYu}-K?IK{t-G!lx|KItcez4kFMM3SoE`T2e9n0_$=kgL5dA2-E)O7L z<0+V&w!I`8Q&oU!J%nen@;zwfZEMThT0|Qw*AHku-$+h}^Z8pTiG98I>Q9^B9Iv!3 zWQ8Md!Ah{7k8RXCwOZK~ZP)iBbER$O0Ir8D^uQIIj zMp@R)NqIZdt<6dQqQZRJ)8~r}>r>B^e`Q$Dr40UihV@lSD#hs$E8$D|;p+9NsZV5B zFY?3HrZituhV@t)KNsB6E${XW>(=x>)aLTj)hqew>dpM`;S6ehcdCc2 zjijrlc?Wv379C45u1`&0(5xUpjGzJv&*aBg-H9mH(%&xT4q_T$xAcoviRM7RA@ii3 zUZ{aJJ=BT4uyf&Ftb>K3IVfbcWwzTk3Iwgy_Mw29NkgU+PrbQpJ4bOhI4|B;$*?`Db)j zkliN8D67m$y`MxqtbX^z;ZY)0_^jr4DcNIWiVmS^f|BQEtEUTBJR;nT_;)&O`T;xE zwL-!F(vI~DQImG(1tMPQaOqg-eKy+<+D;Qw3^9+AlasNcVl0&PLe-yJMQ5rCcYAi* z7)m7G572GL^+X`sjw>iuyml;4fvmQ-b-I|m5d@)pUgx)`I5&s|Vns~v6P+Q`Q~%wI zT+r^XXGINX#G@^l{=xVGXH5~IyUZWrxvU5RsX|lgf*&PW4qdQAPb#1t zYM}U*I@?RKU3vuTAjkotF1SHSF_XI1!H;HIFQunaoL&WkDkU}-Tehhc}XU1`S4F( zyA@Aczvh?A{;%OgbDM_=G3!#Tf^`(kI44_T!_AZxo~M-#d)DdGfT9aF{yu5L)V~ zgIWW7jzL%hyFn1a8rb~=ltgFH8$t`X58&s8v99M?AsOZkVz4h?jd2_7_aP2qoKH^= z#GqflqVMvGFR#+E#PN|Ku`db!{+~V(c<#S>BEY+R?cNI8??ej6F9~AL8-$-^xBXm? z*X`+K+gdR`hvzKE!u(+Gy@$Ds2kbF@V)KPIAwPDVLn_jIpqnut;CD)6>Gz&qpNaQL za9Z%1%lzSEF@JE{!J zQ|J}Dd(#H*>}kE3mP+w$X{m(oOrxROmuabQ^t2x8#?NND`TpF~`c3*m^5NfP9W$Xx92^XQXZd)>c?-}Xo^rae&T6NzjqYY`9r^pk&n zMdUWR=4aIO4eqP4;^%!<=%ujOcTsw075-?oH@&*1pWF(g(?%Zl-X5B_-rgf+A#Lv= z_rNNp`fAaKZ=Z#8{LzWjH<$KPAIP2KvMWm-DJPU-=WBn?c{%zxP2}KARN}q%B|9II zdS$Y8;yYA8v7qON^zHUCs;<1}S(*Qm_hxXH6j?EsAR(G^8uu=4Ny{zwQY|1%_@G?q z)|G|7X5sEoFIeekvi_*tZ6@{^6|E}rBOWRXH4~TL8LE!$UCmIulPP70GE%Slt4Cjg zgYJE$pNX@!=%*2`Rzm9@^gtaYv_ z!D5}jA6)@)k$aJW1PW~kRn9HqNksG-POM&gCYxwULStz#Qi4=bMPxs2=+p>r>0(=2|g;(yGUmhHBY_}iHODI-M>=Mf|gB%F6{ z;e7+L@Bt)!M-&^&snMJB7%eKsoW6B55GSLmfsK02{*qNZEQReP#Mm?b9sKro0m|V^ z`z9J6>1jZFTl*Hgx4M&iw>#eB=j=kG_6XkJ+P+cpwePo8QR{*vZ@0f8NtTK9ZDWo5 zHVbwCh+W)IOS~@!#wz_ba$y?vuSy<3lc?OEtmtc>!GAGDcX`eeC__$>g4&4 z(SOfiiht_qd;9*@l_{wdzdq$4qIoc7_^ta}@2AZFHT_Q=O!42P^^NRrJ(`wE@u$<6 z=8d%Bm+x;~({272`&rkd52pB<^uBHTS)0;RDc+XOG>bBZzq6mUB4hrm^uPOHiht0( z@0$IrNRL#CU)h6c?&>jo)qeDD-~5N^f6u`b|5aw+KkUb!B~bj)Os07$bNJ2sSuMTh zUrYb922=dWtiHe4k6-(v_@*qT`8q3i@qX6*+4H~bYu&%kV2W?vr|$=St#9^8rTAsN zndbMsbKmQ0{j>M{x9I=AgDJkaPu~~%S~vAcrTCqF#uCjZeU4q<*ZMF!$kNWrp9CbZ*i zxVq9i=_v1nirP`5P7^zk^N!u4M#+T_0|wZHS!}m|RO+veU-w?xFMa6L*o?vUK`{(zz&BRGli|uG;r< zr`O(+GOnOtly}hNskEbWqj%Vl5krO@liMh+d>8qK4apgHq(qfGdXr3qr1=xAB>DpI zz@FXGm(kL|L4@+bVITgN-z)pFQ)=>AiqaCa{7pQE80{&UX*O+H z9PLIyNt>JSS?GwgL8dL~LAM6d(NnF^@Sd)=zD2A9sW65~$Ms;kVO^jT`B!u?Jt_aT zp7D8FtZ1)^lilP=E@Zg{J;w4WzlX(ZZM=sChr{@v$kREQTn1h`)~kC{C~oH=pZJWI z44CEbWG%-_$L+nz;t^8#NRWSFo zwK9vI5|Or$^2%~cRN8~O8EK2PToT);l1{RdinNPW+9T7ukoNIZW>UoM7|UIy(spzy zzgvZ1GOI{y(eq6X$)?VZwt6y!1)r?ao}kk1iQKs=?Ny!HS(njT;ZwyVm+R{)(E+Kp z%Fq4O#LP55DMt5>rsGA$o4?JBD?{+DM>!)@XW6e)1Q9)yA^!37TyAA8slu;s?5>gs z9sFc34u|qT?O){AlZh?sI78i!^`+DgslL=p_ZO@CM^M}nc{tt914Gu3hIzBX6;tUP zu9xQ-IwpRiW(aSRZw;B+&|nQ=U`XJs2_y87^SILbP-U>8p{R6Z4L3Kg^H z;b&CTGzN)3@eXlr*%ZDZzIah3z7c`AADZAF!zs->lkyy_H%N1H;z{L5-i6rY%X+(! zj*RCkexhfWv}NK~5jv%{vnFYctbtKR#OHK^EaKQu*q4ige`R}L9)dh05O&X#$%@Ky zsBn>QV{J|K%wWwtb~RG~`@oR8iu&*nUoNI`A>9SZP?`Y5`&4JL^JF;|`-W@(S5vN{ zqS8qL_Ojt(qDHwJ9?-cfDpKkW+l4N}#bhR4o4{Emxw(N^6?MAYW%=-rHMtafJbCPg zqnycOHQA+Z`Ep`qTbN@i2gwue8H!6y;(dF1Wn~~Zw=!544p7Te6QuI)LMp8Pj^y#) z+f^a)sp5qUO)LVVIyp+&b+ULd!%&PgnAvhT%IQM7ctLTBNkO}vAID_zVjMg--pY=- z*<~se67#^}`TTo7@g0!^|IQO2>!H)CgQcfd#@E_}UZ9hz7;D&fRcm8P`HsssfAWnR zQEmm@dN6KwVm(-=S^n1C(LSz9a~XekO7A{*7o|tWSz1=Ky{Y!M=kKC;yo+#?x;NGS zw%lEm9ua44(c0`yt-m#U7qzuDVl{YgYW;1wyC|)VA(j5lY`w?qUDS@Z#_reit~Gs9 z>)q$>taL%*l*FDK4V@62vlqQ(_t`nC?91UktGc45dOl6PsQ1Y8({G>E1ZmWo1EW@J zNayzKDi>5@ST#wG7a1opMoW(!Xx+bVNT5DAoqx@>K0vc9`J1S60?3>K74`KM^RR=q zlZ`7m?d1HDK%k*cac^pTq*f6uY8G90Q8g!Nhm@+dr$e6?ywATWLI z+yMWgF#n)tb$DK2c8)cqGBj%z{iv@sgnj}uIAq*}$;XiMR?bxEgEInE_4K=xR151v zjdfzB=3D(+P76e0jmY3KMqTro7Kf#DTt$aksHVCD0;a!*uDhCEuVZ6+ey-Ei z^kUuKkk1?VcQt)E(Q-if57Tv5)6Wp8_Q!{X&QI59~(z z#SZEDH&?o9zhw^TdF|aye;{GJ+^&{nRVvyx$d1KF)Y7~S_NN$QYRT5dyPE!|l!D7> zPt)^yv6KGG3Flze&1?zV|H~*Q(yKLieWO)HOuLxrxlTCAU$4@OXQ?XACo}zhgy}K? zGHat^p#6~B56+AB=YEQqf2fM(=c;Rcs$`JDo$4&FBrV4^+@B&GPspb#5b-QjC#JKh z|3Q@4N&hL&%S5O@Kf5;d=Y4mbCp1ompCld^5v!de~prV zn2pGYp{B)~k~_(NL_LHqSLsUg*|0d zyhmcAiSn;@k-z+(GLc`UW%jaZ-|is)SO@u^YWar!E%DW)djCb` zflsFWd9!J!^3T~I6P3%8m_PU^Zsxx?C3dQRm)z@6{$4JAMPOkbS+yWiHrP&N`9+K&;G~X4x0AA zK*=|Yf2oqsV;&4<{eQ?s|9iWr|9vj{k9k!}ZB@cqf7;eALH~^|`X7=d6Yfg?1F4@D z{-@;V(-@V$Rs-s6+J8SvPbwsa*Cf=c?y&y+%CBkvu}Z#a|GT@W|D`VaukWJ%3taSX zbM*DnevZrXo88Ygl2oA!UM zi~3Jg>D6#cNu&4vx~TtnO6cT2W8RRgS`|n3pRsh9`d_HzoBE&2lPwCnvj4*>J)Pph zLY1E1wZovYWkdH?{S z@3&LRh^c=jrFYUleXFF$_Pc~2Q~#g3$ls~t-?t0-16<@URPtL@dbZyLI!yT!UF6@p zzfAbFO0Q35{>Qt>AG1xSP~E8Lze@=+BqfnW|MeCg*=5 z9j5%hEBU7X_dZyr-ffy7 zoBD?a%Ji4Zll|ZH|94#U7n2Q2#qWY*F!g`iMgKvc$yBKS6oO3skI!&!KM&%CEecEI z$^LKZzg(p^%xvAO()0VM7)<@?x2_%SKbL=Yhr&j%|Jih{*(vw5K626jm0=>e@Ov4P z|4scT6Mx1`{p)zJM}gl>#bD~s_BBWZ`4nClqcBJ*%>HvO9j5-bDftQh!-FLX7s!+S z-_*Y+&9j{J->K5`d$|}){ku_mC;b=pm6FDQ{uRW?)c;&1-_-x3d?|Gf3a7Z_8Uvqp z(ZB9wNwX{aKjET(EC0d>1+@P(x;FLi)6?1iL*qp9UD|)HN^knlPL-bDPsU){zk$*_ z*?;@tQvd6~|ECipQ-9jaMcCA||E1j7P`Fl}?Ej|ykD+-IV}_cR_cWR0FgvA;nEDT* z^iKLO%#o6GJ!Sttj}BA+Vi)j7b*zmp`Y%)I`JHeKrv9(F=wF^IC0(b+A*_Fh4paZ1^l~o$^L{R+78?p1msU`v zH_N~E9GPCcpDv@~zo~yYrFSa-&-_wSj!Mh=*VAF@f2E83jY_^6#wsp}>jz6*l6}sO={uBrKvmN9=OX=BCrv0RPs&#AEV??Qt9={t0U@sHqBF6e>44ZmEK&}Hq+nbl76E~ z&uumaFJ4gm05XV^{BpJMWZKV6KglKia+Q9dA7DA|c8Bs`NW9GQ|HwstdASt4EBWuc$oHQj>%U?n#$lH_$nQ-RoGCq0oc(`! zxr~mn5gG9s*O`>wDgU=A`F=&u{@+Z8ng2nQo-tGY#&QBFXnJ{-*#4ZM^*74TExpO_ zbQk@1D*bgmW&JM)eKbB-$v4Ysd%4v3D0#B~%TkdxXYdl0-X>6y-W4VyuXTET_g5;t zk$tP5N`G57O)1Z2{;zb&fBLCX(t27S;=uWj(xKDq{8RFTvLnc9ox%U@VG8;3h%OPnczh zr$0o)_L--*$yN-H*WYW?VZ*ab@g&f` zB_fXt`UN(K{k}&$xwCJH$Ol61F*Z2bj=@SJmHB4^MqV}@*_j7j?md-jfAUM)FYm>#I8AZmf)in1?W1S&k6Cw>dGUYc*Nhj zNbot)2IKjhWaAj|SYz-~#BUOOVt72ClN0C}@K^;2_&UKShR5?MN}!i~#wOq&2tF}9 zo{v9)Uh*k+!B2I;OI+{?2{=DjO%^N0^45Jo;jwoKh=I9+zSIVuwqtBJUU^Ln9t&$# z?7l~=bjGfA%wwIYqj6`C++`sS;|q^9NWaL4jAe z;FT^owwf^#k5v`BfSAXc4p*_L$EuE9K+GdnJ^)Zrk64k2$0t%bCc&x`&YwJSwKkT{ zBUT1t*E;60&ezenvq#Lt;~;V2v3Q0YAATeJDu(Of)ICDaW}A479piH0nQmh6h#6=+ z{j*9PO;?O6M76Hvqh_KC-1{a`#E>lfnjSU(ky$NIr|d?8-iagTMW9mj}A%s3E{ zagTLbB1niwjPMh0d8}U~f`Xn$#PQ)}vZv)R?s`q&-gsiV+NkJz8+W!UoVxS4@UFs# z#G#h8L*ZtN_=&>J8u_`x&76Is@CJjwN6Z8EwSH;f{A)X$-|G!r{xr4 zUMqO(Ckn4akm6p2Z#3{D6#j^TAFc3o!*IC@UuNJV6y9p!qZM9C;}i^q3g2$vrzm_7 z^SA3Qk^ivi7h=I>geAMd(Hn&=Ze`F&v5?1(^20mZm z>amG^ccH=$HSBYl!iO685``BT_*Dv@V&K;){5%8yox&Fw_{{=0K+^Urfg8plyiXcu zMf~GPT<}&I0cX6$_TeJLfM2Q9#=iPCD1b9v1h~aw>?%y zJfN;TR(BV?M*@C0nXEU=Pj$aDmhb^EKh>7~oeTac;j~1R5PDLUobX&1{8ShG8W;S2 z7yMxt{ACyXV;6iMT8MDc|5z8igzy0{f4oLnO%j93;r(`e4i|5J&$t1$GPAWT<}^KJnDj9>4M+qf`8(IA44r&_CgVzvO}^QO8ZU62eI?_#DD}!+L^#|7o?rW9tU`y`p_+;?f(| z2lV?Q=L)>SmaE@`xr1;geO9^PZwo%tY(AR*v9z?^8`c5zdma}E{5+ffFcn)ucz>8D z<|zEvF7$T_yvF9E--FmrxRd?|^sA&b-pK_1BbZH!uWot zyWhnTz}6(FLrllmE+B9}aYKl`y{UrBE_L>Xc21j8bh7b*6M3f_EI7#D!#ywTP3@d? z*h8K!+dDW(*u@SM>~9YHh{bKzl|Uo?wktHIXU5BN@&C9@*IXPlch_6FvD$I0oHk-h z$eW|TC)8Op?`C~5?kColJ=@mAVUriifW7rbpp(s9N(yKzjgkV|tFxqFDF35PAxjEq ztHqLn;ruU;|IwzEB?ZUvzmfdUCzFUYyon?sBB@WL@QK7ek~bs|n2+ z7YrBI(l$f1LCe_cV9m6mYNk4s$VL>+mAKkuPneT%pHFU^R8|?P3;J>k>VveEt%Qn7 zCzJ(7R4abI9DlH)PVIF{cVheeSiGMs?EzC=Nl63K8yW(YHPv(-pbd}etg8B8(3PUG zb`I_P=6bu+o0T=eirU1a4Pu*EQlYcELNmLxVta$`aYv~NBlnCEzM+NH4RxW0;JBL5 z)QXy-(l{&X?NqHmprV0P4F{?!s%sowo44e0*#JnEJP8}gyQ0 zU1S~1qPwYBE=P>7m>KLuZt3jOv9oE%$FhLquDN=%;@P}iF$qlAidO6rrhW9d;)W3K zuynk$G`z6Ve zi>q`6K2gzZ^^}p1(uPj_&T|3?9qdnoq)`wnfiyr{lDR8N~`2Vxty1r&ef72IygJdT(YQZ0}6300AXmIcEG4|^BUvZ1<- z%*`oksH~{t&3U1H=K%vG}2PYMzkxQ;|_Tf$WCI@yb*e9aWa23 zd7Of6d$J(WmFV1z^j9<#R5VVXp=zVlV%S*P8N0?VXG0He6LJE!K}78*J#9cWPI}kc zKpiiyGGirJV`t) z)7QBAG&Glb`FJNSt~FfL7>IRscUV=OhRM39f660q%%$2fpFx=GBhBJ8k(FIEomA6I zdNFXaYpL$e?YUW^T$!y{o%Q9J0*k6Uuk49Ug@Y6|R(IQ*ow_T%H9IyfWy9zfFD8`b z^Y9@svWyy$ig06nkcSW2UJ1XF;>*+7*T$ALf{m3(%mrUiLo=lbw23H+<~*yePIjD> zKBhrp4&!Zv+McESc7#=kH^ zdQsHJOljm3o|hk{0r=EL`n4IQsXb^rj!d;nE7=vY^X^6UVMMi9*RZ_p3^YV^ z*KQZPBvZ{x==8c;Yk9P*cC@t@-Dos8tsxYcAvS@gi^{nb0h%-NIFW*W{**%TTj=y@juX^@iGP}nDqM1O2%)cL({h~F$ELXZ;tRIj#@f2y^o10F#T54zx4gB|3xf~7ox)=ECH`dut*yh?k`bje5{FGJW zGbql1@j5y*uAc;QIo=2OJc@HL`7acx#F4*#1BmI*r$h6Gc{B z7)So}c-zKVXHBo4Uz+^06nzGr9{~DXg){x103QQ5+If<~S)T*w&~oW9tq3NcK?-O3 zARU_iSimt~d4M+n{TPLt`QmF1%%96z^Y4n?xIxwQZgwjm8V+o?d+5;gr!q)^y3c7Xll8KBqS?=ij#aP03^13s1F9GD() z{iYA&Yv|B+`%!;6p8V1N(hfiRkF>*oOZ|20M~j71rkx92@N)sj{8j^w z`3(b(`CSM&>iJ8+k^fDAqrW`_IP!TKaP+rzfTO>?1UT|}2XM68dw?T7?s037XK4LJH+J>V#J0pRFwivZ^~O8emrfaARN9>8&& zyc%#EA5LJ$q`)WC{|vy9{#?LuJXsAm^5OlzIq(VfUko_XUjsPO{~mCp&lKDx|5qrk z?QxWg9>vGZ*OR~>^Tl42%KNE1I4*`z- z<^sUq13rrYM?Y_I!LJ1z?fiSd-v|D;E1XYb0Dm6vBLIIx;cVv*0N7LH-aZF6Xq}S_*T#gseq3OpnF$Jc_c7C!zC64X< zIe?=+GXUR2am~LDaI_CUd*#4#aovD@l>_4+(xLfeKzq0i@B+ZG9he9>>RACe+N}z3 zq^|`W+uPZIBmH8)vAw+!aBOey037)|3OMTdB;ZK@GT>O>asG?#EzWJ6u^l)T z=+^BA7U(fwIA6wm z-3s)`|9-$RUoQfV?U?=@L^EHT6+Qdy$8_lO{S5eE{q-;d3Viy64o!aq;F|%*dG{8; z!$7|k@MgfVUA+@<949{kIOca1;ApqMDBR5NMxe+1wgZm&^{0~36!-UD%OjIM zHH{chVEZ8b!GQmZ?&*9TrEunRDBwQ8D*zt>cnI*50AB!jvBFuO`v9K=_-ep^4)_|t zrvr}kA;6J-KHx}yDd0%o0yvKMt^pkBmjjOc?{dLcxZtY+UjzAF4>;3^?{9 z?SLcwkK;-CTrVYwj81|5a~mDHUZ`!n1>OeuSwN5Vx*Bk7XK>tz^f+#O7x-TUe2`x6 zzsGvwc=C3j$MNL-fFqx$0Y^R80FLx;0*>u7jvH}2={9cU-z(<8`eS|3zkka(+Ib&t zkSH*Y#s=TlEQba{;dd>G&*zz4^ZWeVs122LZkk?9d-@q}Tg5viJ*t9>2~aMZIIaLiW(aHQA!Nt*e>aU@>9O?OYNI7u1AU%%vupRy`#(Ss_j`tA%81%&P{@L9`wnV;=Pd~ts{<|1Y zUPLPBavU$!N$~&wwDrjj&~ppu-#tm*U_aRk_)h@e2DtheGLc{G*M0`{Sg)r6z7qK0 zxD@I2^DnMh3(Acz#rS0D*#9SzXp60=yNaNm@gccBA>qkJ?0DF|3Uf*S`Tr{>jXk0+-_^I<$Wd104IW697j(`uUpKe@y{;?7wi`68o>GfFAoV z{d|h`M19=epZQqvG4)AT;|k`3`s@oh>VxAS)MqQuqaE;h&`Pl9zg+0QQaG!N{bLVS zkOH5ud~uwE<$EB|qdvHvhUGg{(X(6}58(4A>>p19{y5H=2{_hw{ylpRd}^aZ`_*c| zQO_3vN4vcOIMQzd{9WMR1~}4x2{_I-el_6R0RI!CXZj$C=ZC4~~0l0j~i4 z8v)00?}dQlxc4%JvpzWPy%O-%!2f!{*8qMq;7I>Rz>%K!cjv%zk^U*bk^awsBmE12 z<2dtGz>&|pfFqxOyWkywBcJZ+LVck>`eARtk^W%7QP0BxNBRMheM0+o4B#s%uKhe0 zaIAMD70!NmG0^*gejVVYfMfqP1#skF2{`s&GXY0CF9saPW7hzV{Feic`Mm{jr2nJB z&HQrP!h!t_^ZSfIC64*!F$@Q$NB;ayEClEI9Qm9A_)4HZ4REBN4mg%eBj7kr!1vA2|J~j< zy8`&2oqr8DjuUQFIG?gXfBoJ&C}$7n1z!T6 zb-)Lor(-*V^9a;uKQ;^nK5e2ym*ZgyXSp~I!S~j1TyY%m!Ewb{;8Owo#{-Vzhe?3r z_yONf!|_8U(Brsej>7qb_2Oc{u^;>e;8>3O_Ye3s(*G9dk^e1#BmKRABmEyy3N5~)NM~LJ62>E~L!hZnep99}U|M@oKgoVUQ``ZsSPPmSA;9%zKCJ751 z>*;NPqaE&1IMMx%27GxET~J{BOFFckuKyOVLw*ijtr)>co-%r~L_+!8y`Md`B zJ3#+A;Aqc6XrEE;X@H~L0N^NhA>b(YF2J!Le*$nU$G-r+67*jWIMU<$&p2Mf{tM|p z0zNoi!hQ$GOMSRtDVXJ}`yIwnPwaP4?ik>M{WX5)h2tfB{~6mu>|YR{0sPU<4S?f# zX}-eQEl#FG`=|b%i}8Vg-wk|lyriEeW)Llom-PE-jNb@+o&`QT0RJ1{Xtxc3<9O)} zz>yyN3&g(xdbEE=Dk(vMZ{v6g*V(Y29hxS{#d9!OHqd7c>8kzb0l?8eTU~H`&kE_g@}3pa<8wFEhkwV91KSzt zzX2TS2MFrK`u=Uk4;K?pZJ!@%{ID4E_2W9jkLwIL&cS{Y$2r)3{b!h(r(|yIztoK`NwqzY3Co;8KfQl8`l|{!Jq#Z#tDlczdR=Az~i)abm;NY zGYnE-9OvD=f7tHj_VJ&&V%!&=|GP-em{tIz7Xhf{h>+WY>qyl|DAx30{mg%gX<4ZDm;T| zas5H>tHbz>z~_13gX<431CDmv1URlgYy%wWaeWE#ZtSoW_=NWF4LGhp91J+l>stUv z{?`GH{($TMNPn}UXZv4Hhprb70H1Y$KMpvyC%FEP{GS8*O~B{yRJx$Rw~;;vaMXV| z;7EUh!dd?&I<)?$0zK+q1~}?}HsHv=3UJhaci&5oDn6_yuIDTR{3_fZvmgxK>rTlxPF4~H6i^MF7)`lB(5)I zrjalTtPk?<2RQQg0*>^90Y`ehj%V^8?Lx2Lt2gOS2YRfhKLdOX)%6dfR!+gJ{)e;XZIANBzbj9W=DT<=rCIQHXZOhEwb zss`i=X_y( z;kv-Vtm+EP5%7=M}P1Fj{b0%;GSsbA%L%>xX#y5z_DC#eu4d3 zDbVw`nVL^I;HiMm06YzFZlgGGIVJ%KwWt(&0a^Y_TH2=Q}RN|Q5=K)81avRQp^^DM=`S2K(1M^=;hsJpgmILEG zK<>W53>|K`@=>$ zv>h%4KIjkly)F8~EsEas2mG!9{o!%okN&U*aP)`g0OvZZ^?Vs{wA&jBXMNa*H9dZx zi{*~*eR0`odR%wS0=zdfroiQ%4LCku#`gbEphrD%{WTZT zt^_^Lb)laHIQoy$DDVmW2fvHKaydrPvp!4c(DnKR;Di1%4si6J zGXY2cnF=`i&v}5O|AYWXJud+q{pT{kkskM(MgO_cg&x1(LH~IY=+S>(037}2O~BEA zwkn+chx=%4=TCqh{U<$@h$!%F^dJ45j_E&xfFAv4DB$QnqX9?%84Ec2&ji5H&XX0+ z`n1rY^ED0V(SJgKqyJnCIQq{o07w713h>n+_gcVF&)We<|G67*q+bCz`p-JRk^W7< z(SNo9j{bx5S@fSYn8%_2==m)B&u5U|gMc3WM}H4)`cILfH~k0SCqe%?8~CIDQ~{3u zQwuoy&uqZaZVMF7`YeTf;dkHYKlt4@`p>PvAN>cv??(T54Cq&b+@}CXJ)Z|0{pV%C zk$x-S=szCfp#K~IIMNRW9Q|h~;OIZ&07w5R104P5EQPcG z@Y;p;pK72-|5*Sy`p;DgH~r_gK#%@&8{p_a4*-t-^Elw>KhFS;cKfr!S)XN)uUCK` z{bvi{=s%wTj{egDIQmaFHY5cuU-X}zfTNy=0FM517~n{s3po1EXuy%a6mayPDS)H@ z)BukDGZ%35pNkdFr?2VI{<9S5(SLpqIQq}S3OD^{CD5b){0(sQpACSc|7-*t{bxJi zXtx~-XMK3BN$2YupkD`gMt8cPz~zqqa{%DzKLY_r|2Z0P^dBGKsOJcUvs(MWIzTbd z-%Izj{uO}Z`syse(LRlUqudJ>&i07_|0vL-eQp4}H|TjQ;F#Z4F8E&oUjuSq0UY^k z104O~Uw|What~rkfy)u;_W>N~4*?wMeSjnVXuy&Fbik3m0&t{1A8@3<1aPFk5^$uy z5pblx4{)S^8gQh4-UZJT)|B?-HE`{R2Lj#)aJD-K_N!_-G(Ga^3-nCOfgtN_5tIK^ z^DOWH;A&bg)}OJyDD{Qh{eVBe%g2H1*G+V2eFiW{f%V-V=(7bX^?6Xm`P2_^{Y?!+ zUcetxaXt+KT(40xg#1@18a^TaR=~X~&i2_|{+#D4I3We(ufMTn9Q9=S-z$2)$AK@` zikST8RdFugR2Apb7!_w+4W$KA4!9ap353@)I554c%HsMF@n7OSRh&;-0Ph7jx4j&g zkG3sej{scz0ORF=>t|<-F9Cdi22^+i@B=hRXZ^h}%RLD2&w&15zz;?hXBg1y_d^)Z1AII1IS%j-0Urst{yvEL zi~?N0zrpwkfR9lPALAziUJST?_R6=zfS&~P%K#q(xc=^j`JW8E_X$VaMrC27@WZJ||Gug?c zO$$OG4LD8%WfephT-g zcjP&Ro~P3DG7HSJv%@2nBp^xU8Y0p*@uTU7IuVvvMah z+sRz*3y*E`Iho534sS2}YUChV zI_cnx&e%uxHXMAx8F`}o%7za$tZTSx-R_yQn?Ocp>ue?Dz`ybPDf;~hvP?geeU~>} z7D~U}&=E@i9_@S{?W}Mz@7H!-E$l=K4rYx5E5^Z!r?VC|K?FIsz;>R+%m*IV{zU8kpk4SDx$yJ?7q;Y_qte(x?7ZcmUU`|N z>*v_u-f;RIWta3I`j70&`cL~43g-a0u&V03zC?E{vN_Q`7>^B{*B9->E0S3M;aFEH zvNaj)uj&Cu==X)oLw%`OvM(BM?v2H}8xw-$2Y79Kft?j#;T_a$_u|qTR80Y-2PP>uyZO zy20MwXndeC+SL=wt9`nBu}n*yOr$*1SUNgBxE{){+!;NXS~~M9E6Yaq%^cZpFDu%5 zt}d|A?>T!K%TY?|1SexV=^r|o`ckM?rB|*yxNnz^>~_XxAc-@!SU<4IT94iYH!60w zHuk@0dTJ@OM} zPdApP%E*kFv+JSVoCL%m_XkR~lW7DejHg~2cFM{pv^EZ0n#I-in42t4=5K?qQSJPw62 zC(Z{#Co^m24jkH?43zJR3MfvW7<6_(3Z#v#8`oKahM9g!Mb#~oelk4P->>4UM&C{~ zhcbixtN|z?qs#}Snk6%3{;JWRgSym*LYWRw+G;Ab0&gF9GS~CJR*9CoRv;Y2l~k=I zvjW=aii+2kAVa1VURo<&I~!g?=_lBfaQan6eDGk=NtHXnuMZY2{86#>YS9wQdc9bc z?a?X^=Wpe4l*;3DqkX)Nl{T+^;A|4w2DA^TZmNwumvWrU+6pX_OH_@RxQ+am66w}P z>Md+=WzgU%LD=AzH|+XTw3o>=5YeXI`U5r*YA@%=_Hz0J?d4AJ;uA#+-z>J?DT0yc z;AGp&k(Up2X7674)cuu~kCRdTT8Fb|rJ7{zSy>9T8S3&YfZ+Vcf~QYC^)yF*>;TN) zJMby-^-6eeXm3+326}oYy<0^?nV=QUbe4v2ArYI~C{j(eY~=aMDb3fx$DN zCpsnT92n1?^oua0uiL$0=4?Hl2M!*%Kkzn>h#>61UiS>o;S6inq<3e<(!dU*XvIvZ zQ?oDJQ)F#{?0>3gD#X5Bqz6)Rft)OMg`23#DI#({vH?IUdgqoZ&J@enwG`|#!XwQ`S_y`7`S(W|`dPGmA z@-6VlYo6(?f4Qdj|HYaUNtkZXa%yeiPX6rH~>mn$AKTom*>UHhFu4q z6t4#!7Cpj&`=E#Hm_QpNaH7(CWA(qLps`t#?*nf_EXxp!M_Dn1k2Wwsg@7Y@ly|jmpxcM<3uwX z2|4dza|ej?0kn_OBSw00t5(QmT(rG4tZKlte?ZDpxgIQn7d792X9{FZ!Bo~G%6b&V zh02QK_-rb(knclC3*m72KB3vH9TVtFYx9e*5&E7z0zSDSjJrb--UP{{feD-Xk<$9R;0bCOtr6J(w(a- zy3VZw5w^E$TWM+6jHBbK2I{w1b&^LOJ|fgIzLv`z_!h) z=z4gjlKR=hG4<<1RX6n9R@M4}0jmmus>s@w8t4TB{?_b|B%zk-Ep>s~=E1(MRBxiM zJ+`?&4!=nRTiODV>Lo3SzQ#oVw&?nJEXUHGjP|AmLT%NNU@+KJ9o%A7C1deuo{E~@ z&Hdr(8Wzh#2@ZER(HY7r*dhun^_+Sj=d&&;9#ZvHlktrGFE>=UX zl2hB3O7`|`1VJreZ@y?S0yF7vO(wvm)HW8SjMy@f>XnD5dO}5JZWCB&SfYWdI>@|u z4Y>Fs;LnX=foeHwlaB+n62zfg`$e+_+x$?7Qtn`1ymwP9zAaZ*atg4ltNNqKR8_z) zd9u|ipY#wUH867L*PV%U*XpTID6rU=>jZiQPU%cVb(tJ_e)P=!ZTZh=A;?P+6IS0pyn z73)t$pwo!Qu%zER?Rh;#f!dltlh==;@4XM+D`O^hNnlY2{dWA`d*CSPK2(NR)34@# ziVPnW-4kcHv2X}2Y#1%Et=OaMX6`<0;>ed9HYe50YYtoN#92}DU_LN;<*t(luu9EK z>ViXhOGvO4#^aW@2u>@OG)KEqiR89Wdn8zwjHL#XeUVhK-5)Xf_yQjW{Gq;H+-1?b z9p*RSty)LzAb|l9I@9csF-hwuEiLCU_z;IL;r^<~%J3yC8p4stz~K5wD6)w*jYQz{ zTTRotx+p8XU~eRvOh&f>pl1S+wLFK*4JV6mT9rRK1Vn~{f%7Ag*44rG_A4UI9W9OR zp-WmK=q+!FM>yIZfubsh9_5dKRZmuqfUzkM+~UcGvt~8jgE|7m0V8qyWi&(2 zl`c=uOu~Ztt!DbJqj|Mot?VQRvEf8gJjbV6rUW-#4wLu|RguWXp`i#&hX)d{6RS71 zEwTlsdR>Xln_+{JRn?bB#i~}ebS#9b+_j1LV?B`#N!;61wK16(?8h&aKPudMtYsbV zBB7oz{FcLj-_on#Qr}YI>Ba8=4F<{I3Gb8TZ$)MZk{|aqPL^MN`y2cl4}-rGXfa6r zJ@7tR{YZ;J^7p~}Wcj&dC4c5H_=iwA1j*kG?~~O(jLZ-u|8?*_S^keI?tFgClgZC} zTh&?_@!(^Zh|4H_)@PwP5JQYU-Lv>)`Ed^|=J81Rah(J8m*6f_5m>*OuW~_y(OckB z{04qEy{k1sk!JFL4AR)Ag3Q`S%hFsAuszI#i_5cuh!4QiO@BRt5Y)P(j;gz<|EGYu z>0fh|W|I1`pE31s06lK{_mO_Jj;TedyQx14bZ+|hy68W_MgQ}pzgp$iUft zGSB*n2mj;5|E9sueEfWe_|5t=P8CwE%?cT2{(lMlZuxiA!lh-sNW577xSyQu=kmV< z>_l74dU_cNok#rqFsiwA5dd!beVv+v9%}q}A3&!55!P=A9wwn^w+v?ful3MB+^MYL z{cEC{qLTvI{}le;&M>_Adj)ZuWnoOtD*svj1zuZ`%I= z@gK_mhk?<}eqXQFFYU)M+O&V+GOVCw&-hyMMf|7of}s2}$Ln)*)zz^(irJPx&4 z)-3(V-i_*LZ6kiue|w1^f6J4>v_A#>ZvJ~9uDR|I_AdpT?qU;t$x#a zaer*N}cA`_{9x!Ql$29O7pA-{)b!Uv1~HtTPRM)BewU*k3xN z89Rv|?Oy?xY5$LaAFCP+LwR8h>1TRQG~d7Pp}&XpR}drWZ-R^Y8UH!u-}GN6={LVC zd?b$_7eYUeJ~jF8CjNFNq^Hk#zsG~$I$0BT8}ugsNzhNb=^rM3v;0i{RuBGh;-7yA z{b>(=^|1oHXB~q7N#eH+2iD`q4g_w0`pvR@9HHkp@Vm92VJiPlqQmkJ!)2ELFFf=Q zPg4JD9{TsW=x=e+fBdo9CbRxOK>FEU$_95U{A#TPek^~}e_s5iycNLj=D+%FS_QWg z^dFu_W`4$dNxxZ650m|8Ycbh7+KPdnN#fUN?*3!q&mlU-e2m{j{6_V$_7ndbhGW@& z=D)!s|7$4!`$;h7zXLAj=ltWEh@nD>ei1)bA>0A-Wiai>chh#He`C4k>c`Fz0`}u; z;WG6@_vNa;6Bm0STxWFHrhZLTct^S^)|&?lQ&1mNdY52ZMrMh|wrDbB@Yt&7H$Zr` z)k;@Bj@@aoz~#D{?Xm*CLD6IB=pfg@YztSC^1}=8S}gF}MY3&CXD%>|+T2MO;DwcU zIXJY)aQjzZ{`cM{>CG1Tl?1k^hxvG}-R0xCdYF&r+C@H|Yj^p0SiWZCwuK{pVX&>% zLJ$yJjj)ADwk2CtF5OlmQtlmNTfv`}OMi8Z!cQ*fDX%9Sxn#JJ@P!hDc!qG(qq_+2 zH0W<5JZ<2gCOm22|ETbj)P7Q#^f{uJ{XVAOL-@Ut7~)?f{80mci16J8{vU)tYv7L) z{v89~qj2a%jWAnHrc|Plg5}#*fFWRKXG8hPHna@4U;~F+uw7?zC?6J?T!LNr)vBm$ z3l=3@f}NdxDU9Oyy$3!Ivg$^^%mcp> z@VWf40+Medd;Z6R-Ufr+~0@u}1)Rv-3D8+F4?pWjoLE!0Q!$Mpizrr(XfMoBU3|=ZbNe*T099oZPs~ z>$)!kKBpMJEOg-cEmk!*`FIx44R7$kZ}7ms=z;&*1NTD}chl>5;KLsHEgtyi0G}o1 zA?%;o(1d1*`3A4YrWKwW?HT`-!WXkU_1=DXI~JzwbHsS$CyKd%&l2;E8p1!Q@Z5ZZ z*D;3yck{!I9{8gk`0thc+&tvFq_+Y-A>8CI1N?X~ZbC7s(BnbB%L9MF1AiLuxniC( zkK|8-PZu|P&H;RunE&uP-$oC5Tn~1WGwy-^)B~Rl--B*)?)1Q)@xZ6U`ly?nB_8+( zfY^;bhPcZxmGq#u+&1vhp7?j~97LYL_u%kDzCOJbmrqFWF^;?q>9FN6d)VSIPCU46 zXneOf1yWw*VTru63~n||uyN0ge8LTaF8Ysfhh_FWgPRRUDAQwmqML?8?4WdGIkL^E zli4C0ZiKCg;YK*y5pIODG2zAjF6zUb%`ztOy4qs10{g z>%3L_+v16>&{yRBE5BebQe6yW+5OzKPhA-ccp#v6Vz+g{NvuFM{69Q6f~KKhD{T9& z>xGTcN!XAY@H??+zgC7Rxoyt5Z0Fp3#N7zxs`|3JKuuFG{0qN<*vfcfeKa0y%`=BL zja!jObO26iq#_%ly>T~F)WIQ-?Y-KCpzQp{IQ%0+Jg?=cr*QK(_ET;e>3CJPHssvG zjX0Ofx>eClu?h6HZfR}af_-|#^*9-yE`mM!K@?iBGnsPll0e26a^MN6$lC6Bt83<( zbaJ7hkKo`Zt!kfS{f)2@NFhbY;K~ZKQE9nS@Q%*+d#W0|7Yw z(40(c?nrH@Q?;MDf~^;K;ZcPEp0dzGZTq(Vm~LJmz1klf=!*8^nJ&?s8Uy)4sMIIj zPi~oy&L;t-K`1L2cTo}9E`b#qk+AB-4Qst zGYGrTUAM5i)yntie3zT*qjRvzUDMGx(d4E{9b>{SuAniy_6blgRnsn@KI}6|k+pqW zH&eCd+EWdugY#=nsL!Z3x@W;k4BdR4?%&~L5S&VlLA&gN>MKW{Tr(&bcHDEIGH2Fv zx5ik&?sZxNoR0De&T0n&(3|j)Fzr+|*fOMglo0%9k0|EK)h;=Rp#P8L^p!R*JH)GE zL>J~f=U(2EJxE2_U!(^zKB!)(hC4Weuo}Oa@~VLDo7Ln5{c6y=dyRYfT2olC7qXf= zP{u=|9uQrNt+ zU`OUEMjx^C zU_Rh%RBBs83jVFY`a$|X3F!C05;j^EKz^@O*PKXp#UOu1zOtt_+iJitS2ZxIbq^#W zJ?g+BymSpkBQTK|>P_YLlfd$^wGOV|!GF}kP)F-Mh~v=%#(Blwr2mMZ$2Cr-AM?O@ zMb4DN>#ru>Ddb3dMg=bQ^13z3k+@&b%lvxf>q*P#O9O>i;&wHhwSFSk=u{!XGd<$qk@ zK_UMx5BZ-H^wR$O1TO9WlE7C$obCTA;pm_B0zcaI5SF)9K)svbVtaT83*uN7jK5p< zaQ}w>m+j&*c*kJsU7%rw{~g5Ho~s0oeG%jR0v{0gzX)8?KOk_dV=U((flK`x<`^ghU{k%coa(*=|aIBLUupP;9uuY*FAAvZ_m)|wA z{o))91ImfQ#q`%B2m$dOa4~)hf)LRDPPiEVG{i9=J<4Q!FM<$?;i`s<@$VoA0dd*B zexOi|uY@?$%kdHGHsik*^iuxs1TN*<)Q(WEY`-%^`;zi21TN=4K7q^jh;tYW=m+U% zIgh##(%60<#4(ukXK7gZ8NZ2`o_A;O)Z3N0+(2L&$u{}|z@SNeaqpqKsUw*vD^`YM6Ta>Tr2K>H;!=290StJ{L1o`{`|J0)^<7&XE`quj&cSB{<^?FA@Fwuew)A#3S8L_Z+)&JnnjQzLL$f9eD->FWh9>q)D?rQg;FT-K9LflK)t3CH?_Yf9|TgrJx8 z=Q@GQ`ZGp2`UkeWW#!y2=x-PJLjsrW_fdgMJ0BPFFA{S03VP}P?+aYY`Gvrx|9>TL zN&j1cOaGT)Mj@E>_5^`T|DP&wDId>qU_k$00~h=MY(X#mzf|DT{|@2!kpAxx^wR(R z0+;^B^CK8AU((KN2*(Gm;jo<?mCF%cpgrl9(|K|u?`rj{bY3C9lKMbP8tdg=e42weJqzrdxPuM>{-M9#-l1q2MsH!AF}KmYDS^xR1G&FoK3t}x=yJaU;_T;HgkyQ(8YAO#2}d=b5;(yYcK7G;3p~pyj`#+F z^Slx9K7sovj`&7_R|>pG;8H%WyK<27;|#*nNAbzZXI7-&&M)xvQ5@^lREp!Hp5lm? zP#hm@1LCCuzmwvKA0zOm1%8~s-x4_I9iehG5CY0MLB;eZslUD^)c&0 zE4pgcidBn4b29I-I#T_E=`EqozP`a^XSR26Ak@>@+n4IL=42Y@WST5cHGeE)U6;uu zdi#e4)7iv8XMal72YR!KOe&d34i02fH)J(<{cvwORfcu| z^Sjly^QJxeV(l>k@>Xsldyeh=hHDR#Ex8n&JwnZP;Zn|=Uvg7;f*X%NMIa^O7r7?# zsmR*MnwayaAJhRO{!9%a>zuWBIvsaRM)wdkceZmAwi6u>j&(rT4@ls{R!ylb<~$Z0 zYXfZOqvP?yH0l>~ei3(G*+*m#QimTTU#5OlCT-!Wl?C10~Ae|QQh?!2MtYh3Qm z^LFwu7{sc64$eHF{O}zv`)X)c#y)!ijl&+@zwX+|XCvz)pNk~cKibnAoIOSZqd|IP zL#P&iTC$^iaudPaxzP6b?RMc4#FLdO-t(7Jr^mn*4q5i2!KT~>6oO5KAJh&wOGofnvpJ+x0h<kvKgD`zv7L0CJ-MWo z+U-el7i3H7bskcA^r+66pOWT8kJ@=&4R&E!tz8&CY8SR0jytJicD{~DlsjKsVPvsM z4wCS~77R)HU%msgrk1!Gq4S6mmzz+Q$nJ4_iE&~9A5?Vk-{W_awknDE(rAxfWo6HT zmPf-++RihIespWCm7Qf5G8n?PqngLodOLS2J4@9j+mto(TSH}Nh$K`P+=k2wdlBad#|Yh`D~ z5w>)QxAWU}lU=7VVMp%u;MfX^w%hmb2IIJMLdL0aJ3kDKU&>8Hg10?pgE&_W;%NBw z$mrWu!*|CE!{f31!f5yq4eJo8TSxkp^wwI(oj*VU*lnDeSv0$AF!yI7FGMFGX&fAw zXo84r=MgNo8?YKnVblX8Id!C(tfZEZ?$x&cp!u(Du#+}y*-s$#-wenmm zw;6YF%~kv{R=4u=VMIo?DZ<%z+ev8XM0XXNm;m0fZ7+9)Wn<3LkfAO9R<%#{Q^*L8 z{S$PLI?csfnW`Pz@6q|Mx3=_LbWPm`D^O2 zv(N~%i4N3ME2}HJU;&GpCcp*ivH_xdQYNH3Q1#W5M3 zpe~s7gPgmI#hz>n5z>)+E?(&0m7N(GxuO9}<}P6HD7eBryRa61M_z@<9(P`4ZF3XD z*IF64WPQJ9VWCcjNh0o%DPWYj5sh6yUfFWRnVM4c-diW@wp zKVFpfjybQ<5$k7c^6f9K!#Yz|&+U2z8#_|Bov)eGNP|Rl4o}#Vx!t-2#XY8&JB8X_ zT`R@h5OL_py+o6-&BA0{Lh&p2Ty_9^G4VM-@*bj6JU^GG46+MQ$Z z!nY>Sj#YaHvOIss3fpR&9Ki?pyNbJF7mhpMB4%8*M<;5~iv|K7kN7&-VDup#B*i}0DKMVk7~&2_(s8ico_8jj3;qzy{gBY@ z`^l`rImYt^(&pV=W8B?$9-y%s6)`9pq@842=ph#G<<&m|iDXhzQyT>#OSsHs@P|rq z#Q4j?DgMH2h%G+}$ma@rgh{0{g9Dw}lzJLrGHdx@sB<{GG11+b?F?=1>>EyndIv)3 z)b+!uOg7Y$9_$Y#`+8FYSw*haKTi8G=WXMSkKC7U^tVJTAjm?T-QgNNJ!Tk zb>5=$MU=PRa(yfM+6s#v*7*_2c~FRU!Q5QslEJZ;0h0?MRv>`vQ4~(}ux$=V!#Ehd zib=rn=t$Y|D0^kT15XX*E1mnh%bcBL2PEL&v$7N`=xEW3`O4JWg|-ldMFgh`8=h0s z5ZOn@*oWzH9RW^<0Fj%92H}t37P1Sg>&*UX+(uJ>0My#AD*8ci>^x9Ju*H(Rsp=xG zArzFXvJB5j{YS`RI6eZd^T?yUYh-I{71XMY7nape*~K5!LyDe*%|0@Ew3;oav>oe0 z?{_tB@!#0@vF}x$1sKPj2%{ZMNNy1Qcz5p6@w#$ps8h&E*c(@#aNS&b#llr7La82Enm=@n91#+{*{CLjMFDsxEve?)=_7 zeX+}AyYl=vsh1;;d*a;TPGtCLZ0-}-kea}gj$I{V@JhWg0C@X;Qn|EP=^>l_B#z@k ztZ; zAcm(DM3ujo-oze{30YuD0OlwX+&PJpMR4aM?aoP@JU?`J3?^Cy6OBDdgzCvXI(8~J z_CIXU;SpjngRII*;vpq_Ce;uf7;sy{Pm>Sa_Na1^v0vjftKtI!+=N|t$UQ9=A3+nI z<8e^WLTJ6%6^I$lpoFLU-RAdco& z*CSeE6XETs9x|{Gn+GxHnYh!}P;0x-VK2~mmA5cVU5L5q?WUF79P5Q1^TuLt(do-Q z%)X3ugM+iWJ1Kq~jmpkG_M(U1h;x2Ju?v)H-&{ZL957EwrCwMEWrqG|bc9Ek=M!TQ z?Pk#8H%wl9%C!$ayXcD`xM{J77IDAk8p3^&E_CcN*1+*nZ@oBJzEHMCRfO757NK-} z(pMyIgerdeO&a6~8D7y-DB~kWv5A{#9>p`(cUXC*r}Z*5G6r+c{+Z6%Da5WXG?WFe z7A#&o^C_d{+gcF3LRK-xV%phu&dxq8OeV;4vAB~bf#oT9k?O8=vYi9Me3#R_OJ%3* zqwBpJ>oFESM#C>3X9^AKh_ek&{0A1Q?7AY4NqEOoSn)Mh?yrm zpkX-|zsFKa!J*__YLvW$vvuZ}1lKBlmAZ&Q9)FgV$5$phh%0=$giqo&K4a107^mM} zydh9qUQM*UoyOJ7KY^G&3f@C8; zlzJq6yb#z?GdeBMz@+UUwTSm^M2Pe}eHpn+b_Ci-YpU~#=_bme=+FR?{X~ZZ7c0?2 z&+4s2WzXDzZ{qtRwIf}G&8EcnD}hfcrJ?gIR-_GliT-@j6=^`~?2fU0bb9p4x^gt>ue^X=I-89S)JBXDxDroOQJ!ntn^fP%8HU6EoAu7CHqpH z15%D3AuplRV5pbkX;AW_F0;y_cT_~j5?-tC#9q_A`^aQ)GI}HuJ;MXZM51}&f`tp9 zj+!%pE|^ydop)I!^pg3N(3XW2&`U47q!PLi(vpMy{dA?!JTRC|H7{Mh_To&oGr0-m zg8gp)`w6cj6#J>t+FD@-u@S&trnlZwm-!m z;&}-^GPUZ;A0>#gk#BOMqwxPbK-Zw@~7JLlybkD}Nc#O7dIv#xtV%kbDYpUisujmE^bT3E_PRG$wiFZ$LvO z`4g9^9uq3#y=?}{Uin`DR!ROI&6M{x&4V(p{LcfcB!6VF>U2b9ET8rtul#=pR!ROY znk*#VD^-!dz4GZwzLNZPV zY0pGz#0R(0Q{=w}tdjf@nk*#V(^Zkbz4A{0tt5Z%m8#PsVva=e{|+DT_-CWNlKd0z zpNF(g@BM&`d=o!z@{!-F4aMi5caXouNB+?^)hUE_N{#rC zOt1W}`^aBOlTGv#bVTyb-#tF^t*GiWt_@4_&&9_p|3_NBHj^u9gEo*?p0|F~r~i=d ze}T(U6};in!D(6kL0H1)$ zaoQ8B1uoB90ZVU!q6@i2wZP^1C}7bEqdd`^S6Lr+LAf3Rmfj@XR#gb_PF)VpL$!)e z+X^q|ql2yJ5@Gs~i^w<-uxKYNPb*NZvPx9t{NGnjtZM;_cBJyO9@Q%AgDzOk$9TQl z%!L3)_Ht|!s#R90w<&F5+}ya7@23IxCZ?QMK=6?*0ikC(Ua~_u9+FkJ91!#3f+z&U zyqDt*vg(!t93k8)7rxBjQ~i90#=V^A4`^uRUBr3m>vk^IO!3gKY217M*`@I%oR_}t z)i}+MOyA^6jdhI#QU12Z>6|aqcezqysqvLs_Gx^)1aawM{+{ZGk7@e5J@k)jdL0Jc z*8kP?-*FLDcuM1kJov9Q{)`8wYQXx)6!iaqoGs#yttpNn_nsZ7=`TKb5COCj{ri1z zdeL2pzR?Gt>w{nEgVQ;+68~-=e3K8p75Lf03(fQ09X|AT`QZ2a;Eyu@Qe6E885!xf zKJ+Jj@EO=tD~Da<6+4Ec<{0bku!w28!gKq(TwtL#LEb~0{FFy3U znVz0BR5H&mkNMC)<%7TAgTLy7zu|+^JLQUY^TESD_+lS?l@H$KgKzf1Z}GwJ^1<)( z!N2W;@Attiyzl2X{kTGJPV%31sf%=ZdtSQCy%g80qJ}HjQf&dQX+;fJxuS;aUQxr9 zu&B|salEaCzHp@*Z^I34ybbsJ@iyEB$J;KYFWdmf+n5el-tjhE9)pCtgqbqTJ;U4~ ztQc^=@B)ip79^I&S1gId6DzL1dUbS7VohX8Jeq(K80^4c!u&$V!r!pbTZGgNc)ONJ z45fPqvOS69#!Xg|f5rnWGayiU?_hp{gDd9ju=Gfrr3QFD2Iz-5>CL@K{fBiVRQ_PdkB_>}XBD9jUN3roP-N8PpB?q2Q>k}; z8_071svjnG!59nXC%RKf{DFz3YpDUQVW0!ap)J0m#SfZv(Qmx&@13}SnW8&?n!E)4 z?rN$4`F3RK>eY$1#PT(XwX37663ZhU(bM<~M`aN4Q!1B>y<+v6C6U$9_5|2{D%LiY zo3A>hSu@i^FN%H1`6UzoB#Yd}{cRW{L!D_jA*$OIO%Hve)7Ex zZ3d_3OiDygSKkJw=SE7{miZm9!IvocNOthW=JT{|SMs z^SzQwSHyANFWl?Q(uGML?9C3QvdrHRsKxR zc83020{@V})pMqzpDys93VJy&($3Nj=WBY>XQ|-RB5-=vGy0J4Q6l;nJ_cVyAd(k1 z&(q%V<`p@wU#X}0+Yh3bdbVqNFaP@mPHWld^N7aDADRSyNZ=uXOS?&X(qEiYBDr!s zzQyR&@qS+TPaHHxAGt0%1pb7em;9d>xU@gr%TuCp(H*kk|F*zG0%W zEyu_3p+9(}L^$1@89XjJbpDplL1TO77UHF^yhdBb5{xDzQQctrVk^a&jlA7LYXSq*F zJ9lY4y>`392RG}N=%qhAE9l!$HujPGDa9^>f6`}Mj?n*NK`-~s4+{KW1--QM_XU4x z=VJnwc78+P(#|u^wQ3A1-=%2j2*JX9Etc#yWP&{RQzs@&p=Lh zrH0S<1ijn`4{DsmHwyYE1b%_Qe=cxoPw9v21ihR`x!${kJwGkzM+GkZ_InzqaeYS6 z)2{?5k$vR2>V!S7MVqn19F0@fEbxyDT#nb=Q&F=VFTIzfMA=+?4F9zPmwY}eaLLEK ze<%H=eQp)>bOtc|cM4qczf<6n|9=YnLcvGIbLofYgN736vlJgA*Y6zCPQ*xF{mBO? z5xyQD!>5lxBrkrWf*F@_b=(Ix=QQFY>Hph@{&9gzzdEjQGLy8=p9HF5G zx#G(jC;sxBV8%r_+1%J?r=XuMaQR##$tNqv?HT-eDU0O#;7A;6oZGePrBF{~sNtr;HEx3HnyS zXP?03`u(NADV7?2UKRKvfu9t3zrasvoa{4C;4{uZ1&MHJ=X!z5@m`>D?|7Sh=$n1$ z7yHm(3`omv*iuVMty(hZt4!rMoghJSh<$-IeQR|26Z=Aim6bp75ClM1D}037;kK69PX= i;2|B)iM~$YD+PYGz()iw-@boW;2#k5zY=)8!2ciIXxHEX diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/Release/obj.target/kerberos/lib/worker.o deleted file mode 100644 index bd3b5c200e2c35bd962ff105477e09423c49beb3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2720 zcmbtV%}*0i5PxM65CsczFk)gkiAFY*G{zWXT58KCHqZ#DK}jiPl>|yjyH(^MhbG3x z3rDa130^#tXrljxTue0a;>|=8oZs6w-IwJx5S?V-%>3r-eeUdJa@meZL@-6fEfHvp z3X$&!>ok8mjUPSVU~n2Adz|K% zhl}5(+fng)u4Bnl>GX}*==^eh!>h*<_H{ckHc^*a{6#!rk0&nss7f}Zcx3yoh-^h8 z!>7A@c4Y7`b^-X_$|1<7U@PHvf zQeoI@&>($h=<9?+#C(`!+}|#M8abM*i{ZOILPlVg?nLr&<1djf=J>Diaf&s~KTkM_ z@29T`5oJN~tHgOPbkpaPzIIN5*gw2f-cQEw5N4{+M=S5P$^jOxpC!yxe_z!fSFxzy zO<%aaOPHztu8KQq{Y&I$svqt36Yx4wA5#j~-yuw%zxKaFh#4tZ$RaRDV>} z*Vm8#X1M+v!cd?6NR+g%_!Y&O!575*ttLx@8hY752MxaO6&6~)h^qLlP(06{;ddmM z*8f1Q-%*bIemS1c1#dt6b`bJP)&Hd8nT3}HJv?{#=5g7GeyM=7B=^x5u8%ums_&@# zi~FHdxV~=FW%zZ9p9ea|vSpkx=3$x%aMKP0m%W$MwzwrdN_rAA0yg4W6B3T*pvtVwLxtk_&>Hl zxG8^8`l~}Hndh_F1{cp{7q&|!5$ef>soczDDp#1vW@j^Vg}KyZE>j?u1YA8;ss9C?`PYm9 diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile deleted file mode 100644 index 69e964f..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/binding.Makefile +++ /dev/null @@ -1,6 +0,0 @@ -# This file is generated by gyp; do not edit. - -export builddir_name ?= ./build/. -.PHONY: all -all: - $(MAKE) kerberos diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi deleted file mode 100644 index e8ac042..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/config.gypi +++ /dev/null @@ -1,138 +0,0 @@ -# Do not edit. File was generated by node-gyp's "configure" step -{ - "target_defaults": { - "cflags": [], - "default_configuration": "Release", - "defines": [], - "include_dirs": [], - "libraries": [] - }, - "variables": { - "clang": 0, - "gcc_version": 44, - "host_arch": "x64", - "icu_data_file": "icudt54l.dat", - "icu_data_in": "../../deps/icu/source/data/in/icudt54l.dat", - "icu_endianness": "l", - "icu_gyp_path": "tools/icu/icu-generic.gyp", - "icu_locales": "en,root", - "icu_path": "./deps/icu", - "icu_small": "true", - "icu_ver_major": "54", - "node_install_npm": "true", - "node_prefix": "/", - "node_shared_cares": "false", - "node_shared_http_parser": "false", - "node_shared_libuv": "false", - "node_shared_openssl": "false", - "node_shared_v8": "false", - "node_shared_zlib": "false", - "node_tag": "", - "node_use_dtrace": "false", - "node_use_etw": "false", - "node_use_mdb": "false", - "node_use_openssl": "true", - "node_use_perfctr": "false", - "openssl_no_asm": 0, - "python": "/data/opt/bin/python", - "target_arch": "x64", - "uv_library": "static_library", - "uv_parent_path": "/deps/uv/", - "uv_use_dtrace": "false", - "v8_enable_gdbjit": 0, - "v8_enable_i18n_support": 1, - "v8_no_strict_aliasing": 1, - "v8_optimized_debug": 0, - "v8_random_seed": 0, - "v8_use_snapshot": "false", - "want_separate_host_toolset": 0, - "nodedir": "/home/fmason/.node-gyp/0.12.7", - "copy_dev_lib": "true", - "standalone_static_library": 1, - "cache_lock_stale": "60000", - "sign_git_tag": "", - "user_agent": "npm/2.11.3 node/v0.12.7 linux x64", - "always_auth": "", - "bin_links": "true", - "key": "", - "description": "true", - "fetch_retries": "2", - "heading": "npm", - "if_present": "", - "init_version": "1.0.0", - "user": "", - "force": "", - "cache_min": "10", - "init_license": "ISC", - "editor": "vi", - "rollback": "true", - "tag_version_prefix": "v", - "cache_max": "Infinity", - "userconfig": "/home/fmason/.npmrc", - "engine_strict": "", - "init_author_name": "", - "init_author_url": "", - "tmp": "/tmp", - "depth": "Infinity", - "save_dev": "", - "usage": "", - "cafile": "", - "https_proxy": "", - "onload_script": "", - "rebuild_bundle": "true", - "save_bundle": "", - "shell": "/bin/bash", - "prefix": "/usr/local", - "browser": "", - "cache_lock_wait": "10000", - "registry": "https://registry.npmjs.org/", - "save_optional": "", - "scope": "", - "searchopts": "", - "versions": "", - "cache": "/home/fmason/.npm", - "ignore_scripts": "", - "searchsort": "name", - "version": "", - "local_address": "", - "viewer": "man", - "color": "true", - "fetch_retry_mintimeout": "10000", - "umask": "0002", - "fetch_retry_maxtimeout": "60000", - "message": "%s", - "ca": "", - "cert": "", - "global": "", - "link": "", - "access": "", - "save": "", - "unicode": "true", - "long": "", - "production": "", - "unsafe_perm": "true", - "node_version": "0.12.7", - "tag": "latest", - "git_tag_version": "true", - "shrinkwrap": "true", - "fetch_retry_factor": "10", - "npat": "", - "proprietary_attribs": "true", - "save_exact": "", - "strict_ssl": "true", - "dev": "", - "globalconfig": "/usr/local/etc/npmrc", - "init_module": "/home/fmason/.npm-init.js", - "parseable": "", - "globalignorefile": "/usr/local/etc/npmignore", - "cache_lock_retries": "10", - "save_prefix": "^", - "group": "1002", - "init_author_email": "", - "searchexclude": "", - "git": "git", - "optional": "true", - "json": "", - "spin": "true" - } -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk deleted file mode 100644 index 36824f0..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/build/kerberos.target.mk +++ /dev/null @@ -1,151 +0,0 @@ -# This file is generated by gyp; do not edit. - -TOOLSET := target -TARGET := kerberos -DEFS_Debug := \ - '-DNODE_GYP_MODULE_NAME=kerberos' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' \ - '-DDEBUG' \ - '-D_DEBUG' - -# Flags passed to all source files. -CFLAGS_Debug := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -g \ - -O0 - -# Flags passed to only C files. -CFLAGS_C_Debug := - -# Flags passed to only C++ files. -CFLAGS_CC_Debug := \ - -fno-rtti - -INCS_Debug := \ - -I/home/fmason/.node-gyp/0.12.7/src \ - -I/home/fmason/.node-gyp/0.12.7/deps/uv/include \ - -I/home/fmason/.node-gyp/0.12.7/deps/v8/include \ - -I$(srcdir)/node_modules/nan \ - -I/usr/include/mit-krb5 - -DEFS_Release := \ - '-DNODE_GYP_MODULE_NAME=kerberos' \ - '-D_LARGEFILE_SOURCE' \ - '-D_FILE_OFFSET_BITS=64' \ - '-DBUILDING_NODE_EXTENSION' - -# Flags passed to all source files. -CFLAGS_Release := \ - -fPIC \ - -pthread \ - -Wall \ - -Wextra \ - -Wno-unused-parameter \ - -m64 \ - -O3 \ - -ffunction-sections \ - -fdata-sections \ - -fno-tree-vrp \ - -fno-tree-sink \ - -fno-omit-frame-pointer - -# Flags passed to only C files. -CFLAGS_C_Release := - -# Flags passed to only C++ files. -CFLAGS_CC_Release := \ - -fno-rtti - -INCS_Release := \ - -I/home/fmason/.node-gyp/0.12.7/src \ - -I/home/fmason/.node-gyp/0.12.7/deps/uv/include \ - -I/home/fmason/.node-gyp/0.12.7/deps/v8/include \ - -I$(srcdir)/node_modules/nan \ - -I/usr/include/mit-krb5 - -OBJS := \ - $(obj).target/$(TARGET)/lib/kerberos.o \ - $(obj).target/$(TARGET)/lib/worker.o \ - $(obj).target/$(TARGET)/lib/kerberosgss.o \ - $(obj).target/$(TARGET)/lib/base64.o \ - $(obj).target/$(TARGET)/lib/kerberos_context.o - -# Add to the list of files we specially track dependencies for. -all_deps += $(OBJS) - -# CFLAGS et al overrides must be target-local. -# See "Target-specific Variable Values" in the GNU Make manual. -$(OBJS): TOOLSET := $(TOOLSET) -$(OBJS): GYP_CFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_C_$(BUILDTYPE)) -$(OBJS): GYP_CXXFLAGS := $(DEFS_$(BUILDTYPE)) $(INCS_$(BUILDTYPE)) $(CFLAGS_$(BUILDTYPE)) $(CFLAGS_CC_$(BUILDTYPE)) - -# Suffix rules, putting all outputs into $(obj). - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(srcdir)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# Try building from generated source, too. - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.cc FORCE_DO_CMD - @$(call do_cmd,cxx,1) - -$(obj).$(TOOLSET)/$(TARGET)/%.o: $(obj)/%.c FORCE_DO_CMD - @$(call do_cmd,cc,1) - -# End of this set of suffix rules -### Rules for final target. -LDFLAGS_Debug := \ - -pthread \ - -rdynamic \ - -m64 - -LDFLAGS_Release := \ - -pthread \ - -rdynamic \ - -m64 - -LIBS := \ - -lkrb5 \ - -lgssapi_krb5 - -$(obj).target/kerberos.node: GYP_LDFLAGS := $(LDFLAGS_$(BUILDTYPE)) -$(obj).target/kerberos.node: LIBS := $(LIBS) -$(obj).target/kerberos.node: TOOLSET := $(TOOLSET) -$(obj).target/kerberos.node: $(OBJS) FORCE_DO_CMD - $(call do_cmd,solink_module) - -all_deps += $(obj).target/kerberos.node -# Add target alias -.PHONY: kerberos -kerberos: $(builddir)/kerberos.node - -# Copy this to the executable output path. -$(builddir)/kerberos.node: TOOLSET := $(TOOLSET) -$(builddir)/kerberos.node: $(obj).target/kerberos.node FORCE_DO_CMD - $(call do_cmd,copy) - -all_deps += $(builddir)/kerberos.node -# Short alias for building this executable. -.PHONY: kerberos.node -kerberos.node: $(obj).target/kerberos.node $(builddir)/kerberos.node - -# Add executable to "all" target. -.PHONY: all -all: $(builddir)/kerberos.node - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log deleted file mode 100644 index 5679d63..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/builderror.log +++ /dev/null @@ -1,25 +0,0 @@ -../lib/kerberos.cc:848:43: error: no viable conversion from 'Handle' to 'Local' - Local info[2] = { Nan::Null(), result}; - ^~~~~~ -/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:269:26: note: candidate constructor (the implicit copy constructor) not viable: cannot bind base class object of type 'Handle' to derived class reference 'const v8::Local &' for 1st argument -template class Local : public Handle { - ^ -/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:272:29: note: candidate template ignored: could not match 'Local' against 'Handle' - template inline Local(Local that) - ^ -/Users/christkv/.node-gyp/0.10.35/deps/v8/include/v8.h:281:29: note: candidate template ignored: could not match 'S *' against 'Handle' - template inline Local(S* that) : Handle(that) { } - ^ -1 error generated. -make: *** [Release/obj.target/kerberos/lib/kerberos.o] Error 1 -gyp ERR! build error -gyp ERR! stack Error: `make` failed with exit code: 2 -gyp ERR! stack at ChildProcess.onExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/build.js:267:23) -gyp ERR! stack at ChildProcess.emit (events.js:98:17) -gyp ERR! stack at Process.ChildProcess._handle.onexit (child_process.js:820:12) -gyp ERR! System Darwin 14.3.0 -gyp ERR! command "node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" -gyp ERR! cwd /Users/christkv/coding/projects/kerberos -gyp ERR! node -v v0.10.35 -gyp ERR! node-gyp -v v1.0.1 -gyp ERR! not ok diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js deleted file mode 100644 index b8c8532..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/index.js +++ /dev/null @@ -1,6 +0,0 @@ -// Get the Kerberos library -module.exports = require('./lib/kerberos'); -// Set up the auth processes -module.exports['processes'] = { - MongoAuthProcess: require('./lib/auth_processes/mongodb').MongoAuthProcess -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js deleted file mode 100644 index f1e9231..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/auth_processes/mongodb.js +++ /dev/null @@ -1,281 +0,0 @@ -var format = require('util').format; - -var MongoAuthProcess = function(host, port, service_name) { - // Check what system we are on - if(process.platform == 'win32') { - this._processor = new Win32MongoProcessor(host, port, service_name); - } else { - this._processor = new UnixMongoProcessor(host, port, service_name); - } -} - -MongoAuthProcess.prototype.init = function(username, password, callback) { - this._processor.init(username, password, callback); -} - -MongoAuthProcess.prototype.transition = function(payload, callback) { - this._processor.transition(payload, callback); -} - -/******************************************************************* - * - * Win32 SSIP Processor for MongoDB - * - *******************************************************************/ -var Win32MongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.ssip = require("../kerberos").SSIP; - // Set up first transition - this._transition = Win32MongoProcessor.first_transition(this); - // Set up service name - service_name = service_name || "mongodb"; - // Set up target - this.target = format("%s/%s", service_name, host); - // Number of retries - this.retries = 10; -} - -Win32MongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - // Save the values used later - this.username = username; - this.password = password; - // Aquire credentials - this.ssip.SecurityCredentials.aquire_kerberos(username, password, function(err, security_credentials) { - if(err) return callback(err); - // Save credentials - self.security_credentials = security_credentials; - // Callback with success - callback(null); - }); -} - -Win32MongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -Win32MongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.ssip.SecurityContext.initialize( - self.security_credentials, - self.target, - payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.second_transition(self); - self.security_context = security_context; - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.second_transition = function(self) { - return function(payload, callback) { - // Perform a step - self.security_context.initialize(self.target, payload, function(err, security_context) { - if(err) return callback(err); - - // If no context try again until we have no more retries - if(!security_context.hasContext) { - if(self.retries == 0) return callback(new Error("Failed to initialize security context")); - // Update the number of retries - self.retries = self.retries - 1; - // Set next transition - self._transition = Win32MongoProcessor.first_transition(self); - // Retry - return self.transition(payload, callback); - } - - // Set next transition - self._transition = Win32MongoProcessor.third_transition(self); - // Return the payload - callback(null, security_context.payload); - }); - } -} - -Win32MongoProcessor.third_transition = function(self) { - return function(payload, callback) { - var messageLength = 0; - // Get the raw bytes - var encryptedBytes = new Buffer(payload, 'base64'); - var encryptedMessage = new Buffer(messageLength); - // Copy first byte - encryptedBytes.copy(encryptedMessage, 0, 0, messageLength); - // Set up trailer - var securityTrailerLength = encryptedBytes.length - messageLength; - var securityTrailer = new Buffer(securityTrailerLength); - // Copy the bytes - encryptedBytes.copy(securityTrailer, 0, messageLength, securityTrailerLength); - - // Types used - var SecurityBuffer = self.ssip.SecurityBuffer; - var SecurityBufferDescriptor = self.ssip.SecurityBufferDescriptor; - - // Set up security buffers - var buffers = [ - new SecurityBuffer(SecurityBuffer.DATA, encryptedBytes) - , new SecurityBuffer(SecurityBuffer.STREAM, securityTrailer) - ]; - - // Set up the descriptor - var descriptor = new SecurityBufferDescriptor(buffers); - - // Decrypt the data - self.security_context.decryptMessage(descriptor, function(err, security_context) { - if(err) return callback(err); - - var length = 4; - if(self.username != null) { - length += self.username.length; - } - - var bytesReceivedFromServer = new Buffer(length); - bytesReceivedFromServer[0] = 0x01; // NO_PROTECTION - bytesReceivedFromServer[1] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[2] = 0x00; // NO_PROTECTION - bytesReceivedFromServer[3] = 0x00; // NO_PROTECTION - - if(self.username != null) { - var authorization_id_bytes = new Buffer(self.username, 'utf8'); - authorization_id_bytes.copy(bytesReceivedFromServer, 4, 0); - } - - self.security_context.queryContextAttributes(0x00, function(err, sizes) { - if(err) return callback(err); - - var buffers = [ - new SecurityBuffer(SecurityBuffer.TOKEN, new Buffer(sizes.securityTrailer)) - , new SecurityBuffer(SecurityBuffer.DATA, bytesReceivedFromServer) - , new SecurityBuffer(SecurityBuffer.PADDING, new Buffer(sizes.blockSize)) - ] - - var descriptor = new SecurityBufferDescriptor(buffers); - - self.security_context.encryptMessage(descriptor, 0x80000001, function(err, security_context) { - if(err) return callback(err); - callback(null, security_context.payload); - }); - }); - }); - } -} - -/******************************************************************* - * - * UNIX MIT Kerberos processor - * - *******************************************************************/ -var UnixMongoProcessor = function(host, port, service_name) { - this.host = host; - this.port = port - // SSIP classes - this.Kerberos = require("../kerberos").Kerberos; - this.kerberos = new this.Kerberos(); - service_name = service_name || "mongodb"; - // Set up first transition - this._transition = UnixMongoProcessor.first_transition(this); - // Set up target - this.target = format("%s@%s", service_name, host); - // Number of retries - this.retries = 10; -} - -UnixMongoProcessor.prototype.init = function(username, password, callback) { - var self = this; - this.username = username; - this.password = password; - // Call client initiate - this.kerberos.authGSSClientInit( - self.target - , this.Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - self.context = context; - // Return the context - callback(null, context); - }); -} - -UnixMongoProcessor.prototype.transition = function(payload, callback) { - if(this._transition == null) return callback(new Error("Transition finished")); - this._transition(payload, callback); -} - -UnixMongoProcessor.first_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, '', function(err, result) { - if(err) return callback(err); - // Set up the next step - self._transition = UnixMongoProcessor.second_transition(self); - // Return the payload - callback(null, self.context.response); - }) - } -} - -UnixMongoProcessor.second_transition = function(self) { - return function(payload, callback) { - self.kerberos.authGSSClientStep(self.context, payload, function(err, result) { - if(err && self.retries == 0) return callback(err); - // Attempt to re-establish a context - if(err) { - // Adjust the number of retries - self.retries = self.retries - 1; - // Call same step again - return self.transition(payload, callback); - } - - // Set up the next step - self._transition = UnixMongoProcessor.third_transition(self); - // Return the payload - callback(null, self.context.response || ''); - }); - } -} - -UnixMongoProcessor.third_transition = function(self) { - return function(payload, callback) { - // GSS Client Unwrap - self.kerberos.authGSSClientUnwrap(self.context, payload, function(err, result) { - if(err) return callback(err, false); - - // Wrap the response - self.kerberos.authGSSClientWrap(self.context, self.context.response, self.username, function(err, result) { - if(err) return callback(err, false); - // Set up the next step - self._transition = UnixMongoProcessor.fourth_transition(self); - // Return the payload - callback(null, self.context.response); - }); - }); - } -} - -UnixMongoProcessor.fourth_transition = function(self) { - return function(payload, callback) { - // Clean up context - self.kerberos.authGSSClientClean(self.context, function(err, result) { - if(err) return callback(err, false); - // Set the transition to null - self._transition = null; - // Callback with valid authentication - callback(null, true); - }); - } -} - -// Set the process -exports.MongoAuthProcess = MongoAuthProcess; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c deleted file mode 100644 index aca0a61..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.c +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "base64.h" - -#include -#include -#include -#include - -void die2(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - if(result == NULL) die2("Memory allocation failed"); - char *out = result; - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - unsigned char oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - *rlen = 0; - int c1, c2, c3, c4; - - int vlen = strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - if(result == NULL) die2("Memory allocation failed"); - unsigned char *out = result; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h deleted file mode 100644 index 9152e6a..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/base64.h +++ /dev/null @@ -1,22 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ -#ifndef BASE64_H -#define BASE64_H - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); - -#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc deleted file mode 100644 index 5b25d74..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.cc +++ /dev/null @@ -1,893 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "worker.h" -#include "kerberos_context.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -void die(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -// Call structs -typedef struct AuthGSSClientCall { - uint32_t flags; - char *uri; -} AuthGSSClientCall; - -typedef struct AuthGSSClientStepCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientStepCall; - -typedef struct AuthGSSClientUnwrapCall { - KerberosContext *context; - char *challenge; -} AuthGSSClientUnwrapCall; - -typedef struct AuthGSSClientWrapCall { - KerberosContext *context; - char *challenge; - char *user_name; -} AuthGSSClientWrapCall; - -typedef struct AuthGSSClientCleanCall { - KerberosContext *context; -} AuthGSSClientCleanCall; - -typedef struct AuthGSSServerInitCall { - char *service; - bool constrained_delegation; - char *username; -} AuthGSSServerInitCall; - -typedef struct AuthGSSServerCleanCall { - KerberosContext *context; -} AuthGSSServerCleanCall; - -typedef struct AuthGSSServerStepCall { - KerberosContext *context; - char *auth_data; -} AuthGSSServerStepCall; - -Kerberos::Kerberos() : Nan::ObjectWrap() { -} - -Nan::Persistent Kerberos::constructor_template; - -void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("Kerberos").ToLocalChecked()); - - // Set up method for the Kerberos instance - Nan::SetPrototypeMethod(t, "authGSSClientInit", AuthGSSClientInit); - Nan::SetPrototypeMethod(t, "authGSSClientStep", AuthGSSClientStep); - Nan::SetPrototypeMethod(t, "authGSSClientUnwrap", AuthGSSClientUnwrap); - Nan::SetPrototypeMethod(t, "authGSSClientWrap", AuthGSSClientWrap); - Nan::SetPrototypeMethod(t, "authGSSClientClean", AuthGSSClientClean); - Nan::SetPrototypeMethod(t, "authGSSServerInit", AuthGSSServerInit); - Nan::SetPrototypeMethod(t, "authGSSServerClean", AuthGSSServerClean); - Nan::SetPrototypeMethod(t, "authGSSServerStep", AuthGSSServerStep); - - constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("Kerberos").ToLocalChecked(), t->GetFunction()); -} - -NAN_METHOD(Kerberos::New) { - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(info.This()); - info.GetReturnValue().Set(info.This()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientInit(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - - // Allocate state - state = (gss_client_state *)malloc(sizeof(gss_client_state)); - if(state == NULL) die("Memory allocation failed"); - - // Unpack the parameter data struct - AuthGSSClientCall *call = (AuthGSSClientCall *)worker->parameters; - // Start the kerberos client - response = authenticate_gss_client_init(call->uri, call->flags, state); - - // Release the parameter struct memory - free(call->uri); - free(call); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - free(state); - } else { - worker->return_value = state; - } - - // Free structure - free(response); -} - -static Local _map_authGSSClientInit(Worker *worker) { - KerberosContext *context = KerberosContext::New(); - context->state = (gss_client_state *)worker->return_value; - return context->handle(); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientInit) { - // Ensure valid call - if(info.Length() != 3) return Nan::ThrowError("Requires a service string uri, integer flags and a callback function"); - if(info.Length() == 3 && (!info[0]->IsString() || !info[1]->IsInt32() || !info[2]->IsFunction())) - return Nan::ThrowError("Requires a service string uri, integer flags and a callback function"); - - Local service = info[0]->ToString(); - // Convert uri string to c-string - char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); - if(service_str == NULL) die("Memory allocation failed"); - - // Write v8 string to c-string - service->WriteUtf8(service_str); - - // Allocate a structure - AuthGSSClientCall *call = (AuthGSSClientCall *)calloc(1, sizeof(AuthGSSClientCall)); - if(call == NULL) die("Memory allocation failed"); - call->flags =info[1]->ToInt32()->Uint32Value(); - call->uri = service_str; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[2]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientInit; - worker->mapper = _map_authGSSClientInit; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientStep -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientStep(Worker *worker) { - gss_client_state *state; - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)worker->parameters; - // Get the state - state = call->context->state; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_step(state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Local _map_authGSSClientStep(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientStep) { - // Ensure valid call - if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsClientInstance()) { - return Nan::ThrowError("GSS context is not a client instance"); - } - - int callbackArg = 1; - - // If we have a challenge string - if(info.Length() == 3) { - // Unpack the challenge string - Local challenge = info[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - if(challenge_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - - callbackArg = 2; - } - - // Allocate a structure - AuthGSSClientStepCall *call = (AuthGSSClientStepCall *)calloc(1, sizeof(AuthGSSClientStepCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[callbackArg]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientStep; - worker->mapper = _map_authGSSClientStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientUnwrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientUnwrap(Worker *worker) { - gss_client_response *response; - char *challenge; - - // Unpack the parameter data struct - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)worker->parameters; - challenge = call->challenge; - - // Check what kind of challenge we have - if(call->challenge == NULL) { - challenge = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_unwrap(call->context->state, challenge); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - free(call); - free(response); -} - -static Local _map_authGSSClientUnwrap(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientUnwrap) { - // Ensure valid call - if(info.Length() != 2 && info.Length() != 3) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - if(info.Length() == 2 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, optional challenge string and callback function"); - - // Challenge string - char *challenge_str = NULL; - // Let's unpack the parameters - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsClientInstance()) { - return Nan::ThrowError("GSS context is not a client instance"); - } - - // If we have a challenge string - if(info.Length() == 3) { - // Unpack the challenge string - Local challenge = info[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - if(challenge_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - } - - // Allocate a structure - AuthGSSClientUnwrapCall *call = (AuthGSSClientUnwrapCall *)calloc(1, sizeof(AuthGSSClientUnwrapCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->challenge = challenge_str; - - // Unpack the callback - Local callbackHandle = info.Length() == 3 ? Local::Cast(info[2]) : Local::Cast(info[1]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientUnwrap; - worker->mapper = _map_authGSSClientUnwrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientWrap -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientWrap(Worker *worker) { - gss_client_response *response; - char *user_name = NULL; - - // Unpack the parameter data struct - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)worker->parameters; - user_name = call->user_name; - - // Check what kind of challenge we have - if(call->user_name == NULL) { - user_name = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_client_wrap(call->context->state, call->challenge, user_name); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->challenge != NULL) free(call->challenge); - if(call->user_name != NULL) free(call->user_name); - free(call); - free(response); -} - -static Local _map_authGSSClientWrap(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientWrap) { - // Ensure valid call - if(info.Length() != 3 && info.Length() != 4) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(info.Length() == 3 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - if(info.Length() == 4 && (!KerberosContext::HasInstance(info[0]) || !info[1]->IsString() || !info[2]->IsString() || !info[3]->IsFunction())) return Nan::ThrowError("Requires a GSS context, the result from the authGSSClientResponse after authGSSClientUnwrap, optional user name and callback function"); - - // Challenge string - char *challenge_str = NULL; - char *user_name_str = NULL; - - // Let's unpack the kerberos context - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsClientInstance()) { - return Nan::ThrowError("GSS context is not a client instance"); - } - - // Unpack the challenge string - Local challenge = info[1]->ToString(); - // Convert uri string to c-string - challenge_str = (char *)calloc(challenge->Utf8Length() + 1, sizeof(char)); - if(challenge_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - challenge->WriteUtf8(challenge_str); - - // If we have a user string - if(info.Length() == 4) { - // Unpack user name - Local user_name = info[2]->ToString(); - // Convert uri string to c-string - user_name_str = (char *)calloc(user_name->Utf8Length() + 1, sizeof(char)); - if(user_name_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - user_name->WriteUtf8(user_name_str); - } - - // Allocate a structure - AuthGSSClientWrapCall *call = (AuthGSSClientWrapCall *)calloc(1, sizeof(AuthGSSClientWrapCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->challenge = challenge_str; - call->user_name = user_name_str; - - // Unpack the callback - Local callbackHandle = info.Length() == 4 ? Local::Cast(info[3]) : Local::Cast(info[2]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientWrap; - worker->mapper = _map_authGSSClientWrap; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientClean -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSClientClean(Worker *worker) { - gss_client_response *response; - - // Unpack the parameter data struct - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)worker->parameters; - - // Perform authentication step - response = authenticate_gss_client_clean(call->context->state); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - free(call); - free(response); -} - -static Local _map_authGSSClientClean(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSClientClean) { - // Ensure valid call - if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function"); - if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function"); - - // Let's unpack the kerberos context - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsClientInstance()) { - return Nan::ThrowError("GSS context is not a client instance"); - } - - // Allocate a structure - AuthGSSClientCleanCall *call = (AuthGSSClientCleanCall *)calloc(1, sizeof(AuthGSSClientCleanCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[1]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSClientClean; - worker->mapper = _map_authGSSClientClean; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSServerInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSServerInit(Worker *worker) { - gss_server_state *state; - gss_client_response *response; - - // Allocate state - state = (gss_server_state *)malloc(sizeof(gss_server_state)); - if(state == NULL) die("Memory allocation failed"); - - // Unpack the parameter data struct - AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)worker->parameters; - // Start the kerberos service - response = authenticate_gss_server_init(call->service, call->constrained_delegation, call->username, state); - - // Release the parameter struct memory - free(call->service); - free(call->username); - free(call); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - free(state); - } else { - worker->return_value = state; - } - - // Free structure - free(response); -} - -static Local _map_authGSSServerInit(Worker *worker) { - KerberosContext *context = KerberosContext::New(); - context->server_state = (gss_server_state *)worker->return_value; - return context->handle(); -} - -// Server Initialize method -NAN_METHOD(Kerberos::AuthGSSServerInit) { - // Ensure valid call - if(info.Length() != 4) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function"); - - if(!info[0]->IsString() || - !info[1]->IsBoolean() || - !(info[2]->IsString() || info[2]->IsNull()) || - !info[3]->IsFunction() - ) return Nan::ThrowError("Requires a service string, constrained delegation boolean, a username string (or NULL) for S4U2Self protocol transition and a callback function"); - - if (!info[1]->BooleanValue() && !info[2]->IsNull()) return Nan::ThrowError("S4U2Self only possible when constrained delegation is enabled"); - - // Allocate a structure - AuthGSSServerInitCall *call = (AuthGSSServerInitCall *)calloc(1, sizeof(AuthGSSServerInitCall)); - if(call == NULL) die("Memory allocation failed"); - - Local service = info[0]->ToString(); - // Convert service string to c-string - char *service_str = (char *)calloc(service->Utf8Length() + 1, sizeof(char)); - if(service_str == NULL) die("Memory allocation failed"); - - // Write v8 string to c-string - service->WriteUtf8(service_str); - - call->service = service_str; - - call->constrained_delegation = info[1]->BooleanValue(); - - if (info[2]->IsNull()) - { - call->username = NULL; - } - else - { - Local tmpString = info[2]->ToString(); - - char *tmpCstr = (char *)calloc(tmpString->Utf8Length() + 1, sizeof(char)); - if(tmpCstr == NULL) die("Memory allocation failed"); - - tmpString->WriteUtf8(tmpCstr); - - call->username = tmpCstr; - } - - // Unpack the callback - Local callbackHandle = Local::Cast(info[3]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSServerInit; - worker->mapper = _map_authGSSServerInit; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSServerClean -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSServerClean(Worker *worker) { - gss_client_response *response; - - // Unpack the parameter data struct - AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)worker->parameters; - - // Perform authentication step - response = authenticate_gss_server_clean(call->context->server_state); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - free(call); - free(response); -} - -static Local _map_authGSSServerClean(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSServerClean) { - // // Ensure valid call - if(info.Length() != 2) return Nan::ThrowError("Requires a GSS context and callback function"); - if(!KerberosContext::HasInstance(info[0]) || !info[1]->IsFunction()) return Nan::ThrowError("Requires a GSS context and callback function"); - - // Let's unpack the kerberos context - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsServerInstance()) { - return Nan::ThrowError("GSS context is not a server instance"); - } - - // Allocate a structure - AuthGSSServerCleanCall *call = (AuthGSSServerCleanCall *)calloc(1, sizeof(AuthGSSServerCleanCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[1]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSServerClean; - worker->mapper = _map_authGSSServerClean; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSServerStep -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authGSSServerStep(Worker *worker) { - gss_server_state *state; - gss_client_response *response; - char *auth_data; - - // Unpack the parameter data struct - AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)worker->parameters; - // Get the state - state = call->context->server_state; - auth_data = call->auth_data; - - // Check if we got auth_data or not - if(call->auth_data == NULL) { - auth_data = (char *)""; - } - - // Perform authentication step - response = authenticate_gss_server_step(state, auth_data); - - // If we have an error mark worker as having had an error - if(response->return_code == AUTH_GSS_ERROR) { - worker->error = TRUE; - worker->error_code = response->return_code; - worker->error_message = response->message; - } else { - worker->return_code = response->return_code; - } - - // Free up structure - if(call->auth_data != NULL) free(call->auth_data); - free(call); - free(response); -} - -static Local _map_authGSSServerStep(Worker *worker) { - Nan::HandleScope scope; - // Return the return code - return Nan::New(worker->return_code); -} - -// Initialize method -NAN_METHOD(Kerberos::AuthGSSServerStep) { - // Ensure valid call - if(info.Length() != 3) return Nan::ThrowError("Requires a GSS context, auth-data string and callback function"); - if(!KerberosContext::HasInstance(info[0])) return Nan::ThrowError("1st arg must be a GSS context"); - if (!info[1]->IsString()) return Nan::ThrowError("2nd arg must be auth-data string"); - if (!info[2]->IsFunction()) return Nan::ThrowError("3rd arg must be a callback function"); - - // Auth-data string - char *auth_data_str = NULL; - // Let's unpack the parameters - Local object = info[0]->ToObject(); - KerberosContext *kerberos_context = KerberosContext::Unwrap(object); - - if (!kerberos_context->IsServerInstance()) { - return Nan::ThrowError("GSS context is not a server instance"); - } - - // Unpack the auth_data string - Local auth_data = info[1]->ToString(); - // Convert uri string to c-string - auth_data_str = (char *)calloc(auth_data->Utf8Length() + 1, sizeof(char)); - if(auth_data_str == NULL) die("Memory allocation failed"); - // Write v8 string to c-string - auth_data->WriteUtf8(auth_data_str); - - // Allocate a structure - AuthGSSServerStepCall *call = (AuthGSSServerStepCall *)calloc(1, sizeof(AuthGSSServerStepCall)); - if(call == NULL) die("Memory allocation failed"); - call->context = kerberos_context; - call->auth_data = auth_data_str; - - // Unpack the callback - Local callbackHandle = Local::Cast(info[2]); - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authGSSServerStep; - worker->mapper = _map_authGSSServerStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Kerberos::Process, (uv_after_work_cb)Kerberos::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void Kerberos::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void Kerberos::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); - Local obj = err->ToObject(); - obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); - Local info[2] = { err, Nan::Null() }; - // Execute the error - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } else { - // // Map the data - Local result = worker->mapper(worker); - // Set up the callback with a null first - #if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ - (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) - Local info[2] = { Nan::Null(), result}; - #else - Local info[2] = { Nan::Null(), Nan::New(result)}; - #endif - - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } - - // Clean up the memory - delete worker->callback; - delete worker; -} - -// Exporting function -NAN_MODULE_INIT(init) { - Kerberos::Initialize(target); - KerberosContext::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h deleted file mode 100644 index beafa4d..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.h +++ /dev/null @@ -1,50 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include - -#include "nan.h" -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public Nan::ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Nan::Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - - // Method available - static NAN_METHOD(AuthGSSClientInit); - static NAN_METHOD(AuthGSSClientStep); - static NAN_METHOD(AuthGSSClientUnwrap); - static NAN_METHOD(AuthGSSClientWrap); - static NAN_METHOD(AuthGSSClientClean); - static NAN_METHOD(AuthGSSServerInit); - static NAN_METHOD(AuthGSSServerClean); - static NAN_METHOD(AuthGSSServerStep); - -private: - static NAN_METHOD(New); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js deleted file mode 100644 index c7bae58..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos.js +++ /dev/null @@ -1,164 +0,0 @@ -var kerberos = require('../build/Release/kerberos') - , KerberosNative = kerberos.Kerberos; - -var Kerberos = function() { - this._native_kerberos = new KerberosNative(); -} - -// callback takes two arguments, an error string if defined and a new context -// uri should be given as service@host. Services are not always defined -// in a straightforward way. Use 'HTTP' for SPNEGO / Negotiate authentication. -Kerberos.prototype.authGSSClientInit = function(uri, flags, callback) { - return this._native_kerberos.authGSSClientInit(uri, flags, callback); -} - -// This will obtain credentials using a credentials cache. To override the default -// location (posible /tmp/krb5cc_nnnnnn, where nnnn is your numeric uid) use -// the environment variable KRB5CNAME. -// The credentials (suitable for using in an 'Authenticate: ' header, when prefixed -// with 'Negotiate ') will be available as context.response inside the callback -// if no error is indicated. -// callback takes one argument, an error string if defined -Kerberos.prototype.authGSSClientStep = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientStep(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientUnwrap = function(context, challenge, callback) { - if(typeof challenge == 'function') { - callback = challenge; - challenge = ''; - } - - return this._native_kerberos.authGSSClientUnwrap(context, challenge, callback); -} - -Kerberos.prototype.authGSSClientWrap = function(context, challenge, user_name, callback) { - if(typeof user_name == 'function') { - callback = user_name; - user_name = ''; - } - - return this._native_kerberos.authGSSClientWrap(context, challenge, user_name, callback); -} - -// free memory used by a context created using authGSSClientInit. -// callback takes one argument, an error string if defined. -Kerberos.prototype.authGSSClientClean = function(context, callback) { - return this._native_kerberos.authGSSClientClean(context, callback); -} - -// The server will obtain credentials using a keytab. To override the -// default location (probably /etc/krb5.keytab) set the KRB5_KTNAME -// environment variable. -// The service name should be in the form service, or service@host.name -// e.g. for HTTP, use "HTTP" or "HTTP@my.host.name". See gss_import_name -// for GSS_C_NT_HOSTBASED_SERVICE. -// -// a boolean turns on "constrained_delegation". this enables acquisition of S4U2Proxy -// credentials which will be stored in a credentials cache during the authGSSServerStep -// method. this parameter is optional. -// -// when "constrained_delegation" is enabled, a username can (optionally) be provided and -// S4U2Self protocol transition will be initiated. In this case, we will not -// require any "auth" data during the authGSSServerStep. This parameter is optional -// but constrained_delegation MUST be enabled for this to work. When S4U2Self is -// used, the username will be assumed to have been already authenticated, and no -// actual authentication will be performed. This is basically a way to "bootstrap" -// kerberos credentials (which can then be delegated with S4U2Proxy) for a user -// authenticated externally. -// -// callback takes two arguments, an error string if defined and a new context -// -Kerberos.prototype.authGSSServerInit = function(service, constrained_delegation, username, callback) { - if(typeof(constrained_delegation) === 'function') { - callback = constrained_delegation; - constrained_delegation = false; - username = null; - } - - if (typeof(constrained_delegation) === 'string') { - throw new Error("S4U2Self protocol transation is not possible without enabling constrained delegation"); - } - - if (typeof(username) === 'function') { - callback = username; - username = null; - } - - constrained_delegation = !!constrained_delegation; - - return this._native_kerberos.authGSSServerInit(service, constrained_delegation, username, callback); -}; - -//callback takes one argument, an error string if defined. -Kerberos.prototype.authGSSServerClean = function(context, callback) { - return this._native_kerberos.authGSSServerClean(context, callback); -}; - -// authData should be the base64 encoded authentication data obtained -// from client, e.g., in the Authorization header (without the leading -// "Negotiate " string) during SPNEGO authentication. The authenticated user -// is available in context.username after successful authentication. -// callback takes one argument, an error string if defined. -// -// Note: when S4U2Self protocol transition was requested in the authGSSServerInit -// no actual authentication will be performed and authData will be ignored. -// -Kerberos.prototype.authGSSServerStep = function(context, authData, callback) { - return this._native_kerberos.authGSSServerStep(context, authData, callback); -}; - -Kerberos.prototype.acquireAlternateCredentials = function(user_name, password, domain) { - return this._native_kerberos.acquireAlternateCredentials(user_name, password, domain); -} - -Kerberos.prototype.prepareOutboundPackage = function(principal, inputdata) { - return this._native_kerberos.prepareOutboundPackage(principal, inputdata); -} - -Kerberos.prototype.decryptMessage = function(challenge) { - return this._native_kerberos.decryptMessage(challenge); -} - -Kerberos.prototype.encryptMessage = function(challenge) { - return this._native_kerberos.encryptMessage(challenge); -} - -Kerberos.prototype.queryContextAttribute = function(attribute) { - if(typeof attribute != 'number' && attribute != 0x00) throw new Error("Attribute not supported"); - return this._native_kerberos.queryContextAttribute(attribute); -} - -// Some useful result codes -Kerberos.AUTH_GSS_CONTINUE = 0; -Kerberos.AUTH_GSS_COMPLETE = 1; - -// Some useful gss flags -Kerberos.GSS_C_DELEG_FLAG = 1; -Kerberos.GSS_C_MUTUAL_FLAG = 2; -Kerberos.GSS_C_REPLAY_FLAG = 4; -Kerberos.GSS_C_SEQUENCE_FLAG = 8; -Kerberos.GSS_C_CONF_FLAG = 16; -Kerberos.GSS_C_INTEG_FLAG = 32; -Kerberos.GSS_C_ANON_FLAG = 64; -Kerberos.GSS_C_PROT_READY_FLAG = 128; -Kerberos.GSS_C_TRANS_FLAG = 256; - -// Export Kerberos class -exports.Kerberos = Kerberos; - -// If we have SSPI (windows) -if(kerberos.SecurityCredentials) { - // Put all SSPI classes in it's own namespace - exports.SSIP = { - SecurityCredentials: require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext: require('./win32/wrappers/security_context').SecurityContext - , SecurityBuffer: require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor: require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - } -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc deleted file mode 100644 index bf24118..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.cc +++ /dev/null @@ -1,134 +0,0 @@ -#include "kerberos_context.h" - -Nan::Persistent KerberosContext::constructor_template; - -KerberosContext::KerberosContext() : Nan::ObjectWrap() { - state = NULL; - server_state = NULL; -} - -KerberosContext::~KerberosContext() { -} - -KerberosContext* KerberosContext::New() { - Nan::HandleScope scope; - Local obj = Nan::New(constructor_template)->GetFunction()->NewInstance(); - KerberosContext *kerberos_context = Nan::ObjectWrap::Unwrap(obj); - return kerberos_context; -} - -NAN_METHOD(KerberosContext::New) { - // Create code object - KerberosContext *kerberos_context = new KerberosContext(); - // Wrap it - kerberos_context->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -void KerberosContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(static_cast(New)); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("KerberosContext").ToLocalChecked()); - - // Get prototype - Local proto = t->PrototypeTemplate(); - - // Getter for the response - Nan::SetAccessor(proto, Nan::New("response").ToLocalChecked(), KerberosContext::ResponseGetter); - - // Getter for the username - Nan::SetAccessor(proto, Nan::New("username").ToLocalChecked(), KerberosContext::UsernameGetter); - - // Getter for the targetname - server side only - Nan::SetAccessor(proto, Nan::New("targetname").ToLocalChecked(), KerberosContext::TargetnameGetter); - - Nan::SetAccessor(proto, Nan::New("delegatedCredentialsCache").ToLocalChecked(), KerberosContext::DelegatedCredentialsCacheGetter); - - // Set persistent - constructor_template.Reset(t); - // NanAssignPersistent(constructor_template, t); - - // Set the symbol - target->ForceSet(Nan::New("KerberosContext").ToLocalChecked(), t->GetFunction()); -} - - -// Response Setter / Getter -NAN_GETTER(KerberosContext::ResponseGetter) { - gss_client_state *client_state; - gss_server_state *server_state; - - // Unpack the object - KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); - - // Response could come from client or server state... - client_state = context->state; - server_state = context->server_state; - - // If client state is in use, take response from there, otherwise from server - char *response = client_state != NULL ? client_state->response : - server_state != NULL ? server_state->response : NULL; - - if(response == NULL) { - info.GetReturnValue().Set(Nan::Null()); - } else { - // Return the response - info.GetReturnValue().Set(Nan::New(response).ToLocalChecked()); - } -} - -// username Getter -NAN_GETTER(KerberosContext::UsernameGetter) { - // Unpack the object - KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); - - gss_client_state *client_state = context->state; - gss_server_state *server_state = context->server_state; - - // If client state is in use, take response from there, otherwise from server - char *username = client_state != NULL ? client_state->username : - server_state != NULL ? server_state->username : NULL; - - if(username == NULL) { - info.GetReturnValue().Set(Nan::Null()); - } else { - info.GetReturnValue().Set(Nan::New(username).ToLocalChecked()); - } -} - -// targetname Getter - server side only -NAN_GETTER(KerberosContext::TargetnameGetter) { - // Unpack the object - KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); - - gss_server_state *server_state = context->server_state; - - char *targetname = server_state != NULL ? server_state->targetname : NULL; - - if(targetname == NULL) { - info.GetReturnValue().Set(Nan::Null()); - } else { - info.GetReturnValue().Set(Nan::New(targetname).ToLocalChecked()); - } -} - -// targetname Getter - server side only -NAN_GETTER(KerberosContext::DelegatedCredentialsCacheGetter) { - // Unpack the object - KerberosContext *context = Nan::ObjectWrap::Unwrap(info.This()); - - gss_server_state *server_state = context->server_state; - - char *delegated_credentials_cache = server_state != NULL ? server_state->delegated_credentials_cache : NULL; - - if(delegated_credentials_cache == NULL) { - info.GetReturnValue().Set(Nan::Null()); - } else { - info.GetReturnValue().Set(Nan::New(delegated_credentials_cache).ToLocalChecked()); - } -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h deleted file mode 100644 index 23eb577..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberos_context.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef KERBEROS_CONTEXT_H -#define KERBEROS_CONTEXT_H - -#include -#include -#include -#include - -#include "nan.h" -#include -#include - -extern "C" { - #include "kerberosgss.h" -} - -using namespace v8; -using namespace node; - -class KerberosContext : public Nan::ObjectWrap { - -public: - KerberosContext(); - ~KerberosContext(); - - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - inline bool IsClientInstance() { - return state != NULL; - } - - inline bool IsServerInstance() { - return server_state != NULL; - } - - // Constructor used for creating new Kerberos objects from C++ - static Nan::Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - - // Public constructor - static KerberosContext* New(); - - // Handle to the kerberos client context - gss_client_state *state; - - // Handle to the kerberos server context - gss_server_state *server_state; - -private: - static NAN_METHOD(New); - // In either client state or server state - static NAN_GETTER(ResponseGetter); - static NAN_GETTER(UsernameGetter); - // Only in the "server_state" - static NAN_GETTER(TargetnameGetter); - static NAN_GETTER(DelegatedCredentialsCacheGetter); -}; -#endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c deleted file mode 100644 index 2fbca00..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.c +++ /dev/null @@ -1,931 +0,0 @@ -/** - * Copyright (c) 2006-2010 Apple Inc. All rights reserved. - * - * 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. - * - **/ -/* - * S4U2Proxy implementation - * Copyright (C) 2015 David Mansfield - * Code inspired by mod_auth_kerb. - */ - -#include "kerberosgss.h" - -#include "base64.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wdeprecated-declarations" - -void die1(const char *message) { - if(errno) { - perror(message); - } else { - printf("ERROR: %s\n", message); - } - - exit(1); -} - -static gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min); -static gss_client_response *other_error(const char *fmt, ...); -static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem); - -static gss_client_response *store_gss_creds(gss_server_state *state); -static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context context, krb5_principal princ, krb5_ccache *ccache); - -/* -char* server_principal_details(const char* service, const char* hostname) -{ - char match[1024]; - int match_len = 0; - char* result = NULL; - - int code; - krb5_context kcontext; - krb5_keytab kt = NULL; - krb5_kt_cursor cursor = NULL; - krb5_keytab_entry entry; - char* pname = NULL; - - // Generate the principal prefix we want to match - snprintf(match, 1024, "%s/%s@", service, hostname); - match_len = strlen(match); - - code = krb5_init_context(&kcontext); - if (code) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot initialize Kerberos5 context", code)); - return NULL; - } - - if ((code = krb5_kt_default(kcontext, &kt))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get default keytab", code)); - goto end; - } - - if ((code = krb5_kt_start_seq_get(kcontext, kt, &cursor))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot get sequence cursor from keytab", code)); - goto end; - } - - while ((code = krb5_kt_next_entry(kcontext, kt, &entry, &cursor)) == 0) - { - if ((code = krb5_unparse_name(kcontext, entry.principal, &pname))) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Cannot parse principal name from keytab", code)); - goto end; - } - - if (strncmp(pname, match, match_len) == 0) - { - result = malloc(strlen(pname) + 1); - strcpy(result, pname); - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - break; - } - - krb5_free_unparsed_name(kcontext, pname); - krb5_free_keytab_entry_contents(kcontext, &entry); - } - - if (result == NULL) - { - PyErr_SetObject(KrbException_class, Py_BuildValue("((s:i))", - "Principal not found in keytab", -1)); - } - -end: - if (cursor) - krb5_kt_end_seq_get(kcontext, kt, &cursor); - if (kt) - krb5_kt_close(kcontext, kt); - krb5_free_context(kcontext); - - return result; -} -*/ -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_COMPLETE; - - state->server_name = GSS_C_NO_NAME; - state->context = GSS_C_NO_CONTEXT; - state->gss_flags = gss_flags; - state->username = NULL; - state->response = NULL; - - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, gss_krb5_nt_service_name, &state->server_name); - - if (GSS_ERROR(maj_stat)) { - response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - -end: - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_clean(gss_client_state *state) { - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - - if(state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - - if(state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - - if(state->username != NULL) { - free(state->username); - state->username = NULL; - } - - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - return response; -} - -gss_client_response *authenticate_gss_client_step(gss_client_state* state, const char* challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - - // Always clear out the old response - if (state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if (challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_init_sec_context(&min_stat, - GSS_C_NO_CREDENTIAL, - &state->context, - state->server_name, - GSS_C_NO_OID, - (OM_uint32)state->gss_flags, - 0, - GSS_C_NO_CHANNEL_BINDINGS, - &input_token, - NULL, - &output_token, - NULL, - NULL); - - if ((maj_stat != GSS_S_COMPLETE) && (maj_stat != GSS_S_CONTINUE_NEEDED)) { - response = gss_error(__func__, "gss_init_sec_context", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - ret = (maj_stat == GSS_S_COMPLETE) ? AUTH_GSS_COMPLETE : AUTH_GSS_CONTINUE; - // Grab the client response to send back to the server - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - - // Try to get the user name if we have completed all GSS operations - if (ret == AUTH_GSS_COMPLETE) { - gss_name_t gssuser = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, &gssuser, NULL, NULL, NULL, NULL, NULL, NULL); - - if(GSS_ERROR(maj_stat)) { - response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - gss_buffer_desc name_token; - name_token.length = 0; - maj_stat = gss_display_name(&min_stat, gssuser, &name_token, NULL); - - if(GSS_ERROR(maj_stat)) { - if(name_token.value) - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - - response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - state->username = (char *)malloc(name_token.length + 1); - if(state->username == NULL) die1("Memory allocation failed"); - strncpy(state->username, (char*) name_token.value, name_token.length); - state->username[name_token.length] = 0; - gss_release_buffer(&min_stat, &name_token); - gss_release_name(&min_stat, &gssuser); - } - } - -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_unwrap(gss_client_state *state, const char *challenge) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - gss_client_response *response = NULL; - int ret = AUTH_GSS_CONTINUE; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - // If there is a challenge (data from the server) we need to give it to GSS - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - // Do GSSAPI step - maj_stat = gss_unwrap(&min_stat, - state->context, - &input_token, - &output_token, - NULL, - NULL); - - if(maj_stat != GSS_S_COMPLETE) { - response = gss_error(__func__, "gss_unwrap", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else { - ret = AUTH_GSS_COMPLETE; - } - - // Grab the client response - if(output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - gss_release_buffer(&min_stat, &output_token); - } -end: - if(output_token.value) - gss_release_buffer(&min_stat, &output_token); - if(input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user) { - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - char buf[4096], server_conf_flags; - unsigned long buf_size; - - // Always clear out the old response - if(state->response != NULL) { - free(state->response); - state->response = NULL; - } - - if(challenge && *challenge) { - int len; - input_token.value = base64_decode(challenge, &len); - input_token.length = len; - } - - if(user) { - // get bufsize - server_conf_flags = ((char*) input_token.value)[0]; - ((char*) input_token.value)[0] = 0; - buf_size = ntohl(*((long *) input_token.value)); - free(input_token.value); -#ifdef PRINTFS - printf("User: %s, %c%c%c\n", user, - server_conf_flags & GSS_AUTH_P_NONE ? 'N' : '-', - server_conf_flags & GSS_AUTH_P_INTEGRITY ? 'I' : '-', - server_conf_flags & GSS_AUTH_P_PRIVACY ? 'P' : '-'); - printf("Maximum GSS token size is %ld\n", buf_size); -#endif - - // agree to terms (hack!) - buf_size = htonl(buf_size); // not relevant without integrity/privacy - memcpy(buf, &buf_size, 4); - buf[0] = GSS_AUTH_P_NONE; - // server decides if principal can log in as user - strncpy(buf + 4, user, sizeof(buf) - 4); - input_token.value = buf; - input_token.length = 4 + strlen(user); - } - - // Do GSSAPI wrap - maj_stat = gss_wrap(&min_stat, - state->context, - 0, - GSS_C_QOP_DEFAULT, - &input_token, - NULL, - &output_token); - - if (maj_stat != GSS_S_COMPLETE) { - response = gss_error(__func__, "gss_wrap", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } else - ret = AUTH_GSS_COMPLETE; - // Grab the client response to send back to the server - if (output_token.length) { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length);; - gss_release_buffer(&min_stat, &output_token); - } -end: - if (output_token.value) - gss_release_buffer(&min_stat, &output_token); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_server_init(const char *service, bool constrained_delegation, const char *username, gss_server_state *state) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc name_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - gss_cred_usage_t usage = GSS_C_ACCEPT; - - state->context = GSS_C_NO_CONTEXT; - state->server_name = GSS_C_NO_NAME; - state->client_name = GSS_C_NO_NAME; - state->server_creds = GSS_C_NO_CREDENTIAL; - state->client_creds = GSS_C_NO_CREDENTIAL; - state->username = NULL; - state->targetname = NULL; - state->response = NULL; - state->constrained_delegation = constrained_delegation; - state->delegated_credentials_cache = NULL; - - // Server name may be empty which means we aren't going to create our own creds - size_t service_len = strlen(service); - if (service_len != 0) - { - // Import server name first - name_token.length = strlen(service); - name_token.value = (char *)service; - - maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_HOSTBASED_SERVICE, &state->server_name); - - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - if (state->constrained_delegation) - { - usage = GSS_C_BOTH; - } - - // Get credentials - maj_stat = gss_acquire_cred(&min_stat, state->server_name, GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, usage, &state->server_creds, NULL, NULL); - - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_acquire_cred", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - } - - // If a username was passed, perform the S4U2Self protocol transition to acquire - // a credentials from that user as if we had done gss_accept_sec_context. - // In this scenario, the passed username is assumed to be already authenticated - // by some external mechanism, and we are here to "bootstrap" some gss credentials. - // In authenticate_gss_server_step we will bypass the actual authentication step. - if (username != NULL) - { - gss_name_t gss_username; - - name_token.length = strlen(username); - name_token.value = (char *)username; - - maj_stat = gss_import_name(&min_stat, &name_token, GSS_C_NT_USER_NAME, &gss_username); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_import_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - maj_stat = gss_acquire_cred_impersonate_name(&min_stat, - state->server_creds, - gss_username, - GSS_C_INDEFINITE, - GSS_C_NO_OID_SET, - GSS_C_INITIATE, - &state->client_creds, - NULL, - NULL); - - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_acquire_cred_impersonate_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - } - - gss_release_name(&min_stat, &gss_username); - - if (response != NULL) - { - goto end; - } - - // because the username MAY be a "local" username, - // we want get the canonical name from the acquired creds. - maj_stat = gss_inquire_cred(&min_stat, state->client_creds, &state->client_name, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_inquire_cred", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - } - -end: - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_server_clean(gss_server_state *state) -{ - OM_uint32 min_stat; - int ret = AUTH_GSS_COMPLETE; - gss_client_response *response = NULL; - - if (state->context != GSS_C_NO_CONTEXT) - gss_delete_sec_context(&min_stat, &state->context, GSS_C_NO_BUFFER); - if (state->server_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->server_name); - if (state->client_name != GSS_C_NO_NAME) - gss_release_name(&min_stat, &state->client_name); - if (state->server_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->server_creds); - if (state->client_creds != GSS_C_NO_CREDENTIAL) - gss_release_cred(&min_stat, &state->client_creds); - if (state->username != NULL) - { - free(state->username); - state->username = NULL; - } - if (state->targetname != NULL) - { - free(state->targetname); - state->targetname = NULL; - } - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - if (state->delegated_credentials_cache) - { - // TODO: what about actually destroying the cache? It can't be done now as - // the whole point is having it around for the lifetime of the "session" - free(state->delegated_credentials_cache); - } - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *auth_data) -{ - OM_uint32 maj_stat; - OM_uint32 min_stat; - gss_buffer_desc input_token = GSS_C_EMPTY_BUFFER; - gss_buffer_desc output_token = GSS_C_EMPTY_BUFFER; - int ret = AUTH_GSS_CONTINUE; - gss_client_response *response = NULL; - - // Always clear out the old response - if (state->response != NULL) - { - free(state->response); - state->response = NULL; - } - - // we don't need to check the authentication token if S4U2Self protocol - // transition was done, because we already have the client credentials. - if (state->client_creds == GSS_C_NO_CREDENTIAL) - { - if (auth_data && *auth_data) - { - int len; - input_token.value = base64_decode(auth_data, &len); - input_token.length = len; - } - else - { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->message = strdup("No auth_data value in request from client"); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - maj_stat = gss_accept_sec_context(&min_stat, - &state->context, - state->server_creds, - &input_token, - GSS_C_NO_CHANNEL_BINDINGS, - &state->client_name, - NULL, - &output_token, - NULL, - NULL, - &state->client_creds); - - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_accept_sec_context", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - // Grab the server response to send back to the client - if (output_token.length) - { - state->response = base64_encode((const unsigned char *)output_token.value, output_token.length); - maj_stat = gss_release_buffer(&min_stat, &output_token); - } - } - - // Get the user name - maj_stat = gss_display_name(&min_stat, state->client_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - state->username = (char *)malloc(output_token.length + 1); - strncpy(state->username, (char*) output_token.value, output_token.length); - state->username[output_token.length] = 0; - - // Get the target name if no server creds were supplied - if (state->server_creds == GSS_C_NO_CREDENTIAL) - { - gss_name_t target_name = GSS_C_NO_NAME; - maj_stat = gss_inquire_context(&min_stat, state->context, NULL, &target_name, NULL, NULL, NULL, NULL, NULL); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_inquire_context", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - maj_stat = gss_display_name(&min_stat, target_name, &output_token, NULL); - if (GSS_ERROR(maj_stat)) - { - response = gss_error(__func__, "gss_display_name", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - state->targetname = (char *)malloc(output_token.length + 1); - strncpy(state->targetname, (char*) output_token.value, output_token.length); - state->targetname[output_token.length] = 0; - } - - if (state->constrained_delegation && state->client_creds != GSS_C_NO_CREDENTIAL) - { - if ((response = store_gss_creds(state)) != NULL) - { - goto end; - } - } - - ret = AUTH_GSS_COMPLETE; - -end: - if (output_token.length) - gss_release_buffer(&min_stat, &output_token); - if (input_token.value) - free(input_token.value); - - if(response == NULL) { - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->return_code = ret; - } - - // Return the response - return response; -} - -static gss_client_response *store_gss_creds(gss_server_state *state) -{ - OM_uint32 maj_stat, min_stat; - krb5_principal princ = NULL; - krb5_ccache ccache = NULL; - krb5_error_code problem; - krb5_context context; - gss_client_response *response = NULL; - - problem = krb5_init_context(&context); - if (problem) { - response = other_error("No auth_data value in request from client"); - return response; - } - - problem = krb5_parse_name(context, state->username, &princ); - if (problem) { - response = krb5_ctx_error(context, problem); - goto end; - } - - if ((response = create_krb5_ccache(state, context, princ, &ccache))) - { - goto end; - } - - maj_stat = gss_krb5_copy_ccache(&min_stat, state->client_creds, ccache); - if (GSS_ERROR(maj_stat)) { - response = gss_error(__func__, "gss_krb5_copy_ccache", maj_stat, min_stat); - response->return_code = AUTH_GSS_ERROR; - goto end; - } - - krb5_cc_close(context, ccache); - ccache = NULL; - - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - // TODO: something other than AUTH_GSS_COMPLETE? - response->return_code = AUTH_GSS_COMPLETE; - - end: - if (princ) - krb5_free_principal(context, princ); - if (ccache) - krb5_cc_destroy(context, ccache); - krb5_free_context(context); - - return response; -} - -static gss_client_response *create_krb5_ccache(gss_server_state *state, krb5_context kcontext, krb5_principal princ, krb5_ccache *ccache) -{ - char *ccname = NULL; - int fd; - krb5_error_code problem; - krb5_ccache tmp_ccache = NULL; - gss_client_response *error = NULL; - - // TODO: mod_auth_kerb used a temp file under /run/httpd/krbcache. what can we do? - ccname = strdup("FILE:/tmp/krb5cc_nodekerberos_XXXXXX"); - if (!ccname) die1("Memory allocation failed"); - - fd = mkstemp(ccname + strlen("FILE:")); - if (fd < 0) { - error = other_error("mkstemp() failed: %s", strerror(errno)); - goto end; - } - - close(fd); - - problem = krb5_cc_resolve(kcontext, ccname, &tmp_ccache); - if (problem) { - error = krb5_ctx_error(kcontext, problem); - goto end; - } - - problem = krb5_cc_initialize(kcontext, tmp_ccache, princ); - if (problem) { - error = krb5_ctx_error(kcontext, problem); - goto end; - } - - state->delegated_credentials_cache = strdup(ccname); - - // TODO: how/when to cleanup the creds cache file? - // TODO: how to expose the credentials expiration time? - - *ccache = tmp_ccache; - tmp_ccache = NULL; - - end: - if (tmp_ccache) - krb5_cc_destroy(kcontext, tmp_ccache); - - if (ccname && error) - unlink(ccname); - - if (ccname) - free(ccname); - - return error; -} - - -gss_client_response *gss_error(const char *func, const char *op, OM_uint32 err_maj, OM_uint32 err_min) { - OM_uint32 maj_stat, min_stat; - OM_uint32 msg_ctx = 0; - gss_buffer_desc status_string; - - gss_client_response *response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - - char *message = NULL; - message = calloc(1024, 1); - if(message == NULL) die1("Memory allocation failed"); - - response->message = message; - - int nleft = 1024; - int n; - - n = snprintf(message, nleft, "%s(%s)", func, op); - message += n; - nleft -= n; - - do { - maj_stat = gss_display_status (&min_stat, - err_maj, - GSS_C_GSS_CODE, - GSS_C_NO_OID, - &msg_ctx, - &status_string); - if(GSS_ERROR(maj_stat)) - break; - - n = snprintf(message, nleft, ": %.*s", - (int)status_string.length, (char*)status_string.value); - message += n; - nleft -= n; - - gss_release_buffer(&min_stat, &status_string); - - maj_stat = gss_display_status (&min_stat, - err_min, - GSS_C_MECH_CODE, - GSS_C_NULL_OID, - &msg_ctx, - &status_string); - if(!GSS_ERROR(maj_stat)) { - n = snprintf(message, nleft, ": %.*s", - (int)status_string.length, (char*)status_string.value); - message += n; - nleft -= n; - - gss_release_buffer(&min_stat, &status_string); - } - } while (!GSS_ERROR(maj_stat) && msg_ctx != 0); - - return response; -} - -static gss_client_response *krb5_ctx_error(krb5_context context, krb5_error_code problem) -{ - gss_client_response *response = NULL; - const char *error_text = krb5_get_error_message(context, problem); - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->message = strdup(error_text); - // TODO: something other than AUTH_GSS_ERROR? AUTH_KRB5_ERROR ? - response->return_code = AUTH_GSS_ERROR; - krb5_free_error_message(context, error_text); - return response; -} - -static gss_client_response *other_error(const char *fmt, ...) -{ - size_t needed; - char *msg; - gss_client_response *response = NULL; - va_list ap, aps; - - va_start(ap, fmt); - - va_copy(aps, ap); - needed = snprintf(NULL, 0, fmt, aps); - va_end(aps); - - msg = malloc(needed); - if (!msg) die1("Memory allocation failed"); - - vsnprintf(msg, needed, fmt, ap); - va_end(ap); - - response = calloc(1, sizeof(gss_client_response)); - if(response == NULL) die1("Memory allocation failed"); - response->message = msg; - - // TODO: something other than AUTH_GSS_ERROR? - response->return_code = AUTH_GSS_ERROR; - - return response; -} - - -#pragma clang diagnostic pop - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h deleted file mode 100644 index fa7e311..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/kerberosgss.h +++ /dev/null @@ -1,73 +0,0 @@ -/** - * Copyright (c) 2006-2009 Apple Inc. All rights reserved. - * - * 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. - **/ -#ifndef KERBEROS_GSS_H -#define KERBEROS_GSS_H - -#include - -#include -#include -#include - -#define krb5_get_err_text(context,code) error_message(code) - -#define AUTH_GSS_ERROR -1 -#define AUTH_GSS_COMPLETE 1 -#define AUTH_GSS_CONTINUE 0 - -#define GSS_AUTH_P_NONE 1 -#define GSS_AUTH_P_INTEGRITY 2 -#define GSS_AUTH_P_PRIVACY 4 - -typedef struct { - int return_code; - char *message; -} gss_client_response; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - long int gss_flags; - char* username; - char* response; -} gss_client_state; - -typedef struct { - gss_ctx_id_t context; - gss_name_t server_name; - gss_name_t client_name; - gss_cred_id_t server_creds; - gss_cred_id_t client_creds; - char* username; - char* targetname; - char* response; - bool constrained_delegation; - char* delegated_credentials_cache; -} gss_server_state; - -// char* server_principal_details(const char* service, const char* hostname); - -gss_client_response *authenticate_gss_client_init(const char* service, long int gss_flags, gss_client_state* state); -gss_client_response *authenticate_gss_client_clean(gss_client_state *state); -gss_client_response *authenticate_gss_client_step(gss_client_state *state, const char *challenge); -gss_client_response *authenticate_gss_client_unwrap(gss_client_state* state, const char* challenge); -gss_client_response *authenticate_gss_client_wrap(gss_client_state* state, const char* challenge, const char* user); - -gss_client_response *authenticate_gss_server_init(const char* service, bool constrained_delegation, const char *username, gss_server_state* state); -gss_client_response *authenticate_gss_server_clean(gss_server_state *state); -gss_client_response *authenticate_gss_server_step(gss_server_state *state, const char *challenge); - -#endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js deleted file mode 100644 index d9120fb..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/sspi.js +++ /dev/null @@ -1,15 +0,0 @@ -// Load the native SSPI classes -var kerberos = require('../build/Release/kerberos') - , Kerberos = kerberos.Kerberos - , SecurityBuffer = require('./win32/wrappers/security_buffer').SecurityBuffer - , SecurityBufferDescriptor = require('./win32/wrappers/security_buffer_descriptor').SecurityBufferDescriptor - , SecurityCredentials = require('./win32/wrappers/security_credentials').SecurityCredentials - , SecurityContext = require('./win32/wrappers/security_context').SecurityContext; -var SSPI = function() { -} - -exports.SSPI = SSPI; -exports.SecurityBuffer = SecurityBuffer; -exports.SecurityBufferDescriptor = SecurityBufferDescriptor; -exports.SecurityCredentials = SecurityCredentials; -exports.SecurityContext = SecurityContext; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c deleted file mode 100644 index 502a021..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.c +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -#include "base64.h" - -#include -#include - -// base64 tables -static char basis_64[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -static signed char index_64[128] = -{ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1,-1,-1,-1, - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1 -}; -#define CHAR64(c) (((c) < 0 || (c) > 127) ? -1 : index_64[(c)]) - -// base64_encode : base64 encode -// -// value : data to encode -// vlen : length of data -// (result) : new char[] - c-str of result -char *base64_encode(const unsigned char *value, int vlen) -{ - char *result = (char *)malloc((vlen * 4) / 3 + 5); - char *out = result; - unsigned char oval; - - while (vlen >= 3) - { - *out++ = basis_64[value[0] >> 2]; - *out++ = basis_64[((value[0] << 4) & 0x30) | (value[1] >> 4)]; - *out++ = basis_64[((value[1] << 2) & 0x3C) | (value[2] >> 6)]; - *out++ = basis_64[value[2] & 0x3F]; - value += 3; - vlen -= 3; - } - if (vlen > 0) - { - *out++ = basis_64[value[0] >> 2]; - oval = (value[0] << 4) & 0x30; - if (vlen > 1) oval |= value[1] >> 4; - *out++ = basis_64[oval]; - *out++ = (vlen < 2) ? '=' : basis_64[(value[1] << 2) & 0x3C]; - *out++ = '='; - } - *out = '\0'; - - return result; -} - -// base64_decode : base64 decode -// -// value : c-str to decode -// rlen : length of decoded result -// (result) : new unsigned char[] - decoded result -unsigned char *base64_decode(const char *value, int *rlen) -{ - int c1, c2, c3, c4; - int vlen = (int)strlen(value); - unsigned char *result =(unsigned char *)malloc((vlen * 3) / 4 + 1); - unsigned char *out = result; - *rlen = 0; - - while (1) - { - if (value[0]==0) - return result; - c1 = value[0]; - if (CHAR64(c1) == -1) - goto base64_decode_error;; - c2 = value[1]; - if (CHAR64(c2) == -1) - goto base64_decode_error;; - c3 = value[2]; - if ((c3 != '=') && (CHAR64(c3) == -1)) - goto base64_decode_error;; - c4 = value[3]; - if ((c4 != '=') && (CHAR64(c4) == -1)) - goto base64_decode_error;; - - value += 4; - *out++ = (CHAR64(c1) << 2) | (CHAR64(c2) >> 4); - *rlen += 1; - if (c3 != '=') - { - *out++ = ((CHAR64(c2) << 4) & 0xf0) | (CHAR64(c3) >> 2); - *rlen += 1; - if (c4 != '=') - { - *out++ = ((CHAR64(c3) << 6) & 0xc0) | CHAR64(c4); - *rlen += 1; - } - } - } - -base64_decode_error: - *result = 0; - *rlen = 0; - return result; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h deleted file mode 100644 index f0e1f06..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/base64.h +++ /dev/null @@ -1,18 +0,0 @@ -/** - * Copyright (c) 2006-2008 Apple Inc. All rights reserved. - * - * 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. - **/ - -char *base64_encode(const unsigned char *value, int vlen); -unsigned char *base64_decode(const char *value, int *rlen); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc deleted file mode 100644 index c7b583f..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.cc +++ /dev/null @@ -1,51 +0,0 @@ -#include "kerberos.h" -#include -#include -#include "base64.h" -#include "wrappers/security_buffer.h" -#include "wrappers/security_buffer_descriptor.h" -#include "wrappers/security_context.h" -#include "wrappers/security_credentials.h" - -Nan::Persistent Kerberos::constructor_template; - -Kerberos::Kerberos() : Nan::ObjectWrap() { -} - -void Kerberos::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("Kerberos").ToLocalChecked()); - - // Set persistent - constructor_template.Reset(t); - - // Set the symbol - Nan::Set(target, Nan::New("Kerberos").ToLocalChecked(), t->GetFunction()); -} - -NAN_METHOD(Kerberos::New) { - // Load the security.dll library - load_library(); - // Create a Kerberos instance - Kerberos *kerberos = new Kerberos(); - // Return the kerberos object - kerberos->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -// Exporting function -NAN_MODULE_INIT(init) { - Kerberos::Initialize(target); - SecurityContext::Initialize(target); - SecurityBuffer::Initialize(target); - SecurityBufferDescriptor::Initialize(target); - SecurityCredentials::Initialize(target); -} - -NODE_MODULE(kerberos, init); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h deleted file mode 100644 index 0fd2760..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos.h +++ /dev/null @@ -1,60 +0,0 @@ -#ifndef KERBEROS_H -#define KERBEROS_H - -#include -#include -#include -#include "nan.h" - -extern "C" { - #include "kerberos_sspi.h" - #include "base64.h" -} - -using namespace v8; -using namespace node; - -class Kerberos : public Nan::ObjectWrap { - -public: - Kerberos(); - ~Kerberos() {}; - - // Constructor used for creating new Kerberos objects from C++ - static Nan::Persistent constructor_template; - - // Initialize function for the object - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - - // Method available - static NAN_METHOD(AcquireAlternateCredentials); - static NAN_METHOD(PrepareOutboundPackage); - static NAN_METHOD(DecryptMessage); - static NAN_METHOD(EncryptMessage); - static NAN_METHOD(QueryContextAttributes); - -private: - static NAN_METHOD(New); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - // package info - SecPkgInfo m_PkgInfo; - // context - CtxtHandle m_Context; - // Do we have a context - bool m_HaveContext; - // Attributes - DWORD CtxtAttr; - - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c deleted file mode 100644 index d75c9ab..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.c +++ /dev/null @@ -1,244 +0,0 @@ -#include "kerberos_sspi.h" -#include -#include - -static HINSTANCE _sspi_security_dll = NULL; -static HINSTANCE _sspi_secur32_dll = NULL; - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo) { - // Create function pointer instance - encryptMessage_fn pfn_encryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function to library method - pfn_encryptMessage = (encryptMessage_fn)GetProcAddress(_sspi_security_dll, "EncryptMessage"); - // Check if the we managed to map function pointer - if(!pfn_encryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_encryptMessage)(phContext, fQOP, pMessage, MessageSeqNo); -} - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - acquireCredentialsHandle_fn pfn_acquireCredentialsHandle = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleW"); - #else - pfn_acquireCredentialsHandle = (acquireCredentialsHandle_fn)GetProcAddress(_sspi_security_dll, "AcquireCredentialsHandleA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_acquireCredentialsHandle) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Status - status = (*pfn_acquireCredentialsHandle)(pszPrincipal, pszPackage, fCredentialUse, - pvLogonId, pAuthData, pGetKeyFn, pvGetKeyArgument, phCredential, ptsExpiry - ); - - // Call the function - return status; -} - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext(PCtxtHandle phContext) { - // Create function pointer instance - deleteSecurityContext_fn pfn_deleteSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_deleteSecurityContext = (deleteSecurityContext_fn)GetProcAddress(_sspi_security_dll, "DeleteSecurityContext"); - - // Check if the we managed to map function pointer - if(!pfn_deleteSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_deleteSecurityContext)(phContext); -} - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage(PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP) { - // Create function pointer instance - decryptMessage_fn pfn_decryptMessage = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - // Map function - pfn_decryptMessage = (decryptMessage_fn)GetProcAddress(_sspi_security_dll, "DecryptMessage"); - - // Check if the we managed to map function pointer - if(!pfn_decryptMessage) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_decryptMessage)(phContext, pMessage, MessageSeqNo, pfQOP); -} - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, PCtxtHandle phContext, - LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, - PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, - unsigned long * pfContextAttr, PTimeStamp ptsExpiry -) { - SECURITY_STATUS status; - // Create function pointer instance - initializeSecurityContext_fn pfn_initializeSecurityContext = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - // Map function - #ifdef _UNICODE - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextW"); - #else - pfn_initializeSecurityContext = (initializeSecurityContext_fn)GetProcAddress(_sspi_security_dll, "InitializeSecurityContextA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_initializeSecurityContext) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Execute intialize context - status = (*pfn_initializeSecurityContext)( - phCredential, phContext, pszTargetName, fContextReq, - Reserved1, TargetDataRep, pInput, Reserved2, - phNewContext, pOutput, pfContextAttr, ptsExpiry - ); - - // Call the function - return status; -} -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer -) { - // Create function pointer instance - queryContextAttributes_fn pfn_queryContextAttributes = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return -1; - - #ifdef _UNICODE - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesW"); - #else - pfn_queryContextAttributes = (queryContextAttributes_fn)GetProcAddress(_sspi_security_dll, "QueryContextAttributesA"); - #endif - - // Check if the we managed to map function pointer - if(!pfn_queryContextAttributes) { - printf("GetProcAddress failed.\n"); - return -2; - } - - // Call the function - return (*pfn_queryContextAttributes)( - phContext, ulAttribute, pBuffer - ); -} - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface() { - INIT_SECURITY_INTERFACE InitSecurityInterface; - PSecurityFunctionTable pSecurityInterface = NULL; - - // Return error if library not loaded - if(_sspi_security_dll == NULL) return NULL; - - #ifdef _UNICODE - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceW")); - #else - // Get the address of the InitSecurityInterface function. - InitSecurityInterface = (INIT_SECURITY_INTERFACE) GetProcAddress ( - _sspi_secur32_dll, - TEXT("InitSecurityInterfaceA")); - #endif - - if(!InitSecurityInterface) { - printf (TEXT("Failed in getting the function address, Error: %x"), GetLastError ()); - return NULL; - } - - // Use InitSecurityInterface to get the function table. - pSecurityInterface = (*InitSecurityInterface)(); - - if(!pSecurityInterface) { - printf (TEXT("Failed in getting the function table, Error: %x"), GetLastError ()); - return NULL; - } - - return pSecurityInterface; -} - -/** - * Load security.dll dynamically - */ -int load_library() { - DWORD err; - // Load the library - _sspi_security_dll = LoadLibrary("security.dll"); - - // Check if the library loaded - if(_sspi_security_dll == NULL) { - err = GetLastError(); - return err; - } - - // Load the library - _sspi_secur32_dll = LoadLibrary("secur32.dll"); - - // Check if the library loaded - if(_sspi_secur32_dll == NULL) { - err = GetLastError(); - return err; - } - - return 0; -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h deleted file mode 100644 index a3008dc..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/kerberos_sspi.h +++ /dev/null @@ -1,106 +0,0 @@ -#ifndef SSPI_C_H -#define SSPI_C_H - -#define SECURITY_WIN32 1 - -#include -#include - -/** - * Encrypt A Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_EncryptMessage(PCtxtHandle phContext, unsigned long fQOP, PSecBufferDesc pMessage, unsigned long MessageSeqNo); - -typedef DWORD (WINAPI *encryptMessage_fn)(PCtxtHandle phContext, ULONG fQOP, PSecBufferDesc pMessage, ULONG MessageSeqNo); - -/** - * Acquire Credentials - */ -SECURITY_STATUS SEC_ENTRY _sspi_AcquireCredentialsHandle( - LPSTR pszPrincipal, // Name of principal - LPSTR pszPackage, // Name of package - unsigned long fCredentialUse, // Flags indicating use - void * pvLogonId, // Pointer to logon ID - void * pAuthData, // Package specific data - SEC_GET_KEY_FN pGetKeyFn, // Pointer to GetKey() func - void * pvGetKeyArgument, // Value to pass to GetKey() - PCredHandle phCredential, // (out) Cred Handle - PTimeStamp ptsExpiry // (out) Lifetime (optional) -); - -typedef DWORD (WINAPI *acquireCredentialsHandle_fn)( - LPSTR pszPrincipal, LPSTR pszPackage, unsigned long fCredentialUse, - void * pvLogonId, void * pAuthData, SEC_GET_KEY_FN pGetKeyFn, void * pvGetKeyArgument, - PCredHandle phCredential, PTimeStamp ptsExpiry - ); - -/** - * Delete Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_DeleteSecurityContext( - PCtxtHandle phContext // Context to delete -); - -typedef DWORD (WINAPI *deleteSecurityContext_fn)(PCtxtHandle phContext); - -/** - * Decrypt Message - */ -SECURITY_STATUS SEC_ENTRY _sspi_DecryptMessage( - PCtxtHandle phContext, - PSecBufferDesc pMessage, - unsigned long MessageSeqNo, - unsigned long pfQOP -); - -typedef DWORD (WINAPI *decryptMessage_fn)( - PCtxtHandle phContext, PSecBufferDesc pMessage, unsigned long MessageSeqNo, unsigned long pfQOP); - -/** - * Initialize Security Context - */ -SECURITY_STATUS SEC_ENTRY _sspi_initializeSecurityContext( - PCredHandle phCredential, // Cred to base context - PCtxtHandle phContext, // Existing context (OPT) - LPSTR pszTargetName, // Name of target - unsigned long fContextReq, // Context Requirements - unsigned long Reserved1, // Reserved, MBZ - unsigned long TargetDataRep, // Data rep of target - PSecBufferDesc pInput, // Input Buffers - unsigned long Reserved2, // Reserved, MBZ - PCtxtHandle phNewContext, // (out) New Context handle - PSecBufferDesc pOutput, // (inout) Output Buffers - unsigned long * pfContextAttr, // (out) Context attrs - PTimeStamp ptsExpiry // (out) Life span (OPT) -); - -typedef DWORD (WINAPI *initializeSecurityContext_fn)( - PCredHandle phCredential, PCtxtHandle phContext, LPSTR pszTargetName, unsigned long fContextReq, - unsigned long Reserved1, unsigned long TargetDataRep, PSecBufferDesc pInput, unsigned long Reserved2, - PCtxtHandle phNewContext, PSecBufferDesc pOutput, unsigned long * pfContextAttr, PTimeStamp ptsExpiry); - -/** - * Query Context Attributes - */ -SECURITY_STATUS SEC_ENTRY _sspi_QueryContextAttributes( - PCtxtHandle phContext, // Context to query - unsigned long ulAttribute, // Attribute to query - void * pBuffer // Buffer for attributes -); - -typedef DWORD (WINAPI *queryContextAttributes_fn)( - PCtxtHandle phContext, unsigned long ulAttribute, void * pBuffer); - -/** - * InitSecurityInterface - */ -PSecurityFunctionTable _ssip_InitSecurityInterface(); - -typedef DWORD (WINAPI *initSecurityInterface_fn) (); - -/** - * Load security.dll dynamically - */ -int load_library(); - -#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc deleted file mode 100644 index e7a472f..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h deleted file mode 100644 index c2ccb6b..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/worker.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - Nan::Callback *callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Local (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc deleted file mode 100644 index fdf8e49..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.cc +++ /dev/null @@ -1,101 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_buffer.h" - -using namespace node; - -Nan::Persistent SecurityBuffer::constructor_template; - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size) : Nan::ObjectWrap() { - this->size = size; - this->data = calloc(size, sizeof(char)); - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::SecurityBuffer(uint32_t security_type, size_t size, void *data) : Nan::ObjectWrap() { - this->size = size; - this->data = data; - this->security_type = security_type; - // Set up the data in the sec_buffer - this->sec_buffer.BufferType = security_type; - this->sec_buffer.cbBuffer = (unsigned long)size; - this->sec_buffer.pvBuffer = this->data; -} - -SecurityBuffer::~SecurityBuffer() { - free(this->data); -} - -NAN_METHOD(SecurityBuffer::New) { - SecurityBuffer *security_obj; - - if(info.Length() != 2) - return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!info[0]->IsInt32()) - return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - if(!info[1]->IsInt32() && !Buffer::HasInstance(info[1])) - return Nan::ThrowError("Two parameters needed integer buffer type and [32 bit integer/Buffer] required"); - - // Unpack buffer type - uint32_t buffer_type = info[0]->ToUint32()->Value(); - - // If we have an integer - if(info[1]->IsInt32()) { - security_obj = new SecurityBuffer(buffer_type, info[1]->ToUint32()->Value()); - } else { - // Get the length of the Buffer - size_t length = Buffer::Length(info[1]->ToObject()); - // Allocate space for the internal void data pointer - void *data = calloc(length, sizeof(char)); - // Write the data to out of V8 heap space - memcpy(data, Buffer::Data(info[1]->ToObject()), length); - // Create new SecurityBuffer - security_obj = new SecurityBuffer(buffer_type, length, data); - } - - // Wrap it - security_obj->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -NAN_METHOD(SecurityBuffer::ToBuffer) { - // Unpack the Security Buffer object - SecurityBuffer *security_obj = Nan::ObjectWrap::Unwrap(info.This()); - // Create a Buffer - Local buffer = Nan::CopyBuffer((char *)security_obj->data, (uint32_t)security_obj->size).ToLocalChecked(); - // Return the buffer - info.GetReturnValue().Set(buffer); -} - -void SecurityBuffer::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("SecurityBuffer").ToLocalChecked()); - - // Class methods - Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer); - - // Set persistent - constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("SecurityBuffer").ToLocalChecked(), t->GetFunction()); -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h deleted file mode 100644 index 0c97d56..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.h +++ /dev/null @@ -1,48 +0,0 @@ -#ifndef SECURITY_BUFFER_H -#define SECURITY_BUFFER_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBuffer : public Nan::ObjectWrap { - public: - SecurityBuffer(uint32_t security_type, size_t size); - SecurityBuffer(uint32_t security_type, size_t size, void *data); - ~SecurityBuffer(); - - // Internal values - void *data; - size_t size; - uint32_t security_type; - SecBuffer sec_buffer; - - // Has instance check - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - static NAN_METHOD(ToBuffer); - - // Constructor used for creating new Long objects from C++ - static Nan::Persistent constructor_template; - - private: - static NAN_METHOD(New); -}; - -#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js deleted file mode 100644 index 4996163..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer.js +++ /dev/null @@ -1,12 +0,0 @@ -var SecurityBufferNative = require('../../../build/Release/kerberos').SecurityBuffer; - -// Add some attributes -SecurityBufferNative.VERSION = 0; -SecurityBufferNative.EMPTY = 0; -SecurityBufferNative.DATA = 1; -SecurityBufferNative.TOKEN = 2; -SecurityBufferNative.PADDING = 9; -SecurityBufferNative.STREAM = 10; - -// Export the modified class -exports.SecurityBuffer = SecurityBufferNative; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc deleted file mode 100644 index fce0d81..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.cc +++ /dev/null @@ -1,182 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include "security_buffer_descriptor.h" -#include "security_buffer.h" - -Nan::Persistent SecurityBufferDescriptor::constructor_template; - -SecurityBufferDescriptor::SecurityBufferDescriptor() : Nan::ObjectWrap() { -} - -SecurityBufferDescriptor::SecurityBufferDescriptor(const Nan::Persistent& arrayObjectPersistent) : Nan::ObjectWrap() { - SecurityBuffer *security_obj = NULL; - // Get the Local value - Local arrayObject = Nan::New(arrayObjectPersistent); - - // Safe reference to array - this->arrayObject = arrayObject; - - // Unpack the array and ensure we have a valid descriptor - this->secBufferDesc.cBuffers = arrayObject->Length(); - this->secBufferDesc.ulVersion = SECBUFFER_VERSION; - - if(arrayObject->Length() == 1) { - // Unwrap the buffer - security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - // Assign the buffer - this->secBufferDesc.pBuffers = &security_obj->sec_buffer; - } else { - this->secBufferDesc.pBuffers = new SecBuffer[arrayObject->Length()]; - this->secBufferDesc.cBuffers = arrayObject->Length(); - - // Assign the buffers - for(uint32_t i = 0; i < arrayObject->Length(); i++) { - security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(i)->ToObject()); - this->secBufferDesc.pBuffers[i].BufferType = security_obj->sec_buffer.BufferType; - this->secBufferDesc.pBuffers[i].pvBuffer = security_obj->sec_buffer.pvBuffer; - this->secBufferDesc.pBuffers[i].cbBuffer = security_obj->sec_buffer.cbBuffer; - } - } -} - -SecurityBufferDescriptor::~SecurityBufferDescriptor() { -} - -size_t SecurityBufferDescriptor::bufferSize() { - SecurityBuffer *security_obj = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - return security_obj->size; - } else { - int bytesToAllocate = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - bytesToAllocate += this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return total size - return bytesToAllocate; - } -} - -char *SecurityBufferDescriptor::toBuffer() { - SecurityBuffer *security_obj = NULL; - char *data = NULL; - - if(this->secBufferDesc.cBuffers == 1) { - security_obj = Nan::ObjectWrap::Unwrap(arrayObject->Get(0)->ToObject()); - data = (char *)malloc(security_obj->size * sizeof(char)); - memcpy(data, security_obj->data, security_obj->size); - } else { - size_t bytesToAllocate = this->bufferSize(); - char *data = (char *)calloc(bytesToAllocate, sizeof(char)); - int offset = 0; - - for(unsigned int i = 0; i < this->secBufferDesc.cBuffers; i++) { - memcpy((data + offset), this->secBufferDesc.pBuffers[i].pvBuffer, this->secBufferDesc.pBuffers[i].cbBuffer); - offset +=this->secBufferDesc.pBuffers[i].cbBuffer; - } - - // Return the data - return data; - } - - return data; -} - -NAN_METHOD(SecurityBufferDescriptor::New) { - SecurityBufferDescriptor *security_obj; - Nan::Persistent arrayObject; - - if(info.Length() != 1) - return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(!info[0]->IsInt32() && !info[0]->IsArray()) - return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - - if(info[0]->IsArray()) { - Local array = Local::Cast(info[0]); - // Iterate over all items and ensure we the right type - for(uint32_t i = 0; i < array->Length(); i++) { - if(!SecurityBuffer::HasInstance(array->Get(i))) { - return Nan::ThrowError("There must be 1 argument passed in where the first argument is a [int32 or an Array of SecurityBuffers]"); - } - } - } - - // We have a single integer - if(info[0]->IsInt32()) { - // Create new SecurityBuffer instance - Local argv[] = {Nan::New(0x02), info[0]}; - Local security_buffer = Nan::New(SecurityBuffer::constructor_template)->GetFunction()->NewInstance(2, argv); - // Create a new array - Local array = Nan::New(1); - // Set the first value - array->Set(0, security_buffer); - - // Create persistent handle - Nan::Persistent persistenHandler; - persistenHandler.Reset(array); - - // Create descriptor - security_obj = new SecurityBufferDescriptor(persistenHandler); - } else { - // Create a persistent handler - Nan::Persistent persistenHandler; - persistenHandler.Reset(Local::Cast(info[0])); - // Create a descriptor - security_obj = new SecurityBufferDescriptor(persistenHandler); - } - - // Wrap it - security_obj->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -NAN_METHOD(SecurityBufferDescriptor::ToBuffer) { - // Unpack the Security Buffer object - SecurityBufferDescriptor *security_obj = Nan::ObjectWrap::Unwrap(info.This()); - - // Get the buffer - char *buffer_data = security_obj->toBuffer(); - size_t buffer_size = security_obj->bufferSize(); - - // Create a Buffer - Local buffer = Nan::CopyBuffer(buffer_data, (uint32_t)buffer_size).ToLocalChecked(); - - // Return the buffer - info.GetReturnValue().Set(buffer); -} - -void SecurityBufferDescriptor::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("SecurityBufferDescriptor").ToLocalChecked()); - - // Class methods - Nan::SetPrototypeMethod(t, "toBuffer", ToBuffer); - - // Set persistent - constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("SecurityBufferDescriptor").ToLocalChecked(), t->GetFunction()); -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h deleted file mode 100644 index dc28f7e..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SECURITY_BUFFER_DESCRIPTOR_H -#define SECURITY_BUFFER_DESCRIPTOR_H - -#include -#include -#include - -#include -#include -#include -#include - -using namespace v8; -using namespace node; - -class SecurityBufferDescriptor : public Nan::ObjectWrap { - public: - Local arrayObject; - SecBufferDesc secBufferDesc; - - SecurityBufferDescriptor(); - SecurityBufferDescriptor(const Nan::Persistent& arrayObjectPersistent); - ~SecurityBufferDescriptor(); - - // Has instance check - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - char *toBuffer(); - size_t bufferSize(); - - // Functions available from V8 - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - static NAN_METHOD(ToBuffer); - - // Constructor used for creating new Long objects from C++ - static Nan::Persistent constructor_template; - - private: - static NAN_METHOD(New); -}; - -#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js deleted file mode 100644 index 9421392..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_buffer_descriptor.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityBufferDescriptorNative = require('../../../build/Release/kerberos').SecurityBufferDescriptor; -// Export the modified class -exports.SecurityBufferDescriptor = SecurityBufferDescriptorNative; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc deleted file mode 100644 index 5d7ad54..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.cc +++ /dev/null @@ -1,856 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_context.h" -#include "security_buffer_descriptor.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -static void After(uv_work_t* work_req) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); - Local obj = err->ToObject(); - obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); - Local info[2] = { err, Nan::Null() }; - // Execute the error - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } else { - // // Map the data - Local result = worker->mapper(worker); - // Set up the callback with a null first - Local info[2] = { Nan::Null(), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } - - // Clean up the memory - delete worker->callback; - delete worker; -} - -Nan::Persistent SecurityContext::constructor_template; - -SecurityContext::SecurityContext() : Nan::ObjectWrap() { -} - -SecurityContext::~SecurityContext() { - if(this->hasContext) { - _sspi_DeleteSecurityContext(&this->m_Context); - } -} - -NAN_METHOD(SecurityContext::New) { - PSecurityFunctionTable pSecurityInterface = NULL; - DWORD dwNumOfPkgs; - SECURITY_STATUS status; - - // Create code object - SecurityContext *security_obj = new SecurityContext(); - // Get security table interface - pSecurityInterface = _ssip_InitSecurityInterface(); - // Call the security interface - status = (*pSecurityInterface->EnumerateSecurityPackages)( - &dwNumOfPkgs, - &security_obj->m_PkgInfo); - if(status != SEC_E_OK) { - printf(TEXT("Failed in retrieving security packages, Error: %x"), GetLastError()); - return Nan::ThrowError("Failed in retrieving security packages"); - } - - // Wrap it - security_obj->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -// -// Async InitializeContext -// -typedef struct SecurityContextStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStaticInitializeCall; - -static void _initializeContext(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - BYTE *out_bound_data_str = NULL; - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)worker->parameters; - - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = call->context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &call->context->security_credentials->m_Credentials - , NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length > 0 ? &ibd : NULL - , 0 - , &call->context->m_Context - , &obd - , &call->context->CtxtAttr - , &call->context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - call->context->hasContext = true; - call->context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - - // Set the context - worker->return_code = status; - worker->return_value = call->context; - } else if(status == SEC_E_INSUFFICIENT_MEMORY) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INSUFFICIENT_MEMORY There is not enough memory available to complete the requested action."; - } else if(status == SEC_E_INTERNAL_ERROR) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INTERNAL_ERROR An error occurred that did not map to an SSPI error code."; - } else if(status == SEC_E_INVALID_HANDLE) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INVALID_HANDLE The handle passed to the function is not valid."; - } else if(status == SEC_E_INVALID_TOKEN) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_INVALID_TOKEN The error is due to a malformed input token, such as a token corrupted in transit, a token of incorrect size, or a token passed into the wrong security package. Passing a token to the wrong package can happen if the client and server did not negotiate the proper security package."; - } else if(status == SEC_E_LOGON_DENIED) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_LOGON_DENIED The logon failed."; - } else if(status == SEC_E_NO_AUTHENTICATING_AUTHORITY) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_NO_AUTHENTICATING_AUTHORITY No authority could be contacted for authentication. The domain name of the authenticating party could be wrong, the domain could be unreachable, or there might have been a trust relationship failure."; - } else if(status == SEC_E_NO_CREDENTIALS) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_NO_CREDENTIALS No credentials are available in the security package."; - } else if(status == SEC_E_TARGET_UNKNOWN) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_TARGET_UNKNOWN The target was not recognized."; - } else if(status == SEC_E_UNSUPPORTED_FUNCTION) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_UNSUPPORTED_FUNCTION A context attribute flag that is not valid (ISC_REQ_DELEGATE or ISC_REQ_PROMPT_FOR_CREDS) was specified in the fContextReq parameter."; - } else if(status == SEC_E_WRONG_PRINCIPAL) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = "SEC_E_WRONG_PRINCIPAL The principal that received the authentication request is not the same as the one passed into the pszTargetName parameter. This indicates a failure in mutual authentication."; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Local _map_initializeContext(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return context->handle(); -} - -NAN_METHOD(SecurityContext::InitializeContext) { - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - // Store reference to security credentials - SecurityCredentials *security_credentials = NULL; - - // We need 3 parameters - if(info.Length() != 4) - return Nan::ThrowError("Initialize must be called with [credential:SecurityCredential, servicePrincipalName:string, input:string, callback:function]"); - - // First parameter must be an instance of SecurityCredentials - if(!SecurityCredentials::HasInstance(info[0])) - return Nan::ThrowError("First parameter for Initialize must be an instance of SecurityCredentials"); - - // Second parameter must be a string - if(!info[1]->IsString()) - return Nan::ThrowError("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!info[2]->IsString()) - return Nan::ThrowError("Second parameter for Initialize must be a string"); - - // Third parameter must be a callback - if(!info[3]->IsFunction()) - return Nan::ThrowError("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = info[1]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = info[2]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free original allocation - free(input_str); - } - - // Unpack the Security credentials - security_credentials = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); - // Create Security context instance - Local security_context_value = Nan::New(constructor_template)->GetFunction()->NewInstance(); - // Unwrap the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(security_context_value); - // Add a reference to the security_credentials - security_context->security_credentials = security_credentials; - - // Build the call function - SecurityContextStaticInitializeCall *call = (SecurityContextStaticInitializeCall *)calloc(1, sizeof(SecurityContextStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(info[3]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _initializeContext; - worker->mapper = _map_initializeContext; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -NAN_GETTER(SecurityContext::PayloadGetter) { - // Unpack the context object - SecurityContext *context = Nan::ObjectWrap::Unwrap(info.This()); - // Return the low bits - info.GetReturnValue().Set(Nan::New(context->payload).ToLocalChecked()); -} - -NAN_GETTER(SecurityContext::HasContextGetter) { - // Unpack the context object - SecurityContext *context = Nan::ObjectWrap::Unwrap(info.This()); - // Return the low bits - info.GetReturnValue().Set(Nan::New(context->hasContext)); -} - -// -// Async InitializeContextStep -// -typedef struct SecurityContextStepStaticInitializeCall { - char *service_principal_name_str; - char *decoded_input_str; - int decoded_input_str_length; - SecurityContext *context; -} SecurityContextStepStaticInitializeCall; - -static void _initializeContextStep(Worker *worker) { - // Outbound data array - BYTE *out_bound_data_str = NULL; - // Status of operation - SECURITY_STATUS status; - // Unpack data - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)worker->parameters; - SecurityContext *context = call->context; - // Structures used for c calls - SecBufferDesc ibd, obd; - SecBuffer ib, ob; - - // - // Prepare data structure for returned data from SSPI - ob.BufferType = SECBUFFER_TOKEN; - ob.cbBuffer = context->m_PkgInfo->cbMaxToken; - // Allocate space for return data - out_bound_data_str = new BYTE[ob.cbBuffer + sizeof(DWORD)]; - ob.pvBuffer = out_bound_data_str; - // prepare buffer description - obd.cBuffers = 1; - obd.ulVersion = SECBUFFER_VERSION; - obd.pBuffers = &ob; - - // - // Prepare the data we are passing to the SSPI method - if(call->decoded_input_str_length > 0) { - ib.BufferType = SECBUFFER_TOKEN; - ib.cbBuffer = call->decoded_input_str_length; - ib.pvBuffer = call->decoded_input_str; - // prepare buffer description - ibd.cBuffers = 1; - ibd.ulVersion = SECBUFFER_VERSION; - ibd.pBuffers = &ib; - } - - // Perform initialization step - status = _sspi_initializeSecurityContext( - &context->security_credentials->m_Credentials - , context->hasContext == true ? &context->m_Context : NULL - , const_cast(call->service_principal_name_str) - , 0x02 // MUTUAL - , 0 - , 0 // Network - , call->decoded_input_str_length ? &ibd : NULL - , 0 - , &context->m_Context - , &obd - , &context->CtxtAttr - , &context->Expiration - ); - - // If we have a ok or continue let's prepare the result - if(status == SEC_E_OK - || status == SEC_I_COMPLETE_NEEDED - || status == SEC_I_CONTINUE_NEEDED - || status == SEC_I_COMPLETE_AND_CONTINUE - ) { - // Set the new payload - if(context->payload != NULL) free(context->payload); - context->payload = base64_encode((const unsigned char *)ob.pvBuffer, ob.cbBuffer); - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } - - // Clean up data - if(call->decoded_input_str != NULL) free(call->decoded_input_str); - if(call->service_principal_name_str != NULL) free(call->service_principal_name_str); -} - -static Local _map_initializeContextStep(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return context->handle(); -} - -NAN_METHOD(SecurityContext::InitalizeStep) { - char *service_principal_name_str = NULL, *input_str = NULL, *decoded_input_str = NULL; - int decoded_input_str_length = NULL; - - // We need 3 parameters - if(info.Length() != 3) - return Nan::ThrowError("Initialize must be called with [servicePrincipalName:string, input:string, callback:function]"); - - // Second parameter must be a string - if(!info[0]->IsString()) - return Nan::ThrowError("First parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!info[1]->IsString()) - return Nan::ThrowError("Second parameter for Initialize must be a string"); - - // Third parameter must be a base64 encoded string - if(!info[2]->IsFunction()) - return Nan::ThrowError("Third parameter for Initialize must be a callback function"); - - // Let's unpack the values - Local service_principal_name = info[0]->ToString(); - service_principal_name_str = (char *)calloc(service_principal_name->Utf8Length() + 1, sizeof(char)); - service_principal_name->WriteUtf8(service_principal_name_str); - - // Unpack the user name - Local input = info[1]->ToString(); - - if(input->Utf8Length() > 0) { - input_str = (char *)calloc(input->Utf8Length() + 1, sizeof(char)); - input->WriteUtf8(input_str); - // Now let's get the base64 decoded string - decoded_input_str = (char *)base64_decode(input_str, &decoded_input_str_length); - // Free input string - free(input_str); - } - - // Unwrap the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); - - // Create call structure - SecurityContextStepStaticInitializeCall *call = (SecurityContextStepStaticInitializeCall *)calloc(1, sizeof(SecurityContextStepStaticInitializeCall)); - call->context = security_context; - call->decoded_input_str = decoded_input_str; - call->decoded_input_str_length = decoded_input_str_length; - call->service_principal_name_str = service_principal_name_str; - - // Callback - Local callback = Local::Cast(info[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _initializeContextStep; - worker->mapper = _map_initializeContextStep; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// -// Async EncryptMessage -// -typedef struct SecurityContextEncryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; - unsigned long flags; -} SecurityContextEncryptMessageCall; - -static void _encryptMessage(Worker *worker) { - SECURITY_STATUS status; - // Unpack call - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)worker->parameters; - // Unpack the security context - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_EncryptMessage( - &context->m_Context - , call->flags - , &descriptor->secBufferDesc - , 0 - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set result - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Local _map_encryptMessage(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return context->handle(); -} - -NAN_METHOD(SecurityContext::EncryptMessage) { - if(info.Length() != 3) - return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(info[0])) - return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!info[1]->IsUint32()) - return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - if(!info[2]->IsFunction()) - return Nan::ThrowError("EncryptMessage takes an instance of SecurityBufferDescriptor, an integer flag and a callback function"); - - // Unpack the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); - - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); - - // Create call structure - SecurityContextEncryptMessageCall *call = (SecurityContextEncryptMessageCall *)calloc(1, sizeof(SecurityContextEncryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - call->flags = (unsigned long)info[1]->ToInteger()->Value(); - - // Callback - Local callback = Local::Cast(info[2]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _encryptMessage; - worker->mapper = _map_encryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// -// Async DecryptMessage -// -typedef struct SecurityContextDecryptMessageCall { - SecurityContext *context; - SecurityBufferDescriptor *descriptor; -} SecurityContextDecryptMessageCall; - -static void _decryptMessage(Worker *worker) { - unsigned long quality = 0; - SECURITY_STATUS status; - - // Unpack parameters - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)worker->parameters; - SecurityContext *context = call->context; - SecurityBufferDescriptor *descriptor = call->descriptor; - - // Let's execute encryption - status = _sspi_DecryptMessage( - &context->m_Context - , &descriptor->secBufferDesc - , 0 - , (unsigned long)&quality - ); - - // We've got ok - if(status == SEC_E_OK) { - int bytesToAllocate = (int)descriptor->bufferSize(); - // Free up existing payload - if(context->payload != NULL) free(context->payload); - // Save the payload - context->payload = base64_encode((unsigned char *)descriptor->toBuffer(), bytesToAllocate); - // Set return values - worker->return_code = status; - worker->return_value = context; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Local _map_decryptMessage(Worker *worker) { - // Unwrap the security context - SecurityContext *context = (SecurityContext *)worker->return_value; - // Return the value - return context->handle(); -} - -NAN_METHOD(SecurityContext::DecryptMessage) { - if(info.Length() != 2) - return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!SecurityBufferDescriptor::HasInstance(info[0])) - return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - if(!info[1]->IsFunction()) - return Nan::ThrowError("DecryptMessage takes an instance of SecurityBufferDescriptor and a callback function"); - - // Unpack the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); - // Unpack the descriptor - SecurityBufferDescriptor *descriptor = Nan::ObjectWrap::Unwrap(info[0]->ToObject()); - // Create call structure - SecurityContextDecryptMessageCall *call = (SecurityContextDecryptMessageCall *)calloc(1, sizeof(SecurityContextDecryptMessageCall)); - call->context = security_context; - call->descriptor = descriptor; - - // Callback - Local callback = Local::Cast(info[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _decryptMessage; - worker->mapper = _map_decryptMessage; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -// -// Async QueryContextAttributes -// -typedef struct SecurityContextQueryContextAttributesCall { - SecurityContext *context; - uint32_t attribute; -} SecurityContextQueryContextAttributesCall; - -static void _queryContextAttributes(Worker *worker) { - SECURITY_STATUS status; - - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - - // Allocate some space - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)calloc(1, sizeof(SecPkgContext_Sizes)); - // Let's grab the query context attribute - status = _sspi_QueryContextAttributes( - &call->context->m_Context, - call->attribute, - sizes - ); - - if(status == SEC_E_OK) { - worker->return_code = status; - worker->return_value = sizes; - } else { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } -} - -static Local _map_queryContextAttributes(Worker *worker) { - // Cast to data structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)worker->parameters; - // Unpack the attribute - uint32_t attribute = call->attribute; - - // Convert data - if(attribute == SECPKG_ATTR_SIZES) { - SecPkgContext_Sizes *sizes = (SecPkgContext_Sizes *)worker->return_value; - // Create object - Local value = Nan::New(); - value->Set(Nan::New("maxToken").ToLocalChecked(), Nan::New(uint32_t(sizes->cbMaxToken))); - value->Set(Nan::New("maxSignature").ToLocalChecked(), Nan::New(uint32_t(sizes->cbMaxSignature))); - value->Set(Nan::New("blockSize").ToLocalChecked(), Nan::New(uint32_t(sizes->cbBlockSize))); - value->Set(Nan::New("securityTrailer").ToLocalChecked(), Nan::New(uint32_t(sizes->cbSecurityTrailer))); - return value; - } - - // Return the value - return Nan::Null(); -} - -NAN_METHOD(SecurityContext::QueryContextAttributes) { - if(info.Length() != 2) - return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!info[0]->IsInt32()) - return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - if(!info[1]->IsFunction()) - return Nan::ThrowError("QueryContextAttributes method takes a an integer Attribute specifier and a callback function"); - - // Unpack the security context - SecurityContext *security_context = Nan::ObjectWrap::Unwrap(info.This()); - - // Unpack the int value - uint32_t attribute = info[0]->ToInt32()->Value(); - - // Check that we have a supported attribute - if(attribute != SECPKG_ATTR_SIZES) - return Nan::ThrowError("QueryContextAttributes only supports the SECPKG_ATTR_SIZES attribute"); - - // Create call structure - SecurityContextQueryContextAttributesCall *call = (SecurityContextQueryContextAttributesCall *)calloc(1, sizeof(SecurityContextQueryContextAttributesCall)); - call->attribute = attribute; - call->context = security_context; - - // Callback - Local callback = Local::Cast(info[1]); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = new Nan::Callback(callback); - worker->parameters = call; - worker->execute = _queryContextAttributes; - worker->mapper = _map_queryContextAttributes; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, Process, (uv_after_work_cb)After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -void SecurityContext::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(static_cast(SecurityContext::New)); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("SecurityContext").ToLocalChecked()); - - // Class methods - Nan::SetMethod(t, "initialize", SecurityContext::InitializeContext); - - // Set up method for the instance - Nan::SetPrototypeMethod(t, "initialize", SecurityContext::InitalizeStep); - Nan::SetPrototypeMethod(t, "decryptMessage", SecurityContext::DecryptMessage); - Nan::SetPrototypeMethod(t, "queryContextAttributes", SecurityContext::QueryContextAttributes); - Nan::SetPrototypeMethod(t, "encryptMessage", SecurityContext::EncryptMessage); - - // Get prototype - Local proto = t->PrototypeTemplate(); - - // Getter for the response - Nan::SetAccessor(proto, Nan::New("payload").ToLocalChecked(), SecurityContext::PayloadGetter); - Nan::SetAccessor(proto, Nan::New("hasContext").ToLocalChecked(), SecurityContext::HasContextGetter); - - // Set persistent - SecurityContext::constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("SecurityContext").ToLocalChecked(), t->GetFunction()); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessageSync (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - } - - return pszName; -} - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h deleted file mode 100644 index 1d9387d..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.h +++ /dev/null @@ -1,74 +0,0 @@ -#ifndef SECURITY_CONTEXT_H -#define SECURITY_CONTEXT_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include -#include "security_credentials.h" -#include "../worker.h" -#include - -extern "C" { - #include "../kerberos_sspi.h" - #include "../base64.h" -} - -using namespace v8; -using namespace node; - -class SecurityContext : public Nan::ObjectWrap { - public: - SecurityContext(); - ~SecurityContext(); - - // Security info package - PSecPkgInfo m_PkgInfo; - // Do we have a context - bool hasContext; - // Reference to security credentials - SecurityCredentials *security_credentials; - // Security context - CtxtHandle m_Context; - // Attributes - DWORD CtxtAttr; - // Expiry time for ticket - TimeStamp Expiration; - // Payload - char *payload; - - // Has instance check - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - static NAN_METHOD(InitializeContext); - static NAN_METHOD(InitalizeStep); - static NAN_METHOD(DecryptMessage); - static NAN_METHOD(QueryContextAttributes); - static NAN_METHOD(EncryptMessage); - - // Payload getter - static NAN_GETTER(PayloadGetter); - // hasContext getter - static NAN_GETTER(HasContextGetter); - - // Constructor used for creating new Long objects from C++ - static Nan::Persistent constructor_template; - - // private: - // Create a new instance - static NAN_METHOD(New); -}; - -#endif diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js deleted file mode 100644 index ef04e92..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_context.js +++ /dev/null @@ -1,3 +0,0 @@ -var SecurityContextNative = require('../../../build/Release/kerberos').SecurityContext; -// Export the modified class -exports.SecurityContext = SecurityContextNative; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc deleted file mode 100644 index 732af3f..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.cc +++ /dev/null @@ -1,348 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "security_credentials.h" - -#ifndef ARRAY_SIZE -# define ARRAY_SIZE(a) (sizeof((a)) / sizeof((a)[0])) -#endif - -static LPSTR DisplaySECError(DWORD ErrCode); - -Nan::Persistent SecurityCredentials::constructor_template; - -SecurityCredentials::SecurityCredentials() : Nan::ObjectWrap() { -} - -SecurityCredentials::~SecurityCredentials() { -} - -NAN_METHOD(SecurityCredentials::New) { - // Create security credentials instance - SecurityCredentials *security_credentials = new SecurityCredentials(); - // Wrap it - security_credentials->Wrap(info.This()); - // Return the object - info.GetReturnValue().Set(info.This()); -} - -// Call structs -typedef struct SecurityCredentialCall { - char *package_str; - char *username_str; - char *password_str; - char *domain_str; - SecurityCredentials *credentials; -} SecurityCredentialCall; - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// authGSSClientInit -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -static void _authSSPIAquire(Worker *worker) { - // Status of operation - SECURITY_STATUS status; - - // Unpack data - SecurityCredentialCall *call = (SecurityCredentialCall *)worker->parameters; - - // // Unwrap the credentials - // SecurityCredentials *security_credentials = (SecurityCredentials *)call->credentials; - SecurityCredentials *security_credentials = new SecurityCredentials(); - - // If we have domain string - if(call->domain_str != NULL) { - security_credentials->m_Identity.Domain = USTR(_tcsdup(call->domain_str)); - security_credentials->m_Identity.DomainLength = (unsigned long)_tcslen(call->domain_str); - } else { - security_credentials->m_Identity.Domain = NULL; - security_credentials->m_Identity.DomainLength = 0; - } - - // Set up the user - security_credentials->m_Identity.User = USTR(_tcsdup(call->username_str)); - security_credentials->m_Identity.UserLength = (unsigned long)_tcslen(call->username_str); - - // If we have a password string - if(call->password_str != NULL) { - // Set up the password - security_credentials->m_Identity.Password = USTR(_tcsdup(call->password_str)); - security_credentials->m_Identity.PasswordLength = (unsigned long)_tcslen(call->password_str); - } - - #ifdef _UNICODE - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_UNICODE; - #else - security_credentials->m_Identity.Flags = SEC_WINNT_AUTH_IDENTITY_ANSI; - #endif - - // Attempt to acquire credentials - status = _sspi_AcquireCredentialsHandle( - NULL, - call->package_str, - SECPKG_CRED_OUTBOUND, - NULL, - call->password_str != NULL ? &security_credentials->m_Identity : NULL, - NULL, NULL, - &security_credentials->m_Credentials, - &security_credentials->Expiration - ); - - // We have an error - if(status != SEC_E_OK) { - worker->error = TRUE; - worker->error_code = status; - worker->error_message = DisplaySECError(status); - } else { - worker->return_code = status; - worker->return_value = security_credentials; - } - - // Free up parameter structure - if(call->package_str != NULL) free(call->package_str); - if(call->domain_str != NULL) free(call->domain_str); - if(call->password_str != NULL) free(call->password_str); - if(call->username_str != NULL) free(call->username_str); - free(call); -} - -static Local _map_authSSPIAquire(Worker *worker) { - return Nan::Null(); -} - -NAN_METHOD(SecurityCredentials::Aquire) { - char *package_str = NULL, *username_str = NULL, *password_str = NULL, *domain_str = NULL; - // Unpack the variables - if(info.Length() != 2 && info.Length() != 3 && info.Length() != 4 && info.Length() != 5) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!info[0]->IsString()) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(!info[1]->IsString()) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(info.Length() == 3 && (!info[2]->IsString() && !info[2]->IsFunction())) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(info.Length() == 4 && (!info[3]->IsString() && !info[3]->IsUndefined() && !info[3]->IsNull()) && !info[3]->IsFunction()) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - if(info.Length() == 5 && !info[4]->IsFunction()) - return Nan::ThrowError("Aquire must be called with either [package:string, username:string, [password:string, domain:string], callback:function]"); - - Local callbackHandle; - - // Figure out which parameter is the callback - if(info.Length() == 5) { - callbackHandle = Local::Cast(info[4]); - } else if(info.Length() == 4) { - callbackHandle = Local::Cast(info[3]); - } else if(info.Length() == 3) { - callbackHandle = Local::Cast(info[2]); - } - - // Unpack the package - Local package = info[0]->ToString(); - package_str = (char *)calloc(package->Utf8Length() + 1, sizeof(char)); - package->WriteUtf8(package_str); - - // Unpack the user name - Local username = info[1]->ToString(); - username_str = (char *)calloc(username->Utf8Length() + 1, sizeof(char)); - username->WriteUtf8(username_str); - - // If we have a password - if(info.Length() == 3 || info.Length() == 4 || info.Length() == 5) { - Local password = info[2]->ToString(); - password_str = (char *)calloc(password->Utf8Length() + 1, sizeof(char)); - password->WriteUtf8(password_str); - } - - // If we have a domain - if((info.Length() == 4 || info.Length() == 5) && info[3]->IsString()) { - Local domain = info[3]->ToString(); - domain_str = (char *)calloc(domain->Utf8Length() + 1, sizeof(char)); - domain->WriteUtf8(domain_str); - } - - // Allocate call structure - SecurityCredentialCall *call = (SecurityCredentialCall *)calloc(1, sizeof(SecurityCredentialCall)); - call->domain_str = domain_str; - call->package_str = package_str; - call->password_str = password_str; - call->username_str = username_str; - - // Unpack the callback - Nan::Callback *callback = new Nan::Callback(callbackHandle); - - // Let's allocate some space - Worker *worker = new Worker(); - worker->error = false; - worker->request.data = worker; - worker->callback = callback; - worker->parameters = call; - worker->execute = _authSSPIAquire; - worker->mapper = _map_authSSPIAquire; - - // Schedule the worker with lib_uv - uv_queue_work(uv_default_loop(), &worker->request, SecurityCredentials::Process, (uv_after_work_cb)SecurityCredentials::After); - - // Return no value as it's callback based - info.GetReturnValue().Set(Nan::Undefined()); -} - -void SecurityCredentials::Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Define a new function template - Local t = Nan::New(New); - t->InstanceTemplate()->SetInternalFieldCount(1); - t->SetClassName(Nan::New("SecurityCredentials").ToLocalChecked()); - - // Class methods - Nan::SetMethod(t, "aquire", Aquire); - - // Set persistent - constructor_template.Reset(t); - - // Set the symbol - target->ForceSet(Nan::New("SecurityCredentials").ToLocalChecked(), t->GetFunction()); - - // Attempt to load the security.dll library - load_library(); -} - -static LPSTR DisplaySECError(DWORD ErrCode) { - LPSTR pszName = NULL; // WinError.h - - switch(ErrCode) { - case SEC_E_BUFFER_TOO_SMALL: - pszName = "SEC_E_BUFFER_TOO_SMALL - The message buffer is too small. Used with the Digest SSP."; - break; - - case SEC_E_CRYPTO_SYSTEM_INVALID: - pszName = "SEC_E_CRYPTO_SYSTEM_INVALID - The cipher chosen for the security context is not supported. Used with the Digest SSP."; - break; - case SEC_E_INCOMPLETE_MESSAGE: - pszName = "SEC_E_INCOMPLETE_MESSAGE - The data in the input buffer is incomplete. The application needs to read more data from the server and call DecryptMessage (General) again."; - break; - - case SEC_E_INVALID_HANDLE: - pszName = "SEC_E_INVALID_HANDLE - A context handle that is not valid was specified in the phContext parameter. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_INVALID_TOKEN: - pszName = "SEC_E_INVALID_TOKEN - The buffers are of the wrong type or no buffer of type SECBUFFER_DATA was found. Used with the Schannel SSP."; - break; - - case SEC_E_MESSAGE_ALTERED: - pszName = "SEC_E_MESSAGE_ALTERED - The message has been altered. Used with the Digest and Schannel SSPs."; - break; - - case SEC_E_OUT_OF_SEQUENCE: - pszName = "SEC_E_OUT_OF_SEQUENCE - The message was not received in the correct sequence."; - break; - - case SEC_E_QOP_NOT_SUPPORTED: - pszName = "SEC_E_QOP_NOT_SUPPORTED - Neither confidentiality nor integrity are supported by the security context. Used with the Digest SSP."; - break; - - case SEC_I_CONTEXT_EXPIRED: - pszName = "SEC_I_CONTEXT_EXPIRED - The message sender has finished using the connection and has initiated a shutdown."; - break; - - case SEC_I_RENEGOTIATE: - pszName = "SEC_I_RENEGOTIATE - The remote party requires a new handshake sequence or the application has just initiated a shutdown."; - break; - - case SEC_E_ENCRYPT_FAILURE: - pszName = "SEC_E_ENCRYPT_FAILURE - The specified data could not be encrypted."; - break; - - case SEC_E_DECRYPT_FAILURE: - pszName = "SEC_E_DECRYPT_FAILURE - The specified data could not be decrypted."; - break; - case -1: - pszName = "Failed to load security.dll library"; - break; - - } - - return pszName; -} - -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -// UV Lib callbacks -// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -void SecurityCredentials::Process(uv_work_t* work_req) { - // Grab the worker - Worker *worker = static_cast(work_req->data); - // Execute the worker code - worker->execute(worker); -} - -void SecurityCredentials::After(uv_work_t* work_req) { - // Grab the scope of the call from Node - Nan::HandleScope scope; - - // Get the worker reference - Worker *worker = static_cast(work_req->data); - - // If we have an error - if(worker->error) { - Local err = v8::Exception::Error(Nan::New(worker->error_message).ToLocalChecked()); - Local obj = err->ToObject(); - obj->Set(Nan::New("code").ToLocalChecked(), Nan::New(worker->error_code)); - Local info[2] = { err, Nan::Null() }; - // Execute the error - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } else { - SecurityCredentials *return_value = (SecurityCredentials *)worker->return_value; - // Create a new instance - Local result = Nan::New(constructor_template)->GetFunction()->NewInstance(); - // Unwrap the credentials - SecurityCredentials *security_credentials = Nan::ObjectWrap::Unwrap(result); - // Set the values - security_credentials->m_Identity = return_value->m_Identity; - security_credentials->m_Credentials = return_value->m_Credentials; - security_credentials->Expiration = return_value->Expiration; - // Set up the callback with a null first - Local info[2] = { Nan::Null(), result}; - // Wrap the callback function call in a TryCatch so that we can call - // node's FatalException afterwards. This makes it possible to catch - // the exception from JavaScript land using the - // process.on('uncaughtException') event. - Nan::TryCatch try_catch; - - // Call the callback - worker->callback->Call(ARRAY_SIZE(info), info); - - // If we have an exception handle it as a fatalexception - if (try_catch.HasCaught()) { - Nan::FatalException(try_catch); - } - } - - // Clean up the memory - delete worker->callback; - delete worker; -} - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h deleted file mode 100644 index 71751a0..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef SECURITY_CREDENTIALS_H -#define SECURITY_CREDENTIALS_H - -#include -#include -#include - -#define SECURITY_WIN32 1 - -#include -#include -#include -#include -#include -#include "../worker.h" -#include - -extern "C" { - #include "../kerberos_sspi.h" -} - -// SEC_WINNT_AUTH_IDENTITY makes it unusually hard -// to compile for both Unicode and ansi, so I use this macro: -#ifdef _UNICODE -#define USTR(str) (str) -#else -#define USTR(str) ((unsigned char*)(str)) -#endif - -using namespace v8; -using namespace node; - -class SecurityCredentials : public Nan::ObjectWrap { - public: - SecurityCredentials(); - ~SecurityCredentials(); - - // Pointer to context object - SEC_WINNT_AUTH_IDENTITY m_Identity; - // credentials - CredHandle m_Credentials; - // Expiry time for ticket - TimeStamp Expiration; - - // Has instance check - static inline bool HasInstance(Local val) { - if (!val->IsObject()) return false; - Local obj = val->ToObject(); - return Nan::New(constructor_template)->HasInstance(obj); - }; - - // Functions available from V8 - static void Initialize(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target); - static NAN_METHOD(Aquire); - - // Constructor used for creating new Long objects from C++ - static Nan::Persistent constructor_template; - - private: - // Create a new instance - static NAN_METHOD(New); - // Handles the uv calls - static void Process(uv_work_t* work_req); - // Called after work is done - static void After(uv_work_t* work_req); -}; - -#endif \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js deleted file mode 100644 index 4215c92..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers/security_credentials.js +++ /dev/null @@ -1,22 +0,0 @@ -var SecurityCredentialsNative = require('../../../build/Release/kerberos').SecurityCredentials; - -// Add simple kebros helper -SecurityCredentialsNative.aquire_kerberos = function(username, password, domain, callback) { - if(typeof password == 'function') { - callback = password; - password = null; - } else if(typeof domain == 'function') { - callback = domain; - domain = null; - } - - // We are going to use the async version - if(typeof callback == 'function') { - return SecurityCredentialsNative.aquire('Kerberos', username, password, domain, callback); - } else { - return SecurityCredentialsNative.aquireSync('Kerberos', username, password, domain); - } -} - -// Export the modified class -exports.SecurityCredentials = SecurityCredentialsNative; \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc deleted file mode 100644 index e7a472f..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.cc +++ /dev/null @@ -1,7 +0,0 @@ -#include "worker.h" - -Worker::Worker() { -} - -Worker::~Worker() { -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h deleted file mode 100644 index 1b0dced..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/worker.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef WORKER_H_ -#define WORKER_H_ - -#include -#include -#include -#include - -using namespace node; -using namespace v8; - -class Worker { - public: - Worker(); - virtual ~Worker(); - - // libuv's request struct. - uv_work_t request; - // Callback - Nan::Callback *callback; - // Parameters - void *parameters; - // Results - void *return_value; - // Did we raise an error - bool error; - // The error message - char *error_message; - // Error code if not message - int error_code; - // Any return code - int return_code; - // Method we are going to fire - void (*execute)(Worker *worker); - Local (*mapper)(Worker *worker); -}; - -#endif // WORKER_H_ diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc deleted file mode 100644 index 47971da..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/.dntrc +++ /dev/null @@ -1,30 +0,0 @@ -## DNT config file -## see https://github.com/rvagg/dnt - -NODE_VERSIONS="\ - master \ - v0.11.13 \ - v0.10.30 \ - v0.10.29 \ - v0.10.28 \ - v0.10.26 \ - v0.10.25 \ - v0.10.24 \ - v0.10.23 \ - v0.10.22 \ - v0.10.21 \ - v0.10.20 \ - v0.10.19 \ - v0.8.28 \ - v0.8.27 \ - v0.8.26 \ - v0.8.24 \ -" -OUTPUT_PREFIX="nan-" -TEST_CMD=" \ - cd /dnt/ && \ - npm install && \ - node_modules/.bin/node-gyp --nodedir /usr/src/node/ rebuild --directory test && \ - node_modules/.bin/tap --gc test/js/*-test.js \ -" - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md deleted file mode 100644 index 457e7c4..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/CHANGELOG.md +++ /dev/null @@ -1,374 +0,0 @@ -# NAN ChangeLog - -**Version 2.0.9: current Node 4.0.0, Node 12: 0.12.7, Node 10: 0.10.40, iojs: 3.2.0** - -### 2.0.9 Sep 8 2015 - - - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7 - -### 2.0.8 Aug 28 2015 - - - Work around duplicate linking bug in clang 11902da - -### 2.0.7 Aug 26 2015 - - - Build: Repackage - -### 2.0.6 Aug 26 2015 - - - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1 - - Bugfix: Remove unused static std::map instances 525bddc - - Bugfix: Make better use of maybe versions of APIs bfba85b - - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d - -### 2.0.5 Aug 10 2015 - - - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1 - - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d - -### 2.0.4 Aug 6 2015 - - - Build: Repackage - -### 2.0.3 Aug 6 2015 - - - Bugfix: Don't use clang++ / g++ syntax extension. 231450e - -### 2.0.2 Aug 6 2015 - - - Build: Repackage - -### 2.0.1 Aug 6 2015 - - - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687 - - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601 - - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f - - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed - -### 2.0.0 Jul 31 2015 - - - Change: Renamed identifiers with leading underscores b5932b4 - - Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1 - - Change: Replace NanScope and NanEscpableScope macros with classes 47751c4 - - Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99 - - Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5 - - Change: Rename NanNewBuffer to NanCopyBuffer d6af78d - - Change: Remove Nan prefix from all names 72d1f67 - - Change: Update Buffer API for new upstream changes d5d3291 - - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a - - Change: Get rid of Handles e6c0daf - - Feature: Support io.js 3 with V8 4.4 - - Feature: Introduce NanPersistent 7fed696 - - Feature: Introduce NanGlobal 4408da1 - - Feature: Added NanTryCatch 10f1ca4 - - Feature: Update for V8 v4.3 4b6404a - - Feature: Introduce NanNewOneByteString c543d32 - - Feature: Introduce namespace Nan 67ed1b1 - - Removal: Remove NanLocker and NanUnlocker dd6e401 - - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9 - - Removal: Remove NanReturn* macros d90a25c - - Removal: Remove HasInstance e8f84fe - - -### 1.9.0 Jul 31 2015 - - - Feature: Added `NanFatalException` 81d4a2c - - Feature: Added more error types 4265f06 - - Feature: Added dereference and function call operators to NanCallback c4b2ed0 - - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c - - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6 - - Feature: Added NanErrnoException dd87d9e - - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130 - - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c - - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b - -### 1.8.4 Apr 26 2015 - - - Build: Repackage - -### 1.8.3 Apr 26 2015 - - - Bugfix: Include missing header 1af8648 - -### 1.8.2 Apr 23 2015 - - - Build: Repackage - -### 1.8.1 Apr 23 2015 - - - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 - -### 1.8.0 Apr 23 2015 - - - Feature: Allow primitives with NanReturnValue 2e4475e - - Feature: Added comparison operators to NanCallback 55b075e - - Feature: Backport thread local storage 15bb7fa - - Removal: Remove support for signatures with arguments 8a2069d - - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 - -### 1.7.0 Feb 28 2015 - - - Feature: Made NanCallback::Call accept optional target 8d54da7 - - Feature: Support atom-shell 0.21 0b7f1bb - -### 1.6.2 Feb 6 2015 - - - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 - -### 1.6.1 Jan 23 2015 - - - Build: version bump - -### 1.5.3 Jan 23 2015 - - - Build: repackage - -### 1.6.0 Jan 23 2015 - - - Deprecated `NanNewContextHandle` in favor of `NanNew` 49259af - - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 - - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 - -### 1.5.2 Jan 23 2015 - - - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 - - Bugfix: Readded missing String constructors 18d828f - - Bugfix: Add overload handling NanNew(..) 5ef813b - - Bugfix: Fix uv_work_cb versioning 997e4ae - - Bugfix: Add function factory and test 4eca89c - - Bugfix: Add object template factory and test cdcb951 - - Correctness: Lifted an io.js related typedef c9490be - - Correctness: Make explicit downcasts of String lengths 00074e6 - - Windows: Limit the scope of disabled warning C4530 83d7deb - -### 1.5.1 Jan 15 2015 - - - Build: version bump - -### 1.4.3 Jan 15 2015 - - - Build: version bump - -### 1.4.2 Jan 15 2015 - - - Feature: Support io.js 0dbc5e8 - -### 1.5.0 Jan 14 2015 - - - Feature: Support io.js b003843 - - Correctness: Improved NanNew internals 9cd4f6a - - Feature: Implement progress to NanAsyncWorker 8d6a160 - -### 1.4.1 Nov 8 2014 - - - Bugfix: Handle DEBUG definition correctly - - Bugfix: Accept int as Boolean - -### 1.4.0 Nov 1 2014 - - - Feature: Added NAN_GC_CALLBACK 6a5c245 - - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 - - Correctness: Added constness to references in NanHasInstance 02c61cd - - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 - - Windoze: Shut Visual Studio up when compiling 8d558c1 - - License: Switch to plain MIT from custom hacked MIT license 11de983 - - Build: Added test target to Makefile e232e46 - - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 - - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 - - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 - -### 1.3.0 Aug 2 2014 - - - Added NanNew(std::string) - - Added NanNew(std::string&) - - Added NanAsciiString helper class - - Added NanUtf8String helper class - - Added NanUcs2String helper class - - Deprecated NanRawString() - - Deprecated NanCString() - - Added NanGetIsolateData(v8::Isolate *isolate) - - Added NanMakeCallback(v8::Handle target, v8::Handle func, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, v8::Handle symbol, int argc, v8::Handle* argv) - - Added NanMakeCallback(v8::Handle target, const char* method, int argc, v8::Handle* argv) - - Added NanSetTemplate(v8::Handle templ, v8::Handle name , v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetPrototypeTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - - Added NanSetInstanceTemplate(v8::Local templ, const char *name, v8::Handle value) - - Added NanSetInstanceTemplate(v8::Local templ, v8::Handle name, v8::Handle value, v8::PropertyAttribute attributes) - -### 1.2.0 Jun 5 2014 - - - Add NanSetPrototypeTemplate - - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, - introduced _NanWeakCallbackDispatcher - - Removed -Wno-unused-local-typedefs from test builds - - Made test builds Windows compatible ('Sleep()') - -### 1.1.2 May 28 2014 - - - Release to fix more stuff-ups in 1.1.1 - -### 1.1.1 May 28 2014 - - - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 - -### 1.1.0 May 25 2014 - - - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead - - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), - (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, - v8::String::ExternalAsciiStringResource* - - Deprecate NanSymbol() - - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker - -### 1.0.0 May 4 2014 - - - Heavy API changes for V8 3.25 / Node 0.11.13 - - Use cpplint.py - - Removed NanInitPersistent - - Removed NanPersistentToLocal - - Removed NanFromV8String - - Removed NanMakeWeak - - Removed NanNewLocal - - Removed NAN_WEAK_CALLBACK_OBJECT - - Removed NAN_WEAK_CALLBACK_DATA - - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions - - Introduce NanUndefined, NanNull, NanTrue and NanFalse - - Introduce NanEscapableScope and NanEscapeScope - - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) - - Introduce NanMakeCallback for node::MakeCallback - - Introduce NanSetTemplate - - Introduce NanGetCurrentContext - - Introduce NanCompileScript and NanRunScript - - Introduce NanAdjustExternalMemory - - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback - - Introduce NanGetHeapStatistics - - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() - -### 0.8.0 Jan 9 2014 - - - NanDispose -> NanDisposePersistent, deprecate NanDispose - - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() - -### 0.7.1 Jan 9 2014 - - - Fixes to work against debug builds of Node - - Safer NanPersistentToLocal (avoid reinterpret_cast) - - Speed up common NanRawString case by only extracting flattened string when necessary - -### 0.7.0 Dec 17 2013 - - - New no-arg form of NanCallback() constructor. - - NanCallback#Call takes Handle rather than Local - - Removed deprecated NanCallback#Run method, use NanCallback#Call instead - - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS - - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() - - Introduce NanRawString() for char* (or appropriate void*) from v8::String - (replacement for NanFromV8String) - - Introduce NanCString() for null-terminated char* from v8::String - -### 0.6.0 Nov 21 2013 - - - Introduce NanNewLocal(v8::Handle value) for use in place of - v8::Local::New(...) since v8 started requiring isolate in Node 0.11.9 - -### 0.5.2 Nov 16 2013 - - - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public - -### 0.5.1 Nov 12 2013 - - - Use node::MakeCallback() instead of direct v8::Function::Call() - -### 0.5.0 Nov 11 2013 - - - Added @TooTallNate as collaborator - - New, much simpler, "include_dirs" for binding.gyp - - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros - -### 0.4.4 Nov 2 2013 - - - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ - -### 0.4.3 Nov 2 2013 - - - Include node_object_wrap.h, removed from node.h for Node 0.11.8. - -### 0.4.2 Nov 2 2013 - - - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for - Node 0.11.8 release. - -### 0.4.1 Sep 16 2013 - - - Added explicit `#include ` as it was removed from node.h for v0.11.8 - -### 0.4.0 Sep 2 2013 - - - Added NAN_INLINE and NAN_DEPRECATED and made use of them - - Added NanError, NanTypeError and NanRangeError - - Cleaned up code - -### 0.3.2 Aug 30 2013 - - - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent - in NanAsyncWorker - -### 0.3.1 Aug 20 2013 - - - fix "not all control paths return a value" compile warning on some platforms - -### 0.3.0 Aug 19 2013 - - - Made NAN work with NPM - - Lots of fixes to NanFromV8String, pulling in features from new Node core - - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API - - Added optional error number argument for NanThrowError() - - Added NanInitPersistent() - - Added NanReturnNull() and NanReturnEmptyString() - - Added NanLocker and NanUnlocker - - Added missing scopes - - Made sure to clear disposed Persistent handles - - Changed NanAsyncWorker to allocate error messages on the heap - - Changed NanThrowError(Local) to NanThrowError(Handle) - - Fixed leak in NanAsyncWorker when errmsg is used - -### 0.2.2 Aug 5 2013 - - - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() - -### 0.2.1 Aug 5 2013 - - - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for - NanFromV8String() - -### 0.2.0 Aug 5 2013 - - - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, - NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY - - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, - _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, - _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, - _NAN_PROPERTY_QUERY_ARGS - - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer - - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, - NAN_WEAK_CALLBACK_DATA, NanMakeWeak - - Renamed THROW_ERROR to _NAN_THROW_ERROR - - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) - - Added NanBufferUse(char*, uint32_t) - - Added NanNewContextHandle(v8::ExtensionConfiguration*, - v8::Handle, v8::Handle) - - Fixed broken NanCallback#GetFunction() - - Added optional encoding and size arguments to NanFromV8String() - - Added NanGetPointerSafe() and NanSetPointerSafe() - - Added initial test suite (to be expanded) - - Allow NanUInt32OptionValue to convert any Number object - -### 0.1.0 Jul 21 2013 - - - Added `NAN_GETTER`, `NAN_SETTER` - - Added `NanThrowError` with single Local argument - - Added `NanNewBufferHandle` with single uint32_t argument - - Added `NanHasInstance(Persistent&, Handle)` - - Added `Local NanCallback#GetFunction()` - - Added `NanCallback#Call(int, Local[])` - - Deprecated `NanCallback#Run(int, Local[])` in favour of Call diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md deleted file mode 100644 index 77666cd..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -The MIT License (MIT) -===================== - -Copyright (c) 2015 NAN contributors ------------------------------------ - -*NAN contributors listed at * - -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/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md deleted file mode 100644 index db3daec..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/README.md +++ /dev/null @@ -1,367 +0,0 @@ -Native Abstractions for Node.js -=============================== - -**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10 and 0.12 as well as io.js.** - -***Current version: 2.0.9*** - -*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* - -[![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) - -[![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](http://travis-ci.org/nodejs/nan) -[![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) - -Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. - -This project also contains some helper utilities that make addon development a bit more pleasant. - - * **[News & Updates](#news)** - * **[Usage](#usage)** - * **[Example](#example)** - * **[API](#api)** - * **[Tests](#tests)** - * **[Governance & Contributing](#governance)** - - -## News & Updates - - -## Usage - -Simply add **NAN** as a dependency in the *package.json* of your Node addon: - -``` bash -$ npm install --save nan -``` - -Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: - -``` python -"include_dirs" : [ - "` when compiling your addon. - - -## Example - -Just getting started with Nan? Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. - -For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. - -For another example, see **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. - - -## API - -Additional to the NAN documentation below, please consult: - -* [The V8 Getting Started Guide](https://developers.google.com/v8/get_started) -* [The V8 Embedders Guide](https://developers.google.com/v8/embed) -* [V8 API Documentation](http://v8docs.nodesource.com/) - - - -### JavaScript-accessible methods - -A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://developers.google.com/v8/embed#templates) for further information. - -In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. - -* **Method argument types** - - Nan::FunctionCallbackInfo - - Nan::PropertyCallbackInfo - - Nan::ReturnValue -* **Method declarations** - - Method declaration - - Getter declaration - - Setter declaration - - Property getter declaration - - Property setter declaration - - Property enumerator declaration - - Property deleter declaration - - Property query declaration - - Index getter declaration - - Index setter declaration - - Index enumerator declaration - - Index deleter declaration - - Index query declaration -* Method and template helpers - - Nan::SetMethod() - - Nan::SetNamedPropertyHandler() - - Nan::SetIndexedPropertyHandler() - - Nan::SetPrototypeMethod() - - Nan::SetTemplate() - - Nan::SetPrototypeTemplate() - - Nan::SetInstanceTemplate() - -### Scopes - -A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. - -A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. - -The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. - - - Nan::HandleScope - - Nan::EscapableHandleScope - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). - -### Persistent references - -An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. - -Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. - - - Nan::PersistentBase & v8::PersistentBase - - Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits - - Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits - - Nan::Persistent - - Nan::Global - - Nan::WeakCallbackInfo - - Nan::WeakCallbackType - -Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). - -### New - -NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. - - - Nan::New() - - Nan::Undefined() - - Nan::Null() - - Nan::True() - - Nan::False() - - Nan::EmptyString() - - -### Converters - -NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. - - - Nan::To() - -### Maybe Types - -The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. - -* **Maybe Types** - - Nan::MaybeLocal - - Nan::Maybe - - Nan::Nothing - - Nan::Just -* **Maybe Helpers** - - Nan::ToDetailString() - - Nan::ToArrayIndex() - - Nan::Equals() - - Nan::NewInstance() - - Nan::GetFunction() - - Nan::Set() - - Nan::ForceSet() - - Nan::Get() - - Nan::GetPropertyAttributes() - - Nan::Has() - - Nan::Delete() - - Nan::GetPropertyNames() - - Nan::GetOwnPropertyNames() - - Nan::SetPrototype() - - Nan::ObjectProtoToString() - - Nan::HasOwnProperty() - - Nan::HasRealNamedProperty() - - Nan::HasRealIndexedProperty() - - Nan::HasRealNamedCallbackProperty() - - Nan::GetRealNamedPropertyInPrototypeChain() - - Nan::GetRealNamedProperty() - - Nan::CallAsFunction() - - Nan::CallAsConstructor() - - Nan::GetSourceLine() - - Nan::GetLineNumber() - - Nan::GetStartColumn() - - Nan::GetEndColumn() - - Nan::CloneElementAt() - -### Script - -NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. - - - Nan::CompileScript() - - Nan::RunScript() - - -### Errors - -NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. - -Note that an Error object is simply a specialized form of `v8::Value`. - -Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. - - - Nan::Error() - - Nan::RangeError() - - Nan::ReferenceError() - - Nan::SyntaxError() - - Nan::TypeError() - - Nan::ThrowError() - - Nan::ThrowRangeError() - - Nan::ThrowReferenceError() - - Nan::ThrowSyntaxError() - - Nan::ThrowTypeError() - - Nan::FatalException() - - Nan::ErrnoException() - - Nan::TryCatch - - -### Buffers - -NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. - - - Nan::NewBuffer() - - Nan::CopyBuffer() - - Nan::FreeCallback() - -### Nan::Callback - -`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. - - - Nan::Callback - -### Asynchronous work helpers - -`Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier. - - - Nan::AsyncWorker - - Nan::AsyncProgressWorker - - Nan::AsyncQueueWorker - -### Strings & Bytes - -Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. - - - Nan::Encoding - - Nan::Encode() - - Nan::DecodeBytes() - - Nan::DecodeWrite() - - -### V8 internals - -The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. - - - NAN_GC_CALLBACK() - - Nan::AddGCEpilogueCallback() - - Nan::RemoveGCEpilogueCallback() - - Nan::AddGCPrologueCallback() - - Nan::RemoveGCPrologueCallback() - - Nan::GetHeapStatistics() - - Nan::SetCounterFunction() - - Nan::SetCreateHistogramFunction() - - Nan::SetAddHistogramSampleFunction() - - Nan::IdleNotification() - - Nan::LowMemoryNotification() - - Nan::ContextDisposedNotification() - - Nan::GetInternalFieldPointer() - - Nan::SetInternalFieldPointer() - - Nan::AdjustExternalMemory() - - -### Miscellaneous V8 Helpers - - - Nan::Utf8String - - Nan::GetCurrentContext() - - Nan::SetIsolateData() - - Nan::GetIsolateData() - - -### Miscellaneous Node Helpers - - - Nan::MakeCallback() - - Nan::ObjectWrap - - NAN_MODULE_INIT() - - Nan::Export() - - - - - -### Tests - -To run the NAN tests do: - -``` sh -npm install -npm run-script rebuild-tests -npm test -``` - -Or just: - -``` sh -npm install -make test -``` - - -## Governance & Contributing - -NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group - -### Addon API Working Group (WG) - -The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. - -Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects. - -The WG has final authority over this project including: - -* Technical direction -* Project governance and process (including this policy) -* Contribution policy -* GitHub repository hosting -* Maintaining the list of additional Collaborators - -For the current list of WG members, see the project [README.md](./README.md#collaborators). - -Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. - -_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. - -For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). - -### Consensus Seeking Process - -The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. - -Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. - -If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. - -### Developer's Certificate of Origin 1.0 - -By making a contribution to this project, I certify that: - -* (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or -* (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or -* (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. - - -### WG Members / Collaborators - - - - - - - - - -
          Rod VaggGitHub/rvaggTwitter/@rvagg
          Benjamin ByholmGitHub/kkoopa-
          Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
          Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
          Brett LawsonGitHub/brett19Twitter/@brett19x
          Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
          David SiegelGitHub/agnat-
          - -## Licence & copyright - -Copyright (c) 2015 NAN WG Members / Collaborators (listed above). - -Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml deleted file mode 100644 index 1378d31..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/appveyor.yml +++ /dev/null @@ -1,38 +0,0 @@ -# http://www.appveyor.com/docs/appveyor-yml - -# Test against these versions of Io.js and Node.js. -environment: - matrix: - # node.js - - nodejs_version: "0.8" - - nodejs_version: "0.10" - - nodejs_version: "0.12" - # io.js - - nodejs_version: "1" - - nodejs_version: "2" - - nodejs_version: "3" - -# Install scripts. (runs after repo cloning) -install: - # Get the latest stable version of Node 0.STABLE.latest - - ps: if($env:nodejs_version -eq "0.8") {Install-Product node $env:nodejs_version} - - ps: if($env:nodejs_version -ne "0.8") {Update-NodeJsInstallation (Get-NodeJsLatestBuild $env:nodejs_version)} - - IF %nodejs_version% LSS 1 npm -g install npm - - IF %nodejs_version% LSS 1 set PATH=%APPDATA%\npm;%PATH% - # Typical npm stuff. - - npm install - - IF %nodejs_version% EQU 0.8 (node node_modules\node-gyp\bin\node-gyp.js rebuild --msvs_version=2013 --directory test) ELSE (npm run rebuild-tests) - -# Post-install test scripts. -test_script: - # Output useful info for debugging. - - node --version - - npm --version - # run tests - - IF %nodejs_version% LSS 1 (npm test) ELSE (iojs node_modules\tap\bin\tap.js --gc test/js/*-test.js) - -# Don't actually build. -build: off - -# Set build version format here instead of in the admin panel. -version: "{build}" diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh deleted file mode 100755 index 75a975a..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/doc/.build.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash - -files=" \ - methods.md \ - scopes.md \ - persistent.md \ - new.md \ - converters.md \ - maybe_types.md \ - script.md \ - errors.md \ - buffers.md \ - callback.md \ - asyncworker.md \ - string_bytes.md \ - v8_internals.md \ - v8_misc.md \ - node_misc.md \ -" - -__dirname=$(dirname "${BASH_SOURCE[0]}") -head=$(perl -e 'while (<>) { if (!$en){print;} if ($_=~/ NanNew("foo").ToLocalChecked() */ - if (arguments[groups[3][0]] === 'NanNew') { - return [arguments[0], '.ToLocalChecked()'].join(''); - } - - /* insert warning for removed functions as comment on new line above */ - switch (arguments[groups[4][0]]) { - case 'GetIndexedPropertiesExternalArrayData': - case 'GetIndexedPropertiesExternalArrayDataLength': - case 'GetIndexedPropertiesExternalArrayDataType': - case 'GetIndexedPropertiesPixelData': - case 'GetIndexedPropertiesPixelDataLength': - case 'HasIndexedPropertiesInExternalArrayData': - case 'HasIndexedPropertiesInPixelData': - case 'SetIndexedPropertiesToExternalArrayData': - case 'SetIndexedPropertiesToPixelData': - return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join(''); - default: - } - - /* remove unnecessary NanScope() */ - switch (arguments[groups[5][0]]) { - case 'NAN_GETTER': - case 'NAN_METHOD': - case 'NAN_SETTER': - case 'NAN_INDEX_DELETER': - case 'NAN_INDEX_ENUMERATOR': - case 'NAN_INDEX_GETTER': - case 'NAN_INDEX_QUERY': - case 'NAN_INDEX_SETTER': - case 'NAN_PROPERTY_DELETER': - case 'NAN_PROPERTY_ENUMERATOR': - case 'NAN_PROPERTY_GETTER': - case 'NAN_PROPERTY_QUERY': - case 'NAN_PROPERTY_SETTER': - return arguments[groups[5][0] - 1]; - default: - } - - /* Value converstion */ - switch (arguments[groups[6][0]]) { - case 'Boolean': - case 'Int32': - case 'Integer': - case 'Number': - case 'Object': - case 'String': - case 'Uint32': - return [arguments[groups[6][0] - 2], 'NanTo(', arguments[groups[6][0] - 1]].join(''); - default: - } - - /* other value conversion */ - switch (arguments[groups[7][0]]) { - case 'BooleanValue': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'Int32Value': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'IntegerValue': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - case 'Uint32Value': - return [arguments[groups[7][0] - 2], 'NanTo(', arguments[groups[7][0] - 1]].join(''); - default: - } - - /* NAN_WEAK_CALLBACK */ - if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') { - return ['template\nvoid ', - arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo &data)'].join(''); - } - - /* use methods on NAN classes instead */ - switch (arguments[groups[9][0]]) { - case 'NanDisposePersistent': - return [arguments[groups[9][0] + 1], '.Reset('].join(''); - case 'NanObjectWrapHandle': - return [arguments[groups[9][0] + 1], '->handle('].join(''); - default: - } - - /* use method on NanPersistent instead */ - if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') { - return arguments[groups[10][0] + 1] + '.SetWeak('; - } - - /* These return Maybes, the upper ones take no arguments */ - switch (arguments[groups[11][0]]) { - case 'GetEndColumn': - case 'GetFunction': - case 'GetLineNumber': - case 'GetOwnPropertyNames': - case 'GetPropertyNames': - case 'GetSourceLine': - case 'GetStartColumn': - case 'NewInstance': - case 'ObjectProtoToString': - case 'ToArrayIndex': - case 'ToDetailString': - return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join(''); - case 'CallAsConstructor': - case 'CallAsFunction': - case 'CloneElementAt': - case 'Delete': - case 'ForceSet': - case 'Get': - case 'GetPropertyAttributes': - case 'GetRealNamedProperty': - case 'GetRealNamedPropertyInPrototypeChain': - case 'Has': - case 'HasOwnProperty': - case 'HasRealIndexedProperty': - case 'HasRealNamedCallbackProperty': - case 'HasRealNamedProperty': - case 'Set': - case 'SetAccessor': - case 'SetIndexedPropertyHandler': - case 'SetNamedPropertyHandler': - case 'SetPrototype': - return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join(''); - default: - } - - /* Automatic ToLocalChecked(), take it or leave it */ - switch (arguments[groups[12][0]]) { - case 'Date': - case 'String': - case 'RegExp': - return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join(''); - default: - } - - /* NanEquals is now required for uniformity */ - if (arguments[groups[13][0]] === 'Equals') { - return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join(''); - } - - /* use method on replacement class instead */ - if (arguments[groups[14][0]] === 'NanAssignPersistent') { - return [arguments[groups[14][0] + 1], '.Reset('].join(''); - } - - /* args --> info */ - if (arguments[groups[15][0]] === 'args') { - return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join(''); - } - - /* ObjectWrap --> NanObjectWrap */ - if (arguments[groups[16][0]] === 'ObjectWrap') { - return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join(''); - } - - /* Persistent --> NanPersistent */ - if (arguments[groups[17][0]] === 'Persistent') { - return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join(''); - } - - /* This should not happen. A switch is probably missing a case if it does. */ - throw 'Unhandled match: ' + arguments[0]; -} - -/* reads a file, runs replacement and writes it back */ -function processFile(file) { - fs.readFile(file, {encoding: 'utf8'}, function (err, data) { - if (err) { - throw err; - } - - /* run replacement twice, might need more runs */ - fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) { - if (err) { - throw err; - } - }); - }); -} - -/* process file names from command line and process the identified files */ -for (i = 2, length = process.argv.length; i < length; i++) { - glob(process.argv[i], function (err, matches) { - if (err) { - throw err; - } - matches.forEach(processFile); - }); -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md deleted file mode 100644 index 7f07e4b..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/README.md +++ /dev/null @@ -1,14 +0,0 @@ -1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, -false positives and missed opportunities. The input files are rewritten in place. Make sure that -you have backups. You will have to manually review the changes afterwards and do some touchups. - -```sh -$ tools/1to2.js - - Usage: 1to2 [options] - - Options: - - -h, --help output usage information - -V, --version output the version number -``` diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json deleted file mode 100644 index 2dcdd78..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/node_modules/nan/tools/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "1to2", - "version": "1.0.0", - "description": "NAN 1 -> 2 Migration Script", - "main": "1to2.js", - "repository": { - "type": "git", - "url": "git://github.com/nodejs/nan.git" - }, - "contributors": [ - "Benjamin Byholm (https://github.com/kkoopa/)", - "Mathias Küsel (https://github.com/mathiask88/)" - ], - "dependencies": { - "glob": "~5.0.10", - "commander": "~2.8.1" - }, - "license": "MIT" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json deleted file mode 100644 index 9955d1f..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/package.json +++ /dev/null @@ -1,55 +0,0 @@ -{ - "name": "kerberos", - "version": "0.0.15", - "description": "Kerberos library for Node.js", - "main": "index.js", - "repository": { - "type": "git", - "url": "https://github.com/christkv/kerberos.git" - }, - "keywords": [ - "kerberos", - "security", - "authentication" - ], - "dependencies": { - "nan": "~2.0" - }, - "devDependencies": { - "nodeunit": "latest" - }, - "scripts": { - "install": "(node-gyp rebuild) || (exit 0)", - "test": "nodeunit ./test" - }, - "author": { - "name": "Christian Amor Kvalheim" - }, - "license": "Apache 2.0", - "gitHead": "035be2e4619d7f3d7ea5103da1f60a6045ef8d7c", - "bugs": { - "url": "https://github.com/christkv/kerberos/issues" - }, - "homepage": "https://github.com/christkv/kerberos", - "_id": "kerberos@0.0.15", - "_shasum": "c7dd5a2d311ce79c308c2670a9187d9bf745ed52", - "_from": "kerberos@>=0.0.0 <0.1.0", - "_npmVersion": "2.14.4", - "_nodeVersion": "4.1.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "c7dd5a2d311ce79c308c2670a9187d9bf745ed52", - "tarball": "http://registry.npmjs.org/kerberos/-/kerberos-0.0.15.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/kerberos/-/kerberos-0.0.15.tgz" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js deleted file mode 100644 index a06c5fd..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_tests.js +++ /dev/null @@ -1,34 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Simple initialize of Kerberos object'] = function(test) { - var Kerberos = require('../lib/kerberos.js').Kerberos; - var kerberos = new Kerberos(); - // console.dir(kerberos) - - // Initiate kerberos client - kerberos.authGSSClientInit('mongodb@kdc.10gen.me', Kerberos.GSS_C_MUTUAL_FLAG, function(err, context) { - console.log("===================================== authGSSClientInit") - test.equal(null, err); - test.ok(context != null && typeof context == 'object'); - // console.log("===================================== authGSSClientInit") - console.dir(err) - console.dir(context) - // console.dir(typeof result) - - // Perform the first step - kerberos.authGSSClientStep(context, function(err, result) { - console.log("===================================== authGSSClientStep") - console.dir(err) - console.dir(result) - console.dir(context) - - test.done(); - }); - }); -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js deleted file mode 100644 index c8509db..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/kerberos_win32_test.js +++ /dev/null @@ -1,15 +0,0 @@ -if (/^win/.test(process.platform)) { - -exports['Simple initialize of Kerberos win32 object'] = function(test) { - var KerberosNative = require('../build/Release/kerberos').Kerberos; - // console.dir(KerberosNative) - var kerberos = new KerberosNative(); - console.log("=========================================== 0") - console.dir(kerberos.acquireAlternateCredentials("dev1@10GEN.ME", "a")); - console.log("=========================================== 1") - console.dir(kerberos.prepareOutboundPackage("mongodb/kdc.10gen.com")); - console.log("=========================================== 2") - test.done(); -} - -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js deleted file mode 100644 index 3531b6b..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_descriptor_tests.js +++ /dev/null @@ -1,41 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer Descriptor'] = function(test) { - var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // Create descriptor with single Buffer - var securityDescriptor = new SecurityBufferDescriptor(100); - try { - // Fail to work due to no valid Security Buffer - securityDescriptor = new SecurityBufferDescriptor(["hello"]); - test.ok(false); - } catch(err){} - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - // Should correctly return a buffer - var result = securityDescriptor.toBuffer(); - test.equal(100, result.length); - - // Should Correctly construct SecurityBuffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - securityDescriptor = new SecurityBufferDescriptor([buffer]); - var result = securityDescriptor.toBuffer(); - test.equal("hello world", result.toString()); - - // Test passing in more than one Buffer - var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - var result = securityDescriptor.toBuffer(); - test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js deleted file mode 100644 index b52b959..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_buffer_tests.js +++ /dev/null @@ -1,22 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a security Buffer'] = function(test) { - var SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - // Create empty buffer - var securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - var buffer = securityBuffer.toBuffer(); - test.equal(100, buffer.length); - - // Access data passed in - var allocated_buffer = new Buffer(256); - securityBuffer = new SecurityBuffer(SecurityBuffer.DATA, allocated_buffer); - buffer = securityBuffer.toBuffer(); - test.deepEqual(allocated_buffer, buffer); - test.done(); -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js deleted file mode 100644 index 7758180..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/test/win32/security_credentials_tests.js +++ /dev/null @@ -1,55 +0,0 @@ -exports.setUp = function(callback) { - callback(); -} - -exports.tearDown = function(callback) { - callback(); -} - -exports['Initialize a set of security credentials'] = function(test) { - var SecurityCredentials = require('../../lib/sspi.js').SecurityCredentials; - - // Aquire some credentials - try { - var credentials = SecurityCredentials.aquire('Kerberos', 'dev1@10GEN.ME', 'a'); - } catch(err) { - console.dir(err) - test.ok(false); - } - - - - // console.dir(SecurityCredentials); - - // var SecurityBufferDescriptor = require('../../lib/sspi.js').SecurityBufferDescriptor - // SecurityBuffer = require('../../lib/sspi.js').SecurityBuffer; - - // // Create descriptor with single Buffer - // var securityDescriptor = new SecurityBufferDescriptor(100); - // try { - // // Fail to work due to no valid Security Buffer - // securityDescriptor = new SecurityBufferDescriptor(["hello"]); - // test.ok(false); - // } catch(err){} - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, 100); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // // Should correctly return a buffer - // var result = securityDescriptor.toBuffer(); - // test.equal(100, result.length); - - // // Should Correctly construct SecurityBuffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // securityDescriptor = new SecurityBufferDescriptor([buffer]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello world", result.toString()); - - // // Test passing in more than one Buffer - // var buffer = new SecurityBuffer(SecurityBuffer.DATA, new Buffer("hello world")); - // var buffer2 = new SecurityBuffer(SecurityBuffer.STREAM, new Buffer("adam and eve")); - // securityDescriptor = new SecurityBufferDescriptor([buffer, buffer2]); - // var result = securityDescriptor.toBuffer(); - // test.equal("hello worldadam and eve", result.toString()); - test.done(); -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/package.json b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/package.json deleted file mode 100644 index f690f67..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "name": "mongodb-core", - "version": "1.2.14", - "description": "Core MongoDB driver functionality, no bells and whistles and meant for integration not end applications", - "main": "index.js", - "scripts": { - "test": "node test/runner.js -t functional" - }, - "repository": { - "type": "git", - "url": "git://github.com/christkv/mongodb-core.git" - }, - "keywords": [ - "mongodb", - "core" - ], - "dependencies": { - "bson": "~0.4", - "kerberos": "~0.0" - }, - "devDependencies": { - "integra": "0.1.8", - "optimist": "latest", - "jsdoc": "3.3.0-alpha8", - "semver": "4.1.0", - "gleak": "0.5.0", - "mongodb-tools": "~1.0", - "mkdirp": "0.5.0", - "rimraf": "2.2.6", - "mongodb-version-manager": "^0.7.1", - "co": "4.5.4" - }, - "optionalDependencies": { - "kerberos": "~0.0" - }, - "author": { - "name": "Christian Kvalheim" - }, - "license": "Apache 2.0", - "bugs": { - "url": "https://github.com/christkv/mongodb-core/issues" - }, - "homepage": "https://github.com/christkv/mongodb-core", - "gitHead": "ea4e6c9fe93e4ace4cbffb816d47ee282c1cd844", - "_id": "mongodb-core@1.2.14", - "_shasum": "0f1393778b71f1e2b86228fd160ec9ad5a8cd9a3", - "_from": "mongodb-core@1.2.14", - "_npmVersion": "2.14.4", - "_nodeVersion": "4.1.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "0f1393778b71f1e2b86228fd160ec9ad5a8cd9a3", - "tarball": "http://registry.npmjs.org/mongodb-core/-/mongodb-core-1.2.14.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-1.2.14.tgz" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat b/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat deleted file mode 100644 index 25ccf0b..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/mongodb-core/simple_2_document_limit_toArray.dat +++ /dev/null @@ -1,11000 +0,0 @@ -1 2 -2 1 -3 0 -4 0 -5 1 -6 0 -7 0 -8 0 -9 0 -10 1 -11 0 -12 0 -13 0 -14 1 -15 0 -16 0 -17 0 -18 1 -19 0 -20 0 -21 0 -22 1 -23 0 -24 0 -25 0 -26 0 -27 1 -28 0 -29 0 -30 0 -31 1 -32 0 -33 0 -34 0 -35 0 -36 0 -37 1 -38 0 -39 0 -40 0 -41 0 -42 0 -43 1 -44 0 -45 0 -46 0 -47 0 -48 0 -49 0 -50 0 -51 0 -52 0 -53 0 -54 0 -55 0 -56 0 -57 0 -58 0 -59 1 -60 0 -61 2 -62 0 -63 0 -64 1 -65 0 -66 0 -67 0 -68 1 -69 0 -70 0 -71 0 -72 0 -73 1 -74 0 -75 0 -76 0 -77 0 -78 0 -79 1 -80 0 -81 0 -82 0 -83 0 -84 0 -85 0 -86 1 -87 0 -88 0 -89 0 -90 0 -91 0 -92 0 -93 1 -94 0 -95 0 -96 0 -97 0 -98 0 -99 0 -100 0 -101 1 -102 0 -103 0 -104 0 -105 0 -106 0 -107 0 -108 1 -109 0 -110 0 -111 0 -112 0 -113 0 -114 0 -115 1 -116 0 -117 0 -118 0 -119 1 -120 0 -121 0 -122 0 -123 0 -124 0 -125 0 -126 1 -127 0 -128 1 -129 0 -130 0 -131 0 -132 1 -133 1 -134 0 -135 0 -136 0 -137 1 -138 0 -139 0 -140 0 -141 0 -142 0 -143 0 -144 1 -145 0 -146 0 -147 0 -148 0 -149 0 -150 0 -151 0 -152 0 -153 1 -154 0 -155 0 -156 0 -157 0 -158 0 -159 0 -160 0 -161 0 -162 0 -163 0 -164 0 -165 0 -166 0 -167 0 -168 0 -169 0 -170 1 -171 0 -172 0 -173 0 -174 0 -175 0 -176 0 -177 0 -178 1 -179 0 -180 0 -181 0 -182 0 -183 0 -184 0 -185 0 -186 1 -187 0 -188 0 -189 0 -190 0 -191 0 -192 1 -193 0 -194 0 -195 0 -196 1 -197 0 -198 0 -199 0 -200 1 -201 0 -202 0 -203 0 -204 0 -205 0 -206 0 -207 1 -208 0 -209 0 -210 0 -211 0 -212 0 -213 0 -214 0 -215 1 -216 0 -217 0 -218 0 -219 0 -220 0 -221 0 -222 0 -223 1 -224 0 -225 0 -226 0 -227 0 -228 0 -229 0 -230 1 -231 0 -232 0 -233 0 -234 0 -235 0 -236 0 -237 1 -238 0 -239 0 -240 0 -241 0 -242 0 -243 0 -244 0 -245 1 -246 0 -247 0 -248 0 -249 0 -250 0 -251 0 -252 0 -253 0 -254 1 -255 0 -256 0 -257 0 -258 0 -259 1 -260 0 -261 0 -262 0 -263 0 -264 0 -265 1 -266 0 -267 0 -268 0 -269 0 -270 0 -271 0 -272 1 -273 0 -274 0 -275 0 -276 0 -277 0 -278 0 -279 0 -280 0 -281 1 -282 0 -283 1 -284 0 -285 0 -286 1 -287 0 -288 0 -289 0 -290 0 -291 1 -292 0 -293 0 -294 0 -295 0 -296 1 -297 0 -298 0 -299 0 -300 0 -301 0 -302 0 -303 1 -304 0 -305 0 -306 0 -307 0 -308 0 -309 1 -310 0 -311 0 -312 0 -313 0 -314 0 -315 0 -316 1 -317 0 -318 0 -319 0 -320 0 -321 0 -322 0 -323 0 -324 0 -325 1 -326 0 -327 0 -328 0 -329 0 -330 0 -331 0 -332 0 -333 0 -334 1 -335 0 -336 0 -337 0 -338 0 -339 0 -340 0 -341 0 -342 0 -343 1 -344 0 -345 0 -346 0 -347 0 -348 0 -349 0 -350 0 -351 0 -352 1 -353 0 -354 0 -355 0 -356 0 -357 0 -358 0 -359 0 -360 0 -361 1 -362 0 -363 0 -364 0 -365 0 -366 0 -367 0 -368 0 -369 1 -370 0 -371 0 -372 0 -373 0 -374 0 -375 0 -376 0 -377 1 -378 0 -379 0 -380 0 -381 0 -382 0 -383 0 -384 0 -385 1 -386 0 -387 0 -388 0 -389 0 -390 1 -391 0 -392 0 -393 0 -394 0 -395 0 -396 0 -397 0 -398 0 -399 0 -400 0 -401 0 -402 1 -403 0 -404 0 -405 0 -406 0 -407 0 -408 0 -409 0 -410 1 -411 0 -412 0 -413 0 -414 0 -415 0 -416 0 -417 0 -418 0 -419 1 -420 0 -421 0 -422 0 -423 0 -424 0 -425 0 -426 0 -427 1 -428 0 -429 0 -430 0 -431 0 -432 0 -433 0 -434 0 -435 1 -436 0 -437 0 -438 0 -439 0 -440 0 -441 0 -442 0 -443 1 -444 0 -445 0 -446 0 -447 0 -448 0 -449 0 -450 1 -451 0 -452 0 -453 0 -454 0 -455 0 -456 1 -457 0 -458 0 -459 0 -460 0 -461 0 -462 0 -463 0 -464 1 -465 0 -466 0 -467 0 -468 0 -469 0 -470 0 -471 0 -472 0 -473 1 -474 0 -475 0 -476 0 -477 0 -478 0 -479 0 -480 0 -481 1 -482 0 -483 0 -484 0 -485 0 -486 0 -487 0 -488 0 -489 0 -490 1 -491 0 -492 0 -493 0 -494 0 -495 0 -496 0 -497 0 -498 0 -499 0 -500 0 -501 0 -502 0 -503 0 -504 1 -505 0 -506 0 -507 0 -508 0 -509 0 -510 0 -511 0 -512 1 -513 0 -514 0 -515 0 -516 0 -517 0 -518 0 -519 4 -520 0 -521 1 -522 0 -523 0 -524 0 -525 1 -526 0 -527 0 -528 0 -529 0 -530 1 -531 0 -532 0 -533 0 -534 1 -535 0 -536 0 -537 0 -538 0 -539 1 -540 0 -541 0 -542 0 -543 0 -544 0 -545 1 -546 0 -547 0 -548 0 -549 0 -550 0 -551 1 -552 0 -553 0 -554 0 -555 0 -556 0 -557 0 -558 0 -559 1 -560 0 -561 0 -562 0 -563 0 -564 0 -565 0 -566 0 -567 1 -568 0 -569 0 -570 0 -571 0 -572 0 -573 0 -574 0 -575 0 -576 1 -577 0 -578 0 -579 0 -580 0 -581 0 -582 0 -583 0 -584 0 -585 0 -586 0 -587 0 -588 0 -589 0 -590 0 -591 0 -592 0 -593 1 -594 0 -595 0 -596 0 -597 0 -598 0 -599 0 -600 0 -601 0 -602 1 -603 0 -604 0 -605 0 -606 0 -607 0 -608 0 -609 0 -610 0 -611 1 -612 0 -613 0 -614 0 -615 0 -616 0 -617 0 -618 0 -619 0 -620 1 -621 0 -622 0 -623 0 -624 0 -625 0 -626 0 -627 0 -628 0 -629 1 -630 0 -631 0 -632 0 -633 0 -634 0 -635 0 -636 0 -637 0 -638 0 -639 1 -640 0 -641 0 -642 0 -643 0 -644 0 -645 0 -646 1 -647 0 -648 0 -649 0 -650 0 -651 0 -652 1 -653 1 -654 0 -655 0 -656 1 -657 0 -658 1 -659 0 -660 0 -661 0 -662 0 -663 0 -664 1 -665 0 -666 0 -667 0 -668 0 -669 0 -670 0 -671 0 -672 0 -673 0 -674 0 -675 0 -676 0 -677 1 -678 0 -679 0 -680 0 -681 0 -682 0 -683 0 -684 0 -685 0 -686 1 -687 0 -688 0 -689 0 -690 0 -691 0 -692 0 -693 0 -694 0 -695 1 -696 0 -697 0 -698 0 -699 0 -700 0 -701 0 -702 0 -703 1 -704 0 -705 0 -706 0 -707 0 -708 0 -709 0 -710 0 -711 0 -712 1 -713 0 -714 0 -715 0 -716 0 -717 0 -718 0 -719 0 -720 1 -721 0 -722 0 -723 0 -724 0 -725 0 -726 0 -727 0 -728 1 -729 0 -730 0 -731 0 -732 0 -733 0 -734 0 -735 0 -736 0 -737 1 -738 0 -739 0 -740 0 -741 0 -742 0 -743 0 -744 0 -745 1 -746 0 -747 0 -748 0 -749 0 -750 0 -751 0 -752 0 -753 1 -754 0 -755 0 -756 0 -757 0 -758 0 -759 0 -760 0 -761 1 -762 0 -763 0 -764 0 -765 0 -766 0 -767 0 -768 1 -769 0 -770 0 -771 0 -772 0 -773 0 -774 0 -775 0 -776 0 -777 1 -778 0 -779 0 -780 0 -781 0 -782 0 -783 0 -784 0 -785 0 -786 1 -787 0 -788 0 -789 0 -790 0 -791 0 -792 1 -793 0 -794 0 -795 0 -796 0 -797 0 -798 0 -799 0 -800 0 -801 1 -802 0 -803 0 -804 0 -805 0 -806 0 -807 0 -808 0 -809 0 -810 0 -811 0 -812 0 -813 0 -814 0 -815 0 -816 0 -817 0 -818 0 -819 0 -820 1 -821 0 -822 0 -823 0 -824 0 -825 0 -826 0 -827 0 -828 0 -829 1 -830 0 -831 0 -832 0 -833 0 -834 0 -835 0 -836 0 -837 1 -838 0 -839 0 -840 0 -841 0 -842 0 -843 0 -844 0 -845 0 -846 1 -847 0 -848 0 -849 0 -850 0 -851 0 -852 0 -853 0 -854 0 -855 2 -856 0 -857 0 -858 0 -859 0 -860 0 -861 0 -862 1 -863 0 -864 0 -865 0 -866 0 -867 0 -868 0 -869 0 -870 0 -871 1 -872 0 -873 0 -874 0 -875 0 -876 0 -877 0 -878 1 -879 0 -880 0 -881 0 -882 0 -883 0 -884 0 -885 0 -886 0 -887 0 -888 0 -889 0 -890 0 -891 0 -892 0 -893 0 -894 0 -895 0 -896 1 -897 0 -898 0 -899 0 -900 0 -901 0 -902 0 -903 0 -904 0 -905 0 -906 1 -907 0 -908 0 -909 0 -910 0 -911 0 -912 0 -913 0 -914 0 -915 1 -916 0 -917 0 -918 0 -919 0 -920 0 -921 0 -922 1 -923 0 -924 0 -925 0 -926 0 -927 0 -928 0 -929 0 -930 1 -931 0 -932 0 -933 0 -934 0 -935 0 -936 0 -937 0 -938 0 -939 1 -940 0 -941 0 -942 0 -943 0 -944 0 -945 0 -946 0 -947 0 -948 0 -949 1 -950 0 -951 0 -952 0 -953 0 -954 0 -955 0 -956 0 -957 0 -958 1 -959 0 -960 0 -961 0 -962 0 -963 0 -964 0 -965 0 -966 0 -967 0 -968 1 -969 0 -970 0 -971 0 -972 0 -973 0 -974 0 -975 0 -976 0 -977 0 -978 1 -979 0 -980 0 -981 0 -982 0 -983 0 -984 0 -985 0 -986 0 -987 0 -988 1 -989 0 -990 0 -991 0 -992 0 -993 0 -994 0 -995 0 -996 0 -997 1 -998 0 -999 0 -1000 0 -1001 0 -1002 0 -1003 0 -1004 0 -1005 1 -1006 0 -1007 0 -1008 0 -1009 0 -1010 0 -1011 0 -1012 1 -1013 0 -1014 0 -1015 0 -1016 0 -1017 0 -1018 0 -1019 0 -1020 0 -1021 0 -1022 0 -1023 0 -1024 0 -1025 0 -1026 0 -1027 0 -1028 0 -1029 0 -1030 0 -1031 1 -1032 0 -1033 0 -1034 0 -1035 0 -1036 0 -1037 0 -1038 0 -1039 0 -1040 0 -1041 0 -1042 1 -1043 0 -1044 0 -1045 0 -1046 0 -1047 0 -1048 0 -1049 0 -1050 1 -1051 0 -1052 0 -1053 0 -1054 0 -1055 0 -1056 0 -1057 1 -1058 0 -1059 0 -1060 0 -1061 0 -1062 0 -1063 0 -1064 0 -1065 0 -1066 0 -1067 1 -1068 0 -1069 0 -1070 0 -1071 0 -1072 0 -1073 0 -1074 0 -1075 0 -1076 0 -1077 1 -1078 0 -1079 0 -1080 0 -1081 0 -1082 0 -1083 0 -1084 0 -1085 0 -1086 0 -1087 1 -1088 0 -1089 0 -1090 0 -1091 0 -1092 0 -1093 0 -1094 1 -1095 0 -1096 0 -1097 0 -1098 0 -1099 0 -1100 0 -1101 0 -1102 1 -1103 0 -1104 0 -1105 0 -1106 0 -1107 0 -1108 0 -1109 0 -1110 0 -1111 1 -1112 0 -1113 0 -1114 0 -1115 0 -1116 0 -1117 0 -1118 0 -1119 0 -1120 1 -1121 0 -1122 0 -1123 0 -1124 0 -1125 0 -1126 0 -1127 0 -1128 0 -1129 0 -1130 1 -1131 0 -1132 0 -1133 0 -1134 0 -1135 0 -1136 0 -1137 0 -1138 0 -1139 0 -1140 1 -1141 0 -1142 0 -1143 0 -1144 0 -1145 0 -1146 0 -1147 0 -1148 0 -1149 0 -1150 0 -1151 1 -1152 0 -1153 0 -1154 0 -1155 0 -1156 0 -1157 0 -1158 0 -1159 0 -1160 1 -1161 0 -1162 0 -1163 0 -1164 0 -1165 0 -1166 0 -1167 1 -1168 0 -1169 0 -1170 0 -1171 0 -1172 0 -1173 0 -1174 0 -1175 0 -1176 1 -1177 0 -1178 0 -1179 0 -1180 0 -1181 0 -1182 1 -1183 0 -1184 0 -1185 0 -1186 0 -1187 0 -1188 0 -1189 0 -1190 1 -1191 0 -1192 0 -1193 0 -1194 0 -1195 0 -1196 0 -1197 0 -1198 1 -1199 0 -1200 0 -1201 0 -1202 0 -1203 0 -1204 0 -1205 0 -1206 1 -1207 0 -1208 0 -1209 0 -1210 0 -1211 0 -1212 0 -1213 0 -1214 0 -1215 0 -1216 1 -1217 0 -1218 0 -1219 0 -1220 0 -1221 0 -1222 0 -1223 0 -1224 0 -1225 0 -1226 1 -1227 0 -1228 0 -1229 0 -1230 0 -1231 0 -1232 0 -1233 0 -1234 0 -1235 0 -1236 0 -1237 0 -1238 0 -1239 1 -1240 0 -1241 0 -1242 0 -1243 0 -1244 0 -1245 0 -1246 0 -1247 0 -1248 1 -1249 0 -1250 0 -1251 0 -1252 0 -1253 0 -1254 0 -1255 0 -1256 0 -1257 1 -1258 0 -1259 0 -1260 0 -1261 0 -1262 0 -1263 0 -1264 0 -1265 0 -1266 1 -1267 0 -1268 0 -1269 0 -1270 0 -1271 0 -1272 0 -1273 0 -1274 0 -1275 1 -1276 0 -1277 0 -1278 0 -1279 0 -1280 0 -1281 0 -1282 0 -1283 0 -1284 0 -1285 0 -1286 0 -1287 0 -1288 0 -1289 0 -1290 0 -1291 0 -1292 0 -1293 1 -1294 0 -1295 0 -1296 0 -1297 0 -1298 0 -1299 0 -1300 0 -1301 0 -1302 0 -1303 0 -1304 0 -1305 0 -1306 0 -1307 0 -1308 0 -1309 0 -1310 1 -1311 0 -1312 0 -1313 0 -1314 0 -1315 0 -1316 0 -1317 0 -1318 1 -1319 0 -1320 0 -1321 0 -1322 0 -1323 0 -1324 0 -1325 0 -1326 0 -1327 1 -1328 0 -1329 0 -1330 0 -1331 0 -1332 0 -1333 0 -1334 0 -1335 0 -1336 1 -1337 0 -1338 0 -1339 0 -1340 0 -1341 0 -1342 0 -1343 0 -1344 0 -1345 0 -1346 1 -1347 0 -1348 0 -1349 0 -1350 0 -1351 0 -1352 0 -1353 0 -1354 0 -1355 0 -1356 1 -1357 0 -1358 0 -1359 0 -1360 0 -1361 0 -1362 0 -1363 0 -1364 0 -1365 1 -1366 0 -1367 0 -1368 0 -1369 0 -1370 0 -1371 0 -1372 0 -1373 1 -1374 0 -1375 0 -1376 0 -1377 0 -1378 0 -1379 0 -1380 0 -1381 0 -1382 0 -1383 1 -1384 0 -1385 0 -1386 0 -1387 0 -1388 0 -1389 0 -1390 0 -1391 0 -1392 1 -1393 0 -1394 0 -1395 0 -1396 0 -1397 0 -1398 0 -1399 0 -1400 1 -1401 0 -1402 0 -1403 0 -1404 0 -1405 0 -1406 0 -1407 0 -1408 0 -1409 0 -1410 1 -1411 0 -1412 0 -1413 0 -1414 0 -1415 0 -1416 0 -1417 0 -1418 0 -1419 0 -1420 1 -1421 0 -1422 0 -1423 0 -1424 0 -1425 0 -1426 0 -1427 0 -1428 0 -1429 0 -1430 0 -1431 1 -1432 0 -1433 0 -1434 0 -1435 0 -1436 0 -1437 0 -1438 0 -1439 0 -1440 0 -1441 1 -1442 0 -1443 0 -1444 0 -1445 0 -1446 0 -1447 2 -1448 0 -1449 0 -1450 0 -1451 0 -1452 0 -1453 0 -1454 0 -1455 1 -1456 0 -1457 0 -1458 0 -1459 0 -1460 0 -1461 0 -1462 0 -1463 0 -1464 0 -1465 1 -1466 0 -1467 0 -1468 0 -1469 0 -1470 0 -1471 0 -1472 0 -1473 0 -1474 0 -1475 1 -1476 0 -1477 0 -1478 0 -1479 0 -1480 0 -1481 0 -1482 0 -1483 0 -1484 0 -1485 1 -1486 0 -1487 0 -1488 0 -1489 0 -1490 0 -1491 0 -1492 0 -1493 0 -1494 1 -1495 0 -1496 0 -1497 0 -1498 0 -1499 0 -1500 0 -1501 0 -1502 0 -1503 1 -1504 0 -1505 0 -1506 0 -1507 0 -1508 0 -1509 0 -1510 0 -1511 0 -1512 0 -1513 0 -1514 0 -1515 0 -1516 0 -1517 0 -1518 0 -1519 0 -1520 1 -1521 0 -1522 0 -1523 0 -1524 0 -1525 0 -1526 0 -1527 0 -1528 0 -1529 1 -1530 0 -1531 0 -1532 0 -1533 0 -1534 0 -1535 0 -1536 0 -1537 0 -1538 0 -1539 1 -1540 0 -1541 0 -1542 0 -1543 0 -1544 0 -1545 0 -1546 0 -1547 0 -1548 1 -1549 0 -1550 0 -1551 0 -1552 0 -1553 0 -1554 0 -1555 0 -1556 0 -1557 1 -1558 0 -1559 0 -1560 0 -1561 0 -1562 0 -1563 0 -1564 0 -1565 0 -1566 0 -1567 1 -1568 0 -1569 0 -1570 0 -1571 0 -1572 0 -1573 0 -1574 0 -1575 1 -1576 0 -1577 0 -1578 0 -1579 0 -1580 0 -1581 0 -1582 0 -1583 0 -1584 1 -1585 0 -1586 0 -1587 0 -1588 0 -1589 0 -1590 0 -1591 0 -1592 0 -1593 1 -1594 0 -1595 0 -1596 0 -1597 0 -1598 0 -1599 0 -1600 0 -1601 0 -1602 1 -1603 0 -1604 0 -1605 0 -1606 0 -1607 0 -1608 0 -1609 0 -1610 0 -1611 1 -1612 0 -1613 0 -1614 0 -1615 0 -1616 0 -1617 0 -1618 0 -1619 0 -1620 0 -1621 1 -1622 0 -1623 0 -1624 0 -1625 0 -1626 0 -1627 0 -1628 0 -1629 0 -1630 0 -1631 1 -1632 0 -1633 0 -1634 0 -1635 0 -1636 0 -1637 0 -1638 0 -1639 0 -1640 1 -1641 0 -1642 0 -1643 0 -1644 0 -1645 0 -1646 0 -1647 0 -1648 0 -1649 0 -1650 1 -1651 0 -1652 0 -1653 0 -1654 0 -1655 0 -1656 0 -1657 0 -1658 0 -1659 0 -1660 1 -1661 0 -1662 0 -1663 0 -1664 0 -1665 0 -1666 0 -1667 0 -1668 0 -1669 0 -1670 1 -1671 0 -1672 0 -1673 0 -1674 0 -1675 0 -1676 0 -1677 0 -1678 0 -1679 0 -1680 1 -1681 0 -1682 0 -1683 0 -1684 0 -1685 0 -1686 0 -1687 0 -1688 0 -1689 0 -1690 1 -1691 0 -1692 0 -1693 0 -1694 0 -1695 0 -1696 0 -1697 0 -1698 0 -1699 0 -1700 0 -1701 1 -1702 0 -1703 0 -1704 0 -1705 0 -1706 0 -1707 0 -1708 1 -1709 0 -1710 0 -1711 0 -1712 0 -1713 0 -1714 0 -1715 0 -1716 1 -1717 0 -1718 0 -1719 0 -1720 0 -1721 0 -1722 0 -1723 0 -1724 0 -1725 0 -1726 0 -1727 0 -1728 0 -1729 0 -1730 0 -1731 0 -1732 0 -1733 0 -1734 1 -1735 0 -1736 0 -1737 0 -1738 0 -1739 0 -1740 0 -1741 0 -1742 0 -1743 1 -1744 0 -1745 0 -1746 0 -1747 0 -1748 0 -1749 0 -1750 0 -1751 0 -1752 0 -1753 1 -1754 0 -1755 0 -1756 0 -1757 0 -1758 0 -1759 0 -1760 0 -1761 0 -1762 0 -1763 1 -1764 0 -1765 0 -1766 0 -1767 0 -1768 0 -1769 0 -1770 0 -1771 0 -1772 0 -1773 1 -1774 0 -1775 0 -1776 0 -1777 0 -1778 0 -1779 0 -1780 0 -1781 0 -1782 0 -1783 1 -1784 0 -1785 0 -1786 0 -1787 0 -1788 0 -1789 0 -1790 0 -1791 0 -1792 0 -1793 1 -1794 0 -1795 0 -1796 0 -1797 0 -1798 0 -1799 0 -1800 0 -1801 0 -1802 0 -1803 1 -1804 0 -1805 0 -1806 0 -1807 0 -1808 0 -1809 0 -1810 0 -1811 0 -1812 0 -1813 1 -1814 0 -1815 0 -1816 0 -1817 0 -1818 0 -1819 0 -1820 0 -1821 0 -1822 1 -1823 0 -1824 0 -1825 0 -1826 0 -1827 0 -1828 0 -1829 1 -1830 0 -1831 0 -1832 0 -1833 0 -1834 0 -1835 0 -1836 0 -1837 0 -1838 0 -1839 1 -1840 0 -1841 0 -1842 0 -1843 0 -1844 0 -1845 0 -1846 0 -1847 0 -1848 0 -1849 1 -1850 0 -1851 0 -1852 0 -1853 0 -1854 0 -1855 0 -1856 0 -1857 0 -1858 0 -1859 1 -1860 0 -1861 0 -1862 0 -1863 0 -1864 0 -1865 0 -1866 0 -1867 0 -1868 0 -1869 1 -1870 0 -1871 0 -1872 0 -1873 0 -1874 0 -1875 0 -1876 0 -1877 0 -1878 0 -1879 1 -1880 0 -1881 0 -1882 0 -1883 0 -1884 0 -1885 0 -1886 0 -1887 0 -1888 0 -1889 1 -1890 0 -1891 0 -1892 0 -1893 0 -1894 0 -1895 0 -1896 0 -1897 0 -1898 0 -1899 0 -1900 0 -1901 0 -1902 0 -1903 0 -1904 0 -1905 0 -1906 0 -1907 0 -1908 0 -1909 0 -1910 1 -1911 0 -1912 0 -1913 0 -1914 0 -1915 0 -1916 0 -1917 0 -1918 0 -1919 0 -1920 0 -1921 0 -1922 0 -1923 0 -1924 0 -1925 0 -1926 0 -1927 0 -1928 0 -1929 0 -1930 1 -1931 0 -1932 0 -1933 0 -1934 0 -1935 0 -1936 0 -1937 0 -1938 0 -1939 1 -1940 0 -1941 0 -1942 0 -1943 0 -1944 0 -1945 0 -1946 0 -1947 0 -1948 0 -1949 1 -1950 0 -1951 0 -1952 0 -1953 0 -1954 0 -1955 0 -1956 0 -1957 0 -1958 1 -1959 0 -1960 0 -1961 0 -1962 0 -1963 0 -1964 0 -1965 0 -1966 0 -1967 0 -1968 1 -1969 0 -1970 0 -1971 0 -1972 0 -1973 0 -1974 0 -1975 0 -1976 0 -1977 0 -1978 1 -1979 0 -1980 0 -1981 0 -1982 0 -1983 0 -1984 0 -1985 0 -1986 0 -1987 0 -1988 1 -1989 0 -1990 0 -1991 0 -1992 0 -1993 0 -1994 0 -1995 0 -1996 1 -1997 0 -1998 0 -1999 0 -2000 0 -2001 0 -2002 0 -2003 0 -2004 1 -2005 0 -2006 0 -2007 0 -2008 0 -2009 0 -2010 0 -2011 0 -2012 0 -2013 0 -2014 1 -2015 0 -2016 0 -2017 0 -2018 0 -2019 0 -2020 0 -2021 0 -2022 0 -2023 0 -2024 1 -2025 0 -2026 0 -2027 0 -2028 0 -2029 0 -2030 0 -2031 0 -2032 0 -2033 1 -2034 0 -2035 0 -2036 0 -2037 0 -2038 0 -2039 0 -2040 0 -2041 2 -2042 0 -2043 0 -2044 0 -2045 0 -2046 0 -2047 0 -2048 0 -2049 1 -2050 0 -2051 0 -2052 0 -2053 0 -2054 0 -2055 0 -2056 0 -2057 0 -2058 0 -2059 0 -2060 0 -2061 0 -2062 0 -2063 0 -2064 0 -2065 0 -2066 0 -2067 1 -2068 0 -2069 0 -2070 0 -2071 0 -2072 0 -2073 0 -2074 0 -2075 0 -2076 1 -2077 0 -2078 0 -2079 0 -2080 0 -2081 0 -2082 0 -2083 0 -2084 0 -2085 0 -2086 1 -2087 0 -2088 0 -2089 0 -2090 0 -2091 0 -2092 0 -2093 0 -2094 0 -2095 0 -2096 1 -2097 0 -2098 0 -2099 0 -2100 0 -2101 0 -2102 0 -2103 0 -2104 0 -2105 1 -2106 0 -2107 0 -2108 0 -2109 0 -2110 0 -2111 0 -2112 0 -2113 0 -2114 0 -2115 0 -2116 1 -2117 0 -2118 0 -2119 0 -2120 0 -2121 0 -2122 0 -2123 0 -2124 0 -2125 1 -2126 0 -2127 0 -2128 0 -2129 0 -2130 0 -2131 0 -2132 0 -2133 1 -2134 0 -2135 0 -2136 0 -2137 0 -2138 0 -2139 0 -2140 0 -2141 1 -2142 0 -2143 0 -2144 0 -2145 0 -2146 0 -2147 0 -2148 0 -2149 0 -2150 1 -2151 0 -2152 0 -2153 0 -2154 0 -2155 0 -2156 0 -2157 0 -2158 0 -2159 1 -2160 0 -2161 0 -2162 0 -2163 0 -2164 0 -2165 0 -2166 0 -2167 0 -2168 0 -2169 1 -2170 0 -2171 0 -2172 0 -2173 0 -2174 0 -2175 0 -2176 0 -2177 1 -2178 0 -2179 0 -2180 0 -2181 0 -2182 0 -2183 0 -2184 0 -2185 0 -2186 0 -2187 1 -2188 0 -2189 0 -2190 0 -2191 0 -2192 0 -2193 0 -2194 0 -2195 0 -2196 1 -2197 0 -2198 0 -2199 0 -2200 0 -2201 0 -2202 0 -2203 0 -2204 1 -2205 0 -2206 0 -2207 0 -2208 0 -2209 0 -2210 0 -2211 0 -2212 0 -2213 0 -2214 1 -2215 0 -2216 0 -2217 0 -2218 0 -2219 0 -2220 0 -2221 0 -2222 0 -2223 0 -2224 1 -2225 0 -2226 0 -2227 0 -2228 0 -2229 0 -2230 0 -2231 0 -2232 0 -2233 1 -2234 0 -2235 0 -2236 0 -2237 0 -2238 0 -2239 0 -2240 0 -2241 0 -2242 1 -2243 0 -2244 0 -2245 0 -2246 0 -2247 0 -2248 0 -2249 0 -2250 1 -2251 0 -2252 0 -2253 0 -2254 0 -2255 0 -2256 0 -2257 0 -2258 0 -2259 0 -2260 1 -2261 0 -2262 0 -2263 0 -2264 0 -2265 0 -2266 0 -2267 0 -2268 0 -2269 0 -2270 1 -2271 0 -2272 0 -2273 0 -2274 0 -2275 0 -2276 0 -2277 0 -2278 0 -2279 0 -2280 1 -2281 0 -2282 0 -2283 0 -2284 0 -2285 0 -2286 0 -2287 0 -2288 0 -2289 0 -2290 1 -2291 0 -2292 0 -2293 0 -2294 0 -2295 0 -2296 0 -2297 0 -2298 1 -2299 0 -2300 0 -2301 0 -2302 0 -2303 0 -2304 0 -2305 0 -2306 1 -2307 0 -2308 0 -2309 0 -2310 0 -2311 0 -2312 0 -2313 0 -2314 0 -2315 1 -2316 0 -2317 0 -2318 0 -2319 0 -2320 0 -2321 0 -2322 0 -2323 0 -2324 0 -2325 1 -2326 0 -2327 0 -2328 0 -2329 0 -2330 0 -2331 0 -2332 0 -2333 0 -2334 0 -2335 1 -2336 0 -2337 0 -2338 0 -2339 0 -2340 0 -2341 0 -2342 0 -2343 0 -2344 0 -2345 1 -2346 0 -2347 0 -2348 0 -2349 0 -2350 0 -2351 0 -2352 0 -2353 1 -2354 0 -2355 0 -2356 0 -2357 0 -2358 0 -2359 0 -2360 0 -2361 1 -2362 0 -2363 0 -2364 0 -2365 0 -2366 0 -2367 0 -2368 0 -2369 0 -2370 0 -2371 1 -2372 0 -2373 0 -2374 0 -2375 0 -2376 0 -2377 0 -2378 0 -2379 0 -2380 0 -2381 1 -2382 0 -2383 0 -2384 0 -2385 0 -2386 0 -2387 0 -2388 0 -2389 0 -2390 1 -2391 0 -2392 0 -2393 0 -2394 0 -2395 0 -2396 0 -2397 0 -2398 0 -2399 0 -2400 0 -2401 0 -2402 0 -2403 0 -2404 0 -2405 0 -2406 0 -2407 0 -2408 0 -2409 0 -2410 0 -2411 1 -2412 0 -2413 0 -2414 0 -2415 0 -2416 0 -2417 0 -2418 0 -2419 0 -2420 0 -2421 1 -2422 0 -2423 0 -2424 0 -2425 0 -2426 0 -2427 0 -2428 0 -2429 0 -2430 0 -2431 0 -2432 0 -2433 0 -2434 0 -2435 0 -2436 0 -2437 0 -2438 0 -2439 0 -2440 1 -2441 0 -2442 0 -2443 0 -2444 0 -2445 0 -2446 0 -2447 0 -2448 0 -2449 0 -2450 0 -2451 1 -2452 0 -2453 0 -2454 0 -2455 0 -2456 0 -2457 0 -2458 0 -2459 0 -2460 0 -2461 1 -2462 0 -2463 0 -2464 0 -2465 0 -2466 0 -2467 0 -2468 0 -2469 1 -2470 0 -2471 0 -2472 0 -2473 0 -2474 0 -2475 0 -2476 0 -2477 1 -2478 0 -2479 0 -2480 0 -2481 0 -2482 0 -2483 0 -2484 0 -2485 0 -2486 1 -2487 0 -2488 0 -2489 0 -2490 0 -2491 0 -2492 0 -2493 0 -2494 0 -2495 0 -2496 1 -2497 0 -2498 0 -2499 0 -2500 0 -2501 0 -2502 0 -2503 0 -2504 0 -2505 0 -2506 1 -2507 0 -2508 0 -2509 0 -2510 0 -2511 0 -2512 0 -2513 0 -2514 0 -2515 0 -2516 1 -2517 0 -2518 0 -2519 0 -2520 0 -2521 0 -2522 0 -2523 0 -2524 0 -2525 0 -2526 0 -2527 1 -2528 0 -2529 0 -2530 0 -2531 0 -2532 0 -2533 0 -2534 0 -2535 0 -2536 0 -2537 1 -2538 0 -2539 0 -2540 0 -2541 0 -2542 0 -2543 0 -2544 0 -2545 0 -2546 0 -2547 0 -2548 0 -2549 0 -2550 0 -2551 0 -2552 0 -2553 0 -2554 0 -2555 0 -2556 0 -2557 1 -2558 0 -2559 0 -2560 0 -2561 0 -2562 0 -2563 0 -2564 0 -2565 0 -2566 1 -2567 0 -2568 0 -2569 0 -2570 0 -2571 0 -2572 0 -2573 0 -2574 0 -2575 1 -2576 0 -2577 0 -2578 0 -2579 0 -2580 0 -2581 0 -2582 0 -2583 0 -2584 1 -2585 0 -2586 0 -2587 0 -2588 0 -2589 0 -2590 0 -2591 0 -2592 0 -2593 0 -2594 0 -2595 1 -2596 0 -2597 0 -2598 0 -2599 0 -2600 0 -2601 0 -2602 0 -2603 0 -2604 0 -2605 1 -2606 0 -2607 0 -2608 0 -2609 0 -2610 0 -2611 0 -2612 0 -2613 0 -2614 0 -2615 0 -2616 0 -2617 0 -2618 0 -2619 0 -2620 0 -2621 0 -2622 0 -2623 0 -2624 0 -2625 1 -2626 0 -2627 0 -2628 0 -2629 0 -2630 0 -2631 0 -2632 0 -2633 0 -2634 0 -2635 1 -2636 0 -2637 0 -2638 0 -2639 1 -2640 0 -2641 0 -2642 0 -2643 1 -2644 0 -2645 0 -2646 0 -2647 0 -2648 0 -2649 0 -2650 0 -2651 0 -2652 0 -2653 1 -2654 0 -2655 0 -2656 0 -2657 0 -2658 0 -2659 0 -2660 0 -2661 0 -2662 0 -2663 1 -2664 0 -2665 0 -2666 0 -2667 0 -2668 0 -2669 0 -2670 0 -2671 1 -2672 0 -2673 0 -2674 0 -2675 0 -2676 0 -2677 0 -2678 0 -2679 1 -2680 0 -2681 0 -2682 0 -2683 0 -2684 0 -2685 0 -2686 0 -2687 0 -2688 0 -2689 1 -2690 0 -2691 0 -2692 0 -2693 0 -2694 0 -2695 0 -2696 0 -2697 0 -2698 0 -2699 1 -2700 0 -2701 0 -2702 0 -2703 0 -2704 0 -2705 0 -2706 0 -2707 0 -2708 0 -2709 1 -2710 0 -2711 0 -2712 0 -2713 0 -2714 0 -2715 0 -2716 1 -2717 0 -2718 0 -2719 0 -2720 0 -2721 0 -2722 0 -2723 0 -2724 1 -2725 0 -2726 0 -2727 0 -2728 0 -2729 0 -2730 0 -2731 0 -2732 0 -2733 0 -2734 1 -2735 0 -2736 0 -2737 0 -2738 0 -2739 0 -2740 0 -2741 0 -2742 0 -2743 0 -2744 1 -2745 0 -2746 0 -2747 0 -2748 0 -2749 0 -2750 0 -2751 0 -2752 0 -2753 1 -2754 0 -2755 0 -2756 0 -2757 0 -2758 0 -2759 0 -2760 0 -2761 0 -2762 0 -2763 1 -2764 0 -2765 0 -2766 0 -2767 0 -2768 0 -2769 0 -2770 0 -2771 0 -2772 0 -2773 1 -2774 0 -2775 0 -2776 0 -2777 0 -2778 0 -2779 0 -2780 0 -2781 0 -2782 0 -2783 1 -2784 0 -2785 0 -2786 0 -2787 0 -2788 0 -2789 0 -2790 0 -2791 0 -2792 1 -2793 0 -2794 0 -2795 0 -2796 0 -2797 0 -2798 0 -2799 0 -2800 0 -2801 0 -2802 0 -2803 0 -2804 0 -2805 0 -2806 0 -2807 0 -2808 0 -2809 0 -2810 0 -2811 0 -2812 0 -2813 0 -2814 0 -2815 0 -2816 0 -2817 0 -2818 0 -2819 0 -2820 0 -2821 1 -2822 0 -2823 0 -2824 0 -2825 0 -2826 0 -2827 0 -2828 0 -2829 0 -2830 0 -2831 1 -2832 0 -2833 0 -2834 0 -2835 0 -2836 0 -2837 0 -2838 0 -2839 0 -2840 0 -2841 1 -2842 0 -2843 0 -2844 0 -2845 0 -2846 0 -2847 0 -2848 0 -2849 0 -2850 0 -2851 1 -2852 0 -2853 0 -2854 0 -2855 0 -2856 0 -2857 0 -2858 0 -2859 0 -2860 0 -2861 1 -2862 0 -2863 0 -2864 0 -2865 0 -2866 0 -2867 0 -2868 0 -2869 0 -2870 0 -2871 1 -2872 0 -2873 0 -2874 0 -2875 0 -2876 0 -2877 0 -2878 0 -2879 0 -2880 1 -2881 0 -2882 0 -2883 0 -2884 0 -2885 0 -2886 0 -2887 0 -2888 1 -2889 0 -2890 0 -2891 0 -2892 0 -2893 0 -2894 0 -2895 0 -2896 0 -2897 1 -2898 0 -2899 0 -2900 0 -2901 0 -2902 0 -2903 0 -2904 0 -2905 0 -2906 1 -2907 0 -2908 0 -2909 0 -2910 0 -2911 0 -2912 0 -2913 0 -2914 1 -2915 0 -2916 0 -2917 0 -2918 0 -2919 0 -2920 0 -2921 0 -2922 1 -2923 0 -2924 0 -2925 0 -2926 0 -2927 0 -2928 0 -2929 0 -2930 0 -2931 0 -2932 0 -2933 0 -2934 0 -2935 0 -2936 0 -2937 0 -2938 1 -2939 0 -2940 0 -2941 0 -2942 0 -2943 0 -2944 0 -2945 0 -2946 0 -2947 0 -2948 0 -2949 1 -2950 0 -2951 0 -2952 0 -2953 0 -2954 0 -2955 0 -2956 0 -2957 0 -2958 0 -2959 1 -2960 0 -2961 0 -2962 0 -2963 0 -2964 0 -2965 0 -2966 0 -2967 0 -2968 1 -2969 0 -2970 0 -2971 0 -2972 0 -2973 0 -2974 0 -2975 0 -2976 0 -2977 1 -2978 0 -2979 0 -2980 0 -2981 0 -2982 0 -2983 0 -2984 0 -2985 0 -2986 0 -2987 1 -2988 0 -2989 0 -2990 0 -2991 0 -2992 0 -2993 0 -2994 0 -2995 0 -2996 0 -2997 1 -2998 0 -2999 0 -3000 0 -3001 0 -3002 0 -3003 0 -3004 0 -3005 0 -3006 0 -3007 0 -3008 0 -3009 0 -3010 0 -3011 0 -3012 0 -3013 0 -3014 0 -3015 1 -3016 0 -3017 0 -3018 0 -3019 0 -3020 0 -3021 0 -3022 0 -3023 0 -3024 0 -3025 1 -3026 0 -3027 0 -3028 0 -3029 0 -3030 0 -3031 0 -3032 0 -3033 0 -3034 1 -3035 0 -3036 0 -3037 0 -3038 0 -3039 0 -3040 0 -3041 0 -3042 1 -3043 0 -3044 0 -3045 0 -3046 0 -3047 0 -3048 0 -3049 0 -3050 0 -3051 0 -3052 1 -3053 0 -3054 0 -3055 0 -3056 0 -3057 0 -3058 0 -3059 0 -3060 0 -3061 0 -3062 1 -3063 0 -3064 0 -3065 0 -3066 0 -3067 0 -3068 0 -3069 0 -3070 0 -3071 0 -3072 1 -3073 0 -3074 0 -3075 0 -3076 0 -3077 0 -3078 0 -3079 0 -3080 0 -3081 0 -3082 1 -3083 0 -3084 0 -3085 0 -3086 0 -3087 0 -3088 0 -3089 0 -3090 0 -3091 0 -3092 1 -3093 0 -3094 0 -3095 0 -3096 0 -3097 0 -3098 0 -3099 0 -3100 0 -3101 0 -3102 1 -3103 0 -3104 0 -3105 0 -3106 0 -3107 0 -3108 0 -3109 0 -3110 0 -3111 0 -3112 1 -3113 0 -3114 0 -3115 0 -3116 0 -3117 0 -3118 0 -3119 0 -3120 1 -3121 0 -3122 0 -3123 0 -3124 0 -3125 0 -3126 0 -3127 0 -3128 0 -3129 1 -3130 0 -3131 0 -3132 0 -3133 0 -3134 0 -3135 0 -3136 0 -3137 0 -3138 0 -3139 1 -3140 0 -3141 0 -3142 0 -3143 0 -3144 0 -3145 0 -3146 0 -3147 0 -3148 0 -3149 1 -3150 0 -3151 0 -3152 0 -3153 0 -3154 0 -3155 0 -3156 0 -3157 1 -3158 0 -3159 0 -3160 0 -3161 0 -3162 0 -3163 0 -3164 0 -3165 1 -3166 0 -3167 0 -3168 0 -3169 0 -3170 0 -3171 0 -3172 0 -3173 0 -3174 0 -3175 1 -3176 0 -3177 0 -3178 0 -3179 0 -3180 0 -3181 0 -3182 0 -3183 0 -3184 0 -3185 1 -3186 0 -3187 0 -3188 0 -3189 0 -3190 0 -3191 0 -3192 0 -3193 0 -3194 0 -3195 0 -3196 1 -3197 0 -3198 0 -3199 0 -3200 0 -3201 0 -3202 0 -3203 0 -3204 0 -3205 0 -3206 0 -3207 1 -3208 0 -3209 0 -3210 0 -3211 0 -3212 0 -3213 0 -3214 0 -3215 1 -3216 0 -3217 0 -3218 0 -3219 0 -3220 0 -3221 0 -3222 0 -3223 1 -3224 0 -3225 0 -3226 0 -3227 0 -3228 0 -3229 0 -3230 0 -3231 0 -3232 1 -3233 0 -3234 1 -3235 0 -3236 0 -3237 0 -3238 0 -3239 1 -3240 0 -3241 0 -3242 0 -3243 0 -3244 0 -3245 0 -3246 0 -3247 0 -3248 1 -3249 0 -3250 0 -3251 0 -3252 0 -3253 0 -3254 0 -3255 0 -3256 0 -3257 0 -3258 1 -3259 0 -3260 0 -3261 0 -3262 0 -3263 0 -3264 0 -3265 0 -3266 0 -3267 0 -3268 0 -3269 1 -3270 0 -3271 0 -3272 0 -3273 0 -3274 0 -3275 0 -3276 0 -3277 0 -3278 1 -3279 0 -3280 0 -3281 0 -3282 0 -3283 0 -3284 0 -3285 0 -3286 0 -3287 1 -3288 0 -3289 0 -3290 0 -3291 0 -3292 0 -3293 0 -3294 0 -3295 0 -3296 0 -3297 1 -3298 0 -3299 0 -3300 0 -3301 0 -3302 0 -3303 0 -3304 0 -3305 0 -3306 0 -3307 1 -3308 0 -3309 0 -3310 0 -3311 0 -3312 0 -3313 0 -3314 0 -3315 0 -3316 0 -3317 1 -3318 0 -3319 0 -3320 0 -3321 0 -3322 0 -3323 0 -3324 0 -3325 1 -3326 0 -3327 0 -3328 0 -3329 0 -3330 0 -3331 0 -3332 0 -3333 0 -3334 0 -3335 1 -3336 0 -3337 0 -3338 0 -3339 0 -3340 0 -3341 0 -3342 0 -3343 0 -3344 1 -3345 0 -3346 0 -3347 0 -3348 0 -3349 0 -3350 0 -3351 0 -3352 0 -3353 0 -3354 1 -3355 0 -3356 0 -3357 0 -3358 0 -3359 0 -3360 0 -3361 0 -3362 0 -3363 0 -3364 0 -3365 1 -3366 0 -3367 0 -3368 0 -3369 0 -3370 0 -3371 0 -3372 0 -3373 0 -3374 0 -3375 1 -3376 0 -3377 0 -3378 0 -3379 0 -3380 0 -3381 0 -3382 0 -3383 0 -3384 0 -3385 0 -3386 1 -3387 0 -3388 0 -3389 0 -3390 0 -3391 0 -3392 0 -3393 0 -3394 0 -3395 0 -3396 0 -3397 1 -3398 0 -3399 0 -3400 0 -3401 0 -3402 0 -3403 0 -3404 0 -3405 0 -3406 0 -3407 1 -3408 0 -3409 0 -3410 0 -3411 0 -3412 0 -3413 0 -3414 0 -3415 0 -3416 0 -3417 1 -3418 0 -3419 0 -3420 0 -3421 0 -3422 0 -3423 0 -3424 0 -3425 0 -3426 0 -3427 0 -3428 1 -3429 0 -3430 0 -3431 0 -3432 0 -3433 0 -3434 0 -3435 0 -3436 0 -3437 1 -3438 0 -3439 0 -3440 0 -3441 0 -3442 0 -3443 0 -3444 0 -3445 1 -3446 0 -3447 0 -3448 0 -3449 0 -3450 0 -3451 0 -3452 0 -3453 0 -3454 1 -3455 0 -3456 0 -3457 0 -3458 0 -3459 0 -3460 0 -3461 0 -3462 0 -3463 0 -3464 1 -3465 0 -3466 0 -3467 0 -3468 0 -3469 0 -3470 0 -3471 0 -3472 0 -3473 0 -3474 1 -3475 0 -3476 0 -3477 0 -3478 0 -3479 0 -3480 0 -3481 0 -3482 0 -3483 0 -3484 1 -3485 0 -3486 0 -3487 0 -3488 0 -3489 0 -3490 0 -3491 0 -3492 0 -3493 0 -3494 1 -3495 0 -3496 0 -3497 0 -3498 0 -3499 0 -3500 0 -3501 0 -3502 0 -3503 0 -3504 1 -3505 0 -3506 0 -3507 0 -3508 0 -3509 0 -3510 0 -3511 0 -3512 0 -3513 0 -3514 1 -3515 0 -3516 0 -3517 0 -3518 0 -3519 0 -3520 0 -3521 0 -3522 0 -3523 0 -3524 1 -3525 0 -3526 0 -3527 0 -3528 0 -3529 0 -3530 0 -3531 0 -3532 0 -3533 1 -3534 0 -3535 0 -3536 0 -3537 0 -3538 0 -3539 0 -3540 0 -3541 0 -3542 0 -3543 0 -3544 0 -3545 0 -3546 0 -3547 0 -3548 0 -3549 0 -3550 0 -3551 1 -3552 0 -3553 0 -3554 0 -3555 0 -3556 0 -3557 0 -3558 0 -3559 0 -3560 0 -3561 1 -3562 0 -3563 0 -3564 0 -3565 0 -3566 0 -3567 0 -3568 0 -3569 0 -3570 1 -3571 0 -3572 0 -3573 0 -3574 0 -3575 0 -3576 0 -3577 0 -3578 0 -3579 0 -3580 1 -3581 0 -3582 0 -3583 0 -3584 0 -3585 0 -3586 0 -3587 0 -3588 0 -3589 0 -3590 1 -3591 0 -3592 0 -3593 0 -3594 0 -3595 0 -3596 0 -3597 0 -3598 0 -3599 1 -3600 0 -3601 0 -3602 0 -3603 0 -3604 0 -3605 0 -3606 0 -3607 0 -3608 0 -3609 1 -3610 0 -3611 0 -3612 0 -3613 0 -3614 0 -3615 0 -3616 0 -3617 0 -3618 0 -3619 0 -3620 1 -3621 0 -3622 0 -3623 0 -3624 0 -3625 0 -3626 0 -3627 0 -3628 0 -3629 0 -3630 1 -3631 0 -3632 0 -3633 0 -3634 0 -3635 0 -3636 0 -3637 0 -3638 0 -3639 1 -3640 0 -3641 0 -3642 0 -3643 0 -3644 0 -3645 1 -3646 0 -3647 0 -3648 0 -3649 0 -3650 0 -3651 1 -3652 0 -3653 0 -3654 0 -3655 0 -3656 0 -3657 0 -3658 1 -3659 0 -3660 0 -3661 0 -3662 0 -3663 0 -3664 0 -3665 0 -3666 1 -3667 0 -3668 0 -3669 0 -3670 0 -3671 0 -3672 0 -3673 0 -3674 0 -3675 0 -3676 1 -3677 0 -3678 0 -3679 0 -3680 0 -3681 0 -3682 0 -3683 0 -3684 0 -3685 1 -3686 0 -3687 0 -3688 0 -3689 0 -3690 0 -3691 0 -3692 0 -3693 0 -3694 0 -3695 1 -3696 0 -3697 0 -3698 0 -3699 0 -3700 0 -3701 0 -3702 0 -3703 0 -3704 0 -3705 0 -3706 1 -3707 0 -3708 0 -3709 0 -3710 0 -3711 0 -3712 0 -3713 0 -3714 0 -3715 0 -3716 1 -3717 0 -3718 0 -3719 0 -3720 0 -3721 0 -3722 0 -3723 0 -3724 0 -3725 0 -3726 0 -3727 0 -3728 0 -3729 0 -3730 0 -3731 0 -3732 0 -3733 0 -3734 0 -3735 0 -3736 1 -3737 0 -3738 0 -3739 0 -3740 0 -3741 0 -3742 0 -3743 0 -3744 0 -3745 0 -3746 1 -3747 0 -3748 0 -3749 0 -3750 0 -3751 0 -3752 0 -3753 0 -3754 0 -3755 0 -3756 1 -3757 0 -3758 0 -3759 0 -3760 0 -3761 0 -3762 0 -3763 1 -3764 0 -3765 0 -3766 0 -3767 0 -3768 0 -3769 0 -3770 0 -3771 1 -3772 0 -3773 0 -3774 0 -3775 0 -3776 0 -3777 0 -3778 1 -3779 0 -3780 0 -3781 0 -3782 0 -3783 0 -3784 0 -3785 0 -3786 0 -3787 0 -3788 0 -3789 0 -3790 0 -3791 0 -3792 0 -3793 0 -3794 0 -3795 0 -3796 0 -3797 1 -3798 0 -3799 0 -3800 0 -3801 0 -3802 0 -3803 0 -3804 0 -3805 0 -3806 1 -3807 0 -3808 0 -3809 0 -3810 0 -3811 0 -3812 0 -3813 0 -3814 0 -3815 0 -3816 0 -3817 1 -3818 0 -3819 0 -3820 0 -3821 0 -3822 0 -3823 0 -3824 0 -3825 0 -3826 0 -3827 1 -3828 0 -3829 1 -3830 0 -3831 0 -3832 0 -3833 0 -3834 1 -3835 0 -3836 0 -3837 0 -3838 0 -3839 0 -3840 0 -3841 0 -3842 0 -3843 0 -3844 0 -3845 1 -3846 0 -3847 0 -3848 0 -3849 0 -3850 0 -3851 0 -3852 0 -3853 0 -3854 0 -3855 1 -3856 0 -3857 0 -3858 0 -3859 0 -3860 0 -3861 0 -3862 0 -3863 1 -3864 0 -3865 0 -3866 0 -3867 0 -3868 0 -3869 0 -3870 0 -3871 0 -3872 0 -3873 1 -3874 0 -3875 0 -3876 0 -3877 0 -3878 0 -3879 0 -3880 0 -3881 0 -3882 0 -3883 1 -3884 0 -3885 0 -3886 0 -3887 0 -3888 0 -3889 0 -3890 0 -3891 0 -3892 0 -3893 0 -3894 1 -3895 0 -3896 0 -3897 0 -3898 0 -3899 0 -3900 0 -3901 0 -3902 0 -3903 0 -3904 0 -3905 1 -3906 0 -3907 0 -3908 0 -3909 0 -3910 0 -3911 0 -3912 0 -3913 0 -3914 1 -3915 0 -3916 0 -3917 0 -3918 0 -3919 0 -3920 0 -3921 0 -3922 0 -3923 0 -3924 0 -3925 1 -3926 0 -3927 0 -3928 0 -3929 0 -3930 0 -3931 0 -3932 0 -3933 0 -3934 1 -3935 0 -3936 0 -3937 0 -3938 0 -3939 0 -3940 0 -3941 0 -3942 0 -3943 0 -3944 0 -3945 1 -3946 0 -3947 0 -3948 0 -3949 0 -3950 0 -3951 0 -3952 0 -3953 0 -3954 0 -3955 1 -3956 0 -3957 0 -3958 0 -3959 0 -3960 0 -3961 0 -3962 0 -3963 0 -3964 0 -3965 0 -3966 1 -3967 0 -3968 0 -3969 0 -3970 0 -3971 0 -3972 0 -3973 0 -3974 0 -3975 1 -3976 0 -3977 0 -3978 0 -3979 0 -3980 0 -3981 0 -3982 0 -3983 0 -3984 1 -3985 0 -3986 0 -3987 0 -3988 0 -3989 0 -3990 0 -3991 0 -3992 0 -3993 0 -3994 1 -3995 0 -3996 0 -3997 0 -3998 0 -3999 0 -4000 0 -4001 0 -4002 0 -4003 0 -4004 0 -4005 0 -4006 0 -4007 0 -4008 0 -4009 0 -4010 0 -4011 0 -4012 0 -4013 0 -4014 1 -4015 0 -4016 0 -4017 0 -4018 0 -4019 0 -4020 0 -4021 0 -4022 0 -4023 0 -4024 1 -4025 0 -4026 0 -4027 0 -4028 0 -4029 0 -4030 0 -4031 0 -4032 0 -4033 0 -4034 0 -4035 1 -4036 0 -4037 0 -4038 0 -4039 0 -4040 0 -4041 0 -4042 0 -4043 0 -4044 0 -4045 1 -4046 0 -4047 0 -4048 0 -4049 0 -4050 0 -4051 0 -4052 0 -4053 0 -4054 0 -4055 0 -4056 1 -4057 0 -4058 0 -4059 0 -4060 0 -4061 0 -4062 0 -4063 0 -4064 0 -4065 0 -4066 1 -4067 0 -4068 0 -4069 0 -4070 0 -4071 0 -4072 0 -4073 0 -4074 1 -4075 0 -4076 0 -4077 0 -4078 0 -4079 0 -4080 0 -4081 0 -4082 0 -4083 0 -4084 1 -4085 0 -4086 0 -4087 0 -4088 0 -4089 0 -4090 0 -4091 0 -4092 0 -4093 1 -4094 0 -4095 0 -4096 0 -4097 0 -4098 0 -4099 0 -4100 0 -4101 0 -4102 1 -4103 0 -4104 0 -4105 0 -4106 0 -4107 0 -4108 0 -4109 0 -4110 0 -4111 0 -4112 1 -4113 0 -4114 0 -4115 0 -4116 0 -4117 0 -4118 0 -4119 0 -4120 0 -4121 0 -4122 1 -4123 0 -4124 0 -4125 0 -4126 0 -4127 0 -4128 0 -4129 0 -4130 0 -4131 0 -4132 0 -4133 1 -4134 0 -4135 0 -4136 0 -4137 0 -4138 0 -4139 0 -4140 0 -4141 0 -4142 0 -4143 0 -4144 1 -4145 0 -4146 0 -4147 0 -4148 0 -4149 0 -4150 0 -4151 0 -4152 0 -4153 0 -4154 1 -4155 0 -4156 0 -4157 0 -4158 0 -4159 0 -4160 0 -4161 0 -4162 0 -4163 0 -4164 0 -4165 1 -4166 0 -4167 0 -4168 0 -4169 0 -4170 0 -4171 0 -4172 0 -4173 0 -4174 0 -4175 0 -4176 1 -4177 0 -4178 0 -4179 0 -4180 0 -4181 0 -4182 0 -4183 0 -4184 0 -4185 1 -4186 0 -4187 0 -4188 0 -4189 0 -4190 0 -4191 0 -4192 0 -4193 0 -4194 0 -4195 1 -4196 0 -4197 0 -4198 0 -4199 0 -4200 0 -4201 0 -4202 0 -4203 0 -4204 0 -4205 0 -4206 0 -4207 0 -4208 0 -4209 0 -4210 0 -4211 0 -4212 1 -4213 0 -4214 0 -4215 0 -4216 0 -4217 0 -4218 0 -4219 0 -4220 0 -4221 1 -4222 0 -4223 0 -4224 0 -4225 0 -4226 0 -4227 0 -4228 0 -4229 0 -4230 1 -4231 0 -4232 0 -4233 0 -4234 0 -4235 0 -4236 0 -4237 0 -4238 0 -4239 1 -4240 0 -4241 0 -4242 0 -4243 0 -4244 0 -4245 0 -4246 0 -4247 0 -4248 0 -4249 1 -4250 0 -4251 0 -4252 0 -4253 0 -4254 0 -4255 0 -4256 0 -4257 0 -4258 1 -4259 0 -4260 0 -4261 0 -4262 0 -4263 0 -4264 0 -4265 0 -4266 0 -4267 0 -4268 1 -4269 0 -4270 0 -4271 0 -4272 0 -4273 0 -4274 0 -4275 0 -4276 0 -4277 0 -4278 1 -4279 0 -4280 0 -4281 0 -4282 0 -4283 0 -4284 0 -4285 0 -4286 0 -4287 0 -4288 0 -4289 1 -4290 0 -4291 0 -4292 0 -4293 0 -4294 0 -4295 0 -4296 0 -4297 0 -4298 0 -4299 1 -4300 0 -4301 0 -4302 0 -4303 0 -4304 0 -4305 0 -4306 0 -4307 0 -4308 0 -4309 1 -4310 0 -4311 0 -4312 0 -4313 0 -4314 0 -4315 0 -4316 0 -4317 0 -4318 1 -4319 0 -4320 0 -4321 0 -4322 0 -4323 0 -4324 0 -4325 0 -4326 0 -4327 1 -4328 0 -4329 0 -4330 0 -4331 0 -4332 0 -4333 0 -4334 0 -4335 0 -4336 0 -4337 1 -4338 0 -4339 0 -4340 0 -4341 0 -4342 0 -4343 0 -4344 0 -4345 0 -4346 0 -4347 1 -4348 0 -4349 0 -4350 0 -4351 0 -4352 0 -4353 0 -4354 0 -4355 1 -4356 0 -4357 0 -4358 0 -4359 0 -4360 0 -4361 0 -4362 0 -4363 0 -4364 0 -4365 0 -4366 0 -4367 0 -4368 0 -4369 0 -4370 0 -4371 0 -4372 0 -4373 0 -4374 1 -4375 0 -4376 0 -4377 0 -4378 0 -4379 0 -4380 0 -4381 0 -4382 0 -4383 0 -4384 1 -4385 0 -4386 0 -4387 0 -4388 0 -4389 0 -4390 0 -4391 0 -4392 0 -4393 1 -4394 0 -4395 0 -4396 0 -4397 0 -4398 0 -4399 0 -4400 0 -4401 0 -4402 0 -4403 1 -4404 0 -4405 0 -4406 0 -4407 0 -4408 0 -4409 0 -4410 0 -4411 0 -4412 1 -4413 0 -4414 0 -4415 0 -4416 0 -4417 0 -4418 0 -4419 0 -4420 0 -4421 0 -4422 0 -4423 1 -4424 0 -4425 0 -4426 0 -4427 0 -4428 0 -4429 0 -4430 2 -4431 0 -4432 0 -4433 0 -4434 0 -4435 0 -4436 0 -4437 1 -4438 0 -4439 0 -4440 0 -4441 0 -4442 0 -4443 0 -4444 0 -4445 1 -4446 0 -4447 0 -4448 0 -4449 0 -4450 0 -4451 0 -4452 0 -4453 0 -4454 1 -4455 0 -4456 0 -4457 0 -4458 0 -4459 0 -4460 0 -4461 0 -4462 1 -4463 0 -4464 0 -4465 0 -4466 0 -4467 0 -4468 0 -4469 0 -4470 0 -4471 1 -4472 0 -4473 0 -4474 0 -4475 0 -4476 0 -4477 0 -4478 0 -4479 0 -4480 1 -4481 0 -4482 0 -4483 0 -4484 0 -4485 0 -4486 0 -4487 0 -4488 1 -4489 0 -4490 0 -4491 0 -4492 0 -4493 0 -4494 0 -4495 0 -4496 0 -4497 1 -4498 0 -4499 0 -4500 0 -4501 0 -4502 0 -4503 0 -4504 0 -4505 1 -4506 0 -4507 0 -4508 0 -4509 0 -4510 0 -4511 0 -4512 0 -4513 1 -4514 0 -4515 0 -4516 0 -4517 0 -4518 0 -4519 0 -4520 1 -4521 0 -4522 0 -4523 0 -4524 0 -4525 0 -4526 0 -4527 0 -4528 0 -4529 1 -4530 0 -4531 0 -4532 0 -4533 0 -4534 0 -4535 0 -4536 0 -4537 0 -4538 1 -4539 0 -4540 0 -4541 0 -4542 0 -4543 0 -4544 0 -4545 0 -4546 1 -4547 0 -4548 0 -4549 0 -4550 0 -4551 0 -4552 1 -4553 0 -4554 0 -4555 0 -4556 0 -4557 0 -4558 0 -4559 1 -4560 0 -4561 0 -4562 0 -4563 0 -4564 0 -4565 0 -4566 0 -4567 1 -4568 0 -4569 0 -4570 0 -4571 0 -4572 0 -4573 0 -4574 0 -4575 1 -4576 0 -4577 0 -4578 0 -4579 0 -4580 0 -4581 0 -4582 0 -4583 1 -4584 0 -4585 0 -4586 0 -4587 0 -4588 0 -4589 0 -4590 0 -4591 1 -4592 0 -4593 0 -4594 0 -4595 0 -4596 0 -4597 0 -4598 0 -4599 0 -4600 1 -4601 0 -4602 0 -4603 0 -4604 0 -4605 0 -4606 0 -4607 1 -4608 0 -4609 0 -4610 0 -4611 0 -4612 0 -4613 0 -4614 0 -4615 0 -4616 1 -4617 0 -4618 0 -4619 0 -4620 0 -4621 0 -4622 0 -4623 0 -4624 0 -4625 1 -4626 0 -4627 0 -4628 0 -4629 0 -4630 0 -4631 0 -4632 0 -4633 0 -4634 1 -4635 0 -4636 0 -4637 0 -4638 0 -4639 0 -4640 0 -4641 0 -4642 0 -4643 0 -4644 0 -4645 0 -4646 0 -4647 0 -4648 0 -4649 0 -4650 0 -4651 0 -4652 1 -4653 0 -4654 0 -4655 0 -4656 0 -4657 0 -4658 0 -4659 0 -4660 0 -4661 1 -4662 0 -4663 0 -4664 0 -4665 1 -4666 0 -4667 0 -4668 0 -4669 0 -4670 0 -4671 0 -4672 1 -4673 0 -4674 0 -4675 0 -4676 0 -4677 0 -4678 1 -4679 0 -4680 0 -4681 0 -4682 0 -4683 0 -4684 0 -4685 0 -4686 1 -4687 0 -4688 0 -4689 0 -4690 0 -4691 0 -4692 0 -4693 0 -4694 1 -4695 0 -4696 0 -4697 0 -4698 0 -4699 0 -4700 0 -4701 0 -4702 1 -4703 0 -4704 0 -4705 0 -4706 0 -4707 0 -4708 0 -4709 1 -4710 0 -4711 0 -4712 0 -4713 0 -4714 0 -4715 0 -4716 0 -4717 1 -4718 0 -4719 0 -4720 0 -4721 0 -4722 0 -4723 0 -4724 0 -4725 1 -4726 0 -4727 0 -4728 0 -4729 0 -4730 0 -4731 0 -4732 0 -4733 0 -4734 1 -4735 0 -4736 0 -4737 0 -4738 0 -4739 0 -4740 0 -4741 0 -4742 0 -4743 0 -4744 1 -4745 0 -4746 0 -4747 0 -4748 0 -4749 0 -4750 0 -4751 0 -4752 1 -4753 0 -4754 0 -4755 0 -4756 0 -4757 0 -4758 0 -4759 0 -4760 1 -4761 0 -4762 0 -4763 0 -4764 0 -4765 0 -4766 0 -4767 0 -4768 0 -4769 1 -4770 0 -4771 0 -4772 0 -4773 0 -4774 0 -4775 0 -4776 0 -4777 0 -4778 1 -4779 0 -4780 0 -4781 0 -4782 0 -4783 0 -4784 0 -4785 0 -4786 1 -4787 0 -4788 0 -4789 0 -4790 0 -4791 0 -4792 0 -4793 0 -4794 0 -4795 0 -4796 1 -4797 0 -4798 0 -4799 0 -4800 0 -4801 0 -4802 0 -4803 0 -4804 1 -4805 0 -4806 0 -4807 0 -4808 0 -4809 0 -4810 0 -4811 0 -4812 0 -4813 1 -4814 0 -4815 0 -4816 0 -4817 0 -4818 0 -4819 0 -4820 0 -4821 0 -4822 1 -4823 0 -4824 0 -4825 0 -4826 0 -4827 0 -4828 0 -4829 0 -4830 0 -4831 1 -4832 0 -4833 0 -4834 0 -4835 0 -4836 0 -4837 0 -4838 0 -4839 0 -4840 0 -4841 0 -4842 0 -4843 0 -4844 0 -4845 0 -4846 0 -4847 0 -4848 0 -4849 0 -4850 0 -4851 0 -4852 0 -4853 0 -4854 0 -4855 0 -4856 0 -4857 0 -4858 0 -4859 0 -4860 0 -4861 0 -4862 0 -4863 0 -4864 0 -4865 1 -4866 0 -4867 0 -4868 0 -4869 0 -4870 0 -4871 0 -4872 1 -4873 0 -4874 0 -4875 0 -4876 0 -4877 0 -4878 0 -4879 0 -4880 1 -4881 0 -4882 0 -4883 0 -4884 0 -4885 0 -4886 0 -4887 0 -4888 0 -4889 0 -4890 1 -4891 0 -4892 0 -4893 0 -4894 0 -4895 0 -4896 0 -4897 0 -4898 1 -4899 0 -4900 0 -4901 0 -4902 0 -4903 0 -4904 0 -4905 1 -4906 0 -4907 0 -4908 0 -4909 0 -4910 0 -4911 0 -4912 0 -4913 1 -4914 0 -4915 0 -4916 0 -4917 0 -4918 0 -4919 0 -4920 0 -4921 0 -4922 0 -4923 1 -4924 0 -4925 0 -4926 0 -4927 0 -4928 0 -4929 0 -4930 0 -4931 0 -4932 0 -4933 1 -4934 0 -4935 0 -4936 0 -4937 0 -4938 0 -4939 0 -4940 0 -4941 0 -4942 0 -4943 0 -4944 0 -4945 0 -4946 0 -4947 0 -4948 1 -4949 0 -4950 0 -4951 0 -4952 0 -4953 0 -4954 0 -4955 0 -4956 1 -4957 0 -4958 0 -4959 0 -4960 0 -4961 0 -4962 0 -4963 0 -4964 1 -4965 0 -4966 0 -4967 0 -4968 0 -4969 0 -4970 0 -4971 0 -4972 1 -4973 0 -4974 0 -4975 0 -4976 0 -4977 0 -4978 0 -4979 1 -4980 0 -4981 0 -4982 0 -4983 0 -4984 0 -4985 0 -4986 0 -4987 1 -4988 0 -4989 0 -4990 0 -4991 0 -4992 0 -4993 0 -4994 1 -4995 0 -4996 0 -4997 0 -4998 0 -4999 0 -5000 0 -5001 0 -5002 0 -5003 1 -5004 0 -5005 0 -5006 0 -5007 0 -5008 0 -5009 0 -5010 0 -5011 0 -5012 1 -5013 0 -5014 0 -5015 0 -5016 0 -5017 0 -5018 0 -5019 0 -5020 1 -5021 0 -5022 0 -5023 0 -5024 0 -5025 0 -5026 0 -5027 0 -5028 0 -5029 1 -5030 0 -5031 0 -5032 0 -5033 0 -5034 0 -5035 0 -5036 0 -5037 1 -5038 0 -5039 0 -5040 0 -5041 0 -5042 0 -5043 0 -5044 0 -5045 1 -5046 0 -5047 0 -5048 0 -5049 0 -5050 0 -5051 0 -5052 0 -5053 1 -5054 0 -5055 0 -5056 0 -5057 0 -5058 0 -5059 0 -5060 0 -5061 0 -5062 1 -5063 0 -5064 0 -5065 0 -5066 0 -5067 0 -5068 0 -5069 0 -5070 0 -5071 0 -5072 0 -5073 0 -5074 0 -5075 0 -5076 0 -5077 0 -5078 0 -5079 1 -5080 0 -5081 0 -5082 0 -5083 0 -5084 0 -5085 0 -5086 1 -5087 0 -5088 0 -5089 0 -5090 0 -5091 0 -5092 0 -5093 0 -5094 1 -5095 0 -5096 0 -5097 0 -5098 0 -5099 0 -5100 0 -5101 0 -5102 0 -5103 1 -5104 0 -5105 0 -5106 0 -5107 0 -5108 0 -5109 0 -5110 1 -5111 0 -5112 0 -5113 0 -5114 0 -5115 0 -5116 0 -5117 0 -5118 1 -5119 0 -5120 0 -5121 0 -5122 0 -5123 0 -5124 0 -5125 0 -5126 0 -5127 1 -5128 0 -5129 0 -5130 0 -5131 0 -5132 0 -5133 0 -5134 1 -5135 0 -5136 0 -5137 0 -5138 0 -5139 0 -5140 0 -5141 1 -5142 0 -5143 0 -5144 0 -5145 0 -5146 0 -5147 0 -5148 0 -5149 1 -5150 0 -5151 0 -5152 0 -5153 0 -5154 0 -5155 0 -5156 0 -5157 0 -5158 1 -5159 0 -5160 0 -5161 0 -5162 0 -5163 0 -5164 0 -5165 0 -5166 0 -5167 1 -5168 0 -5169 0 -5170 0 -5171 0 -5172 0 -5173 0 -5174 0 -5175 1 -5176 0 -5177 0 -5178 0 -5179 0 -5180 0 -5181 0 -5182 1 -5183 0 -5184 0 -5185 0 -5186 0 -5187 0 -5188 0 -5189 0 -5190 1 -5191 0 -5192 0 -5193 0 -5194 0 -5195 0 -5196 0 -5197 0 -5198 0 -5199 1 -5200 0 -5201 0 -5202 0 -5203 0 -5204 0 -5205 0 -5206 0 -5207 0 -5208 1 -5209 0 -5210 0 -5211 0 -5212 0 -5213 0 -5214 0 -5215 0 -5216 0 -5217 0 -5218 1 -5219 0 -5220 0 -5221 0 -5222 0 -5223 0 -5224 0 -5225 0 -5226 1 -5227 0 -5228 0 -5229 0 -5230 0 -5231 0 -5232 0 -5233 0 -5234 1 -5235 0 -5236 0 -5237 0 -5238 0 -5239 0 -5240 0 -5241 0 -5242 1 -5243 0 -5244 0 -5245 0 -5246 0 -5247 0 -5248 0 -5249 0 -5250 0 -5251 1 -5252 0 -5253 0 -5254 0 -5255 0 -5256 0 -5257 0 -5258 0 -5259 0 -5260 0 -5261 0 -5262 0 -5263 0 -5264 0 -5265 0 -5266 0 -5267 0 -5268 1 -5269 0 -5270 0 -5271 0 -5272 0 -5273 0 -5274 0 -5275 0 -5276 1 -5277 0 -5278 0 -5279 0 -5280 0 -5281 0 -5282 0 -5283 1 -5284 0 -5285 0 -5286 0 -5287 0 -5288 0 -5289 0 -5290 0 -5291 0 -5292 0 -5293 1 -5294 0 -5295 0 -5296 0 -5297 0 -5298 0 -5299 0 -5300 0 -5301 1 -5302 0 -5303 0 -5304 0 -5305 0 -5306 0 -5307 0 -5308 0 -5309 0 -5310 1 -5311 0 -5312 0 -5313 0 -5314 0 -5315 0 -5316 0 -5317 0 -5318 1 -5319 0 -5320 0 -5321 0 -5322 0 -5323 0 -5324 0 -5325 1 -5326 0 -5327 0 -5328 0 -5329 0 -5330 0 -5331 0 -5332 0 -5333 0 -5334 0 -5335 0 -5336 0 -5337 0 -5338 0 -5339 0 -5340 0 -5341 0 -5342 1 -5343 0 -5344 0 -5345 0 -5346 0 -5347 0 -5348 0 -5349 1 -5350 0 -5351 0 -5352 0 -5353 0 -5354 0 -5355 0 -5356 0 -5357 0 -5358 1 -5359 0 -5360 0 -5361 0 -5362 0 -5363 0 -5364 0 -5365 0 -5366 1 -5367 0 -5368 0 -5369 0 -5370 0 -5371 0 -5372 0 -5373 1 -5374 0 -5375 0 -5376 0 -5377 0 -5378 0 -5379 0 -5380 0 -5381 1 -5382 0 -5383 0 -5384 0 -5385 0 -5386 0 -5387 0 -5388 0 -5389 0 -5390 1 -5391 0 -5392 0 -5393 0 -5394 0 -5395 0 -5396 0 -5397 0 -5398 1 -5399 0 -5400 0 -5401 0 -5402 0 -5403 0 -5404 0 -5405 0 -5406 1 -5407 0 -5408 0 -5409 0 -5410 0 -5411 0 -5412 0 -5413 0 -5414 1 -5415 0 -5416 0 -5417 0 -5418 0 -5419 0 -5420 0 -5421 0 -5422 1 -5423 0 -5424 0 -5425 0 -5426 0 -5427 0 -5428 0 -5429 0 -5430 0 -5431 0 -5432 0 -5433 0 -5434 0 -5435 0 -5436 0 -5437 0 -5438 1 -5439 0 -5440 0 -5441 0 -5442 0 -5443 0 -5444 0 -5445 0 -5446 0 -5447 1 -5448 0 -5449 0 -5450 0 -5451 0 -5452 0 -5453 0 -5454 0 -5455 0 -5456 1 -5457 0 -5458 0 -5459 0 -5460 0 -5461 0 -5462 0 -5463 0 -5464 1 -5465 0 -5466 0 -5467 0 -5468 0 -5469 0 -5470 0 -5471 0 -5472 1 -5473 0 -5474 0 -5475 0 -5476 0 -5477 0 -5478 0 -5479 0 -5480 0 -5481 1 -5482 0 -5483 0 -5484 0 -5485 0 -5486 0 -5487 0 -5488 0 -5489 1 -5490 0 -5491 0 -5492 0 -5493 0 -5494 0 -5495 0 -5496 0 -5497 0 -5498 1 -5499 0 -5500 0 -5501 0 -5502 0 -5503 0 -5504 0 -5505 0 -5506 1 -5507 0 -5508 0 -5509 0 -5510 0 -5511 0 -5512 0 -5513 0 -5514 1 -5515 0 -5516 0 -5517 0 -5518 0 -5519 0 -5520 0 -5521 0 -5522 0 -5523 1 -5524 0 -5525 0 -5526 0 -5527 0 -5528 0 -5529 0 -5530 0 -5531 1 -5532 0 -5533 0 -5534 0 -5535 0 -5536 0 -5537 0 -5538 0 -5539 0 -5540 1 -5541 0 -5542 0 -5543 0 -5544 0 -5545 0 -5546 0 -5547 0 -5548 0 -5549 1 -5550 0 -5551 0 -5552 0 -5553 0 -5554 0 -5555 0 -5556 0 -5557 0 -5558 0 -5559 0 -5560 0 -5561 0 -5562 0 -5563 0 -5564 0 -5565 1 -5566 0 -5567 0 -5568 0 -5569 0 -5570 0 -5571 1 -5572 0 -5573 0 -5574 0 -5575 0 -5576 0 -5577 0 -5578 0 -5579 1 -5580 0 -5581 0 -5582 0 -5583 0 -5584 0 -5585 0 -5586 0 -5587 0 -5588 1 -5589 0 -5590 0 -5591 0 -5592 0 -5593 0 -5594 0 -5595 0 -5596 1 -5597 0 -5598 0 -5599 0 -5600 0 -5601 0 -5602 0 -5603 0 -5604 0 -5605 0 -5606 1 -5607 0 -5608 0 -5609 0 -5610 0 -5611 0 -5612 0 -5613 0 -5614 1 -5615 0 -5616 0 -5617 0 -5618 0 -5619 0 -5620 0 -5621 0 -5622 1 -5623 0 -5624 0 -5625 0 -5626 0 -5627 0 -5628 0 -5629 0 -5630 0 -5631 0 -5632 0 -5633 0 -5634 0 -5635 0 -5636 0 -5637 0 -5638 1 -5639 0 -5640 0 -5641 0 -5642 0 -5643 0 -5644 0 -5645 0 -5646 0 -5647 1 -5648 0 -5649 0 -5650 0 -5651 0 -5652 0 -5653 0 -5654 1 -5655 0 -5656 0 -5657 0 -5658 0 -5659 0 -5660 0 -5661 0 -5662 1 -5663 0 -5664 0 -5665 0 -5666 0 -5667 0 -5668 0 -5669 0 -5670 1 -5671 0 -5672 0 -5673 0 -5674 0 -5675 0 -5676 0 -5677 0 -5678 0 -5679 1 -5680 2 -5681 1 -5682 0 -5683 0 -5684 0 -5685 0 -5686 0 -5687 1 -5688 0 -5689 0 -5690 0 -5691 0 -5692 1 -5693 0 -5694 0 -5695 0 -5696 0 -5697 1 -5698 0 -5699 0 -5700 0 -5701 0 -5702 0 -5703 0 -5704 0 -5705 1 -5706 0 -5707 0 -5708 0 -5709 0 -5710 0 -5711 1 -5712 0 -5713 0 -5714 0 -5715 0 -5716 0 -5717 0 -5718 0 -5719 0 -5720 0 -5721 0 -5722 0 -5723 0 -5724 0 -5725 0 -5726 1 -5727 0 -5728 0 -5729 0 -5730 0 -5731 0 -5732 0 -5733 0 -5734 1 -5735 0 -5736 0 -5737 0 -5738 0 -5739 0 -5740 0 -5741 0 -5742 1 -5743 0 -5744 0 -5745 0 -5746 0 -5747 0 -5748 0 -5749 0 -5750 0 -5751 1 -5752 0 -5753 0 -5754 0 -5755 0 -5756 0 -5757 0 -5758 0 -5759 1 -5760 0 -5761 0 -5762 0 -5763 0 -5764 0 -5765 0 -5766 1 -5767 0 -5768 0 -5769 0 -5770 0 -5771 0 -5772 0 -5773 0 -5774 1 -5775 0 -5776 0 -5777 0 -5778 0 -5779 0 -5780 0 -5781 0 -5782 1 -5783 0 -5784 0 -5785 0 -5786 0 -5787 0 -5788 0 -5789 0 -5790 0 -5791 1 -5792 0 -5793 0 -5794 0 -5795 0 -5796 0 -5797 0 -5798 0 -5799 0 -5800 1 -5801 0 -5802 0 -5803 0 -5804 0 -5805 0 -5806 0 -5807 0 -5808 0 -5809 1 -5810 0 -5811 0 -5812 0 -5813 0 -5814 0 -5815 0 -5816 1 -5817 0 -5818 0 -5819 0 -5820 0 -5821 0 -5822 0 -5823 0 -5824 0 -5825 1 -5826 0 -5827 0 -5828 0 -5829 0 -5830 0 -5831 0 -5832 0 -5833 0 -5834 1 -5835 0 -5836 0 -5837 0 -5838 0 -5839 0 -5840 0 -5841 0 -5842 1 -5843 0 -5844 0 -5845 0 -5846 0 -5847 0 -5848 0 -5849 0 -5850 1 -5851 0 -5852 0 -5853 0 -5854 0 -5855 0 -5856 0 -5857 0 -5858 1 -5859 0 -5860 0 -5861 0 -5862 0 -5863 0 -5864 0 -5865 0 -5866 0 -5867 1 -5868 0 -5869 0 -5870 0 -5871 0 -5872 0 -5873 0 -5874 0 -5875 1 -5876 0 -5877 0 -5878 0 -5879 0 -5880 0 -5881 0 -5882 0 -5883 0 -5884 1 -5885 0 -5886 0 -5887 0 -5888 0 -5889 0 -5890 0 -5891 1 -5892 0 -5893 0 -5894 0 -5895 0 -5896 0 -5897 0 -5898 0 -5899 0 -5900 1 -5901 0 -5902 0 -5903 0 -5904 0 -5905 0 -5906 0 -5907 0 -5908 0 -5909 1 -5910 0 -5911 0 -5912 0 -5913 0 -5914 0 -5915 0 -5916 0 -5917 1 -5918 0 -5919 0 -5920 0 -5921 0 -5922 0 -5923 0 -5924 0 -5925 0 -5926 1 -5927 0 -5928 0 -5929 0 -5930 0 -5931 0 -5932 0 -5933 0 -5934 1 -5935 0 -5936 0 -5937 0 -5938 0 -5939 0 -5940 0 -5941 0 -5942 0 -5943 0 -5944 1 -5945 0 -5946 0 -5947 0 -5948 0 -5949 0 -5950 0 -5951 0 -5952 0 -5953 0 -5954 0 -5955 0 -5956 0 -5957 0 -5958 0 -5959 0 -5960 0 -5961 0 -5962 0 -5963 0 -5964 0 -5965 0 -5966 0 -5967 0 -5968 0 -5969 0 -5970 1 -5971 0 -5972 0 -5973 0 -5974 0 -5975 0 -5976 0 -5977 0 -5978 1 -5979 0 -5980 0 -5981 0 -5982 0 -5983 0 -5984 0 -5985 0 -5986 0 -5987 1 -5988 0 -5989 0 -5990 0 -5991 0 -5992 0 -5993 0 -5994 0 -5995 0 -5996 1 -5997 0 -5998 0 -5999 0 -6000 0 -6001 0 -6002 0 -6003 0 -6004 0 -6005 0 -6006 1 -6007 0 -6008 0 -6009 0 -6010 0 -6011 0 -6012 0 -6013 0 -6014 1 -6015 0 -6016 0 -6017 0 -6018 0 -6019 0 -6020 0 -6021 0 -6022 0 -6023 1 -6024 0 -6025 0 -6026 0 -6027 0 -6028 0 -6029 0 -6030 0 -6031 1 -6032 0 -6033 0 -6034 0 -6035 0 -6036 0 -6037 0 -6038 1 -6039 0 -6040 0 -6041 0 -6042 0 -6043 0 -6044 0 -6045 0 -6046 0 -6047 0 -6048 1 -6049 0 -6050 0 -6051 0 -6052 0 -6053 0 -6054 0 -6055 1 -6056 0 -6057 0 -6058 0 -6059 0 -6060 0 -6061 1 -6062 0 -6063 0 -6064 0 -6065 0 -6066 0 -6067 0 -6068 1 -6069 0 -6070 0 -6071 0 -6072 0 -6073 0 -6074 0 -6075 0 -6076 1 -6077 0 -6078 0 -6079 0 -6080 0 -6081 0 -6082 0 -6083 0 -6084 0 -6085 1 -6086 0 -6087 0 -6088 0 -6089 0 -6090 0 -6091 0 -6092 0 -6093 0 -6094 0 -6095 1 -6096 0 -6097 0 -6098 0 -6099 0 -6100 0 -6101 0 -6102 0 -6103 0 -6104 1 -6105 0 -6106 0 -6107 0 -6108 0 -6109 0 -6110 0 -6111 0 -6112 1 -6113 0 -6114 0 -6115 0 -6116 0 -6117 0 -6118 0 -6119 0 -6120 0 -6121 0 -6122 0 -6123 0 -6124 0 -6125 1 -6126 0 -6127 0 -6128 0 -6129 0 -6130 0 -6131 0 -6132 0 -6133 0 -6134 0 -6135 0 -6136 0 -6137 0 -6138 0 -6139 0 -6140 0 -6141 0 -6142 1 -6143 0 -6144 0 -6145 0 -6146 0 -6147 0 -6148 0 -6149 0 -6150 1 -6151 0 -6152 0 -6153 0 -6154 0 -6155 0 -6156 0 -6157 0 -6158 0 -6159 1 -6160 0 -6161 0 -6162 0 -6163 0 -6164 0 -6165 0 -6166 0 -6167 1 -6168 0 -6169 0 -6170 0 -6171 0 -6172 0 -6173 0 -6174 0 -6175 1 -6176 0 -6177 0 -6178 0 -6179 0 -6180 0 -6181 0 -6182 0 -6183 1 -6184 0 -6185 0 -6186 0 -6187 0 -6188 0 -6189 0 -6190 0 -6191 0 -6192 1 -6193 0 -6194 0 -6195 0 -6196 0 -6197 0 -6198 0 -6199 0 -6200 0 -6201 1 -6202 0 -6203 0 -6204 0 -6205 0 -6206 0 -6207 0 -6208 0 -6209 0 -6210 1 -6211 0 -6212 0 -6213 0 -6214 0 -6215 0 -6216 0 -6217 1 -6218 0 -6219 0 -6220 0 -6221 0 -6222 0 -6223 0 -6224 0 -6225 1 -6226 0 -6227 0 -6228 0 -6229 0 -6230 0 -6231 0 -6232 0 -6233 0 -6234 1 -6235 0 -6236 0 -6237 0 -6238 0 -6239 0 -6240 0 -6241 1 -6242 0 -6243 0 -6244 0 -6245 0 -6246 0 -6247 0 -6248 0 -6249 0 -6250 1 -6251 0 -6252 0 -6253 0 -6254 0 -6255 0 -6256 0 -6257 0 -6258 1 -6259 0 -6260 0 -6261 0 -6262 0 -6263 0 -6264 0 -6265 0 -6266 0 -6267 0 -6268 1 -6269 0 -6270 0 -6271 0 -6272 0 -6273 0 -6274 0 -6275 0 -6276 0 -6277 1 -6278 0 -6279 0 -6280 0 -6281 0 -6282 0 -6283 0 -6284 0 -6285 1 -6286 0 -6287 0 -6288 0 -6289 0 -6290 0 -6291 0 -6292 1 -6293 0 -6294 0 -6295 0 -6296 0 -6297 0 -6298 0 -6299 1 -6300 0 -6301 0 -6302 0 -6303 0 -6304 0 -6305 0 -6306 0 -6307 1 -6308 0 -6309 0 -6310 0 -6311 0 -6312 0 -6313 0 -6314 0 -6315 1 -6316 0 -6317 0 -6318 0 -6319 0 -6320 0 -6321 0 -6322 0 -6323 0 -6324 1 -6325 0 -6326 0 -6327 0 -6328 0 -6329 0 -6330 0 -6331 0 -6332 1 -6333 0 -6334 0 -6335 0 -6336 0 -6337 0 -6338 0 -6339 0 -6340 0 -6341 1 -6342 0 -6343 0 -6344 0 -6345 0 -6346 0 -6347 0 -6348 0 -6349 0 -6350 1 -6351 0 -6352 0 -6353 0 -6354 0 -6355 0 -6356 0 -6357 0 -6358 1 -6359 0 -6360 0 -6361 0 -6362 0 -6363 0 -6364 0 -6365 0 -6366 1 -6367 0 -6368 0 -6369 0 -6370 0 -6371 0 -6372 0 -6373 0 -6374 0 -6375 1 -6376 0 -6377 0 -6378 0 -6379 0 -6380 0 -6381 0 -6382 0 -6383 1 -6384 0 -6385 0 -6386 0 -6387 0 -6388 0 -6389 0 -6390 0 -6391 4 -6392 0 -6393 1 -6394 0 -6395 0 -6396 0 -6397 1 -6398 0 -6399 0 -6400 0 -6401 0 -6402 1 -6403 0 -6404 0 -6405 0 -6406 0 -6407 1 -6408 0 -6409 0 -6410 0 -6411 0 -6412 1 -6413 0 -6414 0 -6415 0 -6416 0 -6417 0 -6418 1 -6419 0 -6420 0 -6421 0 -6422 0 -6423 0 -6424 0 -6425 1 -6426 0 -6427 0 -6428 0 -6429 0 -6430 0 -6431 0 -6432 0 -6433 0 -6434 1 -6435 0 -6436 0 -6437 0 -6438 0 -6439 0 -6440 0 -6441 0 -6442 0 -6443 1 -6444 0 -6445 0 -6446 0 -6447 0 -6448 0 -6449 0 -6450 0 -6451 0 -6452 1 -6453 0 -6454 0 -6455 0 -6456 0 -6457 0 -6458 0 -6459 0 -6460 0 -6461 0 -6462 0 -6463 1 -6464 0 -6465 0 -6466 0 -6467 0 -6468 0 -6469 0 -6470 0 -6471 0 -6472 1 -6473 0 -6474 0 -6475 0 -6476 0 -6477 0 -6478 0 -6479 0 -6480 0 -6481 0 -6482 1 -6483 0 -6484 0 -6485 0 -6486 0 -6487 0 -6488 0 -6489 0 -6490 0 -6491 0 -6492 1 -6493 0 -6494 0 -6495 0 -6496 0 -6497 0 -6498 0 -6499 0 -6500 0 -6501 0 -6502 0 -6503 0 -6504 0 -6505 0 -6506 0 -6507 0 -6508 0 -6509 0 -6510 0 -6511 0 -6512 1 -6513 0 -6514 0 -6515 0 -6516 0 -6517 0 -6518 0 -6519 0 -6520 0 -6521 1 -6522 0 -6523 0 -6524 0 -6525 0 -6526 0 -6527 0 -6528 0 -6529 0 -6530 0 -6531 1 -6532 0 -6533 0 -6534 0 -6535 0 -6536 0 -6537 0 -6538 0 -6539 0 -6540 1 -6541 0 -6542 0 -6543 0 -6544 0 -6545 0 -6546 0 -6547 0 -6548 0 -6549 0 -6550 1 -6551 0 -6552 0 -6553 0 -6554 0 -6555 0 -6556 0 -6557 0 -6558 0 -6559 0 -6560 1 -6561 0 -6562 0 -6563 0 -6564 0 -6565 0 -6566 0 -6567 0 -6568 0 -6569 1 -6570 0 -6571 0 -6572 0 -6573 0 -6574 0 -6575 0 -6576 0 -6577 1 -6578 0 -6579 0 -6580 0 -6581 0 -6582 0 -6583 0 -6584 0 -6585 0 -6586 1 -6587 0 -6588 0 -6589 0 -6590 0 -6591 0 -6592 0 -6593 0 -6594 0 -6595 1 -6596 0 -6597 0 -6598 0 -6599 0 -6600 0 -6601 0 -6602 0 -6603 0 -6604 1 -6605 0 -6606 0 -6607 0 -6608 0 -6609 0 -6610 0 -6611 0 -6612 0 -6613 1 -6614 0 -6615 0 -6616 0 -6617 0 -6618 0 -6619 0 -6620 0 -6621 0 -6622 1 -6623 0 -6624 0 -6625 0 -6626 0 -6627 0 -6628 0 -6629 0 -6630 0 -6631 1 -6632 0 -6633 0 -6634 0 -6635 0 -6636 0 -6637 0 -6638 0 -6639 0 -6640 1 -6641 0 -6642 0 -6643 0 -6644 0 -6645 0 -6646 0 -6647 0 -6648 0 -6649 0 -6650 1 -6651 0 -6652 0 -6653 0 -6654 0 -6655 0 -6656 0 -6657 0 -6658 0 -6659 0 -6660 1 -6661 0 -6662 0 -6663 0 -6664 0 -6665 0 -6666 0 -6667 0 -6668 0 -6669 1 -6670 0 -6671 0 -6672 0 -6673 0 -6674 0 -6675 0 -6676 0 -6677 0 -6678 0 -6679 1 -6680 0 -6681 0 -6682 0 -6683 0 -6684 0 -6685 0 -6686 0 -6687 0 -6688 1 -6689 0 -6690 0 -6691 0 -6692 0 -6693 0 -6694 0 -6695 0 -6696 0 -6697 0 -6698 1 -6699 0 -6700 0 -6701 0 -6702 0 -6703 0 -6704 0 -6705 0 -6706 1 -6707 0 -6708 0 -6709 0 -6710 0 -6711 0 -6712 0 -6713 0 -6714 0 -6715 0 -6716 1 -6717 0 -6718 0 -6719 0 -6720 0 -6721 0 -6722 0 -6723 0 -6724 0 -6725 0 -6726 1 -6727 0 -6728 0 -6729 0 -6730 0 -6731 0 -6732 0 -6733 0 -6734 0 -6735 0 -6736 0 -6737 1 -6738 0 -6739 0 -6740 0 -6741 0 -6742 0 -6743 0 -6744 0 -6745 0 -6746 1 -6747 0 -6748 0 -6749 0 -6750 0 -6751 0 -6752 0 -6753 0 -6754 0 -6755 0 -6756 1 -6757 0 -6758 0 -6759 0 -6760 0 -6761 0 -6762 0 -6763 0 -6764 0 -6765 0 -6766 1 -6767 0 -6768 0 -6769 0 -6770 0 -6771 0 -6772 0 -6773 0 -6774 0 -6775 1 -6776 0 -6777 0 -6778 0 -6779 0 -6780 0 -6781 0 -6782 0 -6783 0 -6784 1 -6785 0 -6786 0 -6787 0 -6788 0 -6789 0 -6790 0 -6791 0 -6792 0 -6793 0 -6794 1 -6795 0 -6796 0 -6797 0 -6798 0 -6799 0 -6800 0 -6801 0 -6802 0 -6803 1 -6804 0 -6805 0 -6806 0 -6807 0 -6808 0 -6809 0 -6810 0 -6811 0 -6812 0 -6813 1 -6814 0 -6815 0 -6816 0 -6817 0 -6818 0 -6819 0 -6820 0 -6821 0 -6822 0 -6823 0 -6824 1 -6825 0 -6826 0 -6827 0 -6828 0 -6829 0 -6830 0 -6831 0 -6832 1 -6833 0 -6834 0 -6835 0 -6836 0 -6837 0 -6838 0 -6839 0 -6840 0 -6841 0 -6842 1 -6843 0 -6844 0 -6845 0 -6846 0 -6847 0 -6848 0 -6849 0 -6850 0 -6851 1 -6852 0 -6853 0 -6854 0 -6855 0 -6856 0 -6857 0 -6858 0 -6859 0 -6860 0 -6861 0 -6862 1 -6863 0 -6864 0 -6865 0 -6866 0 -6867 0 -6868 0 -6869 0 -6870 0 -6871 1 -6872 0 -6873 0 -6874 0 -6875 0 -6876 0 -6877 0 -6878 0 -6879 1 -6880 0 -6881 0 -6882 0 -6883 0 -6884 0 -6885 0 -6886 1 -6887 0 -6888 0 -6889 0 -6890 0 -6891 0 -6892 0 -6893 0 -6894 0 -6895 1 -6896 0 -6897 0 -6898 0 -6899 0 -6900 0 -6901 0 -6902 0 -6903 0 -6904 0 -6905 0 -6906 0 -6907 0 -6908 0 -6909 0 -6910 0 -6911 0 -6912 0 -6913 0 -6914 1 -6915 0 -6916 0 -6917 0 -6918 0 -6919 0 -6920 0 -6921 0 -6922 0 -6923 1 -6924 0 -6925 0 -6926 0 -6927 0 -6928 0 -6929 0 -6930 0 -6931 0 -6932 0 -6933 0 -6934 1 -6935 0 -6936 0 -6937 0 -6938 0 -6939 0 -6940 0 -6941 0 -6942 0 -6943 0 -6944 1 -6945 0 -6946 0 -6947 0 -6948 0 -6949 0 -6950 0 -6951 0 -6952 0 -6953 0 -6954 1 -6955 0 -6956 0 -6957 0 -6958 0 -6959 0 -6960 0 -6961 0 -6962 0 -6963 0 -6964 1 -6965 0 -6966 0 -6967 0 -6968 0 -6969 0 -6970 0 -6971 0 -6972 0 -6973 0 -6974 1 -6975 0 -6976 0 -6977 0 -6978 0 -6979 0 -6980 0 -6981 0 -6982 0 -6983 1 -6984 0 -6985 0 -6986 0 -6987 0 -6988 0 -6989 0 -6990 0 -6991 0 -6992 1 -6993 0 -6994 0 -6995 0 -6996 0 -6997 0 -6998 0 -6999 0 -7000 0 -7001 1 -7002 0 -7003 0 -7004 0 -7005 0 -7006 0 -7007 0 -7008 0 -7009 0 -7010 1 -7011 0 -7012 0 -7013 0 -7014 0 -7015 0 -7016 0 -7017 0 -7018 0 -7019 0 -7020 1 -7021 0 -7022 0 -7023 0 -7024 0 -7025 0 -7026 0 -7027 0 -7028 0 -7029 0 -7030 1 -7031 0 -7032 0 -7033 0 -7034 0 -7035 0 -7036 0 -7037 0 -7038 0 -7039 1 -7040 0 -7041 0 -7042 0 -7043 0 -7044 0 -7045 0 -7046 0 -7047 0 -7048 1 -7049 0 -7050 0 -7051 0 -7052 0 -7053 0 -7054 0 -7055 0 -7056 0 -7057 0 -7058 0 -7059 1 -7060 0 -7061 0 -7062 0 -7063 0 -7064 0 -7065 0 -7066 0 -7067 0 -7068 0 -7069 1 -7070 0 -7071 0 -7072 0 -7073 0 -7074 0 -7075 0 -7076 0 -7077 0 -7078 0 -7079 1 -7080 0 -7081 0 -7082 0 -7083 0 -7084 0 -7085 0 -7086 0 -7087 1 -7088 0 -7089 0 -7090 0 -7091 0 -7092 0 -7093 0 -7094 0 -7095 0 -7096 0 -7097 1 -7098 0 -7099 0 -7100 0 -7101 0 -7102 0 -7103 0 -7104 0 -7105 1 -7106 0 -7107 0 -7108 0 -7109 0 -7110 0 -7111 0 -7112 0 -7113 0 -7114 1 -7115 0 -7116 0 -7117 0 -7118 0 -7119 0 -7120 0 -7121 0 -7122 0 -7123 0 -7124 1 -7125 0 -7126 0 -7127 0 -7128 0 -7129 0 -7130 0 -7131 0 -7132 0 -7133 0 -7134 1 -7135 0 -7136 0 -7137 0 -7138 0 -7139 0 -7140 0 -7141 0 -7142 0 -7143 1 -7144 0 -7145 0 -7146 0 -7147 0 -7148 0 -7149 0 -7150 0 -7151 0 -7152 1 -7153 0 -7154 0 -7155 0 -7156 0 -7157 0 -7158 0 -7159 0 -7160 0 -7161 0 -7162 1 -7163 0 -7164 0 -7165 0 -7166 0 -7167 0 -7168 0 -7169 0 -7170 0 -7171 0 -7172 1 -7173 0 -7174 0 -7175 0 -7176 0 -7177 0 -7178 0 -7179 0 -7180 0 -7181 0 -7182 1 -7183 0 -7184 0 -7185 0 -7186 0 -7187 0 -7188 0 -7189 0 -7190 0 -7191 0 -7192 0 -7193 1 -7194 0 -7195 0 -7196 0 -7197 0 -7198 0 -7199 0 -7200 0 -7201 0 -7202 0 -7203 1 -7204 0 -7205 0 -7206 0 -7207 0 -7208 0 -7209 0 -7210 0 -7211 0 -7212 0 -7213 0 -7214 0 -7215 0 -7216 0 -7217 0 -7218 0 -7219 0 -7220 0 -7221 0 -7222 1 -7223 0 -7224 0 -7225 0 -7226 0 -7227 0 -7228 0 -7229 0 -7230 0 -7231 0 -7232 1 -7233 0 -7234 0 -7235 0 -7236 0 -7237 0 -7238 0 -7239 0 -7240 0 -7241 0 -7242 0 -7243 1 -7244 0 -7245 0 -7246 0 -7247 0 -7248 0 -7249 0 -7250 0 -7251 0 -7252 0 -7253 1 -7254 0 -7255 0 -7256 0 -7257 0 -7258 0 -7259 0 -7260 0 -7261 0 -7262 0 -7263 0 -7264 1 -7265 0 -7266 0 -7267 0 -7268 0 -7269 0 -7270 0 -7271 0 -7272 0 -7273 0 -7274 1 -7275 0 -7276 0 -7277 0 -7278 0 -7279 0 -7280 0 -7281 0 -7282 0 -7283 0 -7284 0 -7285 1 -7286 0 -7287 0 -7288 0 -7289 0 -7290 0 -7291 0 -7292 0 -7293 0 -7294 0 -7295 0 -7296 0 -7297 0 -7298 0 -7299 0 -7300 0 -7301 0 -7302 0 -7303 0 -7304 1 -7305 0 -7306 0 -7307 0 -7308 0 -7309 0 -7310 0 -7311 0 -7312 0 -7313 0 -7314 0 -7315 1 -7316 0 -7317 0 -7318 0 -7319 0 -7320 0 -7321 0 -7322 0 -7323 0 -7324 1 -7325 0 -7326 0 -7327 0 -7328 0 -7329 0 -7330 0 -7331 0 -7332 0 -7333 1 -7334 0 -7335 0 -7336 0 -7337 0 -7338 0 -7339 0 -7340 0 -7341 0 -7342 1 -7343 0 -7344 0 -7345 0 -7346 0 -7347 0 -7348 0 -7349 0 -7350 0 -7351 0 -7352 1 -7353 0 -7354 0 -7355 0 -7356 0 -7357 0 -7358 0 -7359 0 -7360 0 -7361 0 -7362 0 -7363 1 -7364 0 -7365 0 -7366 0 -7367 0 -7368 0 -7369 0 -7370 0 -7371 0 -7372 1 -7373 0 -7374 0 -7375 0 -7376 0 -7377 0 -7378 0 -7379 0 -7380 0 -7381 0 -7382 1 -7383 0 -7384 0 -7385 0 -7386 0 -7387 0 -7388 0 -7389 0 -7390 0 -7391 1 -7392 0 -7393 0 -7394 0 -7395 0 -7396 0 -7397 0 -7398 0 -7399 0 -7400 0 -7401 1 -7402 0 -7403 0 -7404 0 -7405 0 -7406 0 -7407 0 -7408 0 -7409 0 -7410 0 -7411 0 -7412 1 -7413 0 -7414 0 -7415 0 -7416 0 -7417 0 -7418 0 -7419 0 -7420 0 -7421 0 -7422 1 -7423 0 -7424 0 -7425 0 -7426 0 -7427 0 -7428 0 -7429 0 -7430 0 -7431 0 -7432 1 -7433 0 -7434 0 -7435 0 -7436 0 -7437 0 -7438 0 -7439 0 -7440 0 -7441 1 -7442 0 -7443 0 -7444 0 -7445 0 -7446 0 -7447 0 -7448 0 -7449 1 -7450 0 -7451 0 -7452 0 -7453 0 -7454 0 -7455 0 -7456 0 -7457 0 -7458 0 -7459 0 -7460 1 -7461 0 -7462 0 -7463 0 -7464 0 -7465 0 -7466 0 -7467 0 -7468 0 -7469 1 -7470 0 -7471 0 -7472 0 -7473 0 -7474 0 -7475 0 -7476 0 -7477 0 -7478 1 -7479 0 -7480 0 -7481 0 -7482 0 -7483 0 -7484 0 -7485 0 -7486 0 -7487 1 -7488 0 -7489 0 -7490 0 -7491 0 -7492 0 -7493 0 -7494 0 -7495 0 -7496 0 -7497 1 -7498 0 -7499 0 -7500 0 -7501 0 -7502 0 -7503 0 -7504 0 -7505 0 -7506 0 -7507 0 -7508 1 -7509 0 -7510 0 -7511 0 -7512 0 -7513 0 -7514 0 -7515 0 -7516 0 -7517 0 -7518 1 -7519 0 -7520 0 -7521 0 -7522 0 -7523 0 -7524 0 -7525 0 -7526 0 -7527 0 -7528 0 -7529 0 -7530 0 -7531 0 -7532 0 -7533 0 -7534 0 -7535 0 -7536 0 -7537 0 -7538 0 -7539 1 -7540 0 -7541 0 -7542 0 -7543 0 -7544 0 -7545 0 -7546 0 -7547 0 -7548 0 -7549 2 -7550 0 -7551 0 -7552 0 -7553 0 -7554 0 -7555 0 -7556 0 -7557 1 -7558 0 -7559 0 -7560 0 -7561 0 -7562 0 -7563 0 -7564 0 -7565 0 -7566 0 -7567 0 -7568 1 -7569 0 -7570 0 -7571 0 -7572 0 -7573 0 -7574 0 -7575 0 -7576 0 -7577 0 -7578 0 -7579 0 -7580 0 -7581 0 -7582 0 -7583 0 -7584 0 -7585 0 -7586 0 -7587 0 -7588 1 -7589 0 -7590 0 -7591 0 -7592 0 -7593 0 -7594 0 -7595 0 -7596 0 -7597 0 -7598 0 -7599 1 -7600 0 -7601 0 -7602 0 -7603 0 -7604 0 -7605 0 -7606 0 -7607 0 -7608 0 -7609 0 -7610 1 -7611 0 -7612 0 -7613 0 -7614 0 -7615 0 -7616 0 -7617 0 -7618 0 -7619 0 -7620 0 -7621 1 -7622 0 -7623 0 -7624 0 -7625 0 -7626 0 -7627 1 -7628 0 -7629 0 -7630 0 -7631 0 -7632 0 -7633 0 -7634 1 -7635 0 -7636 0 -7637 0 -7638 0 -7639 0 -7640 0 -7641 1 -7642 0 -7643 0 -7644 0 -7645 0 -7646 0 -7647 0 -7648 0 -7649 1 -7650 0 -7651 0 -7652 0 -7653 0 -7654 0 -7655 0 -7656 0 -7657 0 -7658 0 -7659 0 -7660 1 -7661 0 -7662 0 -7663 0 -7664 0 -7665 0 -7666 0 -7667 0 -7668 0 -7669 0 -7670 1 -7671 0 -7672 0 -7673 0 -7674 0 -7675 0 -7676 0 -7677 0 -7678 0 -7679 0 -7680 0 -7681 1 -7682 0 -7683 0 -7684 0 -7685 0 -7686 0 -7687 0 -7688 0 -7689 0 -7690 0 -7691 1 -7692 0 -7693 0 -7694 0 -7695 0 -7696 0 -7697 0 -7698 0 -7699 0 -7700 0 -7701 0 -7702 1 -7703 0 -7704 0 -7705 0 -7706 0 -7707 0 -7708 0 -7709 0 -7710 0 -7711 0 -7712 1 -7713 0 -7714 0 -7715 0 -7716 0 -7717 0 -7718 0 -7719 0 -7720 0 -7721 0 -7722 1 -7723 0 -7724 0 -7725 0 -7726 0 -7727 0 -7728 0 -7729 0 -7730 0 -7731 0 -7732 1 -7733 0 -7734 0 -7735 0 -7736 0 -7737 0 -7738 0 -7739 0 -7740 0 -7741 0 -7742 1 -7743 0 -7744 0 -7745 0 -7746 0 -7747 0 -7748 0 -7749 0 -7750 0 -7751 0 -7752 1 -7753 0 -7754 0 -7755 0 -7756 0 -7757 0 -7758 0 -7759 0 -7760 0 -7761 1 -7762 0 -7763 0 -7764 0 -7765 0 -7766 0 -7767 0 -7768 0 -7769 0 -7770 1 -7771 0 -7772 0 -7773 0 -7774 0 -7775 0 -7776 0 -7777 0 -7778 0 -7779 1 -7780 0 -7781 0 -7782 0 -7783 0 -7784 0 -7785 0 -7786 0 -7787 0 -7788 0 -7789 1 -7790 0 -7791 0 -7792 0 -7793 0 -7794 0 -7795 0 -7796 0 -7797 0 -7798 0 -7799 1 -7800 0 -7801 0 -7802 0 -7803 0 -7804 0 -7805 0 -7806 0 -7807 0 -7808 0 -7809 0 -7810 1 -7811 0 -7812 0 -7813 0 -7814 0 -7815 0 -7816 0 -7817 0 -7818 0 -7819 1 -7820 0 -7821 0 -7822 0 -7823 0 -7824 0 -7825 0 -7826 0 -7827 0 -7828 1 -7829 0 -7830 0 -7831 0 -7832 0 -7833 0 -7834 0 -7835 0 -7836 0 -7837 0 -7838 0 -7839 1 -7840 0 -7841 0 -7842 0 -7843 0 -7844 0 -7845 0 -7846 0 -7847 0 -7848 0 -7849 1 -7850 0 -7851 0 -7852 0 -7853 0 -7854 0 -7855 0 -7856 0 -7857 0 -7858 1 -7859 0 -7860 0 -7861 0 -7862 0 -7863 0 -7864 0 -7865 0 -7866 0 -7867 0 -7868 1 -7869 0 -7870 0 -7871 0 -7872 0 -7873 0 -7874 0 -7875 0 -7876 0 -7877 0 -7878 0 -7879 0 -7880 0 -7881 0 -7882 0 -7883 0 -7884 0 -7885 0 -7886 0 -7887 1 -7888 0 -7889 0 -7890 0 -7891 0 -7892 0 -7893 0 -7894 0 -7895 0 -7896 0 -7897 0 -7898 1 -7899 0 -7900 0 -7901 0 -7902 0 -7903 0 -7904 0 -7905 0 -7906 0 -7907 0 -7908 1 -7909 0 -7910 0 -7911 0 -7912 0 -7913 0 -7914 0 -7915 0 -7916 0 -7917 0 -7918 1 -7919 0 -7920 0 -7921 0 -7922 0 -7923 0 -7924 0 -7925 0 -7926 0 -7927 0 -7928 1 -7929 0 -7930 0 -7931 0 -7932 0 -7933 0 -7934 0 -7935 0 -7936 0 -7937 0 -7938 1 -7939 0 -7940 0 -7941 0 -7942 0 -7943 0 -7944 0 -7945 0 -7946 0 -7947 0 -7948 1 -7949 0 -7950 0 -7951 0 -7952 0 -7953 0 -7954 0 -7955 0 -7956 0 -7957 0 -7958 1 -7959 0 -7960 0 -7961 0 -7962 0 -7963 0 -7964 0 -7965 0 -7966 0 -7967 0 -7968 1 -7969 0 -7970 0 -7971 0 -7972 0 -7973 0 -7974 0 -7975 0 -7976 0 -7977 0 -7978 1 -7979 0 -7980 0 -7981 0 -7982 0 -7983 0 -7984 0 -7985 1 -7986 0 -7987 0 -7988 0 -7989 0 -7990 0 -7991 0 -7992 0 -7993 0 -7994 0 -7995 1 -7996 0 -7997 0 -7998 0 -7999 0 -8000 0 -8001 0 -8002 0 -8003 0 -8004 0 -8005 0 -8006 1 -8007 0 -8008 0 -8009 0 -8010 0 -8011 0 -8012 0 -8013 0 -8014 0 -8015 1 -8016 0 -8017 0 -8018 0 -8019 0 -8020 0 -8021 0 -8022 0 -8023 0 -8024 0 -8025 1 -8026 0 -8027 0 -8028 0 -8029 0 -8030 0 -8031 0 -8032 0 -8033 0 -8034 0 -8035 0 -8036 1 -8037 0 -8038 0 -8039 0 -8040 0 -8041 0 -8042 0 -8043 0 -8044 0 -8045 0 -8046 1 -8047 0 -8048 0 -8049 0 -8050 0 -8051 0 -8052 0 -8053 0 -8054 0 -8055 0 -8056 0 -8057 1 -8058 0 -8059 0 -8060 0 -8061 0 -8062 0 -8063 0 -8064 0 -8065 0 -8066 0 -8067 1 -8068 0 -8069 0 -8070 0 -8071 0 -8072 0 -8073 0 -8074 0 -8075 0 -8076 0 -8077 0 -8078 1 -8079 0 -8080 0 -8081 0 -8082 0 -8083 0 -8084 0 -8085 0 -8086 0 -8087 0 -8088 1 -8089 0 -8090 0 -8091 0 -8092 0 -8093 0 -8094 0 -8095 0 -8096 0 -8097 0 -8098 1 -8099 0 -8100 0 -8101 0 -8102 0 -8103 0 -8104 0 -8105 1 -8106 0 -8107 0 -8108 0 -8109 0 -8110 0 -8111 0 -8112 0 -8113 0 -8114 0 -8115 1 -8116 0 -8117 0 -8118 0 -8119 0 -8120 0 -8121 0 -8122 0 -8123 0 -8124 0 -8125 1 -8126 0 -8127 0 -8128 0 -8129 0 -8130 0 -8131 0 -8132 0 -8133 0 -8134 1 -8135 0 -8136 0 -8137 0 -8138 0 -8139 0 -8140 0 -8141 0 -8142 0 -8143 0 -8144 0 -8145 1 -8146 0 -8147 0 -8148 0 -8149 0 -8150 0 -8151 0 -8152 0 -8153 0 -8154 0 -8155 0 -8156 1 -8157 0 -8158 0 -8159 0 -8160 0 -8161 0 -8162 0 -8163 0 -8164 0 -8165 0 -8166 1 -8167 0 -8168 0 -8169 0 -8170 0 -8171 0 -8172 0 -8173 0 -8174 0 -8175 0 -8176 1 -8177 0 -8178 0 -8179 0 -8180 0 -8181 0 -8182 0 -8183 0 -8184 0 -8185 0 -8186 1 -8187 0 -8188 0 -8189 0 -8190 0 -8191 0 -8192 0 -8193 0 -8194 0 -8195 0 -8196 0 -8197 1 -8198 0 -8199 0 -8200 0 -8201 0 -8202 0 -8203 0 -8204 0 -8205 0 -8206 0 -8207 1 -8208 0 -8209 0 -8210 0 -8211 0 -8212 0 -8213 0 -8214 0 -8215 0 -8216 1 -8217 0 -8218 0 -8219 0 -8220 0 -8221 0 -8222 0 -8223 0 -8224 0 -8225 1 -8226 0 -8227 0 -8228 0 -8229 0 -8230 0 -8231 0 -8232 0 -8233 0 -8234 0 -8235 1 -8236 0 -8237 0 -8238 0 -8239 0 -8240 0 -8241 0 -8242 0 -8243 0 -8244 1 -8245 0 -8246 0 -8247 0 -8248 0 -8249 0 -8250 0 -8251 0 -8252 0 -8253 0 -8254 1 -8255 0 -8256 0 -8257 0 -8258 0 -8259 0 -8260 0 -8261 0 -8262 0 -8263 0 -8264 0 -8265 1 -8266 0 -8267 0 -8268 0 -8269 0 -8270 0 -8271 0 -8272 0 -8273 0 -8274 0 -8275 1 -8276 0 -8277 0 -8278 0 -8279 0 -8280 0 -8281 0 -8282 0 -8283 0 -8284 0 -8285 0 -8286 1 -8287 0 -8288 0 -8289 0 -8290 0 -8291 0 -8292 0 -8293 0 -8294 0 -8295 0 -8296 1 -8297 0 -8298 0 -8299 0 -8300 0 -8301 0 -8302 0 -8303 0 -8304 1 -8305 0 -8306 0 -8307 0 -8308 0 -8309 0 -8310 0 -8311 0 -8312 0 -8313 0 -8314 1 -8315 0 -8316 0 -8317 0 -8318 0 -8319 0 -8320 0 -8321 0 -8322 0 -8323 0 -8324 1 -8325 0 -8326 0 -8327 0 -8328 0 -8329 0 -8330 0 -8331 0 -8332 0 -8333 0 -8334 0 -8335 0 -8336 0 -8337 0 -8338 0 -8339 0 -8340 0 -8341 0 -8342 1 -8343 0 -8344 0 -8345 0 -8346 0 -8347 0 -8348 0 -8349 0 -8350 0 -8351 1 -8352 0 -8353 0 -8354 0 -8355 0 -8356 0 -8357 0 -8358 0 -8359 0 -8360 0 -8361 1 -8362 0 -8363 0 -8364 0 -8365 0 -8366 0 -8367 0 -8368 0 -8369 0 -8370 0 -8371 1 -8372 0 -8373 0 -8374 0 -8375 0 -8376 0 -8377 0 -8378 0 -8379 0 -8380 1 -8381 0 -8382 0 -8383 0 -8384 0 -8385 0 -8386 0 -8387 0 -8388 0 -8389 1 -8390 0 -8391 0 -8392 0 -8393 0 -8394 0 -8395 0 -8396 0 -8397 0 -8398 0 -8399 1 -8400 0 -8401 0 -8402 0 -8403 0 -8404 0 -8405 0 -8406 0 -8407 0 -8408 0 -8409 1 -8410 0 -8411 0 -8412 0 -8413 0 -8414 0 -8415 0 -8416 0 -8417 0 -8418 0 -8419 1 -8420 0 -8421 0 -8422 0 -8423 0 -8424 0 -8425 0 -8426 0 -8427 0 -8428 0 -8429 0 -8430 1 -8431 0 -8432 0 -8433 0 -8434 0 -8435 0 -8436 0 -8437 0 -8438 1 -8439 0 -8440 0 -8441 0 -8442 0 -8443 0 -8444 0 -8445 0 -8446 0 -8447 1 -8448 0 -8449 0 -8450 0 -8451 0 -8452 0 -8453 0 -8454 0 -8455 0 -8456 0 -8457 1 -8458 0 -8459 0 -8460 0 -8461 0 -8462 0 -8463 0 -8464 0 -8465 0 -8466 0 -8467 1 -8468 0 -8469 0 -8470 0 -8471 0 -8472 0 -8473 0 -8474 0 -8475 0 -8476 0 -8477 1 -8478 0 -8479 0 -8480 0 -8481 0 -8482 0 -8483 0 -8484 0 -8485 0 -8486 1 -8487 0 -8488 0 -8489 0 -8490 0 -8491 0 -8492 0 -8493 0 -8494 0 -8495 0 -8496 0 -8497 0 -8498 0 -8499 0 -8500 0 -8501 0 -8502 0 -8503 0 -8504 0 -8505 0 -8506 1 -8507 0 -8508 0 -8509 0 -8510 0 -8511 0 -8512 0 -8513 0 -8514 0 -8515 0 -8516 0 -8517 0 -8518 0 -8519 0 -8520 0 -8521 0 -8522 0 -8523 1 -8524 0 -8525 0 -8526 0 -8527 0 -8528 0 -8529 0 -8530 0 -8531 0 -8532 1 -8533 0 -8534 0 -8535 0 -8536 0 -8537 0 -8538 0 -8539 0 -8540 0 -8541 1 -8542 0 -8543 0 -8544 0 -8545 0 -8546 0 -8547 0 -8548 0 -8549 1 -8550 0 -8551 0 -8552 0 -8553 0 -8554 0 -8555 0 -8556 0 -8557 0 -8558 0 -8559 1 -8560 0 -8561 0 -8562 0 -8563 0 -8564 0 -8565 0 -8566 0 -8567 0 -8568 1 -8569 0 -8570 0 -8571 0 -8572 0 -8573 0 -8574 0 -8575 0 -8576 0 -8577 1 -8578 0 -8579 0 -8580 0 -8581 0 -8582 0 -8583 0 -8584 0 -8585 0 -8586 1 -8587 0 -8588 0 -8589 0 -8590 0 -8591 0 -8592 0 -8593 0 -8594 0 -8595 0 -8596 1 -8597 0 -8598 0 -8599 0 -8600 0 -8601 0 -8602 0 -8603 0 -8604 0 -8605 0 -8606 1 -8607 0 -8608 0 -8609 0 -8610 0 -8611 0 -8612 0 -8613 0 -8614 0 -8615 0 -8616 1 -8617 0 -8618 0 -8619 0 -8620 0 -8621 0 -8622 0 -8623 0 -8624 0 -8625 1 -8626 0 -8627 0 -8628 0 -8629 0 -8630 0 -8631 0 -8632 0 -8633 1 -8634 0 -8635 0 -8636 0 -8637 0 -8638 0 -8639 0 -8640 0 -8641 0 -8642 0 -8643 1 -8644 0 -8645 0 -8646 0 -8647 0 -8648 0 -8649 0 -8650 0 -8651 1 -8652 0 -8653 0 -8654 0 -8655 0 -8656 0 -8657 0 -8658 0 -8659 0 -8660 1 -8661 0 -8662 0 -8663 0 -8664 0 -8665 0 -8666 0 -8667 0 -8668 0 -8669 1 -8670 0 -8671 0 -8672 0 -8673 0 -8674 0 -8675 0 -8676 0 -8677 1 -8678 0 -8679 0 -8680 0 -8681 0 -8682 0 -8683 0 -8684 0 -8685 0 -8686 1 -8687 0 -8688 0 -8689 0 -8690 0 -8691 0 -8692 0 -8693 0 -8694 0 -8695 0 -8696 1 -8697 0 -8698 0 -8699 0 -8700 0 -8701 0 -8702 0 -8703 0 -8704 0 -8705 1 -8706 0 -8707 0 -8708 0 -8709 0 -8710 0 -8711 0 -8712 0 -8713 0 -8714 0 -8715 1 -8716 0 -8717 0 -8718 0 -8719 0 -8720 0 -8721 0 -8722 0 -8723 0 -8724 0 -8725 1 -8726 0 -8727 0 -8728 0 -8729 0 -8730 0 -8731 0 -8732 0 -8733 0 -8734 0 -8735 1 -8736 0 -8737 0 -8738 0 -8739 0 -8740 0 -8741 0 -8742 0 -8743 0 -8744 0 -8745 1 -8746 0 -8747 0 -8748 0 -8749 0 -8750 0 -8751 0 -8752 0 -8753 0 -8754 0 -8755 1 -8756 0 -8757 0 -8758 0 -8759 0 -8760 0 -8761 0 -8762 0 -8763 1 -8764 0 -8765 0 -8766 0 -8767 0 -8768 0 -8769 0 -8770 1 -8771 0 -8772 0 -8773 0 -8774 0 -8775 0 -8776 0 -8777 0 -8778 0 -8779 0 -8780 1 -8781 0 -8782 0 -8783 0 -8784 0 -8785 0 -8786 0 -8787 0 -8788 0 -8789 1 -8790 0 -8791 0 -8792 0 -8793 0 -8794 0 -8795 0 -8796 0 -8797 0 -8798 1 -8799 0 -8800 0 -8801 0 -8802 0 -8803 0 -8804 0 -8805 0 -8806 0 -8807 3 -8808 0 -8809 0 -8810 1 -8811 0 -8812 0 -8813 0 -8814 0 -8815 1 -8816 0 -8817 0 -8818 0 -8819 0 -8820 1 -8821 0 -8822 0 -8823 0 -8824 1 -8825 0 -8826 0 -8827 0 -8828 0 -8829 0 -8830 1 -8831 0 -8832 0 -8833 0 -8834 0 -8835 0 -8836 0 -8837 1 -8838 0 -8839 0 -8840 0 -8841 0 -8842 0 -8843 0 -8844 0 -8845 1 -8846 0 -8847 0 -8848 0 -8849 0 -8850 0 -8851 0 -8852 0 -8853 0 -8854 0 -8855 1 -8856 0 -8857 0 -8858 0 -8859 0 -8860 0 -8861 0 -8862 0 -8863 0 -8864 0 -8865 1 -8866 0 -8867 0 -8868 0 -8869 0 -8870 0 -8871 0 -8872 1 -8873 0 -8874 0 -8875 0 -8876 0 -8877 0 -8878 0 -8879 0 -8880 1 -8881 0 -8882 0 -8883 0 -8884 0 -8885 0 -8886 0 -8887 0 -8888 1 -8889 0 -8890 0 -8891 0 -8892 0 -8893 0 -8894 0 -8895 0 -8896 0 -8897 0 -8898 0 -8899 0 -8900 0 -8901 0 -8902 0 -8903 0 -8904 0 -8905 1 -8906 0 -8907 0 -8908 0 -8909 0 -8910 0 -8911 0 -8912 1 -8913 0 -8914 0 -8915 0 -8916 0 -8917 0 -8918 0 -8919 0 -8920 1 -8921 0 -8922 0 -8923 0 -8924 0 -8925 0 -8926 0 -8927 0 -8928 0 -8929 1 -8930 0 -8931 0 -8932 0 -8933 0 -8934 0 -8935 0 -8936 0 -8937 0 -8938 0 -8939 1 -8940 0 -8941 0 -8942 0 -8943 0 -8944 0 -8945 0 -8946 0 -8947 0 -8948 0 -8949 1 -8950 0 -8951 0 -8952 0 -8953 0 -8954 0 -8955 0 -8956 0 -8957 0 -8958 0 -8959 1 -8960 0 -8961 0 -8962 0 -8963 0 -8964 0 -8965 0 -8966 0 -8967 0 -8968 0 -8969 1 -8970 0 -8971 0 -8972 0 -8973 0 -8974 0 -8975 0 -8976 0 -8977 0 -8978 1 -8979 0 -8980 0 -8981 0 -8982 0 -8983 0 -8984 0 -8985 0 -8986 0 -8987 1 -8988 0 -8989 0 -8990 0 -8991 0 -8992 0 -8993 0 -8994 0 -8995 0 -8996 0 -8997 1 -8998 0 -8999 0 -9000 0 -9001 0 -9002 0 -9003 0 -9004 0 -9005 0 -9006 1 -9007 0 -9008 0 -9009 0 -9010 0 -9011 0 -9012 0 -9013 0 -9014 1 -9015 0 -9016 0 -9017 0 -9018 0 -9019 0 -9020 0 -9021 0 -9022 1 -9023 0 -9024 0 -9025 0 -9026 0 -9027 0 -9028 0 -9029 0 -9030 1 -9031 0 -9032 0 -9033 0 -9034 0 -9035 0 -9036 0 -9037 0 -9038 1 -9039 0 -9040 0 -9041 0 -9042 0 -9043 0 -9044 0 -9045 0 -9046 0 -9047 1 -9048 0 -9049 0 -9050 0 -9051 0 -9052 0 -9053 0 -9054 0 -9055 1 -9056 0 -9057 0 -9058 0 -9059 0 -9060 0 -9061 0 -9062 0 -9063 1 -9064 0 -9065 0 -9066 0 -9067 0 -9068 0 -9069 0 -9070 0 -9071 0 -9072 0 -9073 1 -9074 0 -9075 0 -9076 0 -9077 0 -9078 0 -9079 0 -9080 0 -9081 0 -9082 0 -9083 0 -9084 0 -9085 0 -9086 0 -9087 0 -9088 0 -9089 0 -9090 0 -9091 0 -9092 1 -9093 0 -9094 0 -9095 0 -9096 0 -9097 0 -9098 0 -9099 0 -9100 1 -9101 0 -9102 0 -9103 0 -9104 0 -9105 0 -9106 0 -9107 0 -9108 1 -9109 0 -9110 0 -9111 0 -9112 0 -9113 0 -9114 0 -9115 0 -9116 0 -9117 1 -9118 0 -9119 0 -9120 0 -9121 0 -9122 0 -9123 0 -9124 0 -9125 0 -9126 1 -9127 0 -9128 0 -9129 0 -9130 0 -9131 0 -9132 0 -9133 0 -9134 0 -9135 1 -9136 0 -9137 0 -9138 0 -9139 0 -9140 0 -9141 0 -9142 0 -9143 1 -9144 0 -9145 0 -9146 0 -9147 0 -9148 0 -9149 0 -9150 0 -9151 0 -9152 1 -9153 0 -9154 0 -9155 0 -9156 0 -9157 0 -9158 0 -9159 0 -9160 0 -9161 1 -9162 0 -9163 0 -9164 0 -9165 0 -9166 0 -9167 0 -9168 0 -9169 1 -9170 0 -9171 0 -9172 0 -9173 0 -9174 0 -9175 0 -9176 0 -9177 0 -9178 1 -9179 0 -9180 0 -9181 0 -9182 0 -9183 0 -9184 0 -9185 0 -9186 0 -9187 0 -9188 1 -9189 0 -9190 0 -9191 0 -9192 0 -9193 0 -9194 0 -9195 0 -9196 0 -9197 1 -9198 0 -9199 0 -9200 0 -9201 0 -9202 0 -9203 0 -9204 0 -9205 0 -9206 0 -9207 0 -9208 0 -9209 0 -9210 0 -9211 0 -9212 0 -9213 0 -9214 0 -9215 0 -9216 0 -9217 0 -9218 0 -9219 0 -9220 0 -9221 1 -9222 0 -9223 0 -9224 0 -9225 0 -9226 0 -9227 0 -9228 1 -9229 0 -9230 0 -9231 0 -9232 0 -9233 0 -9234 0 -9235 0 -9236 0 -9237 1 -9238 0 -9239 0 -9240 0 -9241 0 -9242 0 -9243 0 -9244 0 -9245 0 -9246 1 -9247 0 -9248 0 -9249 0 -9250 0 -9251 0 -9252 0 -9253 0 -9254 0 -9255 1 -9256 0 -9257 0 -9258 0 -9259 0 -9260 0 -9261 1 -9262 0 -9263 0 -9264 0 -9265 0 -9266 0 -9267 0 -9268 0 -9269 0 -9270 0 -9271 0 -9272 0 -9273 0 -9274 0 -9275 0 -9276 1 -9277 0 -9278 0 -9279 0 -9280 0 -9281 0 -9282 0 -9283 0 -9284 0 -9285 0 -9286 0 -9287 0 -9288 0 -9289 0 -9290 1 -9291 0 -9292 0 -9293 0 -9294 0 -9295 0 -9296 0 -9297 0 -9298 0 -9299 0 -9300 1 -9301 0 -9302 0 -9303 0 -9304 0 -9305 0 -9306 0 -9307 0 -9308 1 -9309 0 -9310 0 -9311 0 -9312 0 -9313 0 -9314 0 -9315 0 -9316 1 -9317 0 -9318 0 -9319 0 -9320 0 -9321 0 -9322 0 -9323 1 -9324 0 -9325 0 -9326 0 -9327 0 -9328 0 -9329 0 -9330 0 -9331 1 -9332 0 -9333 0 -9334 0 -9335 0 -9336 0 -9337 0 -9338 1 -9339 0 -9340 0 -9341 0 -9342 0 -9343 0 -9344 0 -9345 1 -9346 0 -9347 0 -9348 0 -9349 0 -9350 0 -9351 0 -9352 0 -9353 0 -9354 0 -9355 1 -9356 0 -9357 0 -9358 0 -9359 0 -9360 0 -9361 0 -9362 0 -9363 1 -9364 0 -9365 0 -9366 0 -9367 0 -9368 0 -9369 0 -9370 1 -9371 0 -9372 0 -9373 0 -9374 0 -9375 0 -9376 0 -9377 0 -9378 1 -9379 0 -9380 0 -9381 0 -9382 0 -9383 0 -9384 0 -9385 0 -9386 0 -9387 0 -9388 0 -9389 0 -9390 0 -9391 0 -9392 0 -9393 0 -9394 0 -9395 1 -9396 0 -9397 0 -9398 0 -9399 0 -9400 0 -9401 0 -9402 0 -9403 1 -9404 0 -9405 0 -9406 0 -9407 0 -9408 0 -9409 0 -9410 0 -9411 0 -9412 1 -9413 0 -9414 0 -9415 0 -9416 0 -9417 0 -9418 0 -9419 0 -9420 1 -9421 0 -9422 0 -9423 0 -9424 0 -9425 0 -9426 0 -9427 0 -9428 0 -9429 1 -9430 0 -9431 0 -9432 0 -9433 0 -9434 0 -9435 0 -9436 0 -9437 0 -9438 0 -9439 1 -9440 0 -9441 0 -9442 0 -9443 0 -9444 0 -9445 0 -9446 0 -9447 0 -9448 0 -9449 1 -9450 0 -9451 0 -9452 0 -9453 0 -9454 0 -9455 0 -9456 0 -9457 1 -9458 0 -9459 0 -9460 0 -9461 0 -9462 0 -9463 0 -9464 1 -9465 0 -9466 0 -9467 0 -9468 0 -9469 0 -9470 0 -9471 0 -9472 0 -9473 1 -9474 0 -9475 0 -9476 0 -9477 0 -9478 0 -9479 0 -9480 0 -9481 1 -9482 0 -9483 0 -9484 0 -9485 0 -9486 0 -9487 0 -9488 1 -9489 0 -9490 0 -9491 0 -9492 0 -9493 0 -9494 0 -9495 0 -9496 0 -9497 1 -9498 0 -9499 0 -9500 0 -9501 0 -9502 0 -9503 0 -9504 0 -9505 0 -9506 0 -9507 0 -9508 0 -9509 0 -9510 0 -9511 0 -9512 0 -9513 0 -9514 1 -9515 0 -9516 0 -9517 0 -9518 0 -9519 0 -9520 0 -9521 0 -9522 1 -9523 0 -9524 0 -9525 0 -9526 0 -9527 0 -9528 0 -9529 0 -9530 1 -9531 0 -9532 0 -9533 0 -9534 0 -9535 0 -9536 0 -9537 0 -9538 1 -9539 0 -9540 0 -9541 0 -9542 0 -9543 0 -9544 0 -9545 0 -9546 0 -9547 1 -9548 0 -9549 0 -9550 0 -9551 0 -9552 0 -9553 0 -9554 0 -9555 1 -9556 0 -9557 0 -9558 0 -9559 0 -9560 0 -9561 0 -9562 0 -9563 1 -9564 0 -9565 0 -9566 0 -9567 0 -9568 0 -9569 0 -9570 0 -9571 0 -9572 1 -9573 0 -9574 0 -9575 0 -9576 0 -9577 0 -9578 0 -9579 0 -9580 1 -9581 0 -9582 0 -9583 0 -9584 0 -9585 0 -9586 0 -9587 0 -9588 0 -9589 1 -9590 0 -9591 0 -9592 0 -9593 0 -9594 0 -9595 0 -9596 0 -9597 0 -9598 0 -9599 0 -9600 0 -9601 0 -9602 0 -9603 0 -9604 0 -9605 0 -9606 0 -9607 0 -9608 1 -9609 0 -9610 0 -9611 0 -9612 0 -9613 0 -9614 0 -9615 1 -9616 0 -9617 0 -9618 0 -9619 0 -9620 0 -9621 0 -9622 1 -9623 0 -9624 0 -9625 0 -9626 0 -9627 0 -9628 0 -9629 0 -9630 1 -9631 0 -9632 0 -9633 0 -9634 0 -9635 0 -9636 0 -9637 0 -9638 0 -9639 1 -9640 0 -9641 0 -9642 0 -9643 0 -9644 0 -9645 0 -9646 0 -9647 0 -9648 1 -9649 0 -9650 0 -9651 0 -9652 0 -9653 0 -9654 0 -9655 0 -9656 1 -9657 0 -9658 0 -9659 0 -9660 0 -9661 0 -9662 0 -9663 1 -9664 0 -9665 0 -9666 0 -9667 0 -9668 0 -9669 0 -9670 0 -9671 0 -9672 0 -9673 1 -9674 0 -9675 0 -9676 0 -9677 0 -9678 0 -9679 0 -9680 0 -9681 1 -9682 0 -9683 0 -9684 0 -9685 0 -9686 0 -9687 0 -9688 0 -9689 1 -9690 0 -9691 0 -9692 0 -9693 0 -9694 0 -9695 0 -9696 1 -9697 0 -9698 0 -9699 0 -9700 0 -9701 0 -9702 0 -9703 0 -9704 1 -9705 0 -9706 0 -9707 0 -9708 0 -9709 0 -9710 0 -9711 0 -9712 1 -9713 0 -9714 0 -9715 0 -9716 0 -9717 0 -9718 0 -9719 0 -9720 0 -9721 0 -9722 1 -9723 0 -9724 0 -9725 0 -9726 0 -9727 0 -9728 0 -9729 0 -9730 0 -9731 1 -9732 0 -9733 0 -9734 0 -9735 0 -9736 0 -9737 0 -9738 0 -9739 0 -9740 1 -9741 0 -9742 0 -9743 0 -9744 0 -9745 0 -9746 0 -9747 0 -9748 0 -9749 1 -9750 0 -9751 0 -9752 0 -9753 0 -9754 0 -9755 0 -9756 1 -9757 0 -9758 0 -9759 0 -9760 0 -9761 0 -9762 0 -9763 0 -9764 0 -9765 0 -9766 0 -9767 0 -9768 0 -9769 0 -9770 0 -9771 0 -9772 0 -9773 1 -9774 0 -9775 0 -9776 0 -9777 0 -9778 0 -9779 0 -9780 1 -9781 0 -9782 0 -9783 0 -9784 0 -9785 0 -9786 0 -9787 0 -9788 1 -9789 0 -9790 0 -9791 0 -9792 0 -9793 0 -9794 0 -9795 0 -9796 0 -9797 0 -9798 0 -9799 0 -9800 0 -9801 0 -9802 0 -9803 1 -9804 0 -9805 0 -9806 0 -9807 0 -9808 0 -9809 0 -9810 0 -9811 0 -9812 1 -9813 0 -9814 0 -9815 0 -9816 0 -9817 0 -9818 0 -9819 0 -9820 1 -9821 0 -9822 0 -9823 0 -9824 0 -9825 0 -9826 0 -9827 0 -9828 0 -9829 1 -9830 0 -9831 0 -9832 0 -9833 0 -9834 0 -9835 0 -9836 0 -9837 0 -9838 1 -9839 0 -9840 0 -9841 0 -9842 0 -9843 0 -9844 0 -9845 0 -9846 0 -9847 0 -9848 1 -9849 0 -9850 0 -9851 0 -9852 0 -9853 0 -9854 4 -9855 0 -9856 0 -9857 1 -9858 0 -9859 0 -9860 0 -9861 0 -9862 1 -9863 0 -9864 0 -9865 0 -9866 0 -9867 0 -9868 1 -9869 0 -9870 0 -9871 0 -9872 0 -9873 1 -9874 0 -9875 0 -9876 0 -9877 0 -9878 1 -9879 0 -9880 0 -9881 0 -9882 0 -9883 0 -9884 0 -9885 0 -9886 1 -9887 0 -9888 0 -9889 0 -9890 0 -9891 0 -9892 0 -9893 0 -9894 0 -9895 1 -9896 0 -9897 0 -9898 0 -9899 0 -9900 0 -9901 0 -9902 0 -9903 0 -9904 1 -9905 0 -9906 0 -9907 0 -9908 0 -9909 0 -9910 0 -9911 0 -9912 0 -9913 0 -9914 0 -9915 0 -9916 0 -9917 0 -9918 0 -9919 0 -9920 0 -9921 0 -9922 0 -9923 0 -9924 1 -9925 0 -9926 0 -9927 0 -9928 0 -9929 0 -9930 0 -9931 0 -9932 0 -9933 0 -9934 1 -9935 0 -9936 0 -9937 0 -9938 0 -9939 0 -9940 0 -9941 0 -9942 0 -9943 0 -9944 1 -9945 0 -9946 0 -9947 0 -9948 0 -9949 0 -9950 0 -9951 0 -9952 0 -9953 0 -9954 1 -9955 0 -9956 0 -9957 0 -9958 0 -9959 0 -9960 0 -9961 0 -9962 0 -9963 1 -9964 0 -9965 0 -9966 0 -9967 0 -9968 0 -9969 0 -9970 0 -9971 0 -9972 1 -9973 0 -9974 0 -9975 0 -9976 0 -9977 0 -9978 0 -9979 0 -9980 0 -9981 0 -9982 0 -9983 1 -9984 0 -9985 0 -9986 0 -9987 0 -9988 0 -9989 0 -9990 0 -9991 0 -9992 0 -9993 1 -9994 0 -9995 0 -9996 0 -9997 0 -9998 0 -9999 0 -10000 0 -10001 0 -10002 0 -10003 0 -10004 1 -10005 0 -10006 0 -10007 0 -10008 0 -10009 0 -10010 0 -10011 0 -10012 0 -10013 1 -10014 0 -10015 0 -10016 0 -10017 0 -10018 0 -10019 0 -10020 0 -10021 0 -10022 0 -10023 1 -10024 0 -10025 0 -10026 0 -10027 0 -10028 0 -10029 0 -10030 0 -10031 1 -10032 0 -10033 0 -10034 0 -10035 0 -10036 0 -10037 0 -10038 0 -10039 0 -10040 0 -10041 1 -10042 0 -10043 0 -10044 0 -10045 0 -10046 0 -10047 0 -10048 0 -10049 0 -10050 0 -10051 1 -10052 0 -10053 0 -10054 0 -10055 0 -10056 0 -10057 0 -10058 0 -10059 0 -10060 1 -10061 0 -10062 0 -10063 0 -10064 0 -10065 0 -10066 0 -10067 0 -10068 0 -10069 1 -10070 0 -10071 0 -10072 0 -10073 0 -10074 0 -10075 0 -10076 0 -10077 0 -10078 1 -10079 0 -10080 0 -10081 0 -10082 0 -10083 0 -10084 0 -10085 0 -10086 0 -10087 1 -10088 0 -10089 0 -10090 0 -10091 0 -10092 0 -10093 0 -10094 0 -10095 0 -10096 0 -10097 1 -10098 0 -10099 0 -10100 0 -10101 0 -10102 0 -10103 0 -10104 0 -10105 0 -10106 0 -10107 0 -10108 1 -10109 0 -10110 0 -10111 0 -10112 0 -10113 0 -10114 0 -10115 0 -10116 0 -10117 0 -10118 1 -10119 0 -10120 0 -10121 0 -10122 0 -10123 0 -10124 0 -10125 0 -10126 0 -10127 1 -10128 0 -10129 0 -10130 0 -10131 0 -10132 0 -10133 0 -10134 0 -10135 0 -10136 0 -10137 1 -10138 0 -10139 0 -10140 0 -10141 0 -10142 0 -10143 0 -10144 0 -10145 0 -10146 0 -10147 1 -10148 0 -10149 0 -10150 0 -10151 0 -10152 0 -10153 0 -10154 0 -10155 0 -10156 0 -10157 1 -10158 0 -10159 0 -10160 0 -10161 0 -10162 0 -10163 0 -10164 0 -10165 0 -10166 0 -10167 1 -10168 0 -10169 0 -10170 0 -10171 0 -10172 0 -10173 0 -10174 0 -10175 0 -10176 1 -10177 0 -10178 0 -10179 0 -10180 0 -10181 0 -10182 0 -10183 0 -10184 0 -10185 1 -10186 0 -10187 0 -10188 0 -10189 0 -10190 0 -10191 0 -10192 0 -10193 1 -10194 0 -10195 0 -10196 0 -10197 0 -10198 0 -10199 0 -10200 0 -10201 1 -10202 0 -10203 0 -10204 0 -10205 0 -10206 0 -10207 0 -10208 0 -10209 0 -10210 0 -10211 1 -10212 0 -10213 0 -10214 0 -10215 0 -10216 0 -10217 0 -10218 0 -10219 0 -10220 1 -10221 0 -10222 0 -10223 0 -10224 0 -10225 0 -10226 0 -10227 0 -10228 0 -10229 0 -10230 1 -10231 0 -10232 0 -10233 0 -10234 0 -10235 0 -10236 0 -10237 0 -10238 0 -10239 0 -10240 1 -10241 0 -10242 0 -10243 0 -10244 0 -10245 0 -10246 0 -10247 0 -10248 0 -10249 0 -10250 1 -10251 0 -10252 0 -10253 0 -10254 0 -10255 0 -10256 0 -10257 0 -10258 0 -10259 0 -10260 1 -10261 0 -10262 0 -10263 0 -10264 1 -10265 0 -10266 0 -10267 0 -10268 0 -10269 0 -10270 1 -10271 0 -10272 0 -10273 0 -10274 0 -10275 0 -10276 0 -10277 0 -10278 1 -10279 0 -10280 0 -10281 0 -10282 0 -10283 0 -10284 0 -10285 0 -10286 1 -10287 0 -10288 0 -10289 0 -10290 0 -10291 0 -10292 0 -10293 0 -10294 0 -10295 0 -10296 1 -10297 0 -10298 0 -10299 0 -10300 0 -10301 0 -10302 0 -10303 0 -10304 0 -10305 1 -10306 0 -10307 0 -10308 0 -10309 0 -10310 0 -10311 0 -10312 0 -10313 0 -10314 1 -10315 0 -10316 0 -10317 0 -10318 0 -10319 0 -10320 0 -10321 0 -10322 0 -10323 1 -10324 0 -10325 0 -10326 0 -10327 0 -10328 0 -10329 0 -10330 0 -10331 0 -10332 0 -10333 1 -10334 0 -10335 0 -10336 0 -10337 0 -10338 0 -10339 0 -10340 0 -10341 0 -10342 0 -10343 0 -10344 0 -10345 0 -10346 0 -10347 0 -10348 0 -10349 0 -10350 0 -10351 1 -10352 0 -10353 0 -10354 0 -10355 0 -10356 0 -10357 0 -10358 0 -10359 0 -10360 1 -10361 0 -10362 0 -10363 0 -10364 0 -10365 0 -10366 0 -10367 0 -10368 0 -10369 0 -10370 1 -10371 0 -10372 0 -10373 0 -10374 0 -10375 0 -10376 0 -10377 0 -10378 0 -10379 0 -10380 1 -10381 0 -10382 0 -10383 0 -10384 0 -10385 0 -10386 0 -10387 1 -10388 0 -10389 0 -10390 0 -10391 0 -10392 0 -10393 0 -10394 0 -10395 1 -10396 0 -10397 0 -10398 0 -10399 0 -10400 0 -10401 0 -10402 0 -10403 0 -10404 1 -10405 0 -10406 0 -10407 0 -10408 0 -10409 0 -10410 0 -10411 0 -10412 0 -10413 0 -10414 1 -10415 0 -10416 0 -10417 0 -10418 0 -10419 0 -10420 0 -10421 0 -10422 0 -10423 1 -10424 0 -10425 0 -10426 0 -10427 0 -10428 0 -10429 0 -10430 0 -10431 0 -10432 0 -10433 1 -10434 0 -10435 0 -10436 0 -10437 0 -10438 0 -10439 0 -10440 0 -10441 0 -10442 0 -10443 1 -10444 0 -10445 0 -10446 0 -10447 0 -10448 0 -10449 0 -10450 0 -10451 0 -10452 1 -10453 0 -10454 0 -10455 0 -10456 0 -10457 0 -10458 0 -10459 0 -10460 1 -10461 0 -10462 0 -10463 0 -10464 0 -10465 0 -10466 0 -10467 0 -10468 0 -10469 1 -10470 0 -10471 0 -10472 0 -10473 0 -10474 0 -10475 0 -10476 0 -10477 0 -10478 0 -10479 1 -10480 0 -10481 0 -10482 0 -10483 0 -10484 0 -10485 0 -10486 0 -10487 0 -10488 0 -10489 1 -10490 0 -10491 0 -10492 0 -10493 0 -10494 0 -10495 0 -10496 0 -10497 0 -10498 1 -10499 0 -10500 0 -10501 0 -10502 0 -10503 0 -10504 0 -10505 0 -10506 1 -10507 0 -10508 0 -10509 0 -10510 0 -10511 0 -10512 0 -10513 0 -10514 0 -10515 0 -10516 0 -10517 1 -10518 0 -10519 0 -10520 0 -10521 0 -10522 0 -10523 0 -10524 0 -10525 0 -10526 0 -10527 1 -10528 0 -10529 0 -10530 0 -10531 0 -10532 0 -10533 0 -10534 0 -10535 0 -10536 1 -10537 0 -10538 0 -10539 0 -10540 0 -10541 0 -10542 0 -10543 0 -10544 0 -10545 1 -10546 0 -10547 0 -10548 0 -10549 0 -10550 0 -10551 0 -10552 0 -10553 0 -10554 0 -10555 1 -10556 0 -10557 0 -10558 0 -10559 0 -10560 0 -10561 0 -10562 0 -10563 0 -10564 0 -10565 0 -10566 1 -10567 0 -10568 0 -10569 0 -10570 0 -10571 0 -10572 0 -10573 0 -10574 0 -10575 0 -10576 0 -10577 0 -10578 0 -10579 0 -10580 0 -10581 0 -10582 0 -10583 0 -10584 0 -10585 0 -10586 0 -10587 1 -10588 0 -10589 0 -10590 0 -10591 0 -10592 0 -10593 0 -10594 0 -10595 0 -10596 0 -10597 0 -10598 1 -10599 0 -10600 0 -10601 0 -10602 0 -10603 0 -10604 0 -10605 0 -10606 0 -10607 0 -10608 0 -10609 1 -10610 0 -10611 0 -10612 0 -10613 0 -10614 0 -10615 0 -10616 0 -10617 1 -10618 0 -10619 0 -10620 0 -10621 0 -10622 0 -10623 0 -10624 0 -10625 1 -10626 0 -10627 0 -10628 0 -10629 0 -10630 0 -10631 0 -10632 0 -10633 0 -10634 1 -10635 0 -10636 0 -10637 0 -10638 0 -10639 0 -10640 0 -10641 0 -10642 0 -10643 0 -10644 1 -10645 0 -10646 0 -10647 0 -10648 0 -10649 0 -10650 0 -10651 0 -10652 0 -10653 1 -10654 0 -10655 0 -10656 0 -10657 0 -10658 0 -10659 0 -10660 0 -10661 1 -10662 0 -10663 0 -10664 0 -10665 0 -10666 0 -10667 0 -10668 0 -10669 0 -10670 0 -10671 1 -10672 0 -10673 0 -10674 0 -10675 0 -10676 0 -10677 0 -10678 0 -10679 0 -10680 0 -10681 1 -10682 0 -10683 0 -10684 0 -10685 0 -10686 0 -10687 0 -10688 0 -10689 0 -10690 0 -10691 0 -10692 0 -10693 0 -10694 0 -10695 0 -10696 0 -10697 0 -10698 0 -10699 0 -10700 0 -10701 1 -10702 0 -10703 0 -10704 0 -10705 0 -10706 0 -10707 0 -10708 0 -10709 0 -10710 0 -10711 1 -10712 0 -10713 0 -10714 0 -10715 0 -10716 0 -10717 0 -10718 0 -10719 0 -10720 0 -10721 1 -10722 0 -10723 0 -10724 0 -10725 0 -10726 0 -10727 0 -10728 0 -10729 0 -10730 1 -10731 0 -10732 0 -10733 0 -10734 0 -10735 0 -10736 0 -10737 0 -10738 0 -10739 0 -10740 1 -10741 0 -10742 0 -10743 0 -10744 0 -10745 0 -10746 0 -10747 0 -10748 0 -10749 1 -10750 0 -10751 0 -10752 0 -10753 0 -10754 0 -10755 0 -10756 0 -10757 0 -10758 0 -10759 1 -10760 0 -10761 0 -10762 0 -10763 0 -10764 0 -10765 0 -10766 0 -10767 0 -10768 0 -10769 0 -10770 1 -10771 0 -10772 0 -10773 0 -10774 0 -10775 0 -10776 0 -10777 0 -10778 0 -10779 0 -10780 1 -10781 0 -10782 0 -10783 0 -10784 0 -10785 0 -10786 0 -10787 0 -10788 0 -10789 0 -10790 1 -10791 0 -10792 0 -10793 0 -10794 0 -10795 0 -10796 0 -10797 0 -10798 0 -10799 0 -10800 1 -10801 0 -10802 0 -10803 0 -10804 0 -10805 0 -10806 0 -10807 0 -10808 0 -10809 0 -10810 0 -10811 0 -10812 0 -10813 0 -10814 0 -10815 0 -10816 0 -10817 0 -10818 0 -10819 0 -10820 1 -10821 0 -10822 0 -10823 0 -10824 0 -10825 0 -10826 0 -10827 0 -10828 0 -10829 0 -10830 0 -10831 1 -10832 0 -10833 0 -10834 0 -10835 0 -10836 0 -10837 0 -10838 0 -10839 0 -10840 1 -10841 0 -10842 0 -10843 0 -10844 0 -10845 0 -10846 0 -10847 0 -10848 0 -10849 0 -10850 0 -10851 0 -10852 0 -10853 0 -10854 0 -10855 0 -10856 0 -10857 0 -10858 0 -10859 0 -10860 1 -10861 0 -10862 0 -10863 0 -10864 0 -10865 0 -10866 0 -10867 0 -10868 0 -10869 1 -10870 0 -10871 0 -10872 0 -10873 0 -10874 0 -10875 0 -10876 0 -10877 0 -10878 0 -10879 0 -10880 1 -10881 0 -10882 0 -10883 0 -10884 0 -10885 0 -10886 0 -10887 0 -10888 0 -10889 0 -10890 1 -10891 0 -10892 0 -10893 0 -10894 0 -10895 0 -10896 0 -10897 0 -10898 0 -10899 0 -10900 1 -10901 0 -10902 0 -10903 0 -10904 0 -10905 0 -10906 0 -10907 0 -10908 0 -10909 0 -10910 0 -10911 1 -10912 0 -10913 0 -10914 0 -10915 0 -10916 0 -10917 0 -10918 0 -10919 0 -10920 0 -10921 1 -10922 0 -10923 0 -10924 0 -10925 0 -10926 0 -10927 0 -10928 0 -10929 0 -10930 0 -10931 1 -10932 0 -10933 0 -10934 0 -10935 0 -10936 0 -10937 0 -10938 0 -10939 0 -10940 1 -10941 0 -10942 0 -10943 0 -10944 0 -10945 0 -10946 0 -10947 0 -10948 0 -10949 1 -10950 0 -10951 0 -10952 0 -10953 0 -10954 0 -10955 0 -10956 0 -10957 0 -10958 1 -10959 0 -10960 0 -10961 0 -10962 0 -10963 0 -10964 0 -10965 0 -10966 0 -10967 0 -10968 1 -10969 0 -10970 0 -10971 0 -10972 0 -10973 0 -10974 0 -10975 0 -10976 0 -10977 0 -10978 1 -10979 0 -10980 0 -10981 0 -10982 0 -10983 0 -10984 0 -10985 0 -10986 0 -10987 0 -10988 0 -10989 1 -10990 0 -10991 0 -10992 0 -10993 0 -10994 0 -10995 0 -10996 0 -10997 0 -10998 0 -10999 0 -11000 1 \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore deleted file mode 100644 index 38344f8..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -build/ -test/ -examples/ -fs.js -zlib.js \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE deleted file mode 100644 index 0c44ae7..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) Isaac Z. Schlueter ("Author") -All rights reserved. - -The BSD License - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS -BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN -IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/README.md deleted file mode 100644 index 34c1189..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# readable-stream - -***Node-core streams for userland*** - -[![NPM](https://nodei.co/npm/readable-stream.png?downloads=true)](https://nodei.co/npm/readable-stream/) -[![NPM](https://nodei.co/npm-dl/readable-stream.png)](https://nodei.co/npm/readable-stream/) - -This package is a mirror of the Streams2 and Streams3 implementations in Node-core. - -If you want to guarantee a stable streams base, regardless of what version of Node you, or the users of your libraries are using, use **readable-stream** *only* and avoid the *"stream"* module in Node-core. - -**readable-stream** comes in two major versions, v1.0.x and v1.1.x. The former tracks the Streams2 implementation in Node 0.10, including bug-fixes and minor improvements as they are added. The latter tracks Streams3 as it develops in Node 0.11; we will likely see a v1.2.x branch for Node 0.12. - -**readable-stream** uses proper patch-level versioning so if you pin to `"~1.0.0"` you’ll get the latest Node 0.10 Streams2 implementation, including any fixes and minor non-breaking improvements. The patch-level versions of 1.0.x and 1.1.x should mirror the patch-level versions of Node-core releases. You should prefer the **1.0.x** releases for now and when you’re ready to start using Streams3, pin to `"~1.1.0"` - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js deleted file mode 100644 index ca807af..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/duplex.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_duplex.js") diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js deleted file mode 100644 index b513d61..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_duplex.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -module.exports = Duplex; - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -} -/**/ - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -forEach(objectKeys(Writable.prototype), function(method) { - if (!Duplex.prototype[method]) - Duplex.prototype[method] = Writable.prototype[method]; -}); - -function Duplex(options) { - if (!(this instanceof Duplex)) - return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) - this.readable = false; - - if (options && options.writable === false) - this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) - this.allowHalfOpen = false; - - this.once('end', onend); -} - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) - return; - - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(this.end.bind(this)); -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js deleted file mode 100644 index 895ca50..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_passthrough.js +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) - return new PassThrough(options); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function(chunk, encoding, cb) { - cb(null, chunk); -}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js deleted file mode 100644 index 6307220..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_readable.js +++ /dev/null @@ -1,982 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -module.exports = Readable; - -/**/ -var isArray = require('isarray'); -/**/ - - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Readable.ReadableState = ReadableState; - -var EE = require('events').EventEmitter; - -/**/ -if (!EE.listenerCount) EE.listenerCount = function(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -var Stream = require('stream'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var StringDecoder; - -util.inherits(Readable, Stream); - -function ReadableState(options, stream) { - options = options || {}; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.buffer = []; - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = false; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // In streams that never have any data, and do push(null) right away, - // the consumer can miss the 'end' event if they do some I/O before - // consuming the stream. So, we don't emit('end') until some reading - // happens. - this.calledRead = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // when piping, we only care about 'readable' events that happen - // after read()ing all the bytes and not getting any pushback. - this.ranOut = false; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - if (!(this instanceof Readable)) - return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - Stream.call(this); -} - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function(chunk, encoding) { - var state = this._readableState; - - if (typeof chunk === 'string' && !state.objectMode) { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = new Buffer(chunk, encoding); - encoding = ''; - } - } - - return readableAddChunk(this, state, chunk, encoding, false); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function(chunk) { - var state = this._readableState; - return readableAddChunk(this, state, chunk, '', true); -}; - -function readableAddChunk(stream, state, chunk, encoding, addToFront) { - var er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (chunk === null || chunk === undefined) { - state.reading = false; - if (!state.ended) - onEofChunk(stream, state); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (state.ended && !addToFront) { - var e = new Error('stream.push() after EOF'); - stream.emit('error', e); - } else if (state.endEmitted && addToFront) { - var e = new Error('stream.unshift() after end event'); - stream.emit('error', e); - } else { - if (state.decoder && !addToFront && !encoding) - chunk = state.decoder.write(chunk); - - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) { - state.buffer.unshift(chunk); - } else { - state.reading = false; - state.buffer.push(chunk); - } - - if (state.needReadable) - emitReadable(stream); - - maybeReadMore(stream, state); - } - } else if (!addToFront) { - state.reading = false; - } - - return needMoreData(state); -} - - - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && - (state.needReadable || - state.length < state.highWaterMark || - state.length === 0); -} - -// backwards compatibility. -Readable.prototype.setEncoding = function(enc) { - if (!StringDecoder) - StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; -}; - -// Don't raise the hwm > 128MB -var MAX_HWM = 0x800000; -function roundUpToNextPowerOf2(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 - n--; - for (var p = 1; p < 32; p <<= 1) n |= n >> p; - n++; - } - return n; -} - -function howMuchToRead(n, state) { - if (state.length === 0 && state.ended) - return 0; - - if (state.objectMode) - return n === 0 ? 0 : 1; - - if (n === null || isNaN(n)) { - // only flow one buffer at a time - if (state.flowing && state.buffer.length) - return state.buffer[0].length; - else - return state.length; - } - - if (n <= 0) - return 0; - - // If we're asking for more than the target buffer level, - // then raise the water mark. Bump up to the next highest - // power of 2, to prevent increasing it excessively in tiny - // amounts. - if (n > state.highWaterMark) - state.highWaterMark = roundUpToNextPowerOf2(n); - - // don't have that much. return null, unless we've ended. - if (n > state.length) { - if (!state.ended) { - state.needReadable = true; - return 0; - } else - return state.length; - } - - return n; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function(n) { - var state = this._readableState; - state.calledRead = true; - var nOrig = n; - var ret; - - if (typeof n !== 'number' || n > 0) - state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && - state.needReadable && - (state.length >= state.highWaterMark || state.ended)) { - emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - ret = null; - - // In cases where the decoder did not receive enough data - // to produce a full chunk, then immediately received an - // EOF, state.buffer will contain [, ]. - // howMuchToRead will see this and coerce the amount to - // read to zero (because it's looking at the length of the - // first in state.buffer), and we'll end up here. - // - // This can only happen via state.decoder -- no other venue - // exists for pushing a zero-length chunk into state.buffer - // and triggering this behavior. In this case, we return our - // remaining data and end the stream, if appropriate. - if (state.length > 0 && state.decoder) { - ret = fromList(n, state); - state.length -= ret.length; - } - - if (state.length === 0) - endReadable(this); - - return ret; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - - // if we currently have less than the highWaterMark, then also read some - if (state.length - n <= state.highWaterMark) - doRead = true; - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) - doRead = false; - - if (doRead) { - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) - state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - } - - // If _read called its callback synchronously, then `reading` - // will be false, and we need to re-evaluate how much data we - // can return to the user. - if (doRead && !state.reading) - n = howMuchToRead(nOrig, state); - - if (n > 0) - ret = fromList(n, state); - else - ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } - - state.length -= n; - - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (state.length === 0 && !state.ended) - state.needReadable = true; - - // If we happened to read() exactly the remaining amount in the - // buffer, and the EOF has been seen at this point, then make sure - // that we emit 'end' on the very next tick. - if (state.ended && !state.endEmitted && state.length === 0) - endReadable(this); - - return ret; -}; - -function chunkInvalid(state, chunk) { - var er = null; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - - -function onEofChunk(stream, state) { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // if we've ended and we have some data left, then emit - // 'readable' now to make sure it gets picked up. - if (state.length > 0) - emitReadable(stream); - else - endReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (state.emittedReadable) - return; - - state.emittedReadable = true; - if (state.sync) - process.nextTick(function() { - emitReadable_(stream); - }); - else - emitReadable_(stream); -} - -function emitReadable_(stream) { - stream.emit('readable'); -} - - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - process.nextTick(function() { - maybeReadMore_(stream, state); - }); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && - state.length < state.highWaterMark) { - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break; - else - len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function(n) { - this.emit('error', new Error('not implemented')); -}; - -Readable.prototype.pipe = function(dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && - dest !== process.stdout && - dest !== process.stderr; - - var endFn = doEnd ? onend : cleanup; - if (state.endEmitted) - process.nextTick(endFn); - else - src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable) { - if (readable !== src) return; - cleanup(); - } - - function onend() { - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - function cleanup() { - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', cleanup); - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (!dest._writableState || dest._writableState.needDrain) - ondrain(); - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - unpipe(); - dest.removeListener('error', onerror); - if (EE.listenerCount(dest, 'error') === 0) - dest.emit('error', er); - } - // This is a brutally ugly hack to make sure that our error handler - // is attached before any userland ones. NEVER DO THIS. - if (!dest._events || !dest._events.error) - dest.on('error', onerror); - else if (isArray(dest._events.error)) - dest._events.error.unshift(onerror); - else - dest._events.error = [onerror, dest._events.error]; - - - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - // the handler that waits for readable events after all - // the data gets sucked out in flow. - // This would be easier to follow with a .once() handler - // in flow(), but that is too slow. - this.on('readable', pipeOnReadable); - - state.flowing = true; - process.nextTick(function() { - flow(src); - }); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function() { - var dest = this; - var state = src._readableState; - state.awaitDrain--; - if (state.awaitDrain === 0) - flow(src); - }; -} - -function flow(src) { - var state = src._readableState; - var chunk; - state.awaitDrain = 0; - - function write(dest, i, list) { - var written = dest.write(chunk); - if (false === written) { - state.awaitDrain++; - } - } - - while (state.pipesCount && null !== (chunk = src.read())) { - - if (state.pipesCount === 1) - write(state.pipes, 0, null); - else - forEach(state.pipes, write); - - src.emit('data', chunk); - - // if anyone needs a drain, then we have to wait for that. - if (state.awaitDrain > 0) - return; - } - - // if every destination was unpiped, either before entering this - // function, or in the while loop, then stop flowing. - // - // NB: This is a pretty rare edge case. - if (state.pipesCount === 0) { - state.flowing = false; - - // if there were data event listeners added, then switch to old mode. - if (EE.listenerCount(src, 'data') > 0) - emitDataEvents(src); - return; - } - - // at this point, no one needed a drain, so we just ran out of data - // on the next readable event, start it over again. - state.ranOut = true; -} - -function pipeOnReadable() { - if (this._readableState.ranOut) { - this._readableState.ranOut = false; - flow(this); - } -} - - -Readable.prototype.unpipe = function(dest) { - var state = this._readableState; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) - return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) - return this; - - if (!dest) - dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - if (dest) - dest.emit('unpipe', this); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - this.removeListener('readable', pipeOnReadable); - state.flowing = false; - - for (var i = 0; i < len; i++) - dests[i].emit('unpipe', this); - return this; - } - - // try to find the right one. - var i = indexOf(state.pipes, dest); - if (i === -1) - return this; - - state.pipes.splice(i, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) - state.pipes = state.pipes[0]; - - dest.emit('unpipe', this); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function(ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data' && !this._readableState.flowing) - emitDataEvents(this); - - if (ev === 'readable' && this.readable) { - var state = this._readableState; - if (!state.readableListening) { - state.readableListening = true; - state.emittedReadable = false; - state.needReadable = true; - if (!state.reading) { - this.read(0); - } else if (state.length) { - emitReadable(this, state); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function() { - emitDataEvents(this); - this.read(0); - this.emit('resume'); -}; - -Readable.prototype.pause = function() { - emitDataEvents(this, true); - this.emit('pause'); -}; - -function emitDataEvents(stream, startPaused) { - var state = stream._readableState; - - if (state.flowing) { - // https://github.com/isaacs/readable-stream/issues/16 - throw new Error('Cannot switch to old mode now.'); - } - - var paused = startPaused || false; - var readable = false; - - // convert to an old-style stream. - stream.readable = true; - stream.pipe = Stream.prototype.pipe; - stream.on = stream.addListener = Stream.prototype.on; - - stream.on('readable', function() { - readable = true; - - var c; - while (!paused && (null !== (c = stream.read()))) - stream.emit('data', c); - - if (c === null) { - readable = false; - stream._readableState.needReadable = true; - } - }); - - stream.pause = function() { - paused = true; - this.emit('pause'); - }; - - stream.resume = function() { - paused = false; - if (readable) - process.nextTick(function() { - stream.emit('readable'); - }); - else - this.read(0); - this.emit('resume'); - }; - - // now make it start, just in case it hadn't already. - stream.emit('readable'); -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function(stream) { - var state = this._readableState; - var paused = false; - - var self = this; - stream.on('end', function() { - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) - self.push(chunk); - } - - self.push(null); - }); - - stream.on('data', function(chunk) { - if (state.decoder) - chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - //if (state.objectMode && util.isNullOrUndefined(chunk)) - if (state.objectMode && (chunk === null || chunk === undefined)) - return; - else if (!state.objectMode && (!chunk || !chunk.length)) - return; - - var ret = self.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (typeof stream[i] === 'function' && - typeof this[i] === 'undefined') { - this[i] = function(method) { return function() { - return stream[method].apply(stream, arguments); - }}(i); - } - } - - // proxy certain important events. - var events = ['error', 'close', 'destroy', 'pause', 'resume']; - forEach(events, function(ev) { - stream.on(ev, self.emit.bind(self, ev)); - }); - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - self._read = function(n) { - if (paused) { - paused = false; - stream.resume(); - } - }; - - return self; -}; - - - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -function fromList(n, state) { - var list = state.buffer; - var length = state.length; - var stringMode = !!state.decoder; - var objectMode = !!state.objectMode; - var ret; - - // nothing in the list, definitely empty. - if (list.length === 0) - return null; - - if (length === 0) - ret = null; - else if (objectMode) - ret = list.shift(); - else if (!n || n >= length) { - // read it all, truncate the array. - if (stringMode) - ret = list.join(''); - else - ret = Buffer.concat(list, length); - list.length = 0; - } else { - // read just some of it. - if (n < list[0].length) { - // just take a part of the first list item. - // slice is the same for buffers and strings. - var buf = list[0]; - ret = buf.slice(0, n); - list[0] = buf.slice(n); - } else if (n === list[0].length) { - // first list is a perfect match - ret = list.shift(); - } else { - // complex case. - // we have enough to cover it, but it spans past the first buffer. - if (stringMode) - ret = ''; - else - ret = new Buffer(n); - - var c = 0; - for (var i = 0, l = list.length; i < l && c < n; i++) { - var buf = list[0]; - var cpy = Math.min(n - c, buf.length); - - if (stringMode) - ret += buf.slice(0, cpy); - else - buf.copy(ret, c, 0, cpy); - - if (cpy < buf.length) - list[0] = buf.slice(cpy); - else - list.shift(); - - c += cpy; - } - } - } - - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) - throw new Error('endReadable called on non-empty stream'); - - if (!state.endEmitted && state.calledRead) { - state.ended = true; - process.nextTick(function() { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } - }); - } -} - -function forEach (xs, f) { - for (var i = 0, l = xs.length; i < l; i++) { - f(xs[i], i); - } -} - -function indexOf (xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js deleted file mode 100644 index eb188df..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_transform.js +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - -module.exports = Transform; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(Transform, Duplex); - - -function TransformState(options, stream) { - this.afterTransform = function(er, data) { - return afterTransform(stream, er, data); - }; - - this.needTransform = false; - this.transforming = false; - this.writecb = null; - this.writechunk = null; -} - -function afterTransform(stream, er, data) { - var ts = stream._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) - return stream.emit('error', new Error('no writecb in Transform class')); - - ts.writechunk = null; - ts.writecb = null; - - if (data !== null && data !== undefined) - stream.push(data); - - if (cb) - cb(er); - - var rs = stream._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - stream._read(rs.highWaterMark); - } -} - - -function Transform(options) { - if (!(this instanceof Transform)) - return new Transform(options); - - Duplex.call(this, options); - - var ts = this._transformState = new TransformState(options, this); - - // when the writable side finishes, then flush out anything remaining. - var stream = this; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - this.once('finish', function() { - if ('function' === typeof this._flush) - this._flush(function(er) { - done(stream, er); - }); - else - done(stream); - }); -} - -Transform.prototype.push = function(chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function(chunk, encoding, cb) { - throw new Error('not implemented'); -}; - -Transform.prototype._write = function(chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || - rs.needReadable || - rs.length < rs.highWaterMark) - this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function(n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - - -function done(stream, er) { - if (er) - return stream.emit('error', er); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - var ws = stream._writableState; - var rs = stream._readableState; - var ts = stream._transformState; - - if (ws.length) - throw new Error('calling transform done when ws.length != 0'); - - if (ts.transforming) - throw new Error('calling transform done when still transforming'); - - return stream.push(null); -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js deleted file mode 100644 index 4bdaa4f..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/lib/_stream_writable.js +++ /dev/null @@ -1,386 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, cb), and it'll handle all -// the drain event emission and buffering. - -module.exports = Writable; - -/**/ -var Buffer = require('buffer').Buffer; -/**/ - -Writable.WritableState = WritableState; - - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Stream = require('stream'); - -util.inherits(Writable, Stream); - -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; -} - -function WritableState(options, stream) { - options = options || {}; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - this.highWaterMark = (hwm || hwm === 0) ? hwm : 16 * 1024; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - // cast to ints. - this.highWaterMark = ~~this.highWaterMark; - - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, becuase any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function(er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.buffer = []; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; -} - -function Writable(options) { - var Duplex = require('./_stream_duplex'); - - // Writable ctor is applied to Duplexes, though they're not - // instanceof Writable, they're instanceof Readable. - if (!(this instanceof Writable) && !(this instanceof Duplex)) - return new Writable(options); - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function() { - this.emit('error', new Error('Cannot pipe. Not readable.')); -}; - - -function writeAfterEnd(stream, state, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); -} - -// If we get something that is not a buffer, string, null, or undefined, -// and we're not in objectMode, then that's an error. -// Otherwise stream chunks are all considered to be of length=1, and the -// watermarks determine how many objects to keep in the buffer, rather than -// how many bytes or characters. -function validChunk(stream, state, chunk, cb) { - var valid = true; - if (!Buffer.isBuffer(chunk) && - 'string' !== typeof chunk && - chunk !== null && - chunk !== undefined && - !state.objectMode) { - var er = new TypeError('Invalid non-string/buffer chunk'); - stream.emit('error', er); - process.nextTick(function() { - cb(er); - }); - valid = false; - } - return valid; -} - -Writable.prototype.write = function(chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - else if (!encoding) - encoding = state.defaultEncoding; - - if (typeof cb !== 'function') - cb = function() {}; - - if (state.ended) - writeAfterEnd(this, state, cb); - else if (validChunk(this, state, chunk, cb)) - ret = writeOrBuffer(this, state, chunk, encoding, cb); - - return ret; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && - state.decodeStrings !== false && - typeof chunk === 'string') { - chunk = new Buffer(chunk, encoding); - } - return chunk; -} - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, chunk, encoding, cb) { - chunk = decodeChunk(state, chunk, encoding); - if (Buffer.isBuffer(chunk)) - encoding = 'buffer'; - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) - state.needDrain = true; - - if (state.writing) - state.buffer.push(new WriteReq(chunk, encoding, cb)); - else - doWrite(stream, state, len, chunk, encoding, cb); - - return ret; -} - -function doWrite(stream, state, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - if (sync) - process.nextTick(function() { - cb(er); - }); - else - cb(er); - - stream._writableState.errorEmitted = true; - stream.emit('error', er); -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) - onwriteError(stream, state, sync, er, cb); - else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(stream, state); - - if (!finished && !state.bufferProcessing && state.buffer.length) - clearBuffer(stream, state); - - if (sync) { - process.nextTick(function() { - afterWrite(stream, state, finished, cb); - }); - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) - onwriteDrain(stream, state); - cb(); - if (finished) - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - - for (var c = 0; c < state.buffer.length; c++) { - var entry = state.buffer[c]; - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, len, chunk, encoding, cb); - - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - c++; - break; - } - } - - state.bufferProcessing = false; - if (c < state.buffer.length) - state.buffer = state.buffer.slice(c); - else - state.buffer.length = 0; -} - -Writable.prototype._write = function(chunk, encoding, cb) { - cb(new Error('not implemented')); -}; - -Writable.prototype.end = function(chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (typeof chunk !== 'undefined' && chunk !== null) - this.write(chunk, encoding); - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) - endWritable(this, state, cb); -}; - - -function needFinish(stream, state) { - return (state.ending && - state.length === 0 && - !state.finished && - !state.writing); -} - -function finishMaybe(stream, state) { - var need = needFinish(stream, state); - if (need) { - state.finished = true; - stream.emit('finish'); - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) - process.nextTick(cb); - else - stream.once('finish', cb); - } - state.ended = true; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md deleted file mode 100644 index 5a76b41..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# core-util-is - -The `util.is*` functions introduced in Node v0.12. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch deleted file mode 100644 index a06d5c0..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/float.patch +++ /dev/null @@ -1,604 +0,0 @@ -diff --git a/lib/util.js b/lib/util.js -index a03e874..9074e8e 100644 ---- a/lib/util.js -+++ b/lib/util.js -@@ -19,430 +19,6 @@ - // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE - // USE OR OTHER DEALINGS IN THE SOFTWARE. - --var formatRegExp = /%[sdj%]/g; --exports.format = function(f) { -- if (!isString(f)) { -- var objects = []; -- for (var i = 0; i < arguments.length; i++) { -- objects.push(inspect(arguments[i])); -- } -- return objects.join(' '); -- } -- -- var i = 1; -- var args = arguments; -- var len = args.length; -- var str = String(f).replace(formatRegExp, function(x) { -- if (x === '%%') return '%'; -- if (i >= len) return x; -- switch (x) { -- case '%s': return String(args[i++]); -- case '%d': return Number(args[i++]); -- case '%j': -- try { -- return JSON.stringify(args[i++]); -- } catch (_) { -- return '[Circular]'; -- } -- default: -- return x; -- } -- }); -- for (var x = args[i]; i < len; x = args[++i]) { -- if (isNull(x) || !isObject(x)) { -- str += ' ' + x; -- } else { -- str += ' ' + inspect(x); -- } -- } -- return str; --}; -- -- --// Mark that a method should not be used. --// Returns a modified function which warns once by default. --// If --no-deprecation is set, then it is a no-op. --exports.deprecate = function(fn, msg) { -- // Allow for deprecating things in the process of starting up. -- if (isUndefined(global.process)) { -- return function() { -- return exports.deprecate(fn, msg).apply(this, arguments); -- }; -- } -- -- if (process.noDeprecation === true) { -- return fn; -- } -- -- var warned = false; -- function deprecated() { -- if (!warned) { -- if (process.throwDeprecation) { -- throw new Error(msg); -- } else if (process.traceDeprecation) { -- console.trace(msg); -- } else { -- console.error(msg); -- } -- warned = true; -- } -- return fn.apply(this, arguments); -- } -- -- return deprecated; --}; -- -- --var debugs = {}; --var debugEnviron; --exports.debuglog = function(set) { -- if (isUndefined(debugEnviron)) -- debugEnviron = process.env.NODE_DEBUG || ''; -- set = set.toUpperCase(); -- if (!debugs[set]) { -- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { -- var pid = process.pid; -- debugs[set] = function() { -- var msg = exports.format.apply(exports, arguments); -- console.error('%s %d: %s', set, pid, msg); -- }; -- } else { -- debugs[set] = function() {}; -- } -- } -- return debugs[set]; --}; -- -- --/** -- * Echos the value of a value. Trys to print the value out -- * in the best way possible given the different types. -- * -- * @param {Object} obj The object to print out. -- * @param {Object} opts Optional options object that alters the output. -- */ --/* legacy: obj, showHidden, depth, colors*/ --function inspect(obj, opts) { -- // default options -- var ctx = { -- seen: [], -- stylize: stylizeNoColor -- }; -- // legacy... -- if (arguments.length >= 3) ctx.depth = arguments[2]; -- if (arguments.length >= 4) ctx.colors = arguments[3]; -- if (isBoolean(opts)) { -- // legacy... -- ctx.showHidden = opts; -- } else if (opts) { -- // got an "options" object -- exports._extend(ctx, opts); -- } -- // set default options -- if (isUndefined(ctx.showHidden)) ctx.showHidden = false; -- if (isUndefined(ctx.depth)) ctx.depth = 2; -- if (isUndefined(ctx.colors)) ctx.colors = false; -- if (isUndefined(ctx.customInspect)) ctx.customInspect = true; -- if (ctx.colors) ctx.stylize = stylizeWithColor; -- return formatValue(ctx, obj, ctx.depth); --} --exports.inspect = inspect; -- -- --// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics --inspect.colors = { -- 'bold' : [1, 22], -- 'italic' : [3, 23], -- 'underline' : [4, 24], -- 'inverse' : [7, 27], -- 'white' : [37, 39], -- 'grey' : [90, 39], -- 'black' : [30, 39], -- 'blue' : [34, 39], -- 'cyan' : [36, 39], -- 'green' : [32, 39], -- 'magenta' : [35, 39], -- 'red' : [31, 39], -- 'yellow' : [33, 39] --}; -- --// Don't use 'blue' not visible on cmd.exe --inspect.styles = { -- 'special': 'cyan', -- 'number': 'yellow', -- 'boolean': 'yellow', -- 'undefined': 'grey', -- 'null': 'bold', -- 'string': 'green', -- 'date': 'magenta', -- // "name": intentionally not styling -- 'regexp': 'red' --}; -- -- --function stylizeWithColor(str, styleType) { -- var style = inspect.styles[styleType]; -- -- if (style) { -- return '\u001b[' + inspect.colors[style][0] + 'm' + str + -- '\u001b[' + inspect.colors[style][1] + 'm'; -- } else { -- return str; -- } --} -- -- --function stylizeNoColor(str, styleType) { -- return str; --} -- -- --function arrayToHash(array) { -- var hash = {}; -- -- array.forEach(function(val, idx) { -- hash[val] = true; -- }); -- -- return hash; --} -- -- --function formatValue(ctx, value, recurseTimes) { -- // Provide a hook for user-specified inspect functions. -- // Check that value is an object with an inspect function on it -- if (ctx.customInspect && -- value && -- isFunction(value.inspect) && -- // Filter out the util module, it's inspect function is special -- value.inspect !== exports.inspect && -- // Also filter out any prototype objects using the circular check. -- !(value.constructor && value.constructor.prototype === value)) { -- var ret = value.inspect(recurseTimes, ctx); -- if (!isString(ret)) { -- ret = formatValue(ctx, ret, recurseTimes); -- } -- return ret; -- } -- -- // Primitive types cannot have properties -- var primitive = formatPrimitive(ctx, value); -- if (primitive) { -- return primitive; -- } -- -- // Look up the keys of the object. -- var keys = Object.keys(value); -- var visibleKeys = arrayToHash(keys); -- -- if (ctx.showHidden) { -- keys = Object.getOwnPropertyNames(value); -- } -- -- // Some type of object without properties can be shortcutted. -- if (keys.length === 0) { -- if (isFunction(value)) { -- var name = value.name ? ': ' + value.name : ''; -- return ctx.stylize('[Function' + name + ']', 'special'); -- } -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } -- if (isDate(value)) { -- return ctx.stylize(Date.prototype.toString.call(value), 'date'); -- } -- if (isError(value)) { -- return formatError(value); -- } -- } -- -- var base = '', array = false, braces = ['{', '}']; -- -- // Make Array say that they are Array -- if (isArray(value)) { -- array = true; -- braces = ['[', ']']; -- } -- -- // Make functions say that they are functions -- if (isFunction(value)) { -- var n = value.name ? ': ' + value.name : ''; -- base = ' [Function' + n + ']'; -- } -- -- // Make RegExps say that they are RegExps -- if (isRegExp(value)) { -- base = ' ' + RegExp.prototype.toString.call(value); -- } -- -- // Make dates with properties first say the date -- if (isDate(value)) { -- base = ' ' + Date.prototype.toUTCString.call(value); -- } -- -- // Make error with message first say the error -- if (isError(value)) { -- base = ' ' + formatError(value); -- } -- -- if (keys.length === 0 && (!array || value.length == 0)) { -- return braces[0] + base + braces[1]; -- } -- -- if (recurseTimes < 0) { -- if (isRegExp(value)) { -- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); -- } else { -- return ctx.stylize('[Object]', 'special'); -- } -- } -- -- ctx.seen.push(value); -- -- var output; -- if (array) { -- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); -- } else { -- output = keys.map(function(key) { -- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); -- }); -- } -- -- ctx.seen.pop(); -- -- return reduceToSingleString(output, base, braces); --} -- -- --function formatPrimitive(ctx, value) { -- if (isUndefined(value)) -- return ctx.stylize('undefined', 'undefined'); -- if (isString(value)) { -- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') -- .replace(/'/g, "\\'") -- .replace(/\\"/g, '"') + '\''; -- return ctx.stylize(simple, 'string'); -- } -- if (isNumber(value)) { -- // Format -0 as '-0'. Strict equality won't distinguish 0 from -0, -- // so instead we use the fact that 1 / -0 < 0 whereas 1 / 0 > 0 . -- if (value === 0 && 1 / value < 0) -- return ctx.stylize('-0', 'number'); -- return ctx.stylize('' + value, 'number'); -- } -- if (isBoolean(value)) -- return ctx.stylize('' + value, 'boolean'); -- // For some reason typeof null is "object", so special case here. -- if (isNull(value)) -- return ctx.stylize('null', 'null'); --} -- -- --function formatError(value) { -- return '[' + Error.prototype.toString.call(value) + ']'; --} -- -- --function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { -- var output = []; -- for (var i = 0, l = value.length; i < l; ++i) { -- if (hasOwnProperty(value, String(i))) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- String(i), true)); -- } else { -- output.push(''); -- } -- } -- keys.forEach(function(key) { -- if (!key.match(/^\d+$/)) { -- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, -- key, true)); -- } -- }); -- return output; --} -- -- --function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { -- var name, str, desc; -- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; -- if (desc.get) { -- if (desc.set) { -- str = ctx.stylize('[Getter/Setter]', 'special'); -- } else { -- str = ctx.stylize('[Getter]', 'special'); -- } -- } else { -- if (desc.set) { -- str = ctx.stylize('[Setter]', 'special'); -- } -- } -- if (!hasOwnProperty(visibleKeys, key)) { -- name = '[' + key + ']'; -- } -- if (!str) { -- if (ctx.seen.indexOf(desc.value) < 0) { -- if (isNull(recurseTimes)) { -- str = formatValue(ctx, desc.value, null); -- } else { -- str = formatValue(ctx, desc.value, recurseTimes - 1); -- } -- if (str.indexOf('\n') > -1) { -- if (array) { -- str = str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n').substr(2); -- } else { -- str = '\n' + str.split('\n').map(function(line) { -- return ' ' + line; -- }).join('\n'); -- } -- } -- } else { -- str = ctx.stylize('[Circular]', 'special'); -- } -- } -- if (isUndefined(name)) { -- if (array && key.match(/^\d+$/)) { -- return str; -- } -- name = JSON.stringify('' + key); -- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { -- name = name.substr(1, name.length - 2); -- name = ctx.stylize(name, 'name'); -- } else { -- name = name.replace(/'/g, "\\'") -- .replace(/\\"/g, '"') -- .replace(/(^"|"$)/g, "'"); -- name = ctx.stylize(name, 'string'); -- } -- } -- -- return name + ': ' + str; --} -- -- --function reduceToSingleString(output, base, braces) { -- var numLinesEst = 0; -- var length = output.reduce(function(prev, cur) { -- numLinesEst++; -- if (cur.indexOf('\n') >= 0) numLinesEst++; -- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; -- }, 0); -- -- if (length > 60) { -- return braces[0] + -- (base === '' ? '' : base + '\n ') + -- ' ' + -- output.join(',\n ') + -- ' ' + -- braces[1]; -- } -- -- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; --} -- -- - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray(ar) { -@@ -522,166 +98,10 @@ function isPrimitive(arg) { - exports.isPrimitive = isPrimitive; - - function isBuffer(arg) { -- return arg instanceof Buffer; -+ return Buffer.isBuffer(arg); - } - exports.isBuffer = isBuffer; - - function objectToString(o) { - return Object.prototype.toString.call(o); --} -- -- --function pad(n) { -- return n < 10 ? '0' + n.toString(10) : n.toString(10); --} -- -- --var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', -- 'Oct', 'Nov', 'Dec']; -- --// 26 Feb 16:19:34 --function timestamp() { -- var d = new Date(); -- var time = [pad(d.getHours()), -- pad(d.getMinutes()), -- pad(d.getSeconds())].join(':'); -- return [d.getDate(), months[d.getMonth()], time].join(' '); --} -- -- --// log is just a thin wrapper to console.log that prepends a timestamp --exports.log = function() { -- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); --}; -- -- --/** -- * Inherit the prototype methods from one constructor into another. -- * -- * The Function.prototype.inherits from lang.js rewritten as a standalone -- * function (not on Function.prototype). NOTE: If this file is to be loaded -- * during bootstrapping this function needs to be rewritten using some native -- * functions as prototype setup using normal JavaScript does not work as -- * expected during bootstrapping (see mirror.js in r114903). -- * -- * @param {function} ctor Constructor function which needs to inherit the -- * prototype. -- * @param {function} superCtor Constructor function to inherit prototype from. -- */ --exports.inherits = function(ctor, superCtor) { -- ctor.super_ = superCtor; -- ctor.prototype = Object.create(superCtor.prototype, { -- constructor: { -- value: ctor, -- enumerable: false, -- writable: true, -- configurable: true -- } -- }); --}; -- --exports._extend = function(origin, add) { -- // Don't do anything if add isn't an object -- if (!add || !isObject(add)) return origin; -- -- var keys = Object.keys(add); -- var i = keys.length; -- while (i--) { -- origin[keys[i]] = add[keys[i]]; -- } -- return origin; --}; -- --function hasOwnProperty(obj, prop) { -- return Object.prototype.hasOwnProperty.call(obj, prop); --} -- -- --// Deprecated old stuff. -- --exports.p = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- console.error(exports.inspect(arguments[i])); -- } --}, 'util.p: Use console.error() instead'); -- -- --exports.exec = exports.deprecate(function() { -- return require('child_process').exec.apply(this, arguments); --}, 'util.exec is now called `child_process.exec`.'); -- -- --exports.print = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(String(arguments[i])); -- } --}, 'util.print: Use console.log instead'); -- -- --exports.puts = exports.deprecate(function() { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stdout.write(arguments[i] + '\n'); -- } --}, 'util.puts: Use console.log instead'); -- -- --exports.debug = exports.deprecate(function(x) { -- process.stderr.write('DEBUG: ' + x + '\n'); --}, 'util.debug: Use console.error instead'); -- -- --exports.error = exports.deprecate(function(x) { -- for (var i = 0, len = arguments.length; i < len; ++i) { -- process.stderr.write(arguments[i] + '\n'); -- } --}, 'util.error: Use console.error instead'); -- -- --exports.pump = exports.deprecate(function(readStream, writeStream, callback) { -- var callbackCalled = false; -- -- function call(a, b, c) { -- if (callback && !callbackCalled) { -- callback(a, b, c); -- callbackCalled = true; -- } -- } -- -- readStream.addListener('data', function(chunk) { -- if (writeStream.write(chunk) === false) readStream.pause(); -- }); -- -- writeStream.addListener('drain', function() { -- readStream.resume(); -- }); -- -- readStream.addListener('end', function() { -- writeStream.end(); -- }); -- -- readStream.addListener('close', function() { -- call(); -- }); -- -- readStream.addListener('error', function(err) { -- writeStream.end(); -- call(err); -- }); -- -- writeStream.addListener('error', function(err) { -- readStream.destroy(); -- call(err); -- }); --}, 'util.pump(): Use readableStream.pipe() instead'); -- -- --var uv; --exports._errnoException = function(err, syscall) { -- if (isUndefined(uv)) uv = process.binding('uv'); -- var errname = uv.errname(err); -- var e = new Error(syscall + ' ' + errname); -- e.code = errname; -- e.errno = errname; -- e.syscall = syscall; -- return e; --}; -+} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js deleted file mode 100644 index 9074e8e..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/lib/util.js +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return Buffer.isBuffer(arg); -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json deleted file mode 100644 index 466dfdf..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "core-util-is", - "version": "1.0.1", - "description": "The `util.is*` functions introduced in Node v0.12.", - "main": "lib/util.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/core-util-is.git" - }, - "keywords": [ - "util", - "isBuffer", - "isArray", - "isNumber", - "isString", - "isRegExp", - "isThis", - "isThat", - "polyfill" - ], - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/isaacs/core-util-is/issues" - }, - "readme": "# core-util-is\n\nThe `util.is*` functions introduced in Node v0.12.\n", - "readmeFilename": "README.md", - "homepage": "https://github.com/isaacs/core-util-is", - "_id": "core-util-is@1.0.1", - "dist": { - "shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", - "tarball": "http://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" - }, - "_from": "core-util-is@>=1.0.0 <1.1.0", - "_npmVersion": "1.3.23", - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "directories": {}, - "_shasum": "6b07085aef9a3ccac6ee53bf9d3df0c1521a5538", - "_resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.1.tgz" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js deleted file mode 100644 index 007fa10..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/core-util-is/util.js +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && objectToString(e) === '[object Error]'; -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -function isBuffer(arg) { - return arg instanceof Buffer; -} -exports.isBuffer = isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE deleted file mode 100644 index dea3013..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -The ISC License - -Copyright (c) Isaac Z. Schlueter - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md deleted file mode 100644 index b1c5665..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/README.md +++ /dev/null @@ -1,42 +0,0 @@ -Browser-friendly inheritance fully compatible with standard node.js -[inherits](http://nodejs.org/api/util.html#util_util_inherits_constructor_superconstructor). - -This package exports standard `inherits` from node.js `util` module in -node environment, but also provides alternative browser-friendly -implementation through [browser -field](https://gist.github.com/shtylman/4339901). Alternative -implementation is a literal copy of standard one located in standalone -module to avoid requiring of `util`. It also has a shim for old -browsers with no `Object.create` support. - -While keeping you sure you are using standard `inherits` -implementation in node.js environment, it allows bundlers such as -[browserify](https://github.com/substack/node-browserify) to not -include full `util` package to your client code if all you need is -just `inherits` function. It worth, because browser shim for `util` -package is large and `inherits` is often the single function you need -from it. - -It's recommended to use this package instead of -`require('util').inherits` for any code that has chances to be used -not only in node.js but in browser too. - -## usage - -```js -var inherits = require('inherits'); -// then use exactly as the standard one -``` - -## note on version ~1.0 - -Version ~1.0 had completely different motivation and is not compatible -neither with 2.0 nor with standard node.js `inherits`. - -If you are using version ~1.0 and planning to switch to ~2.0, be -careful: - -* new version uses `super_` instead of `super` for referencing - superclass -* new version overwrites current prototype while old one preserves any - existing fields on it diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js deleted file mode 100644 index 29f5e24..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('util').inherits diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js deleted file mode 100644 index c1e78a7..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/inherits_browser.js +++ /dev/null @@ -1,23 +0,0 @@ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json deleted file mode 100644 index 93d5078..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/package.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "name": "inherits", - "description": "Browser-friendly inheritance fully compatible with standard node.js inherits()", - "version": "2.0.1", - "keywords": [ - "inheritance", - "class", - "klass", - "oop", - "object-oriented", - "inherits", - "browser", - "browserify" - ], - "main": "./inherits.js", - "browser": "./inherits_browser.js", - "repository": { - "type": "git", - "url": "git://github.com/isaacs/inherits.git" - }, - "license": "ISC", - "scripts": { - "test": "node test" - }, - "bugs": { - "url": "https://github.com/isaacs/inherits/issues" - }, - "_id": "inherits@2.0.1", - "dist": { - "shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", - "tarball": "http://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz" - }, - "_from": "inherits@>=2.0.1 <2.1.0", - "_npmVersion": "1.3.8", - "_npmUser": { - "name": "isaacs", - "email": "i@izs.me" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - } - ], - "directories": {}, - "_shasum": "b17d08d326b4423e568eff719f91b0b1cbdf69f1", - "_resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.1.tgz", - "readme": "ERROR: No README data found!", - "homepage": "https://github.com/isaacs/inherits#readme" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js deleted file mode 100644 index fc53012..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/inherits/test.js +++ /dev/null @@ -1,25 +0,0 @@ -var inherits = require('./inherits.js') -var assert = require('assert') - -function test(c) { - assert(c.constructor === Child) - assert(c.constructor.super_ === Parent) - assert(Object.getPrototypeOf(c) === Child.prototype) - assert(Object.getPrototypeOf(Object.getPrototypeOf(c)) === Parent.prototype) - assert(c instanceof Child) - assert(c instanceof Parent) -} - -function Child() { - Parent.call(this) - test(this) -} - -function Parent() {} - -inherits(Child, Parent) - -var c = new Child -test(c) - -console.log('ok') diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md deleted file mode 100644 index 052a62b..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/README.md +++ /dev/null @@ -1,54 +0,0 @@ - -# isarray - -`Array#isArray` for older browsers. - -## Usage - -```js -var isArray = require('isarray'); - -console.log(isArray([])); // => true -console.log(isArray({})); // => false -``` - -## Installation - -With [npm](http://npmjs.org) do - -```bash -$ npm install isarray -``` - -Then bundle for the browser with -[browserify](https://github.com/substack/browserify). - -With [component](http://component.io) do - -```bash -$ component install juliangruber/isarray -``` - -## License - -(MIT) - -Copyright (c) 2013 Julian Gruber <julian@juliangruber.com> - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js deleted file mode 100644 index ec58596..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/build/build.js +++ /dev/null @@ -1,209 +0,0 @@ - -/** - * Require the given path. - * - * @param {String} path - * @return {Object} exports - * @api public - */ - -function require(path, parent, orig) { - var resolved = require.resolve(path); - - // lookup failed - if (null == resolved) { - orig = orig || path; - parent = parent || 'root'; - var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); - err.path = orig; - err.parent = parent; - err.require = true; - throw err; - } - - var module = require.modules[resolved]; - - // perform real require() - // by invoking the module's - // registered function - if (!module.exports) { - module.exports = {}; - module.client = module.component = true; - module.call(this, module.exports, require.relative(resolved), module); - } - - return module.exports; -} - -/** - * Registered modules. - */ - -require.modules = {}; - -/** - * Registered aliases. - */ - -require.aliases = {}; - -/** - * Resolve `path`. - * - * Lookup: - * - * - PATH/index.js - * - PATH.js - * - PATH - * - * @param {String} path - * @return {String} path or null - * @api private - */ - -require.resolve = function(path) { - if (path.charAt(0) === '/') path = path.slice(1); - var index = path + '/index.js'; - - var paths = [ - path, - path + '.js', - path + '.json', - path + '/index.js', - path + '/index.json' - ]; - - for (var i = 0; i < paths.length; i++) { - var path = paths[i]; - if (require.modules.hasOwnProperty(path)) return path; - } - - if (require.aliases.hasOwnProperty(index)) { - return require.aliases[index]; - } -}; - -/** - * Normalize `path` relative to the current path. - * - * @param {String} curr - * @param {String} path - * @return {String} - * @api private - */ - -require.normalize = function(curr, path) { - var segs = []; - - if ('.' != path.charAt(0)) return path; - - curr = curr.split('/'); - path = path.split('/'); - - for (var i = 0; i < path.length; ++i) { - if ('..' == path[i]) { - curr.pop(); - } else if ('.' != path[i] && '' != path[i]) { - segs.push(path[i]); - } - } - - return curr.concat(segs).join('/'); -}; - -/** - * Register module at `path` with callback `definition`. - * - * @param {String} path - * @param {Function} definition - * @api private - */ - -require.register = function(path, definition) { - require.modules[path] = definition; -}; - -/** - * Alias a module definition. - * - * @param {String} from - * @param {String} to - * @api private - */ - -require.alias = function(from, to) { - if (!require.modules.hasOwnProperty(from)) { - throw new Error('Failed to alias "' + from + '", it does not exist'); - } - require.aliases[to] = from; -}; - -/** - * Return a require function relative to the `parent` path. - * - * @param {String} parent - * @return {Function} - * @api private - */ - -require.relative = function(parent) { - var p = require.normalize(parent, '..'); - - /** - * lastIndexOf helper. - */ - - function lastIndexOf(arr, obj) { - var i = arr.length; - while (i--) { - if (arr[i] === obj) return i; - } - return -1; - } - - /** - * The relative require() itself. - */ - - function localRequire(path) { - var resolved = localRequire.resolve(path); - return require(resolved, parent, path); - } - - /** - * Resolve relative to the parent. - */ - - localRequire.resolve = function(path) { - var c = path.charAt(0); - if ('/' == c) return path.slice(1); - if ('.' == c) return require.normalize(p, path); - - // resolve deps by returning - // the dep in the nearest "deps" - // directory - var segs = parent.split('/'); - var i = lastIndexOf(segs, 'deps') + 1; - if (!i) i = 0; - path = segs.slice(0, i + 1).join('/') + '/deps/' + path; - return path; - }; - - /** - * Check if module is defined at `path`. - */ - - localRequire.exists = function(path) { - return require.modules.hasOwnProperty(localRequire.resolve(path)); - }; - - return localRequire; -}; -require.register("isarray/index.js", function(exports, require, module){ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; - -}); -require.alias("isarray/index.js", "isarray/index.js"); - diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json deleted file mode 100644 index 9e31b68..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/component.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name" : "isarray", - "description" : "Array#isArray for older browsers", - "version" : "0.0.1", - "repository" : "juliangruber/isarray", - "homepage": "https://github.com/juliangruber/isarray", - "main" : "index.js", - "scripts" : [ - "index.js" - ], - "dependencies" : {}, - "keywords": ["browser","isarray","array"], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js deleted file mode 100644 index 5f5ad45..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/index.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Array.isArray || function (arr) { - return Object.prototype.toString.call(arr) == '[object Array]'; -}; diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json deleted file mode 100644 index 19228ab..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/isarray/package.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "name": "isarray", - "description": "Array#isArray for older browsers", - "version": "0.0.1", - "repository": { - "type": "git", - "url": "git://github.com/juliangruber/isarray.git" - }, - "homepage": "https://github.com/juliangruber/isarray", - "main": "index.js", - "scripts": { - "test": "tap test/*.js" - }, - "dependencies": {}, - "devDependencies": { - "tap": "*" - }, - "keywords": [ - "browser", - "isarray", - "array" - ], - "author": { - "name": "Julian Gruber", - "email": "mail@juliangruber.com", - "url": "http://juliangruber.com" - }, - "license": "MIT", - "_id": "isarray@0.0.1", - "dist": { - "shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", - "tarball": "http://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz" - }, - "_from": "isarray@0.0.1", - "_npmVersion": "1.2.18", - "_npmUser": { - "name": "juliangruber", - "email": "julian@juliangruber.com" - }, - "maintainers": [ - { - "name": "juliangruber", - "email": "julian@juliangruber.com" - } - ], - "directories": {}, - "_shasum": "8a18acfca9a8f4177e09abfc6038939b05d1eedf", - "_resolved": "https://registry.npmjs.org/isarray/-/isarray-0.0.1.tgz", - "bugs": { - "url": "https://github.com/juliangruber/isarray/issues" - }, - "readme": "ERROR: No README data found!" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore deleted file mode 100644 index 206320c..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/.npmignore +++ /dev/null @@ -1,2 +0,0 @@ -build -test diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE deleted file mode 100644 index 6de584a..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright Joyent, Inc. and other Node contributors. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to permit -persons to whom the Software is furnished to do so, subject to the -following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md deleted file mode 100644 index 4d2aa00..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/README.md +++ /dev/null @@ -1,7 +0,0 @@ -**string_decoder.js** (`require('string_decoder')`) from Node.js core - -Copyright Joyent, Inc. and other Node contributors. See LICENCE file for details. - -Version numbers match the versions found in Node core, e.g. 0.10.24 matches Node 0.10.24, likewise 0.11.10 matches Node 0.11.10. **Prefer the stable version over the unstable.** - -The *build/* directory contains a build script that will scrape the source from the [joyent/node](https://github.com/joyent/node) repo given a specific Node version. \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js deleted file mode 100644 index b00e54f..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/index.js +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -var Buffer = require('buffer').Buffer; - -var isBufferEncoding = Buffer.isEncoding - || function(encoding) { - switch (encoding && encoding.toLowerCase()) { - case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; - default: return false; - } - } - - -function assertEncoding(encoding) { - if (encoding && !isBufferEncoding(encoding)) { - throw new Error('Unknown encoding: ' + encoding); - } -} - -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. CESU-8 is handled as part of the UTF-8 encoding. -// -// @TODO Handling all encodings inside a single object makes it very difficult -// to reason about this code, so it should be split up in the future. -// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code -// points as used by CESU-8. -var StringDecoder = exports.StringDecoder = function(encoding) { - this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); - assertEncoding(encoding); - switch (this.encoding) { - case 'utf8': - // CESU-8 represents each of Surrogate Pair by 3-bytes - this.surrogateSize = 3; - break; - case 'ucs2': - case 'utf16le': - // UTF-16 represents each of Surrogate Pair by 2-bytes - this.surrogateSize = 2; - this.detectIncompleteChar = utf16DetectIncompleteChar; - break; - case 'base64': - // Base-64 stores 3 bytes in 4 chars, and pads the remainder. - this.surrogateSize = 3; - this.detectIncompleteChar = base64DetectIncompleteChar; - break; - default: - this.write = passThroughWrite; - return; - } - - // Enough space to store all bytes of a single character. UTF-8 needs 4 - // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer(6); - // Number of bytes received for the current incomplete multi-byte character. - this.charReceived = 0; - // Number of bytes expected for the current incomplete multi-byte character. - this.charLength = 0; -}; - - -// write decodes the given buffer and returns it as JS string that is -// guaranteed to not contain any partial multi-byte characters. Any partial -// character found at the end of the buffer is buffered up, and will be -// returned when calling write again with the remaining bytes. -// -// Note: Converting a Buffer containing an orphan surrogate to a String -// currently works, but converting a String to a Buffer (via `new Buffer`, or -// Buffer#write) will replace incomplete surrogates with the unicode -// replacement character. See https://codereview.chromium.org/121173009/ . -StringDecoder.prototype.write = function(buffer) { - var charStr = ''; - // if our last write ended with an incomplete multibyte character - while (this.charLength) { - // determine how many remaining bytes this buffer has to offer for this char - var available = (buffer.length >= this.charLength - this.charReceived) ? - this.charLength - this.charReceived : - buffer.length; - - // add the new bytes to the char buffer - buffer.copy(this.charBuffer, this.charReceived, 0, available); - this.charReceived += available; - - if (this.charReceived < this.charLength) { - // still not enough chars in this buffer? wait for more ... - return ''; - } - - // remove bytes belonging to the current character from the buffer - buffer = buffer.slice(available, buffer.length); - - // get the character that was split - charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); - - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - var charCode = charStr.charCodeAt(charStr.length - 1); - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - this.charLength += this.surrogateSize; - charStr = ''; - continue; - } - this.charReceived = this.charLength = 0; - - // if there are no more bytes in this buffer, just emit our char - if (buffer.length === 0) { - return charStr; - } - break; - } - - // determine and set charLength / charReceived - this.detectIncompleteChar(buffer); - - var end = buffer.length; - if (this.charLength) { - // buffer the incomplete character bytes we got - buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); - end -= this.charReceived; - } - - charStr += buffer.toString(this.encoding, 0, end); - - var end = charStr.length - 1; - var charCode = charStr.charCodeAt(end); - // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character - if (charCode >= 0xD800 && charCode <= 0xDBFF) { - var size = this.surrogateSize; - this.charLength += size; - this.charReceived += size; - this.charBuffer.copy(this.charBuffer, size, 0, size); - buffer.copy(this.charBuffer, 0, 0, size); - return charStr.substring(0, end); - } - - // or just emit the charStr - return charStr; -}; - -// detectIncompleteChar determines if there is an incomplete UTF-8 character at -// the end of the given buffer. If so, it sets this.charLength to the byte -// length that character, and sets this.charReceived to the number of bytes -// that are available for this character. -StringDecoder.prototype.detectIncompleteChar = function(buffer) { - // determine how many bytes we have to check at the end of this buffer - var i = (buffer.length >= 3) ? 3 : buffer.length; - - // Figure out if one of the last i bytes of our buffer announces an - // incomplete char. - for (; i > 0; i--) { - var c = buffer[buffer.length - i]; - - // See http://en.wikipedia.org/wiki/UTF-8#Description - - // 110XXXXX - if (i == 1 && c >> 5 == 0x06) { - this.charLength = 2; - break; - } - - // 1110XXXX - if (i <= 2 && c >> 4 == 0x0E) { - this.charLength = 3; - break; - } - - // 11110XXX - if (i <= 3 && c >> 3 == 0x1E) { - this.charLength = 4; - break; - } - } - this.charReceived = i; -}; - -StringDecoder.prototype.end = function(buffer) { - var res = ''; - if (buffer && buffer.length) - res = this.write(buffer); - - if (this.charReceived) { - var cr = this.charReceived; - var buf = this.charBuffer; - var enc = this.encoding; - res += buf.slice(0, cr).toString(enc); - } - - return res; -}; - -function passThroughWrite(buffer) { - return buffer.toString(this.encoding); -} - -function utf16DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 2; - this.charLength = this.charReceived ? 2 : 0; -} - -function base64DetectIncompleteChar(buffer) { - this.charReceived = buffer.length % 3; - this.charLength = this.charReceived ? 3 : 0; -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json deleted file mode 100644 index 0364d54..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/node_modules/string_decoder/package.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "string_decoder", - "version": "0.10.31", - "description": "The string_decoder module from Node core", - "main": "index.js", - "dependencies": {}, - "devDependencies": { - "tap": "~0.4.8" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/rvagg/string_decoder.git" - }, - "homepage": "https://github.com/rvagg/string_decoder", - "keywords": [ - "string", - "decoder", - "browser", - "browserify" - ], - "license": "MIT", - "gitHead": "d46d4fd87cf1d06e031c23f1ba170ca7d4ade9a0", - "bugs": { - "url": "https://github.com/rvagg/string_decoder/issues" - }, - "_id": "string_decoder@0.10.31", - "_shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", - "_from": "string_decoder@>=0.10.0 <0.11.0", - "_npmVersion": "1.4.23", - "_npmUser": { - "name": "rvagg", - "email": "rod@vagg.org" - }, - "maintainers": [ - { - "name": "substack", - "email": "mail@substack.net" - }, - { - "name": "rvagg", - "email": "rod@vagg.org" - } - ], - "dist": { - "shasum": "62e203bc41766c6c28c9fc84301dab1c5310fa94", - "tarball": "http://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-0.10.31.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/package.json b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/package.json deleted file mode 100644 index 2dc3a25..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/package.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "name": "readable-stream", - "version": "1.0.31", - "description": "Streams2, a user-land copy of the stream library from Node.js v0.10.x", - "main": "readable.js", - "dependencies": { - "core-util-is": "~1.0.0", - "isarray": "0.0.1", - "string_decoder": "~0.10.x", - "inherits": "~2.0.1" - }, - "devDependencies": { - "tap": "~0.2.6" - }, - "scripts": { - "test": "tap test/simple/*.js" - }, - "repository": { - "type": "git", - "url": "git://github.com/isaacs/readable-stream.git" - }, - "keywords": [ - "readable", - "stream", - "pipe" - ], - "browser": { - "util": false - }, - "author": { - "name": "Isaac Z. Schlueter", - "email": "i@izs.me", - "url": "http://blog.izs.me/" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/isaacs/readable-stream/issues" - }, - "homepage": "https://github.com/isaacs/readable-stream", - "_id": "readable-stream@1.0.31", - "_shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", - "_from": "readable-stream@1.0.31", - "_npmVersion": "1.4.9", - "_npmUser": { - "name": "rvagg", - "email": "rod@vagg.org" - }, - "maintainers": [ - { - "name": "isaacs", - "email": "i@izs.me" - }, - { - "name": "tootallnate", - "email": "nathan@tootallnate.net" - }, - { - "name": "rvagg", - "email": "rod@vagg.org" - } - ], - "dist": { - "shasum": "8f2502e0bc9e3b0da1b94520aabb4e2603ecafae", - "tarball": "http://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-1.0.31.tgz", - "readme": "ERROR: No README data found!" -} diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js deleted file mode 100644 index 27e8d8a..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/passthrough.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_passthrough.js") diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/readable.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/readable.js deleted file mode 100644 index 4d1ddfc..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/readable.js +++ /dev/null @@ -1,6 +0,0 @@ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/transform.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/transform.js deleted file mode 100644 index 5d482f0..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/transform.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_transform.js") diff --git a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/writable.js b/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/writable.js deleted file mode 100644 index e1e9efd..0000000 --- a/util/retroImporter/node_modules/mongodb/node_modules/readable-stream/writable.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./lib/_stream_writable.js") diff --git a/util/retroImporter/node_modules/mongodb/package.json b/util/retroImporter/node_modules/mongodb/package.json deleted file mode 100644 index 9036dce..0000000 --- a/util/retroImporter/node_modules/mongodb/package.json +++ /dev/null @@ -1,66 +0,0 @@ -{ - "name": "mongodb", - "version": "2.0.45", - "description": "MongoDB legacy driver emulation layer on top of mongodb-core", - "main": "index.js", - "repository": { - "type": "git", - "url": "git@github.com:mongodb/node-mongodb-native.git" - }, - "keywords": [ - "mongodb", - "driver", - "legacy" - ], - "dependencies": { - "mongodb-core": "1.2.14", - "readable-stream": "1.0.31", - "es6-promise": "2.1.1" - }, - "devDependencies": { - "integra": "0.1.8", - "optimist": "0.6.1", - "bson": "~0.4", - "jsdoc": "3.3.0-beta3", - "semver": "4.1.0", - "rimraf": "2.2.6", - "gleak": "0.5.0", - "mongodb-version-manager": "^0.7.1", - "mongodb-tools": "~1.0", - "co": "4.5.4", - "bluebird": "2.9.27" - }, - "author": { - "name": "Christian Kvalheim" - }, - "license": "Apache-2.0", - "bugs": { - "url": "https://github.com/mongodb/node-mongodb-native/issues" - }, - "scripts": { - "test": "node test/runner.js -t functional" - }, - "homepage": "https://github.com/mongodb/node-mongodb-native", - "gitHead": "45d433baa92cb160f895d47911ee5776fbaad3be", - "_id": "mongodb@2.0.45", - "_shasum": "c63d42b918f19a53b32d4c64043f6a9f66c9aba5", - "_from": "mongodb@*", - "_npmVersion": "2.14.4", - "_nodeVersion": "4.1.1", - "_npmUser": { - "name": "christkv", - "email": "christkv@gmail.com" - }, - "maintainers": [ - { - "name": "christkv", - "email": "christkv@gmail.com" - } - ], - "dist": { - "shasum": "c63d42b918f19a53b32d4c64043f6a9f66c9aba5", - "tarball": "http://registry.npmjs.org/mongodb/-/mongodb-2.0.45.tgz" - }, - "directories": {}, - "_resolved": "https://registry.npmjs.org/mongodb/-/mongodb-2.0.45.tgz" -} diff --git a/util/retroImporter/node_modules/mongodb/t.js b/util/retroImporter/node_modules/mongodb/t.js deleted file mode 100644 index af73362..0000000 --- a/util/retroImporter/node_modules/mongodb/t.js +++ /dev/null @@ -1,73 +0,0 @@ -var MongoClient = require('./').MongoClient - , assert = require('assert') - , cappedCollectionName = "capped_test"; - - -function capitalizeFirstLetter(string) { - return string.charAt(0).toUpperCase() + string.slice(1); -} - - function createTailedCursor(db, callback) { - var collection = db.collection(cappedCollectionName) - , cursor = collection.find({}, { tailable: true, awaitdata: true, numberOfRetries: Number.MAX_VALUE}) - , stream = cursor.stream() - , statusGetters = ['notified', 'closed', 'dead', 'killed']; - - console.log('After stream open'); - statusGetters.forEach(function (s) { - var getter = 'is' + capitalizeFirstLetter(s); - console.log("cursor " + getter + " => ", cursor[getter]()); - }); - - - stream.on('error', callback); - stream.on('end', callback.bind(null, 'end')); - stream.on('close', callback.bind(null, 'close')); - stream.on('readable', callback.bind(null, 'readable')); - stream.on('data', callback.bind(null, null, 'data')); - - console.log('After stream attach events'); - statusGetters.forEach(function (s) { - var getter = 'is' + capitalizeFirstLetter(s); - console.log("cursor " + getter + " => ", cursor[getter]()); - }); - } - - function cappedStreamEvent(err, evName, data) { - if (err) { - console.log("capped stream got error", err); - return; - } - - if (evName) { - console.log("capped stream got event", evName); - } - - if (data) { - console.log("capped stream got data", data); - } - } - - -// Connection URL -var url = 'mongodb://localhost:27017/myproject'; -// Use connect method to connect to the Server -MongoClient.connect(url, function(err, db) { - assert.equal(null, err); - console.log("Connected correctly to server"); - - db.createCollection(cappedCollectionName, - { "capped": true, - "size": 100000, - "max": 5000 }, - function(err, collection) { - - assert.equal(null, err); - console.log("Created capped collection " + cappedCollectionName); - - createTailedCursor(db, cappedStreamEvent); - }); - - - //db.close(); -}); \ No newline at end of file diff --git a/util/retroImporter/node_modules/mongodb/t1.js b/util/retroImporter/node_modules/mongodb/t1.js deleted file mode 100644 index 392ed8e..0000000 --- a/util/retroImporter/node_modules/mongodb/t1.js +++ /dev/null @@ -1,77 +0,0 @@ -var MongoClient = require('./').MongoClient; - -MongoClient.connect('mongodb://localhost:27017/page-testing', function (err, db) { - collection = db.collection('test'); - - collection.insertMany([{a:1}, {a:2}], {w:1}, function (err, docs) { - if (err) { - console.log("ERROR"); - } - - collection.find().sort({'a': -1}).toArray(function(err, items) { - if (err) { - console.log("ERROR"); - } - console.log("Items: ", items); - }); - }); -}); -// var database = null; -// -// var MongoClient = require('./').MongoClient; -// -// function connect_to_mongo(callback) { -// if (database != null) { -// callback(null, database); -// } else { -// var connection = "mongodb://127.0.0.1:27017/test_db"; -// MongoClient.connect(connection, { -// server : { -// reconnectTries : 5, -// reconnectInterval: 1000, -// autoReconnect : true -// } -// }, function (err, db) { -// database = db; -// callback(err, db); -// }); -// } -// } -// -// function log(message) { -// console.log(new Date(), message); -// } -// -// var queryNumber = 0; -// -// function make_query(db) { -// var currentNumber = queryNumber; -// ++queryNumber; -// log("query " + currentNumber + ": started"); -// -// setTimeout(function() { -// make_query(db); -// }, 5000); -// -// var collection = db.collection('test_collection'); -// collection.findOne({}, -// function (err, result) { -// if (err != null) { -// log("query " + currentNumber + ": find one error: " + err.message); -// return; -// } -// log("query " + currentNumber + ": find one result: " + result); -// } -// ); -// } -// -// connect_to_mongo( -// function(err, db) { -// if (err != null) { -// log(err.message); -// return; -// } -// -// make_query(db); -// } -// ); diff --git a/util/retroImporter/node_modules/mongodb/wercker.yml b/util/retroImporter/node_modules/mongodb/wercker.yml deleted file mode 100644 index b64845f..0000000 --- a/util/retroImporter/node_modules/mongodb/wercker.yml +++ /dev/null @@ -1,19 +0,0 @@ -box: wercker/nodejs -services: - - wercker/mongodb@1.0.1 -# Build definition -build: - # The steps that will be executed on build - steps: - # A step that executes `npm install` command - - npm-install - # A step that executes `npm test` command - - npm-test - - # A custom script step, name value is used in the UI - # and the code value contains the command that get executed - - script: - name: echo nodejs information - code: | - echo "node version $(node -v) running" - echo "npm version $(npm -v) running" diff --git a/util/retroImporter/package.json b/util/retroImporter/package.json deleted file mode 100644 index 317d037..0000000 --- a/util/retroImporter/package.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "name": "retroimporter", - "version": "1.0.0", - "description": "", - "main": "retroImporter.js", - "dependencies": { - "mongodb": "^2.0.45" - }, - "devDependencies": {}, - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "author": "", - "license": "ISC" -} From c8a78ccde3cd89b593a929d10d8179dd46eeedc3 Mon Sep 17 00:00:00 2001 From: sdiemert Date: Wed, 18 Nov 2015 23:00:49 +0000 Subject: [PATCH 10/10] fixes to retroImport --- util/retroImporter/retroImporter.js | 84 ++++++++++++++++++++++------- 1 file changed, 66 insertions(+), 18 deletions(-) diff --git a/util/retroImporter/retroImporter.js b/util/retroImporter/retroImporter.js index 93d78c5..9ac0f34 100644 --- a/util/retroImporter/retroImporter.js +++ b/util/retroImporter/retroImporter.js @@ -23,7 +23,7 @@ else console.log('RETRO_QUERY_TITLE: ' + process.env.RETRO_QUERY_TITLE); } // Connect to the db -MongoClient.connect('mongodb://localhost:27017/query_composer_development', function(err, db) { +MongoClient.connect('mongodb://hubdb:27017/query_composer_development', function(err, db) { if(err) { return console.dir(err); } db.collection('queries', null, @@ -129,28 +129,76 @@ MongoClient.connect('mongodb://localhost:27017/query_composer_development', func else { simulatedExecution = simulatedExecutions[date]; + console.log("simulatedExecution:") + console.log(simulatedExecution); + console.log("execution:") + console.log(execution); if(!simulatedExecution) { throw new Error('simulatedExecution evaluted to false'); } - - if(execution.value === 'numerator' && - simulatedExecution.aggregate_result['denominator_' + execution.pid] !== undefined && - simulatedExecution.aggregate_result['denominator_' + execution.pid] !== null - ) - { - simulatedExecution.aggregate_result['numerator_' + execution.pid] = retroResults[key]; - } - else if(execution.value === 'denominator' && - simulatedExecution.aggregate_result['numerator_' + execution.pid] !== undefined && - simulatedExecution.aggregate_result['numerator_' + execution.pid] !== null ) - { - simulatedExecution.aggregate_result['denominator_' + execution.pid] = retroResults[key]; - } - else + + var FIELD = 0; + var PID = 1; + + function getPIDMatch(simulatedExecution, execution) + { + var keys = Object.keys(simulatedExecution.aggregate_result); + + + for( var key in keys) + { + if(!keys.hasOwnProperty(key)) + { + continue; + } + + + var attributes = keys[key].split('_'); + + var pid = attributes[PID]; + //var field_test = attributes[FIELD]; + + if(execution.pid === pid) + { + + return attributes; + } + + console.log("execution.pid: "+ execution.pid); + console.log("pid: "+ pid); + } + return null; + + } + + var pidMatch = getPIDMatch(simulatedExecution, execution); + + if(pidMatch !== null) { - throw new Error("ERROR: no match for date: " + date); - } + + console.log("pidMatch: "+ pidMatch); + console.log("execution.value: "+ execution.value); + + if(execution.value==='denominator') + { + simulatedExecution.aggregate_result['denominator_' + execution.pid] = retroResults[key]; + } + else if(execution.value === 'numerator') + { + simulatedExecution.aggregate_result['numerator_' + execution.pid] = retroResults[key]; + } + else + { + console.log(simulatedExecutions[date]); + throw new Error("ERROR: no match for date: " + date); + } + } + else + { + simulatedExecution.aggregate_result[execution.value + '_' + execution.pid] = retroResults[key]; + } + simulatedExecution.aggregate_result.simulated = true; }